Skip to main content

plexus_core/plexus/
schema.rs

1/// JSON Schema types with strong typing
2///
3/// This module provides strongly-typed JSON Schema structures that plugins
4/// use to describe their methods and parameters.
5///
6/// Schema generation is fully automatic via schemars. By using proper types
7/// (uuid::Uuid instead of String) and doc comments, schemars generates complete
8/// schemas with format annotations, descriptions, and required arrays.
9
10use schemars::{JsonSchema, schema_for};
11use serde::{Deserialize, Serialize};
12use std::collections::HashMap;
13
14use plexus_auth_core::{
15    AttachmentSite, CredentialFieldMarker, CredentialIssuer, CredentialKind, CredentialMetadata,
16};
17
18/// Re-exported so macro-generated code (R-1: `#[plexus::method(scope = "...")]`)
19/// can construct `RequiredCredential` scope values through `plexus-core`'s
20/// path alone — consumers don't need a direct `plexus-auth-core` dependency
21/// (the umbrella path `::plexus_rpc::core::plexus::schema::Scope` also
22/// resolves, per Z2H-2).
23pub use plexus_auth_core::Scope;
24
25use super::content_hash::{canonical_json, hash16, hash16_lines};
26
27// =============================================================================
28// Method Role
29// =============================================================================
30
31/// Describes how a method participates in the activation graph.
32///
33/// Every method on a plugin is exactly one of three kinds:
34///
35/// - `Rpc` — a regular RPC endpoint (the default).
36/// - `StaticChild` — the method returns a child activation by a static name
37///   (no lookup argument). Used by `#[child]`-annotated methods on hubs.
38/// - `DynamicChild { .. }` — the method gates a dynamic child keyed by its
39///   argument. `list_method` optionally names a sibling method that enumerates
40///   available keys, and `search_method` optionally names a sibling method
41///   that searches keys.
42///
43/// This tag is consumed by downstream tooling (synapse, synapse-cc,
44/// introspection clients) to reconstruct the child graph without a separate
45/// side-table. Today's macros emit `MethodRole::Rpc` for every method; IR-3
46/// populates child roles from `#[child]` annotations.
47///
48/// # Wire back-compat
49///
50/// Added in IR-2. Serde defaults to `Rpc` for pre-IR schemas.
51/// `#[non_exhaustive]` reserves space for future variants without breaking
52/// downstream match arms.
53#[derive(Debug, Clone, PartialEq, Eq)]
54#[non_exhaustive]
55pub enum MethodRole {
56    /// Method is an RPC endpoint (the default for ordinary methods).
57    Rpc,
58    /// Method returns a child activation by static name (no lookup arg).
59    StaticChild,
60    /// Method gates a dynamic child keyed by its argument.
61    DynamicChild {
62        /// Optional sibling method that lists available keys.
63        list_method: Option<String>,
64        /// Optional sibling method that searches available keys.
65        search_method: Option<String>,
66        /// NEST-5: the slot's type — the schema every instance in the slot
67        /// serves (`fn item(&self, name: &str) -> Option<Item>`: `Item`'s).
68        /// Absent for an untyped slot (`#[child(opaque)]`, a hand-written
69        /// router), which the gate admits whole (`tickets.{item}`).
70        child: Option<Box<PluginSchema>>,
71    },
72    /// NEST-7: a peer slot — `#[plexus_macros::peer] async fn x(&self, name:
73    /// &str) -> Result<Box<dyn I>, PeerError>`: an activation returned by
74    /// name, in this process or across the network. `interface` is the
75    /// slot's type (`None`: an untyped peer, admitted whole). It is reached
76    /// as `<parent>.<slot>.<name>`: on the wire it is a `static_child` (the
77    /// slot, whose own schema is one dynamic child — any name) marked
78    /// `peer: true` beside its `interface`, so a reader that knows only
79    /// static and dynamic children navigates it.
80    Peer {
81        /// Optional sibling method that lists available names.
82        list_method: Option<String>,
83        /// Optional sibling method that searches available names.
84        search_method: Option<String>,
85        /// The interface every peer in the slot serves; `None` for an
86        /// untyped slot.
87        interface: Option<super::peer::Interface>,
88    },
89}
90
91/// Describes how a method participates in the activation graph: `rpc`,
92/// `static_child` (a child by its own name; `peer` set for a slot of peers,
93/// reached as `<slot>.<name>`, `interface` the slot's type), or
94/// `dynamic_child` (a child found by name at call time; `child` its slot's
95/// type).
96#[derive(Serialize, Deserialize, JsonSchema)]
97#[serde(tag = "kind", rename_all = "snake_case")]
98#[schemars(rename = "MethodRole")]
99enum MethodRoleWire {
100    /// Method is an RPC endpoint (the default for ordinary methods).
101    Rpc,
102    /// Method returns a child activation by static name (no lookup arg) —
103    /// or, marked `peer`, a slot of peers by name.
104    StaticChild {
105        /// NEST-7: the child is a slot of peers (`#[plexus_macros::peer]`).
106        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
107        peer: bool,
108        /// NEST-7: a peer slot's sibling method that lists its names.
109        #[serde(default, skip_serializing_if = "Option::is_none")]
110        list_method: Option<String>,
111        /// NEST-7: a peer slot's sibling method that searches its names.
112        #[serde(default, skip_serializing_if = "Option::is_none")]
113        search_method: Option<String>,
114        /// NEST-7: a typed peer slot's interface.
115        #[serde(default, skip_serializing_if = "Option::is_none")]
116        interface: Option<Box<super::peer::Interface>>,
117    },
118    /// Method gates a dynamic child keyed by its argument.
119    DynamicChild {
120        /// Optional sibling method that lists available keys.
121        #[serde(default, skip_serializing_if = "Option::is_none")]
122        list_method: Option<String>,
123        /// Optional sibling method that searches available keys.
124        #[serde(default, skip_serializing_if = "Option::is_none")]
125        search_method: Option<String>,
126        /// NEST-5: the slot's type, for a typed dynamic child.
127        #[serde(default, skip_serializing_if = "Option::is_none")]
128        child: Option<Box<PluginSchema>>,
129    },
130}
131
132impl From<MethodRole> for MethodRoleWire {
133    fn from(r: MethodRole) -> Self {
134        match r {
135            MethodRole::Rpc => MethodRoleWire::Rpc,
136            MethodRole::StaticChild => {
137                MethodRoleWire::StaticChild { peer: false, list_method: None, search_method: None, interface: None }
138            }
139            MethodRole::DynamicChild { list_method, search_method, child } => {
140                MethodRoleWire::DynamicChild { list_method, search_method, child }
141            }
142            MethodRole::Peer { list_method, search_method, interface } => MethodRoleWire::StaticChild {
143                peer: true,
144                list_method,
145                search_method,
146                interface: interface.map(Box::new),
147            },
148        }
149    }
150}
151
152impl From<MethodRoleWire> for MethodRole {
153    fn from(r: MethodRoleWire) -> Self {
154        match r {
155            MethodRoleWire::Rpc => MethodRole::Rpc,
156            MethodRoleWire::StaticChild { peer: true, list_method, search_method, interface } => {
157                MethodRole::Peer { list_method, search_method, interface: interface.map(|i| *i) }
158            }
159            MethodRoleWire::StaticChild { .. } => MethodRole::StaticChild,
160            MethodRoleWire::DynamicChild { list_method, search_method, child } => {
161                MethodRole::DynamicChild { list_method, search_method, child }
162            }
163        }
164    }
165}
166
167impl Serialize for MethodRole {
168    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
169        MethodRoleWire::from(self.clone()).serialize(s)
170    }
171}
172
173impl<'de> Deserialize<'de> for MethodRole {
174    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
175        MethodRoleWire::deserialize(d).map(MethodRole::from)
176    }
177}
178
179impl JsonSchema for MethodRole {
180    fn schema_name() -> std::borrow::Cow<'static, str> {
181        <MethodRoleWire as JsonSchema>::schema_name()
182    }
183
184    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
185        <MethodRoleWire as JsonSchema>::json_schema(generator)
186    }
187}
188
189impl MethodRole {
190    /// NEST-5/NEST-7: whether this role names a slot — a child or a peer
191    /// found by name at call time.
192    pub fn is_slot(&self) -> bool {
193        matches!(self, MethodRole::DynamicChild { .. } | MethodRole::Peer { .. })
194    }
195
196    /// NEST-5: the slot's type as a schema (a typed dynamic child's
197    /// `child`); `None` for an untyped slot or a role that is no slot.
198    pub fn slot_schema(&self) -> Option<PluginSchema> {
199        match self {
200            MethodRole::DynamicChild { child, .. } => child.as_deref().cloned(),
201            MethodRole::Peer { interface, .. } => interface.as_ref().map(|i| i.schema().clone()),
202            _ => None,
203        }
204    }
205
206    /// Whether this role is a child or peer of any kind (not an RPC).
207    pub fn is_child(&self) -> bool {
208        !matches!(self, MethodRole::Rpc)
209    }
210}
211
212/// NEST-5: a schema compares by what it serializes to — so a role carrying
213/// one (`DynamicChild { child }`) keeps `PartialEq`/`Eq`.
214impl PartialEq for PluginSchema {
215    fn eq(&self, other: &Self) -> bool {
216        serde_json::to_value(self).ok() == serde_json::to_value(other).ok()
217    }
218}
219impl Eq for PluginSchema {}
220
221impl Default for MethodRole {
222    fn default() -> Self {
223        MethodRole::Rpc
224    }
225}
226
227// =============================================================================
228// Deprecation Info
229// =============================================================================
230
231/// Structured deprecation metadata attached to a `MethodSchema`.
232///
233/// Downstream consumers (CLI help, docs generators, IDEs) use these fields
234/// to surface migration guidance to users.
235///
236/// # Example
237///
238/// ```
239/// use plexus_core::DeprecationInfo;
240///
241/// let info = DeprecationInfo {
242///     since: "0.5".into(),
243///     removed_in: "0.6".into(),
244///     message: "Use `new_method` instead.".into(),
245/// };
246/// ```
247#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
248pub struct DeprecationInfo {
249    /// The plexus-core version at which deprecation began (e.g., `"0.5"`).
250    pub since: String,
251    /// The plexus-core version planned for removal (e.g., `"0.6"`).
252    ///
253    /// Not binding — serves as a consumer-visible hint.
254    pub removed_in: String,
255    /// Human-readable migration guidance.
256    pub message: String,
257}
258
259// =============================================================================
260// Param Schema
261// =============================================================================
262
263/// Per-parameter metadata for a method's parameters.
264///
265/// `MethodSchema.params` already carries the fine-grained JSON Schema for the
266/// combined parameter object. `ParamSchema` carries orthogonal, parameter-
267/// scoped metadata that doesn't fit on a JSON Schema node — currently just
268/// deprecation info (IR-5).
269///
270/// The `name` field matches the parameter identifier in the method signature
271/// so consumers can correlate entries against the `params` JSON Schema's
272/// `properties` map.
273///
274/// Added in IR-5. Defaults to an empty list on `MethodSchema` so pre-IR
275/// schemas deserialize cleanly.
276#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
277pub struct ParamSchema {
278    /// Parameter name, matching the identifier in the method signature.
279    pub name: String,
280    /// If set, this parameter is deprecated.
281    ///
282    /// Populated by `#[deprecated(...)]` (+ optional
283    /// `#[plexus_macros::removed_in("...")]`) on the parameter in the
284    /// method signature (IR-5).
285    #[serde(default, skip_serializing_if = "Option::is_none")]
286    pub deprecation: Option<DeprecationInfo>,
287}
288
289impl ParamSchema {
290    /// Create a new `ParamSchema` carrying just a name and no metadata.
291    pub fn new(name: impl Into<String>) -> Self {
292        Self {
293            name: name.into(),
294            deprecation: None,
295        }
296    }
297
298    /// Attach deprecation metadata for this parameter.
299    pub fn with_deprecation(mut self, info: DeprecationInfo) -> Self {
300        self.deprecation = Some(info);
301        self
302    }
303}
304
305// =============================================================================
306// Credential projections (AUTHZ-CRED-CORE-3)
307// =============================================================================
308
309/// One entry per credential-bearing field in a method's return type.
310///
311/// Pinned by `AUTHZ-CRED-S01-output.md` §4 and `AUTHZ-CRED-CORE-3` §"Required
312/// behavior". Projected onto `MethodSchema.credentials` at schema-build time
313/// from the `CredentialFieldMarker` registry the `#[derive(Credentials)]` macro
314/// emits per credential-bearing type (`AUTHZ-CRED-MACRO-1`).
315///
316/// # Field path semantics (Tier B Q-IR-1)
317///
318/// `field_path` is the JSON-object path to the credential field within the
319/// method's return type. v1 always uses object-field paths (one segment per
320/// field name walked); array indices and JSON Pointer syntax are intentionally
321/// excluded because credentials always live on object fields in v1, never
322/// inside array elements.
323///
324/// Example: for a return type
325/// `struct LoginResult { session: Credential<String> }`, the field path is
326/// `["session"]`. For a nested case
327/// `struct LoginResult { auth: AuthBundle }` where `AuthBundle` itself
328/// declares a `#[plexus::credential(..)]` field `token: Credential<String>`,
329/// the field path is `["auth", "token"]`.
330///
331/// # Variant tagging
332///
333/// `variant_tag` is `Some(tag)` when the method's return type is an enum and
334/// the credential lives on a single variant. The tag matches the variant
335/// identifier as the macro registry records it (e.g. `"Issued"` for the
336/// `LoginEvent::Issued` variant). `None` means the return type is a struct,
337/// or the credential appears on every variant of the enum (rare).
338///
339/// # Wire back-compat
340///
341/// Added in `AUTHZ-CRED-CORE-3`. Pre-existing readers tolerate `credentials:
342/// []` (the default on `MethodSchema` when no credentials are declared) and
343/// pre-existing IRs that omit the field altogether decode cleanly via
344/// `#[serde(default)]` on the field site.
345#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
346pub struct CredentialFieldDecl {
347    /// JSON-object path to the credential field within the method's return
348    /// type. One segment per field-name walk; pinned to object paths (no
349    /// array indices, no JSON Pointer) per Tier B Q-IR-1.
350    pub field_path: Vec<String>,
351
352    /// Variant tag when the return type is an enum and the credential lives
353    /// on a single variant. `None` for structs.
354    #[serde(default, skip_serializing_if = "Option::is_none")]
355    pub variant_tag: Option<String>,
356
357    /// The credential's metadata (kind, attach site, scheme, scopes, expiry,
358    /// refresh/revoke hints, issuer, sensitivity). Carried verbatim so
359    /// consumers embed identical storage-and-attach logic to the runtime.
360    pub metadata: CredentialMetadata,
361}
362
363impl CredentialFieldDecl {
364    /// Construct a `CredentialFieldDecl` by composing a `CredentialFieldMarker`
365    /// from the macro-emitted registry with the runtime-supplied pieces
366    /// (`expires_at` known only at mint time; `issuer` known at schema-build
367    /// time from the originating method's `(Origin, MethodPath)`).
368    ///
369    /// `path_prefix` is the field-path walk to the marker's parent type — for
370    /// a flat struct it is empty; for a nested case where this marker lives
371    /// inside a field of the method's return type the prefix is the path to
372    /// that wrapping field. The marker's own `field` and `variant` are
373    /// appended.
374    pub fn from_marker(
375        marker: &CredentialFieldMarker,
376        path_prefix: &[&str],
377        issuer: CredentialIssuer,
378    ) -> Self {
379        let mut field_path: Vec<String> = path_prefix.iter().map(|s| (*s).to_owned()).collect();
380        field_path.push(marker.field.to_owned());
381        let variant_tag = marker.variant.map(|v| v.to_owned());
382        let metadata = marker.to_metadata(None, issuer);
383        Self {
384            field_path,
385            variant_tag,
386            metadata,
387        }
388    }
389}
390
391/// What a method requires on input — the implicit-derivation projection of
392/// scope tagging and credential-graph linkage onto a per-method filter.
393///
394/// Pinned by `AUTHZ-CRED-S01-output.md` §4 (Q-SELECT-1 resolution: implicit
395/// derivation from scope tagging plus refresh/revoke linkage) and
396/// `AUTHZ-CRED-CORE-3` §"Implicit derivation". This ticket explicitly does
397/// NOT add a `#[plexus::method(requires_credential = { .. })]` attribute
398/// surface — the proposal from `AUTHZ-CRED-S01-output` §10 is superseded by
399/// the implicit-derivation approach pinned here.
400///
401/// # Matching semantics (consumer-side)
402///
403/// A candidate credential matches this `RequiredCredential` iff:
404/// 1. `kind`: if `Some(k)`, the candidate's `CredentialMetadata.kind`
405///    matches `k` (or the kind-subsumption table per `AUTHZ-CRED-CORE-1`
406///    accepts the substitution; e.g. `OauthAccess <: Bearer`). If `None`,
407///    any kind whose scope set matches is acceptable.
408/// 2. `scopes`: each scope in this set must be wildcard-matched by the
409///    candidate's `CredentialMetadata.scopes`. The wildcard rules belong to
410///    the `Scope` type itself.
411/// 3. `site_hint`: when populated, prefers the candidate whose
412///    `CredentialMetadata.attach_as` equals the hint. Advisory only — a
413///    candidate without the hint is not rejected.
414///
415/// # Wire back-compat
416///
417/// Added in `AUTHZ-CRED-CORE-3`. Pre-existing readers tolerate
418/// `requires_credential: null` (omitted on the wire when `None`) and
419/// pre-existing IRs that omit the field altogether decode cleanly via
420/// `#[serde(default)]` on the field site.
421#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
422pub struct RequiredCredential {
423    /// Specific kind a candidate credential must have (e.g.,
424    /// `OauthRefresh`), or `None` for "any kind whose scope set matches".
425    #[serde(default, skip_serializing_if = "Option::is_none")]
426    pub kind: Option<CredentialKind>,
427
428    /// Required scope set. A candidate credential's metadata scopes must
429    /// wildcard-match each scope in this set.
430    #[serde(default, skip_serializing_if = "Vec::is_empty")]
431    pub scopes: Vec<Scope>,
432
433    /// Preferred attach site for the client to use when the candidate
434    /// credential has multiple alternates. Advisory only.
435    #[serde(default, skip_serializing_if = "Option::is_none")]
436    pub site_hint: Option<AttachmentSite>,
437}
438
439impl RequiredCredential {
440    /// Derive a `RequiredCredential` from a method's required scope tagging
441    /// (per `AUTHZ-S01-output` §4). The `kind` field is left `None` — any
442    /// kind whose scope set wildcard-matches `scope` is acceptable.
443    ///
444    /// Used when a method declares `#[plexus::method(scope = "...")]` (or
445    /// the framework derives an implicit scope from the method's path).
446    pub fn from_method_scope(scope: Scope) -> Self {
447        Self {
448            kind: None,
449            scopes: vec![scope],
450            site_hint: None,
451        }
452    }
453
454    /// Multi-scope variant of [`Self::from_method_scope`] for methods that
455    /// declare `scope = "..."` more than once (AUTHZ-CORE-2: the caller must
456    /// satisfy ALL listed scopes — conjunction, not alternation). The `kind`
457    /// field is left `None` — any kind whose scope set wildcard-matches every
458    /// listed scope is acceptable.
459    ///
460    /// Added in R-2 (`ir-credential-emission`) alongside the macro-side
461    /// population (R-1).
462    pub fn from_method_scopes(scopes: Vec<Scope>) -> Self {
463        Self {
464            kind: None,
465            scopes,
466            site_hint: None,
467        }
468    }
469
470    /// Derive a `RequiredCredential` for a method that appears as the target
471    /// of another credential's `metadata.refresh_via` or `metadata.revoke_via`
472    /// (per `AUTHZ-CRED-CORE-3` §"Implicit derivation" row 3). The `kind`
473    /// field narrows to the issuing credential's kind so the selection step
474    /// picks the right kind (e.g., `OauthRefresh` for the
475    /// `auth.refresh` call on an `OauthAccess` credential per the OAuth
476    /// flow described in `AUTHZ-CRED-S01-output` §7.2).
477    pub fn from_refresh_revoke_target(kind: CredentialKind, scopes: Vec<Scope>) -> Self {
478        Self {
479            kind: Some(kind),
480            scopes,
481            site_hint: None,
482        }
483    }
484
485    /// CA-1 (trak facet `ccc924ad-0e78-4d4b-b71f-0018d249d0bf`): fill
486    /// `site_hint` with the hub-derived attach site — but only when no hint
487    /// is already present. An explicitly-populated hint (e.g. a future
488    /// per-method override, or a refresh/revoke derivation that learned the
489    /// site from the issuing credential) always wins over the
490    /// capability-derived default.
491    pub fn fill_site_hint(&mut self, site: &AttachmentSite) {
492        if self.site_hint.is_none() {
493            self.site_hint = Some(site.clone());
494        }
495    }
496}
497
498// =============================================================================
499// Auth Posture
500// =============================================================================
501
502/// Declared auth-enforcement posture of the activation a method belongs to.
503///
504/// Mirrors `plexus-macros`' RED-6 `auth = "required" | "optional" | "mixed" |
505/// "none"` activation attribute, which until R-1/R-2 (the ROLES+AP merged
506/// wave) was parsed and compile-enforced but never emitted — invisible to
507/// every downstream IR consumer (synapse, hub-codegen, generated clients).
508///
509/// Semantics (compile-time enforcement lives in plexus-macros; this is the
510/// escaped declaration):
511///
512/// - `Required` — every method is auth-gated (`#[from_auth]`) or explicitly
513///   `public`.
514/// - `Optional` — no enforcement; auth may be asymmetric across methods.
515/// - `Mixed` — like `Optional`, but the asymmetry is explicitly acknowledged.
516/// - `None` — affirmatively public activation; no method takes auth.
517///
518/// # Wire back-compat
519///
520/// Added in R-2 (joint AP-1). Pre-existing readers tolerate the field's
521/// absence (`auth_posture` is omitted on the wire when the activation never
522/// declared a posture) and pre-existing IRs that omit the field decode
523/// cleanly via `#[serde(default)]` on the field site. `#[non_exhaustive]`
524/// reserves space for future postures without breaking downstream match arms.
525#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
526#[serde(rename_all = "snake_case")]
527#[non_exhaustive]
528pub enum AuthPosture {
529    /// Every method is auth-gated or explicitly public.
530    Required,
531    /// No enforcement; auth may be asymmetric across methods.
532    Optional,
533    /// Asymmetric auth, explicitly acknowledged.
534    Mixed,
535    /// Affirmatively public activation; no method takes auth.
536    None,
537}
538
539// =============================================================================
540// Cardinality
541// =============================================================================
542
543/// How many items a method yields: exactly one, or a stream of them.
544///
545/// Read from the method's signature (RETURNS-1 decision 2): a plain return
546/// type (`-> T`, `-> Result<T, E>`) is [`Cardinality::One`]; `-> impl
547/// Stream<Item = …>` is [`Cardinality::Many`]. A reader decides how to present
548/// a method (a single awaited value vs. a stream) from this field alone —
549/// never from the presence of a stream type or a guess at the item's shape.
550///
551/// Serialized as `"one"` / `"many"`.
552#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
553#[serde(rename_all = "snake_case")]
554pub enum Cardinality {
555    /// The method yields exactly one item.
556    One,
557    /// The method yields a stream of zero or more items.
558    Many,
559}
560
561// =============================================================================
562// HTTP Method Enum
563// =============================================================================
564
565/// HTTP method for REST endpoint routing
566#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
567#[serde(rename_all = "UPPERCASE")]
568pub enum HttpMethod {
569    /// GET: Idempotent read operations with no side effects
570    Get,
571    /// POST: Create operations or non-idempotent actions (default)
572    Post,
573    /// PUT: Replace/update operations (idempotent)
574    Put,
575    /// DELETE: Remove operations (idempotent)
576    Delete,
577    /// PATCH: Partial update operations
578    Patch,
579}
580
581impl Default for HttpMethod {
582    fn default() -> Self {
583        HttpMethod::Post
584    }
585}
586
587impl HttpMethod {
588    /// Parse from string (case-insensitive)
589    pub fn from_str(s: &str) -> Option<Self> {
590        match s.to_uppercase().as_str() {
591            "GET" => Some(HttpMethod::Get),
592            "POST" => Some(HttpMethod::Post),
593            "PUT" => Some(HttpMethod::Put),
594            "DELETE" => Some(HttpMethod::Delete),
595            "PATCH" => Some(HttpMethod::Patch),
596            _ => None,
597        }
598    }
599
600    /// Convert to uppercase string
601    pub fn as_str(&self) -> &'static str {
602        match self {
603            HttpMethod::Get => "GET",
604            HttpMethod::Post => "POST",
605            HttpMethod::Put => "PUT",
606            HttpMethod::Delete => "DELETE",
607            HttpMethod::Patch => "PATCH",
608        }
609    }
610}
611
612// ============================================================================
613// Plugin Schema
614// ============================================================================
615
616/// A plugin's schema with methods and child summaries.
617///
618/// Children are represented as summaries (namespace, description, hash) rather
619/// than full recursive schemas. This enables lazy traversal - clients can fetch
620/// child schemas individually via `{namespace}.schema`.
621///
622/// - Leaf plugins have `children = None`
623/// - Hub plugins have `children = Some([ChildSummary, ...])`
624#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
625pub struct PluginSchema {
626    /// The plugin's namespace (e.g., "echo", "plexus")
627    pub namespace: String,
628
629    /// The plugin's version (e.g., "1.0.0")
630    pub version: String,
631
632    /// Short description of the plugin (max 15 words)
633    pub description: String,
634
635    /// Detailed description of the plugin (optional)
636    #[serde(skip_serializing_if = "Option::is_none")]
637    pub long_description: Option<String>,
638
639    /// Hash of ONLY this plugin's methods (ignores children): of each
640    /// method's `hash`, so it changes whenever any method's schema changes
641    pub self_hash: String,
642
643    /// Hash of ONLY child plugin hashes (None for leaf plugins)
644    /// Changes when any child's hash changes (recursively)
645    #[serde(skip_serializing_if = "Option::is_none")]
646    pub children_hash: Option<String>,
647
648    /// Composite hash = hash(self_hash + children_hash)
649    /// Use this if you want a single hash for the entire subtree
650    pub hash: String,
651
652    /// Methods exposed by this plugin
653    pub methods: Vec<MethodSchema>,
654
655    /// Child plugin summaries (None = leaf plugin, Some = hub plugin)
656    ///
657    /// # Deprecated (IR-4)
658    ///
659    /// This side-table is deterministically derived from the method list's
660    /// `MethodRole` tags (one `ChildSummary` per non-`Rpc` method). It stays
661    /// on the wire for back-compat during the 0.5 transition window and is
662    /// slated for removal in 0.6.
663    ///
664    /// Consumers reading child metadata should switch to iterating
665    /// `methods` and filtering by `role != MethodRole::Rpc`. The name field
666    /// on each `MethodSchema` is the child's namespace.
667    #[serde(skip_serializing_if = "Option::is_none")]
668    #[deprecated(
669        since = "0.5",
670        note = "Derive from MethodRole on MethodSchema. Field will be removed in 0.7."
671    )]
672    pub children: Option<Vec<ChildSummary>>,
673
674    /// JSON Schema for the HTTP request type this activation extracts from incoming connections.
675    ///
676    /// Present when the activation declares `request = MyRequest` in `#[plexus::activation(...)]`.
677    /// The schema includes `x-plexus-source` extension fields on each property describing
678    /// where each field is sourced from (cookie, header, query param, peer address, etc.).
679    ///
680    /// Clients can use this to understand what request data the activation expects and
681    /// to generate appropriate authentication/context documentation.
682    #[serde(skip_serializing_if = "Option::is_none")]
683    pub request: Option<serde_json::Value>,
684
685    /// If set, this whole activation is deprecated.
686    ///
687    /// Added in IR-5. Defaults to `None` via `#[serde(default)]` so pre-IR
688    /// schemas deserialize cleanly.
689    ///
690    /// Populated by the `#[deprecated(...)]` attribute on the `impl
691    /// Activation for Foo` block (IR-5).
692    #[serde(default, skip_serializing_if = "Option::is_none")]
693    pub deprecation: Option<DeprecationInfo>,
694
695    /// AUTH-3: this activation's default roles — role name → the grants it
696    /// lists (`<activation>.<method>`, role inclusion already flattened), as
697    /// declared by `#[plexus_macros::activation(roles(...))]`. `admin` is
698    /// built in and never listed. Empty (and absent on the wire) when the
699    /// activation declares none.
700    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
701    pub roles: std::collections::BTreeMap<String, Vec<String>>,
702
703    /// AUTH-4: which view of a gated hub this schema answers from —
704    /// `anonymous` (only the door: the public methods) or `caller` (the
705    /// methods the caller holds). Absent from every schema a hub without a
706    /// gate answers, so those stay byte-identical.
707    #[serde(default, skip_serializing_if = "Option::is_none")]
708    pub view: Option<ViewKind>,
709
710    /// NEST-16: what this activation calls of the service it is grafted
711    /// onto — each method by its path from that service's root and the
712    /// shape hash it was built against (`#[activation(parent = ShopClient)]`,
713    /// inferred from the bodies). `None` (absent on the wire, so every older
714    /// schema reads): the activation declares nothing — it may call its
715    /// service's standard upward interface alone (`host.schema`,
716    /// `host.whoami`, `host.log`, `host.notify`). `Some([])`: it knows its
717    /// parent and calls none of its methods.
718    ///
719    /// Not in `PluginSchema`'s own JSON Schema (`schemars(skip)`): that
720    /// schema is every activation's `schema` method's `returns`, and a new
721    /// property there would move every service's hash for a field few
722    /// schemas carry. A client reads it as an extra key.
723    #[serde(default, skip_serializing_if = "Option::is_none")]
724    #[schemars(skip)]
725    pub needs: Option<Vec<Need>>,
726}
727
728/// NEST-16: one method an activation calls of the service it is grafted
729/// onto (its parent): a graft is refused where `method` is missing, or its
730/// shape moved from `hash`.
731#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema)]
732pub struct Need {
733    /// The method's dotted path from the parent's root: `shop.items`,
734    /// `shop.ui.slots.list`.
735    pub method: String,
736    /// The method's shape hash ([`super::peer::Interface::method_hash`]) as
737    /// the child was built against it; empty when it could not be known at
738    /// build (an entry named by hand in `uses(…)`): then only its presence
739    /// is checked.
740    #[serde(default, skip_serializing_if = "String::is_empty")]
741    pub hash: String,
742}
743
744impl Need {
745    /// A need for `method`, its shape `hash` (empty: presence only).
746    pub fn new(method: impl Into<String>, hash: impl Into<String>) -> Self {
747        Self { method: method.into(), hash: hash.into() }
748    }
749}
750
751/// AUTH-4: the two views of a gated hub. On the wire, `"anonymous"` or
752/// `"caller"`.
753#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
754#[serde(rename_all = "snake_case")]
755pub enum ViewKind {
756    /// Not signed in: only how to sign in (the public methods).
757    Anonymous,
758    /// Signed in: the methods whose grant some held role lists.
759    Caller,
760}
761
762impl ViewKind {
763    /// `"anonymous"` / `"caller"`.
764    pub fn as_str(&self) -> &'static str {
765        match self {
766            Self::Anonymous => "anonymous",
767            Self::Caller => "caller",
768        }
769    }
770}
771
772/// Result of a schema query - either full plugin or single method
773#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
774#[serde(untagged)]
775pub enum SchemaResult {
776    /// Full plugin schema (when no method specified)
777    Plugin(PluginSchema),
778    /// Single method schema (when method specified)
779    Method(MethodSchema),
780}
781
782/// Schema for a single method exposed by a plugin
783#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
784pub struct MethodSchema {
785    /// Method name (e.g., "echo", "check")
786    pub name: String,
787
788    /// Human-readable description of what this method does
789    pub description: String,
790
791    /// Content hash of this method's schema (for cache invalidation): 16
792    /// lowercase hex, SHA-256 of every other field as canonical JSON, so it
793    /// changes whenever anything a client is generated from changes
794    pub hash: String,
795
796    /// JSON Schema for the method's parameters (None if no params)
797    #[serde(skip_serializing_if = "Option::is_none")]
798    #[schemars(with = "Option<serde_json::Value>")] // a JSON Schema document: the JSON type
799    pub params: Option<schemars::Schema>,
800
801    /// JSON Schema for the method's item type `T` — what one success carries.
802    ///
803    /// Always present: every method has a return type. For a `Result<T, E>`
804    /// or `Progress<T, P>` item it is `T` alone — `E` and `P` have fields of
805    /// their own. [`MethodSchema::new`] starts it at the empty schema `{}`
806    /// (any value) until [`MethodSchema::with_returns`] sets it.
807    #[schemars(with = "serde_json::Value")] // a JSON Schema document: the JSON type
808    pub returns: schemars::Schema,
809
810    /// JSON Schema for the method's error type `E` — what the activation says
811    /// when it says no (`-> Result<T, E>`). Absent from the wire when the
812    /// method is infallible.
813    #[serde(default, skip_serializing_if = "Option::is_none")]
814    #[schemars(with = "Option<serde_json::Value>")] // a JSON Schema document: the JSON type
815    pub error: Option<schemars::Schema>,
816
817    /// JSON Schema for the method's progress type `P` (an item of
818    /// `Progress<T, P>`), carried by progress frames. Absent from the wire
819    /// when the method reports no progress.
820    #[serde(default, skip_serializing_if = "Option::is_none")]
821    #[schemars(with = "Option<serde_json::Value>")] // a JSON Schema document: the JSON type
822    pub progress: Option<schemars::Schema>,
823
824    /// Whether the method yields one item or many — `"one"` / `"many"`.
825    ///
826    /// Required on the wire: a schema that does not state its cardinality is
827    /// not a 0.7 schema, and guessing would reintroduce the disagreement this
828    /// field exists to end.
829    pub cardinality: Cardinality,
830
831    // ASK-1: an older schema's `bidirectional`, `request_type` and
832    // `response_type` (the in-call question, removed) are read and ignored.
833
834    /// HTTP method for REST endpoints (GET, POST, PUT, DELETE, PATCH)
835    ///
836    /// This field is used by the HTTP gateway to determine which HTTP method
837    /// to use when exposing this method as a REST endpoint. Defaults to POST
838    /// for backward compatibility.
839    ///
840    /// - GET: Idempotent read operations (no side effects)
841    /// - POST: Create operations or non-idempotent actions (default)
842    /// - PUT: Replace/update operations (idempotent)
843    /// - DELETE: Remove operations (idempotent)
844    /// - PATCH: Partial update operations
845    #[serde(default)]
846    pub http_method: HttpMethod,
847
848    /// How this method participates in the activation graph.
849    ///
850    /// Added in IR-2. Defaults to `MethodRole::Rpc` via `#[serde(default)]`
851    /// so pre-IR schemas deserialize cleanly.
852    ///
853    /// Populated by the `#[plexus::method]` / `#[child]` macros (IR-3).
854    #[serde(default)]
855    pub role: MethodRole,
856
857    /// If set, this method is deprecated.
858    ///
859    /// Added in IR-2. Defaults to `None` via `#[serde(default)]` so pre-IR
860    /// schemas deserialize cleanly.
861    ///
862    /// Populated by the `#[deprecated(...)]` attribute on the underlying
863    /// method (IR-5).
864    #[serde(default, skip_serializing_if = "Option::is_none")]
865    pub deprecation: Option<DeprecationInfo>,
866
867    /// Per-parameter metadata (currently just deprecation).
868    ///
869    /// Added in IR-5. Defaults to an empty vec via `#[serde(default)]` so
870    /// pre-IR schemas deserialize cleanly. Only parameters that carry
871    /// metadata appear in this list — absence means "no metadata" for that
872    /// parameter, not a bug.
873    ///
874    /// Populated by the `#[deprecated(...)]` attribute on individual
875    /// parameters (IR-5).
876    #[serde(default, skip_serializing_if = "Vec::is_empty")]
877    pub params_meta: Vec<ParamSchema>,
878
879    /// Credential-bearing fields in this method's return type.
880    ///
881    /// One entry per `#[plexus::credential(...)]`-annotated field on the
882    /// return-type struct/enum, in stable declaration order. Empty when
883    /// the return type contains no credentials.
884    ///
885    /// Added in `AUTHZ-CRED-CORE-3`. Defaults to an empty vec via
886    /// `#[serde(default)]` so pre-IR schemas deserialize cleanly. The
887    /// `skip_serializing_if = "Vec::is_empty"` clause keeps the wire JSON
888    /// shape unchanged for methods with no credential-bearing fields
889    /// (back-compat per the ticket's "Wire-format back-compat" table).
890    ///
891    /// Populated at schema-build time from the `CredentialFieldMarker`
892    /// registry emitted by `#[derive(Credentials)]` (`AUTHZ-CRED-MACRO-1`).
893    #[serde(default, skip_serializing_if = "Vec::is_empty")]
894    pub credentials: Vec<CredentialFieldDecl>,
895
896    /// What credential this method requires on input (if any).
897    ///
898    /// Derived implicitly from the method's scope tagging and the
899    /// credential-graph linkage at schema-build time (per
900    /// `AUTHZ-CRED-CORE-3` §"Implicit derivation"):
901    ///
902    /// - `scope = "..."` → `RequiredCredential::from_method_scope(scope)`.
903    /// - `public` method → `None` (the absence of this field).
904    /// - target of `refresh_via`/`revoke_via` of another credential →
905    ///   `RequiredCredential::from_refresh_revoke_target(kind, scopes)`.
906    ///
907    /// Added in `AUTHZ-CRED-CORE-3`. Defaults to `None` via
908    /// `#[serde(default)]` so pre-IR schemas deserialize cleanly. The
909    /// `skip_serializing_if = "Option::is_none"` clause keeps the wire JSON
910    /// shape unchanged for public methods and methods with no scope-derived
911    /// requirement.
912    #[serde(default, skip_serializing_if = "Option::is_none")]
913    pub requires_credential: Option<RequiredCredential>,
914
915    /// Declared auth posture of the activation this method belongs to.
916    ///
917    /// Populated by `#[plexus_macros::activation(auth = "...")]` (R-1) —
918    /// stamped onto every RPC method of the activation. `None` means the
919    /// activation never declared a posture (pre-R-1 emissions and
920    /// posture-silent activations are byte-identical on the wire).
921    ///
922    /// Added in R-2 (joint AP-1). Defaults to `None` via `#[serde(default)]`
923    /// so pre-R IRs decode cleanly; `skip_serializing_if` keeps the wire
924    /// shape unchanged when unset.
925    #[serde(default, skip_serializing_if = "Option::is_none")]
926    pub auth_posture: Option<AuthPosture>,
927
928    /// Whether this method is explicitly public — exempt from the
929    /// default-deny gate (AUTHZ-CORE-2's `#[plexus::method(public)]`).
930    ///
931    /// `public` and a populated `requires_credential` are mutually exclusive
932    /// by construction: the macro rejects `public` + `scope = "..."` at
933    /// compile time.
934    ///
935    /// Added in R-2. Defaults to `false` via `#[serde(default)]` so pre-R
936    /// IRs decode cleanly; `skip_serializing_if` keeps the wire shape
937    /// unchanged for non-public methods (i.e., every pre-R method).
938    #[serde(default, skip_serializing_if = "is_false")]
939    pub public: bool,
940
941    /// AUTH-3: the grant this method is — `<activation>.<method>`, inherent
942    /// (AUTH-1: "every method should be its own grant"). The macro emits it
943    /// for every method; `None` only on a hand-built or pre-AUTH schema, and
944    /// a gate then takes the method's dotted path.
945    ///
946    /// Optional on the wire (`serde(default)`, skipped when unset) so older
947    /// schemas and clients parse unchanged.
948    #[serde(default, skip_serializing_if = "Option::is_none")]
949    pub grant: Option<String>,
950
951    /// AUTH-3: the param that locates what this call acts on
952    /// (`#[plexus_macros::method(target = "id")]`). A gate resolves its
953    /// value to the scopes it lives in and asks for the grant there; a
954    /// method without one is allowed where the grant is held anywhere and
955    /// answers only from there.
956    #[serde(default, skip_serializing_if = "Option::is_none")]
957    pub target: Option<String>,
958
959    /// KEEL-31: the method acts on the whole service
960    /// (`#[plexus_macros::method(everywhere)]`): it names no target because
961    /// its target is everything — a key rotated, a process spawned, a peer
962    /// connected. A gate admits it only where its grant is held on `*`,
963    /// within every ceiling layer; a role held on some scope is not enough.
964    /// Never with `public` or `target`.
965    ///
966    /// Optional on the wire (`serde(default)`, skipped when false) so a
967    /// method without it, and every older schema and client, is unchanged.
968    #[serde(default, skip_serializing_if = "is_false")]
969    pub everywhere: bool,
970
971    /// AUTH-3: the method's `///` doc comment, when it says more than
972    /// `description` (the macro used to drop it whenever `description =
973    /// "..."` was given).
974    #[serde(default, skip_serializing_if = "Option::is_none")]
975    pub long_description: Option<String>,
976
977    /// AUTH-4: in a caller's view of a gated hub, where the caller holds this
978    /// method's grant (`["MENGER"]`, `["*"]`), within its session's ceiling.
979    /// Absent outside a caller's view (and on a public method the caller
980    /// holds nowhere).
981    #[serde(default, skip_serializing_if = "Option::is_none")]
982    pub held_on: Option<Vec<String>>,
983
984    /// SYNAPSE-13: the method's group in a listing (`"read"`, `"write"`, …)
985    /// — one group, like an OpenAPI operation's first tag. Clients list the
986    /// methods of a group together and alphabetically within it.
987    ///
988    /// Optional on the wire (`serde(default)`, skipped when unset) so older
989    /// schemas and clients parse unchanged.
990    #[serde(default, skip_serializing_if = "Option::is_none")]
991    pub group: Option<String>,
992
993    /// BIDIR-8: who may answer a question this method asks mid-call
994    /// (`#[method(answer_by = "person" | "grant:<g>")]`; BIDIR-1
995    /// `answerer`). Absent for the default, `caller` — the call's own
996    /// connection — so a method without the attribute is byte-identical.
997    #[serde(default, skip_serializing_if = "Option::is_none")]
998    pub answer_by: Option<String>,
999
1000    /// SYNAPSE-13: worked calls of this method, each its params object and a
1001    /// note saying what it does — OpenAPI's `examples`. A client renders them
1002    /// as command lines (`synapse … --id MENGER-40 --status Coding`).
1003    ///
1004    /// Optional on the wire (`serde(default)`, skipped when empty).
1005    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1006    pub examples: Vec<MethodExample>,
1007
1008    // BIDIR-6 fills this now. The doc comment below is left as it stands: it
1009    // is this field's description in `{ns}.schema`'s own `returns`, so a word
1010    // of it moves every service's hash, and with it the metadata of every item.
1011    /// SYNAPSE-CC-9: reserved for BIDIR-6 — the JSON Schema of the items a
1012    /// client streams *in* to this method (`Input<T>`). Always `None` until
1013    /// BIDIR-6 fills it; absent from the wire while `None`, so a schema
1014    /// without it is byte-identical to 0.6.1's.
1015    #[serde(default, skip_serializing_if = "Option::is_none")]
1016    #[schemars(with = "Option<serde_json::Value>")] // a JSON Schema document: the JSON type
1017    pub input: Option<schemars::Schema>,
1018}
1019
1020/// SYNAPSE-13: one worked call of a method — the params it sends and a note
1021/// saying what it does (`#[plexus_macros::method(example(note = "…", params
1022/// = r#"{…}"#))]`).
1023#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1024pub struct MethodExample {
1025    /// The params object, as the method takes it.
1026    pub params: serde_json::Value,
1027    /// What the call does, in a line.
1028    #[serde(default, skip_serializing_if = "Option::is_none")]
1029    pub note: Option<String>,
1030}
1031
1032impl MethodExample {
1033    /// An example of these params, with no note.
1034    pub fn new(params: serde_json::Value) -> Self {
1035        Self { params, note: None }
1036    }
1037
1038    /// An example of these params, with a note.
1039    pub fn with_note(params: serde_json::Value, note: impl Into<String>) -> Self {
1040        Self { params, note: Some(note.into()) }
1041    }
1042}
1043
1044/// SYNAPSE-13: the JSON Schema extension key on a param's property that lists
1045/// the values it is meant to take — a hint for help and completion, never
1046/// enforced (the server may accept synonyms, e.g. `active` for `Coding`).
1047pub const X_PLEXUS_VALUES: &str = "x-plexus-values";
1048
1049/// SYNAPSE-CC-9: the JSON type — what a `serde_json::Value` is, the JSON sum
1050/// type — as plexus spells it in a schema: `{"type": [these six]}`, in this
1051/// order, inline (never a `$ref`), annotations beside it. schemars writes a
1052/// `Value` as `true` (or annotations alone); [`spell_json_values`] rewrites
1053/// each such position to this, and every `MethodSchema` schema setter applies
1054/// it, so the schema says "any JSON value" one way, which a client reads as a
1055/// type (SYNAPSE-CC-8's `RefJson`). The owner, 2026-10-29: nothing is opaque.
1056pub const JSON_TYPES: [&str; 6] = ["null", "boolean", "number", "string", "array", "object"];
1057
1058/// SYNAPSE-CC-9: the closed list of keywords synapse reads in a type position
1059/// (IR 2.1). Any other is reported by [`foreign_keywords`].
1060pub const CONTRACT_KEYWORDS: &[&str] = &[
1061    "type", "$ref", "properties", "required", "additionalProperties", "items", "prefixItems",
1062    "oneOf", "anyOf", "enum", "const", "format", "minimum", "maximum", "exclusiveMinimum",
1063    "exclusiveMaximum", "minLength", "maxLength", "pattern", "minItems", "maxItems", "default",
1064    "description", "title", "examples", "deprecated", "$schema", "$defs", "definitions",
1065    "x-plexus-source", "x-plexus-values",
1066];
1067
1068/// The keywords that only annotate (or hold definitions): a schema of these
1069/// alone accepts any JSON value.
1070const ANNOTATIONS: &[&str] = &[
1071    "description", "title", "default", "examples", "deprecated", "$schema", "$comment", "readOnly",
1072    "writeOnly", "x-plexus-values", "$defs", "definitions",
1073];
1074
1075/// SYNAPSE-CC-9: is this schema node "any JSON value" — `true`, `{}`,
1076/// annotations alone, or the spelled JSON type? An injected parameter
1077/// (`x-plexus-source`) is not a value a client sends, so never.
1078pub fn is_json_type(v: &serde_json::Value) -> bool {
1079    match v {
1080        serde_json::Value::Bool(true) => true,
1081        serde_json::Value::Object(o) => is_json_type_object(o),
1082        _ => false,
1083    }
1084}
1085
1086fn is_json_type_object(o: &serde_json::Map<String, serde_json::Value>) -> bool {
1087    if o.contains_key("x-plexus-source") {
1088        return false;
1089    }
1090    let spelled = match o.get("type") {
1091        None => true,
1092        Some(serde_json::Value::Array(ts)) => {
1093            let set: std::collections::BTreeSet<&str> = ts.iter().filter_map(|t| t.as_str()).collect();
1094            ts.len() == JSON_TYPES.len() && JSON_TYPES.iter().all(|t| set.contains(t))
1095        }
1096        Some(_) => false,
1097    };
1098    spelled && o.keys().all(|k| k == "type" || ANNOTATIONS.contains(&k.as_str()))
1099}
1100
1101/// SYNAPSE-CC-9: rewrite every "any JSON value" position in `schema` —
1102/// `true`, `{}`, annotations alone — to the JSON type
1103/// (`{"type": JSON_TYPES}`, annotations kept), through `properties`,
1104/// `items`, `prefixItems`, `additionalProperties`, the unions and `$defs`.
1105/// Idempotent; a typed node and an injected parameter are left as they are.
1106/// In place: a schemars `Schema` is a JSON value, so nothing is copied.
1107pub fn spell_json_values(schema: &mut schemars::Schema) {
1108    if schema.as_bool() == Some(false) {
1109        return; // accepts nothing: no value position
1110    }
1111    spell_object(schema.ensure_object()); // `true` becomes `{}`, then the JSON type
1112}
1113
1114fn spell(v: &mut serde_json::Value) {
1115    if matches!(v, serde_json::Value::Bool(true)) {
1116        *v = serde_json::Value::Object(serde_json::Map::new());
1117    }
1118    if let serde_json::Value::Object(o) = v {
1119        spell_object(o);
1120    }
1121}
1122
1123fn spell_object(o: &mut serde_json::Map<String, serde_json::Value>) {
1124    use serde_json::Value;
1125    let any = is_json_type_object(o);
1126    for key in ["$defs", "definitions"] {
1127        if let Some(Value::Object(m)) = o.get_mut(key) {
1128            m.values_mut().for_each(spell);
1129        }
1130    }
1131    if any {
1132        o.insert("type".into(), Value::Array(JSON_TYPES.iter().map(|t| Value::String((*t).into())).collect()));
1133        return;
1134    }
1135    if let Some(Value::Object(m)) = o.get_mut("properties") {
1136        m.values_mut().for_each(spell);
1137    }
1138    for key in ["items", "additionalProperties"] {
1139        if let Some(x) = o.get_mut(key) {
1140            if !matches!(x, Value::Bool(false)) {
1141                spell(x);
1142            }
1143        }
1144    }
1145    for key in ["prefixItems", "oneOf", "anyOf", "allOf"] {
1146        if let Some(Value::Array(xs)) = o.get_mut(key) {
1147            xs.iter_mut().for_each(spell);
1148        }
1149    }
1150}
1151
1152/// SYNAPSE-CC-9: the params of every activation's `schema` method.
1153#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
1154pub struct SchemaParams {
1155    /// One method's schema instead of the whole activation's.
1156    #[serde(default, skip_serializing_if = "Option::is_none")]
1157    pub method: Option<String>,
1158}
1159
1160impl SchemaParams {
1161    /// The params object as a method's `params` carries it: the struct's
1162    /// schema without the document-level `$schema`, `title` and
1163    /// `description` (a params object carries none; its properties do).
1164    pub fn params_schema() -> schemars::Schema {
1165        let mut s = schema_for!(SchemaParams);
1166        if let Some(o) = s.as_object_mut() {
1167            o.remove("$schema");
1168            o.remove("title");
1169            o.remove("description");
1170        }
1171        s
1172    }
1173}
1174
1175pub use super::schema_sites::{foreign_keywords, schema_untyped_sites, untyped_sites};
1176
1177/// `skip_serializing_if` helper: omit `false` booleans from the wire so
1178/// additive flags keep pre-existing JSON byte-identical (see
1179/// `MethodSchema::public`).
1180fn is_false(v: &bool) -> bool {
1181    !*v
1182}
1183
1184impl PluginSchema {
1185    /// NEST-16: what this activation calls of its parent ([`Need`]).
1186    pub fn with_needs(mut self, needs: Vec<Need>) -> Self {
1187        self.needs = Some(needs);
1188        self
1189    }
1190
1191    /// Compute all three hashes (self, children, composite).
1192    ///
1193    /// RETURNS-10: SHA-256, 16 lowercase hex, each the
1194    /// [`hash16_lines`] of its inputs in order — one per line, so another
1195    /// language recomputes them from the JSON a server sends:
1196    ///
1197    /// - `self_hash` = `hash16_lines(methods[*].hash)`
1198    /// - `children_hash` = `hash16_lines(children[*].hash)`, `None` for a leaf
1199    /// - `hash` = `hash16_lines([self_hash, children_hash])`, the second only
1200    ///   for a service
1201    ///
1202    /// Same structure and width as the `DefaultHasher` roll-up it replaces,
1203    /// whose output std does not promise across Rust releases.
1204    fn compute_hashes(
1205        methods: &[MethodSchema],
1206        children: Option<&[ChildSummary]>,
1207    ) -> (String, Option<String>, String) {
1208        let self_hash = hash16_lines(methods.iter().map(|m| m.hash.as_str()));
1209        let children_hash =
1210            children.map(|kids| hash16_lines(kids.iter().map(|c| c.hash.as_str())));
1211        let hash = hash16_lines(std::iter::once(self_hash.as_str()).chain(children_hash.as_deref()));
1212        (self_hash, children_hash, hash)
1213    }
1214
1215    /// Inspect each method's `returns` JSON Schema for the framework-
1216    /// reserved `_credentials` top-level field name; emit a tracing
1217    /// warning when a collision is detected (AUTHZ-CRED-CORE-2
1218    /// acceptance criterion #8). Returns the number of collisions found,
1219    /// so callers can chain into a metrics counter or assertion if they
1220    /// want one.
1221    ///
1222    /// The framework reserves the `_credentials` top-level field name
1223    /// for the credential sidecar (see
1224    /// `crate::plexus::credential_envelope`). Backends that define a
1225    /// domain field of the same name have it shadowed at dispatch time;
1226    /// the warning surfaces that fact at build time so backends can
1227    /// rename.
1228    /// PERF-15: [`Self::warn_on_credentials_field_collisions`] once for
1229    /// each schema a process builds — by namespace and hash — not in every
1230    /// constructor call. A service's `_info`, `hash` and `schema` built
1231    /// every activation's schema each time, and serializing each method's
1232    /// `returns` to lint it was 39 % of that (PERF-5). A schema whose
1233    /// methods change has another hash, and is linted again.
1234    fn lint_once(namespace: &str, hash: &str, methods: &[MethodSchema]) {
1235        static LINTED: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<(String, String)>>> =
1236            std::sync::OnceLock::new();
1237        let first = LINTED
1238            .get_or_init(Default::default)
1239            .lock()
1240            .map(|mut seen| seen.insert((namespace.to_string(), hash.to_string())))
1241            .unwrap_or(true);
1242        if first {
1243            let _ = Self::warn_on_credentials_field_collisions(namespace, methods);
1244        }
1245    }
1246
1247    fn warn_on_credentials_field_collisions(
1248        namespace: &str,
1249        methods: &[MethodSchema],
1250    ) -> usize {
1251        let mut count = 0;
1252        for m in methods {
1253            let Ok(returns_json) = serde_json::to_value(&m.returns) else { continue };
1254            if super::credential_envelope::check_returns_schema_for_credentials_collision(
1255                namespace,
1256                &m.name,
1257                &returns_json,
1258            ) {
1259                count += 1;
1260            }
1261        }
1262        count
1263    }
1264
1265    /// Validate no name collisions exist within a plugin
1266    ///
1267    /// Checks for:
1268    /// - Duplicate method names
1269    /// - Duplicate child names (for hubs)
1270    /// - Method/child name collisions for `Rpc`-role methods (for hubs)
1271    ///
1272    /// Panics if a collision is detected (system error).
1273    ///
1274    /// # IR-4 relaxation
1275    ///
1276    /// As of IR-4, a method with `MethodRole::StaticChild` or
1277    /// `MethodRole::DynamicChild { .. }` that shares a name with a
1278    /// `ChildSummary` entry is **not** a collision — it's the same child
1279    /// surfaced via two wire representations (the role-tagged method list
1280    /// and the deprecated `children` side-table). Only `Rpc`-role methods
1281    /// whose name matches a child summary are flagged.
1282    fn validate_no_collisions(
1283        namespace: &str,
1284        methods: &[MethodSchema],
1285        children: Option<&[ChildSummary]>,
1286    ) {
1287        use std::collections::HashSet;
1288
1289        let mut seen: HashSet<&str> = HashSet::new();
1290
1291        // Check method names
1292        for m in methods {
1293            if !seen.insert(&m.name) {
1294                panic!(
1295                    "Name collision in plugin '{}': duplicate method '{}'",
1296                    namespace, m.name
1297                );
1298            }
1299        }
1300
1301        // Check child names (and collisions with methods)
1302        if let Some(kids) = children {
1303            for c in kids {
1304                if !seen.insert(&c.namespace) {
1305                    // IR-4: a role-tagged child method whose name matches a
1306                    // child summary is expected by construction (the two
1307                    // wire-surfaces describe the same child). Skip silently.
1308                    let colliding_method =
1309                        methods.iter().find(|m| m.name == c.namespace);
1310                    if let Some(m) = colliding_method {
1311                        if matches!(
1312                            m.role,
1313                            MethodRole::StaticChild | MethodRole::DynamicChild { .. } | MethodRole::Peer { .. }
1314                        ) {
1315                            continue;
1316                        }
1317                    }
1318                    // Could be duplicate child or collision with an Rpc-role method
1319                    let collision_type = if colliding_method.is_some() {
1320                        "method/child collision"
1321                    } else {
1322                        "duplicate child"
1323                    };
1324                    panic!(
1325                        "Name collision in plugin '{}': {} for '{}'",
1326                        namespace, collision_type, c.namespace
1327                    );
1328                }
1329            }
1330        }
1331    }
1332
1333    /// Derive the deprecated `(children, is_hub)` side-table fields from a
1334    /// role-tagged method list.
1335    ///
1336    /// Added in IR-4 as the **centralized shim** that backfills the
1337    /// pre-IR `children: Option<Vec<ChildSummary>>` and `is_hub: bool`
1338    /// representations from the authoritative `MethodRole` on each
1339    /// `MethodSchema`.
1340    ///
1341    /// # Semantics
1342    ///
1343    /// One `ChildSummary` is produced per non-`Rpc` method, preserving the
1344    /// source order. The shim writes:
1345    ///
1346    /// | Field | Value |
1347    /// |---|---|
1348    /// | `namespace` | The method's name. |
1349    /// | `description` | The method's `description`. |
1350    /// | `hash` | Empty string — the shim does **not** compute child hashes. Callers that want per-child hashes must populate them out-of-band. |
1351    ///
1352    /// The returned `bool` matches [`PluginSchema::is_hub_by_role`] — `true`
1353    /// iff at least one method carries a child role.
1354    ///
1355    /// # Example
1356    ///
1357    /// ```
1358    /// use plexus_core::plexus::schema::{MethodRole, MethodSchema, PluginSchema};
1359    ///
1360    /// let methods = vec![
1361    ///     MethodSchema::new("ping", "rpc", "h1"),
1362    ///     MethodSchema::new("kid",  "static child", "h2")
1363    ///         .with_role(MethodRole::StaticChild),
1364    /// ];
1365    /// let (children, is_hub) = PluginSchema::derive_legacy_fields(&methods);
1366    /// assert_eq!(children.len(), 1);
1367    /// assert_eq!(children[0].namespace, "kid");
1368    /// assert!(is_hub);
1369    /// ```
1370    pub fn derive_legacy_fields(
1371        methods: &[MethodSchema],
1372    ) -> (Vec<ChildSummary>, bool) {
1373        let children: Vec<ChildSummary> = methods
1374            .iter()
1375            .filter(|m| {
1376                matches!(
1377                    m.role,
1378                    MethodRole::StaticChild | MethodRole::DynamicChild { .. } | MethodRole::Peer { .. }
1379                )
1380            })
1381            .map(|m| ChildSummary {
1382                namespace: m.name.clone(),
1383                description: m.description.clone(),
1384                hash: String::new(),
1385            })
1386            .collect();
1387        let is_hub = !children.is_empty();
1388        (children, is_hub)
1389    }
1390
1391    /// Create a new leaf plugin schema (no children)
1392    #[allow(deprecated)]
1393    pub fn leaf(
1394        namespace: impl Into<String>,
1395        version: impl Into<String>,
1396        description: impl Into<String>,
1397        methods: Vec<MethodSchema>,
1398    ) -> Self {
1399        let namespace = namespace.into();
1400        Self::validate_no_collisions(&namespace, &methods, None);
1401        // AUTHZ-CRED-CORE-2 acceptance criterion #8: warn at schema-build
1402        // time when a method's return-type schema declares a top-level
1403        // field named `_credentials` (reserved by the framework's
1404        // credential sidecar) — once for each schema the process builds
1405        // (PERF-15, `lint_once`).
1406        let (self_hash, children_hash, hash) = Self::compute_hashes(&methods, None);
1407        Self::lint_once(&namespace, &hash, &methods);
1408        Self {
1409            namespace,
1410            version: version.into(),
1411            description: description.into(),
1412            long_description: None,
1413            self_hash,
1414            children_hash,
1415            hash,
1416            methods,
1417            children: None,
1418            request: None,
1419            deprecation: None,
1420            roles: std::collections::BTreeMap::new(),
1421            view: None,
1422            needs: None,
1423        }
1424    }
1425
1426    /// Create a new leaf plugin schema with long description
1427    #[allow(deprecated)]
1428    pub fn leaf_with_long_description(
1429        namespace: impl Into<String>,
1430        version: impl Into<String>,
1431        description: impl Into<String>,
1432        long_description: impl Into<String>,
1433        methods: Vec<MethodSchema>,
1434    ) -> Self {
1435        let namespace = namespace.into();
1436        Self::validate_no_collisions(&namespace, &methods, None);
1437        // AUTHZ-CRED-CORE-2 AC #8: see PluginSchema::leaf.
1438        let (self_hash, children_hash, hash) = Self::compute_hashes(&methods, None);
1439        Self::lint_once(&namespace, &hash, &methods);
1440        Self {
1441            namespace,
1442            version: version.into(),
1443            description: description.into(),
1444            long_description: Some(long_description.into()),
1445            self_hash,
1446            children_hash,
1447            hash,
1448            methods,
1449            children: None,
1450            request: None,
1451            deprecation: None,
1452            roles: std::collections::BTreeMap::new(),
1453            view: None,
1454            needs: None,
1455        }
1456    }
1457
1458    /// Create a new hub plugin schema (with child summaries)
1459    #[allow(deprecated)]
1460    pub fn hub(
1461        namespace: impl Into<String>,
1462        version: impl Into<String>,
1463        description: impl Into<String>,
1464        methods: Vec<MethodSchema>,
1465        children: Vec<ChildSummary>,
1466    ) -> Self {
1467        let namespace = namespace.into();
1468        Self::validate_no_collisions(&namespace, &methods, Some(&children));
1469        // AUTHZ-CRED-CORE-2 AC #8: see PluginSchema::leaf.
1470        let (self_hash, children_hash, hash) = Self::compute_hashes(&methods, Some(&children));
1471        Self::lint_once(&namespace, &hash, &methods);
1472        Self {
1473            namespace,
1474            version: version.into(),
1475            description: description.into(),
1476            long_description: None,
1477            self_hash,
1478            children_hash,
1479            hash,
1480            methods,
1481            children: Some(children),
1482            request: None,
1483            deprecation: None,
1484            roles: std::collections::BTreeMap::new(),
1485            view: None,
1486            needs: None,
1487        }
1488    }
1489
1490    /// Create a new hub plugin schema with long description
1491    #[allow(deprecated)]
1492    pub fn hub_with_long_description(
1493        namespace: impl Into<String>,
1494        version: impl Into<String>,
1495        description: impl Into<String>,
1496        long_description: impl Into<String>,
1497        methods: Vec<MethodSchema>,
1498        children: Vec<ChildSummary>,
1499    ) -> Self {
1500        let namespace = namespace.into();
1501        Self::validate_no_collisions(&namespace, &methods, Some(&children));
1502        // AUTHZ-CRED-CORE-2 AC #8: see PluginSchema::leaf.
1503        let (self_hash, children_hash, hash) = Self::compute_hashes(&methods, Some(&children));
1504        Self::lint_once(&namespace, &hash, &methods);
1505        Self {
1506            namespace,
1507            version: version.into(),
1508            description: description.into(),
1509            long_description: Some(long_description.into()),
1510            self_hash,
1511            children_hash,
1512            hash,
1513            methods,
1514            children: Some(children),
1515            request: None,
1516            deprecation: None,
1517            roles: std::collections::BTreeMap::new(),
1518            view: None,
1519            needs: None,
1520        }
1521    }
1522
1523    /// Check if this is a hub.
1524    ///
1525    /// Returns `true` iff the plugin exposes child activations. As of IR-2,
1526    /// this is derived from **either** source of truth:
1527    ///
1528    /// 1. Any method tagged with a child `MethodRole` (`StaticChild` or
1529    ///    `DynamicChild { .. }`). This is the post-IR-3 authoritative signal.
1530    /// 2. The legacy `children: Option<Vec<ChildSummary>>` field is `Some`.
1531    ///    Preserved for back-compat during the IR transition window —
1532    ///    today's macros populate `children` but not yet `role`.
1533    ///
1534    /// # Deprecated (IR-4)
1535    ///
1536    /// The legacy transition-window fallback on `children.is_some()` is
1537    /// redundant now that `MethodRole` tags are authoritative. Callers
1538    /// should migrate to [`PluginSchema::is_hub_by_role`], which reads
1539    /// only role-tagged methods. This method will be removed in 0.7.
1540    #[deprecated(
1541        since = "0.5",
1542        note = "Use `PluginSchema::is_hub_by_role()` which reads MethodRole from methods. This method will be removed in 0.7."
1543    )]
1544    #[allow(deprecated)]
1545    pub fn is_hub(&self) -> bool {
1546        self.is_hub_by_role() || self.children.is_some()
1547    }
1548
1549    /// Returns `true` iff any method carries a child `MethodRole`.
1550    ///
1551    /// This is the **derived query** specified by IR-2: it reads only
1552    /// `self.methods`, ignoring the legacy `children` side channel. Use this
1553    /// when you want the post-IR-3 authoritative answer without the transition
1554    /// fallback that `is_hub()` provides.
1555    pub fn is_hub_by_role(&self) -> bool {
1556        self.methods.iter().any(|m| {
1557            matches!(
1558                m.role,
1559                MethodRole::StaticChild | MethodRole::DynamicChild { .. } | MethodRole::Peer { .. }
1560            )
1561        })
1562    }
1563
1564    /// Check if this is a leaf (no children)
1565    #[allow(deprecated)]
1566    pub fn is_leaf(&self) -> bool {
1567        self.children.is_none()
1568    }
1569
1570    /// Mark this plugin as deprecated.
1571    ///
1572    /// Added in IR-5. Populates the `deprecation` field with the provided
1573    /// `DeprecationInfo`. Populated by the `#[deprecated(...)]` attribute on
1574    /// an `impl Activation for Foo` block via `plexus-macros`.
1575    pub fn with_deprecation(mut self, info: DeprecationInfo) -> Self {
1576        self.deprecation = Some(info);
1577        self
1578    }
1579
1580    /// CA-1: fill `site_hint` on every method's `requires_credential` that
1581    /// lacks one, using the hub-derived attach site. Applied at
1582    /// schema-assembly time by [`DynamicHub`] when the backend's advertised
1583    /// auth capabilities imply a site — service authors write nothing.
1584    ///
1585    /// RETURNS-10: filled after the hashes are computed, so the hints are
1586    /// not covered by them — they come from the serving service's
1587    /// configuration, not the activation's code, and re-hashing on every
1588    /// schema response is the per-call cost the hashes are cached to avoid.
1589    ///
1590    /// [`DynamicHub`]: super::DynamicHub
1591    pub fn fill_site_hints(&mut self, site: &AttachmentSite) {
1592        for method in &mut self.methods {
1593            method.fill_site_hint(site);
1594        }
1595    }
1596}
1597
1598impl SchemaResult {
1599    /// CA-1: fill `site_hint`s across whichever schema shape this result
1600    /// carries — see [`PluginSchema::fill_site_hints`].
1601    pub fn fill_site_hints(&mut self, site: &AttachmentSite) {
1602        match self {
1603            SchemaResult::Plugin(plugin) => plugin.fill_site_hints(site),
1604            SchemaResult::Method(method) => method.fill_site_hint(site),
1605        }
1606    }
1607}
1608
1609/// Summary of a child plugin
1610#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1611pub struct ChildSummary {
1612    /// The child's namespace
1613    pub namespace: String,
1614
1615    /// Human-readable description
1616    pub description: String,
1617
1618    /// Content hash for cache invalidation
1619    pub hash: String,
1620}
1621
1622/// Schema summary containing only hashes (for cache validation)
1623#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1624pub struct PluginHashes {
1625    pub namespace: String,
1626    pub self_hash: String,
1627    #[serde(skip_serializing_if = "Option::is_none")]
1628    pub children_hash: Option<String>,
1629    pub hash: String,
1630    /// Child plugin hashes (for recursive checking)
1631    #[serde(skip_serializing_if = "Option::is_none")]
1632    pub children: Option<Vec<ChildHashes>>,
1633}
1634
1635#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1636pub struct ChildHashes {
1637    pub namespace: String,
1638    pub hash: String,
1639}
1640
1641impl MethodSchema {
1642    /// Create a new method schema with name, description, and hash
1643    ///
1644    /// RETURNS-10: a method's hash is its schema's
1645    /// [`content_hash`](Self::content_hash). Build the schema with `hash`
1646    /// empty and finish with [`with_content_hash`](Self::with_content_hash),
1647    /// as the code `#[plexus_macros::activation]` emits does.
1648    ///
1649    /// Starts as an infallible, progress-free [`Cardinality::One`] method
1650    /// whose `returns` is the empty schema `{}` (any value); the builders
1651    /// [`with_returns`](Self::with_returns), [`with_error`](Self::with_error),
1652    /// [`with_progress`](Self::with_progress) and
1653    /// [`with_cardinality`](Self::with_cardinality) state the real contract.
1654    pub fn new(
1655        name: impl Into<String>,
1656        description: impl Into<String>,
1657        hash: impl Into<String>,
1658    ) -> Self {
1659        Self {
1660            name: name.into(),
1661            description: description.into(),
1662            hash: hash.into(),
1663            params: None,
1664            returns: schemars::Schema::default(),
1665            error: None,
1666            progress: None,
1667            cardinality: Cardinality::One,
1668            http_method: HttpMethod::default(),
1669            role: MethodRole::Rpc,
1670            deprecation: None,
1671            params_meta: Vec::new(),
1672            credentials: Vec::new(),
1673            requires_credential: None,
1674            auth_posture: None,
1675            public: false,
1676            grant: None,
1677            target: None,
1678            everywhere: false,
1679            long_description: None,
1680            held_on: None,
1681            group: None,
1682            answer_by: None,
1683            examples: Vec::new(),
1684            input: None,
1685        }
1686    }
1687
1688    /// SYNAPSE-CC-9: the entry of the `schema` method every activation
1689    /// answers — `params` `{method?: string}` ([`SchemaParams`]) and
1690    /// `returns` [`SchemaResult`] (this `PluginSchema`, or one `MethodSchema`
1691    /// when called with `{"method": …}`; RETURNS-26). The macro adds the
1692    /// activation's grant.
1693    pub fn auto_schema() -> Self {
1694        Self::new(
1695            "schema",
1696            "Get plugin or method schema. Pass {\"method\": \"name\"} for a specific method.",
1697            "auto_schema", // fixed: the entry is the same in every activation
1698        )
1699        .with_params(SchemaParams::params_schema())
1700        .with_returns(schema_for!(SchemaResult))
1701    }
1702
1703    /// Is this the `schema` entry every activation's macro adds
1704    /// ([`auto_schema`](Self::auto_schema))?
1705    ///
1706    /// RETURNS-36: known by what every 0.8.x build writes alike, never by a
1707    /// hash recomputed with this build (review #11): named `schema`, an Rpc
1708    /// of one item with no error and no progress, its params `{method?}`
1709    /// alone and its `returns` titled `SchemaResult` — or main's fixed
1710    /// marker hash, `"auto_schema"`, from a peer still sending it. A method
1711    /// an author named `schema` with other params or another return is not
1712    /// it.
1713    pub fn is_auto_schema(&self) -> bool {
1714        if self.name != "schema" || !matches!(self.role, MethodRole::Rpc) {
1715            return false;
1716        }
1717        if self.hash == "auto_schema" {
1718            return true;
1719        }
1720        let params_are_method_alone = self
1721            .params
1722            .as_ref()
1723            .and_then(|p| p.as_object())
1724            .and_then(|o| o.get("properties"))
1725            .and_then(|p| p.as_object())
1726            .is_some_and(|props| props.len() == 1 && props.contains_key("method"));
1727        let returns_schema_result = self
1728            .returns
1729            .as_object()
1730            .and_then(|o| o.get("title"))
1731            .and_then(|t| t.as_str())
1732            == Some("SchemaResult");
1733        self.cardinality == Cardinality::One
1734            && self.error.is_none()
1735            && self.progress.is_none()
1736            && params_are_method_alone
1737            && returns_schema_result
1738    }
1739
1740    /// SYNAPSE-CC-9: reserved for BIDIR-6 — the schema of the items a client
1741    /// streams in.
1742    pub fn with_input(mut self, mut input: schemars::Schema) -> Self {
1743        spell_json_values(&mut input);
1744        self.input = Some(input);
1745        self
1746    }
1747
1748    /// RETURNS-10: this method's content hash — 16 lowercase hex.
1749    ///
1750    /// The schema as it serializes, without its own `hash` field, written as
1751    /// [canonical JSON](canonical_json) (keys sorted, no whitespace, arrays
1752    /// in order) and hashed with [`hash16`] (SHA-256, first 8 bytes). It
1753    /// covers everything a client is generated from — name, description,
1754    /// params, `returns` / `error` / `progress` down to every nested field,
1755    /// variant and doc comment, cardinality, role, deprecation, credentials,
1756    /// auth posture — so one hash means one schema. A consumer recomputes it
1757    /// from the wire, e.g. in Python:
1758    ///
1759    /// ```text
1760    /// m = dict(method); del m["hash"]
1761    /// sha256(json.dumps(m, sort_keys=True, separators=(",", ":"),
1762    ///                   ensure_ascii=False).encode()).hexdigest()[:16]
1763    /// ```
1764    ///
1765    /// Costs one serialization and one SHA-256 pass over the schema: compute
1766    /// it once where schemas are cached, not per `plugin_schema()` call.
1767    pub fn content_hash(&self) -> String {
1768        let mut value = serde_json::to_value(self).expect("a MethodSchema serializes");
1769        if let Some(fields) = value.as_object_mut() {
1770            fields.remove("hash");
1771        }
1772        hash16(canonical_json(&value).as_bytes())
1773    }
1774
1775    /// RETURNS-10: set `hash` to [`content_hash`](Self::content_hash) —
1776    /// the last step of building a schema (a builder applied after it would
1777    /// change the schema without moving its hash).
1778    pub fn with_content_hash(mut self) -> Self {
1779        self.hash = self.content_hash();
1780        self
1781    }
1782
1783    /// Add parameter schema
1784    pub fn with_params(mut self, mut params: schemars::Schema) -> Self {
1785        spell_json_values(&mut params);
1786        self.params = Some(params);
1787        self
1788    }
1789
1790    /// Set the schema of the method's item type `T`.
1791    pub fn with_returns(mut self, mut returns: schemars::Schema) -> Self {
1792        spell_json_values(&mut returns);
1793        self.returns = returns;
1794        self
1795    }
1796
1797    /// Set the schema of the method's error type `E` (a fallible method,
1798    /// `Result<T, E>`).
1799    pub fn with_error(mut self, mut error: schemars::Schema) -> Self {
1800        spell_json_values(&mut error);
1801        self.error = Some(error);
1802        self
1803    }
1804
1805    /// Set the schema of the method's progress type `P` (an item of
1806    /// `Progress<T, P>`).
1807    pub fn with_progress(mut self, mut progress: schemars::Schema) -> Self {
1808        spell_json_values(&mut progress);
1809        self.progress = Some(progress);
1810        self
1811    }
1812
1813    /// Set whether the method yields one item or many.
1814    ///
1815    /// [`MethodSchema::new`] starts at [`Cardinality::One`].
1816    pub fn with_cardinality(mut self, cardinality: Cardinality) -> Self {
1817        self.cardinality = cardinality;
1818        self
1819    }
1820
1821    /// Set the HTTP method for REST endpoints
1822    ///
1823    /// Defaults to POST for backward compatibility.
1824    ///
1825    /// # Guidelines
1826    /// - GET: Idempotent read operations with no side effects
1827    /// - POST: Create operations or non-idempotent actions
1828    /// - PUT: Replace/update operations (idempotent)
1829    /// - DELETE: Remove operations (idempotent)
1830    /// - PATCH: Partial update operations
1831    pub fn with_http_method(mut self, http_method: HttpMethod) -> Self {
1832        self.http_method = http_method;
1833        self
1834    }
1835
1836    /// Set this method's role in the activation graph.
1837    ///
1838    /// Added in IR-2. Defaults to `MethodRole::Rpc`.
1839    pub fn with_role(mut self, role: MethodRole) -> Self {
1840        self.role = role;
1841        self
1842    }
1843
1844    /// Mark this method as deprecated.
1845    ///
1846    /// Added in IR-2. Populates the `deprecation` field with the provided
1847    /// `DeprecationInfo`.
1848    pub fn with_deprecation(mut self, info: DeprecationInfo) -> Self {
1849        self.deprecation = Some(info);
1850        self
1851    }
1852
1853    /// Attach per-parameter metadata for this method's parameters.
1854    ///
1855    /// Added in IR-5. Only parameters that carry metadata (e.g. a
1856    /// `#[deprecated]` annotation) need appear in `entries`; absence means
1857    /// "no metadata" for a given parameter. The consumer correlates entries
1858    /// against `self.params` by matching `ParamSchema.name` against the
1859    /// `properties` map of the JSON Schema.
1860    pub fn with_params_meta(mut self, entries: Vec<ParamSchema>) -> Self {
1861        self.params_meta = entries;
1862        self
1863    }
1864
1865    /// Attach the credential-field projection for this method's return type.
1866    ///
1867    /// Added in `AUTHZ-CRED-CORE-3`. The build-path supplies one
1868    /// `CredentialFieldDecl` per `#[plexus::credential(...)]`-annotated
1869    /// field in the return type, in stable declaration order. Absence (the
1870    /// default empty vec) means the return type carries no credentials.
1871    ///
1872    /// The constructor `CredentialFieldDecl::from_marker` composes one
1873    /// entry from a `CredentialFieldMarker` (emitted by the
1874    /// `#[derive(Credentials)]` macro) plus the runtime-known issuer.
1875    pub fn with_credentials(mut self, credentials: Vec<CredentialFieldDecl>) -> Self {
1876        self.credentials = credentials;
1877        self
1878    }
1879
1880    /// Attach the implicit-derived `requires_credential` filter for this
1881    /// method.
1882    ///
1883    /// Added in `AUTHZ-CRED-CORE-3`. The build-path supplies a
1884    /// `RequiredCredential` derived from either (a) the method's `scope`
1885    /// attribute or (b) the method's appearance as a `refresh_via` /
1886    /// `revoke_via` target of some other credential in the schema. Public
1887    /// methods leave this field as `None` (the default).
1888    ///
1889    /// `RequiredCredential::from_method_scope` and
1890    /// `RequiredCredential::from_refresh_revoke_target` are the two derivation
1891    /// entry points.
1892    pub fn with_requires_credential(mut self, req: RequiredCredential) -> Self {
1893        self.requires_credential = Some(req);
1894        self
1895    }
1896
1897    /// Stamp the activation-declared auth posture onto this method.
1898    ///
1899    /// Added in R-2 (joint AP-1). Populated by the `#[plexus_macros::
1900    /// activation(auth = "...")]` emission (R-1); only explicitly declared
1901    /// postures are stamped — activations that never declare `auth = "..."`
1902    /// leave this `None` so their wire output is byte-identical to pre-R
1903    /// emissions.
1904    pub fn with_auth_posture(mut self, posture: AuthPosture) -> Self {
1905        self.auth_posture = Some(posture);
1906        self
1907    }
1908
1909    /// Mark this method as explicitly public (AUTHZ-CORE-2's
1910    /// `#[plexus::method(public)]`) — exempt from the default-deny gate.
1911    ///
1912    /// Added in R-2. Populated by the macro emission (R-1); the macro
1913    /// rejects `public` + `scope = "..."` at compile time, so a public
1914    /// method never carries a scope-derived `requires_credential`.
1915    pub fn with_public(mut self, public: bool) -> Self {
1916        self.public = public;
1917        self
1918    }
1919
1920    /// AUTH-3: set the method's grant (`<activation>.<method>`).
1921    pub fn with_grant(mut self, grant: impl Into<String>) -> Self {
1922        self.grant = Some(grant.into());
1923        self
1924    }
1925
1926    /// AUTH-3: name the param that locates what this call acts on.
1927    pub fn with_target(mut self, target: impl Into<String>) -> Self {
1928        self.target = Some(target.into());
1929        self
1930    }
1931
1932    /// KEEL-31: mark the method as acting on the whole service — its grant
1933    /// is needed on `*` ([`MethodSchema::everywhere`]).
1934    pub fn with_everywhere(mut self, everywhere: bool) -> Self {
1935        self.everywhere = everywhere;
1936        self
1937    }
1938
1939    /// AUTH-3: the doc comment's fuller text.
1940    pub fn with_long_description(mut self, long_description: impl Into<String>) -> Self {
1941        self.long_description = Some(long_description.into());
1942        self
1943    }
1944
1945    /// BIDIR-8: who may answer a question this method asks mid-call, as
1946    /// `#[method(answer_by = "…")]` declares it (`person`, `grant:<g>`);
1947    /// the default (`caller`) is left unset.
1948    pub fn with_answer_by(mut self, answer_by: impl Into<String>) -> Self {
1949        self.answer_by = Some(answer_by.into());
1950        self
1951    }
1952
1953    /// BIDIR-8: the method's [`Answerer`](plexus_auth_core::duplex::Answerer)
1954    /// — [`answer_by`](Self::answer_by) read, absent the default (`caller`).
1955    /// A spelling the macro would refuse is an error, never a wider answerer.
1956    pub fn answerer(&self) -> Result<plexus_auth_core::duplex::Answerer, String> {
1957        plexus_auth_core::duplex::Answerer::of_schema(self.answer_by.as_deref())
1958    }
1959
1960    /// SYNAPSE-13: put this method in a listing group (`"read"`, `"write"`).
1961    pub fn with_group(mut self, group: impl Into<String>) -> Self {
1962        self.group = Some(group.into());
1963        self
1964    }
1965
1966    /// SYNAPSE-13: add a worked call of this method.
1967    pub fn with_example(mut self, example: MethodExample) -> Self {
1968        self.examples.push(example);
1969        self
1970    }
1971
1972    /// SYNAPSE-13: say which values `param` is meant to take, as
1973    /// [`X_PLEXUS_VALUES`] on its property in `params` — a hint, never
1974    /// enforced. A param the schema does not have is left alone.
1975    pub fn with_param_values<I, S>(mut self, param: &str, values: I) -> Self
1976    where
1977        I: IntoIterator<Item = S>,
1978        S: Into<String>,
1979    {
1980        let values: Vec<serde_json::Value> =
1981            values.into_iter().map(|v| serde_json::Value::String(v.into())).collect();
1982        if let Some(params) = self.params.take() {
1983            let mut value = serde_json::to_value(&params).unwrap_or_default();
1984            if let Some(prop) = value
1985                .get_mut("properties")
1986                .and_then(|p| p.get_mut(param))
1987                .and_then(|p| p.as_object_mut())
1988            {
1989                prop.insert(X_PLEXUS_VALUES.to_string(), serde_json::Value::Array(values));
1990            }
1991            self.params = Some(serde_json::from_value(value).unwrap_or(params));
1992        }
1993        self
1994    }
1995
1996    /// SYNAPSE-13: the values `param` is meant to take, when its property
1997    /// says them ([`X_PLEXUS_VALUES`]).
1998    pub fn param_values(&self, param: &str) -> Option<Vec<String>> {
1999        let value = serde_json::to_value(self.params.as_ref()?).ok()?;
2000        let list = value.get("properties")?.get(param)?.get(X_PLEXUS_VALUES)?.as_array()?;
2001        Some(list.iter().filter_map(|v| v.as_str().map(str::to_string)).collect())
2002    }
2003
2004    /// AUTH-2: the grant a gate asks for this method under `activation`:
2005    /// the schema's own `grant`, else `<activation>.<name>`.
2006    pub fn grant_or(&self, activation: &str) -> String {
2007        self.grant.clone().unwrap_or_else(|| format!("{activation}.{}", self.name))
2008    }
2009
2010    /// CA-1: fill `requires_credential.site_hint` with the hub-derived
2011    /// attach site when the method carries a requirement that lacks one.
2012    /// Methods without a `requires_credential` are untouched — derivation
2013    /// never *creates* a requirement (AUTHZ-CRED-CORE-3's implicit-only
2014    /// contract).
2015    pub fn fill_site_hint(&mut self, site: &AttachmentSite) {
2016        if let Some(req) = self.requires_credential.as_mut() {
2017            req.fill_site_hint(site);
2018        }
2019    }
2020}
2021
2022// ============================================================================
2023// JSON Schema Types
2024// ============================================================================
2025
2026/// A complete JSON Schema with metadata
2027#[derive(Debug, Clone, Serialize, Deserialize)]
2028pub struct Schema {
2029    /// The JSON Schema specification version
2030    #[serde(rename = "$schema", skip_serializing_if = "Option::is_none", default)]
2031    pub schema_version: Option<String>,
2032
2033    /// Title of the schema
2034    #[serde(skip_serializing_if = "Option::is_none")]
2035    pub title: Option<String>,
2036
2037    /// Description of what this schema represents
2038    #[serde(skip_serializing_if = "Option::is_none")]
2039    pub description: Option<String>,
2040
2041    /// The schema type (typically "object" for root, can be string or array)
2042    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
2043    pub schema_type: Option<serde_json::Value>,
2044
2045    /// Properties for object types
2046    #[serde(skip_serializing_if = "Option::is_none")]
2047    pub properties: Option<HashMap<String, SchemaProperty>>,
2048
2049    /// Required properties
2050    #[serde(skip_serializing_if = "Option::is_none")]
2051    pub required: Option<Vec<String>>,
2052
2053    /// Enum variants (for discriminated unions)
2054    #[serde(rename = "oneOf", skip_serializing_if = "Option::is_none")]
2055    pub one_of: Option<Vec<Schema>>,
2056
2057    /// Schema definitions (for $defs or definitions)
2058    #[serde(rename = "$defs", skip_serializing_if = "Option::is_none")]
2059    pub defs: Option<HashMap<String, serde_json::Value>>,
2060
2061    /// Any additional schema properties
2062    #[serde(flatten)]
2063    pub additional: HashMap<String, serde_json::Value>,
2064}
2065
2066/// Schema type enumeration
2067#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2068#[serde(rename_all = "lowercase")]
2069pub enum SchemaType {
2070    Object,
2071    Array,
2072    String,
2073    Number,
2074    Integer,
2075    Boolean,
2076    Null,
2077}
2078
2079/// A property definition in a schema
2080#[derive(Debug, Clone, Serialize, Deserialize)]
2081pub struct SchemaProperty {
2082    /// The type of this property (can be a single type or array of types for nullable)
2083    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
2084    pub property_type: Option<serde_json::Value>,
2085
2086    /// Description of this property
2087    #[serde(skip_serializing_if = "Option::is_none")]
2088    pub description: Option<String>,
2089
2090    /// Format hint (e.g., "uuid", "date-time", "email")
2091    #[serde(skip_serializing_if = "Option::is_none")]
2092    pub format: Option<String>,
2093
2094    /// For array types, the schema of items
2095    #[serde(skip_serializing_if = "Option::is_none")]
2096    pub items: Option<Box<SchemaProperty>>,
2097
2098    /// For object types, nested properties
2099    #[serde(skip_serializing_if = "Option::is_none")]
2100    pub properties: Option<HashMap<String, SchemaProperty>>,
2101
2102    /// Required properties (for object types)
2103    #[serde(skip_serializing_if = "Option::is_none")]
2104    pub required: Option<Vec<String>>,
2105
2106    /// Default value for this property
2107    #[serde(skip_serializing_if = "Option::is_none")]
2108    pub default: Option<serde_json::Value>,
2109
2110    /// Enum values if this is an enum
2111    #[serde(rename = "enum", skip_serializing_if = "Option::is_none")]
2112    pub enum_values: Option<Vec<serde_json::Value>>,
2113
2114    /// Reference to another schema definition
2115    #[serde(rename = "$ref", skip_serializing_if = "Option::is_none")]
2116    pub reference: Option<String>,
2117
2118    /// Any additional property metadata
2119    #[serde(flatten)]
2120    pub additional: HashMap<String, serde_json::Value>,
2121}
2122
2123impl Schema {
2124    /// Create a new schema with basic metadata
2125    pub fn new(title: impl Into<String>, description: impl Into<String>) -> Self {
2126        Self {
2127            schema_version: Some("http://json-schema.org/draft-07/schema#".to_string()),
2128            title: Some(title.into()),
2129            description: Some(description.into()),
2130            schema_type: None,
2131            properties: None,
2132            required: None,
2133            one_of: None,
2134            defs: None,
2135            additional: HashMap::new(),
2136        }
2137    }
2138
2139    /// Create an object schema
2140    pub fn object() -> Self {
2141        Self {
2142            schema_version: Some("http://json-schema.org/draft-07/schema#".to_string()),
2143            title: None,
2144            description: None,
2145            schema_type: Some(serde_json::json!("object")),
2146            properties: Some(HashMap::new()),
2147            required: None,
2148            one_of: None,
2149            defs: None,
2150            additional: HashMap::new(),
2151        }
2152    }
2153
2154    /// Add a property to this schema
2155    pub fn with_property(mut self, name: impl Into<String>, property: SchemaProperty) -> Self {
2156        self.properties
2157            .get_or_insert_with(HashMap::new)
2158            .insert(name.into(), property);
2159        self
2160    }
2161
2162    /// Mark a property as required
2163    pub fn with_required(mut self, name: impl Into<String>) -> Self {
2164        self.required
2165            .get_or_insert_with(Vec::new)
2166            .push(name.into());
2167        self
2168    }
2169
2170    /// Set the description
2171    pub fn with_description(mut self, description: impl Into<String>) -> Self {
2172        self.description = Some(description.into());
2173        self
2174    }
2175
2176    /// Extract a single method's schema from the oneOf array
2177    ///
2178    /// Searches the oneOf variants for a method matching the given name.
2179    /// Returns the variant schema if found, None otherwise.
2180    pub fn get_method_schema(&self, method_name: &str) -> Option<Schema> {
2181        let variants = self.one_of.as_ref()?;
2182
2183        for variant in variants {
2184            // Check if this variant has a "method" property with const or enum
2185            if let Some(props) = &variant.properties {
2186                if let Some(method_prop) = props.get("method") {
2187                    // Try "const" first (schemars uses this for literal values)
2188                    if let Some(const_val) = method_prop.additional.get("const") {
2189                        if const_val.as_str() == Some(method_name) {
2190                            return Some(variant.clone());
2191                        }
2192                    }
2193                    // Fall back to enum_values
2194                    if let Some(enum_vals) = &method_prop.enum_values {
2195                        if enum_vals.first().and_then(|v| v.as_str()) == Some(method_name) {
2196                            return Some(variant.clone());
2197                        }
2198                    }
2199                }
2200            }
2201        }
2202        None
2203    }
2204
2205    /// List all method names from the oneOf array
2206    pub fn list_methods(&self) -> Vec<String> {
2207        let Some(variants) = &self.one_of else {
2208            return Vec::new();
2209        };
2210
2211        variants
2212            .iter()
2213            .filter_map(|variant| {
2214                let props = variant.properties.as_ref()?;
2215                let method_prop = props.get("method")?;
2216
2217                // Try "const" first
2218                if let Some(const_val) = method_prop.additional.get("const") {
2219                    return const_val.as_str().map(String::from);
2220                }
2221                // Fall back to enum_values
2222                method_prop
2223                    .enum_values
2224                    .as_ref()?
2225                    .first()?
2226                    .as_str()
2227                    .map(String::from)
2228            })
2229            .collect()
2230    }
2231}
2232
2233impl SchemaProperty {
2234    /// Create a string property
2235    pub fn string() -> Self {
2236        Self {
2237            property_type: Some(serde_json::json!("string")),
2238            description: None,
2239            format: None,
2240            items: None,
2241            properties: None,
2242            required: None,
2243            default: None,
2244            enum_values: None,
2245            reference: None,
2246            additional: HashMap::new(),
2247        }
2248    }
2249
2250    /// Create a UUID property (string with format)
2251    pub fn uuid() -> Self {
2252        Self {
2253            property_type: Some(serde_json::json!("string")),
2254            description: None,
2255            format: Some("uuid".to_string()),
2256            items: None,
2257            properties: None,
2258            required: None,
2259            default: None,
2260            enum_values: None,
2261            reference: None,
2262            additional: HashMap::new(),
2263        }
2264    }
2265
2266    /// Create an integer property
2267    pub fn integer() -> Self {
2268        Self {
2269            property_type: Some(serde_json::json!("integer")),
2270            description: None,
2271            format: None,
2272            items: None,
2273            properties: None,
2274            required: None,
2275            default: None,
2276            enum_values: None,
2277            reference: None,
2278            additional: HashMap::new(),
2279        }
2280    }
2281
2282    /// Create an object property
2283    pub fn object() -> Self {
2284        Self {
2285            property_type: Some(serde_json::json!("object")),
2286            description: None,
2287            format: None,
2288            items: None,
2289            properties: Some(HashMap::new()),
2290            required: None,
2291            default: None,
2292            enum_values: None,
2293            reference: None,
2294            additional: HashMap::new(),
2295        }
2296    }
2297
2298    /// Create an array property
2299    pub fn array(items: SchemaProperty) -> Self {
2300        Self {
2301            property_type: Some(serde_json::json!("array")),
2302            description: None,
2303            format: None,
2304            items: Some(Box::new(items)),
2305            properties: None,
2306            required: None,
2307            default: None,
2308            enum_values: None,
2309            reference: None,
2310            additional: HashMap::new(),
2311        }
2312    }
2313
2314    /// Add a description
2315    pub fn with_description(mut self, description: impl Into<String>) -> Self {
2316        self.description = Some(description.into());
2317        self
2318    }
2319
2320    /// Add a default value
2321    pub fn with_default(mut self, default: serde_json::Value) -> Self {
2322        self.default = Some(default);
2323        self
2324    }
2325
2326    /// Add nested properties (for object types)
2327    pub fn with_property(mut self, name: impl Into<String>, property: SchemaProperty) -> Self {
2328        self.properties
2329            .get_or_insert_with(HashMap::new)
2330            .insert(name.into(), property);
2331        self
2332    }
2333}
2334
2335#[cfg(test)]
2336#[allow(deprecated)]
2337mod tests {
2338    use super::*;
2339
2340    /// SYNAPSE-13: group, examples and a param's values on the wire, and
2341    /// absent when unset (an older client sees the shape it always did).
2342    #[test]
2343    fn synapse13_group_examples_values() {
2344        let params: schemars::Schema = serde_json::from_value(serde_json::json!({
2345            "type": "object",
2346            "properties": { "id": { "type": "string" }, "status": { "type": "string", "description": "New status" } },
2347            "required": ["id", "status"],
2348        }))
2349        .unwrap();
2350        let bare = MethodSchema::new("set_status", "Set a ticket's status", "h").with_params(params);
2351        let wire = serde_json::to_value(&bare).unwrap();
2352        assert!(wire.get("group").is_none() && wire.get("examples").is_none());
2353        assert_eq!(bare.param_values("status"), None);
2354
2355        let m = bare
2356            .with_group("write")
2357            .with_example(MethodExample::with_note(serde_json::json!({"id": "MENGER-40", "status": "Coding"}), "start work"))
2358            .with_param_values("status", ["Pending", "Ready"])
2359            .with_param_values("nope", ["x"]);
2360        assert_eq!(m.param_values("status"), Some(vec!["Pending".to_string(), "Ready".to_string()]));
2361        let wire = serde_json::to_value(&m).unwrap();
2362        assert_eq!(wire["group"], "write");
2363        assert_eq!(wire["examples"], serde_json::json!([{ "params": {"id": "MENGER-40", "status": "Coding"}, "note": "start work" }]));
2364        assert_eq!(wire["params"]["properties"]["status"]["x-plexus-values"], serde_json::json!(["Pending", "Ready"]));
2365        assert_eq!(wire["params"]["properties"]["status"]["description"], "New status");
2366        assert!(wire["params"]["properties"].get("nope").is_none());
2367        let back: MethodSchema = serde_json::from_value(wire).unwrap();
2368        assert_eq!(back.group.as_deref(), Some("write"));
2369        assert_eq!(back.examples, m.examples);
2370    }
2371
2372    #[test]
2373    fn test_schema_creation() {
2374        let schema = Schema::object()
2375            .with_property("id", SchemaProperty::uuid().with_description("The unique identifier"))
2376            .with_property("name", SchemaProperty::string().with_description("The name"))
2377            .with_required("id");
2378
2379        assert_eq!(schema.schema_type, Some(serde_json::json!("object")));
2380        assert!(schema.properties.is_some());
2381        assert_eq!(schema.required, Some(vec!["id".to_string()]));
2382    }
2383
2384    #[test]
2385    fn test_serialization() {
2386        let schema = Schema::object()
2387            .with_property("id", SchemaProperty::uuid());
2388
2389        let json = serde_json::to_string_pretty(&schema).unwrap();
2390        assert!(json.contains("uuid"));
2391    }
2392
2393    #[test]
2394    fn test_self_hash_changes_on_method_change() {
2395        let schema1 = PluginSchema::leaf(
2396            "test",
2397            "1.0",
2398            "desc",
2399            vec![MethodSchema::new("foo", "bar", "hash1")],
2400        );
2401
2402        let schema2 = PluginSchema::leaf(
2403            "test",
2404            "1.0",
2405            "desc",
2406            vec![MethodSchema::new("foo", "baz", "hash2")],  // Changed description
2407        );
2408
2409        assert_ne!(schema1.self_hash, schema2.self_hash, "self_hash should change when methods change");
2410        assert_eq!(schema1.children_hash, schema2.children_hash, "children_hash should stay same (both None)");
2411        assert_ne!(schema1.hash, schema2.hash, "composite hash should change");
2412    }
2413
2414    #[test]
2415    fn test_children_hash_changes_on_child_change() {
2416        let child1 = ChildSummary {
2417            namespace: "child".into(),
2418            description: "desc".into(),
2419            hash: "old_hash".into(),
2420        };
2421
2422        let child2 = ChildSummary {
2423            namespace: "child".into(),
2424            description: "desc".into(),
2425            hash: "new_hash".into(),
2426        };
2427
2428        let schema1 = PluginSchema::hub(
2429            "parent",
2430            "1.0",
2431            "desc",
2432            vec![],
2433            vec![child1],
2434        );
2435
2436        let schema2 = PluginSchema::hub(
2437            "parent",
2438            "1.0",
2439            "desc",
2440            vec![],
2441            vec![child2],
2442        );
2443
2444        assert_eq!(schema1.self_hash, schema2.self_hash, "self_hash should stay same (no methods changed)");
2445        assert_ne!(schema1.children_hash, schema2.children_hash, "children_hash should change when child hash changes");
2446        assert_ne!(schema1.hash, schema2.hash, "composite hash should change");
2447    }
2448
2449    #[test]
2450    fn test_leaf_has_no_children_hash() {
2451        let schema = PluginSchema::leaf(
2452            "leaf",
2453            "1.0",
2454            "desc",
2455            vec![MethodSchema::new("method", "desc", "hash")],
2456        );
2457
2458        assert!(schema.children_hash.is_none(), "leaf plugin should have None for children_hash");
2459        assert_ne!(schema.self_hash, schema.hash, "leaf plugin's composite hash is hash(self_hash), not equal to self_hash");
2460    }
2461
2462    // =========================================================================
2463    // RETURNS-10: content hashes and the SHA-256 roll-up
2464    // =========================================================================
2465
2466    fn sample_method() -> MethodSchema {
2467        MethodSchema::new("get", "Fetch one", "")
2468            .with_returns(serde_json::from_value(serde_json::json!({
2469                "title": "Item", "type": "object",
2470                "properties": {"id": {"type": "string"}}, "required": ["id"]
2471            })).unwrap())
2472    }
2473
2474    #[test]
2475    fn returns10_content_hash_is_sha256_of_canonical_json_without_hash() {
2476        let m = sample_method();
2477        let mut v = serde_json::to_value(&m).unwrap();
2478        v.as_object_mut().unwrap().remove("hash");
2479        assert_eq!(m.content_hash(), hash16(canonical_json(&v).as_bytes()));
2480        assert_eq!(m.content_hash().len(), 16);
2481        // `hash` itself is not covered: sealing twice is a no-op.
2482        let sealed = m.clone().with_content_hash();
2483        assert_eq!(sealed.hash, m.content_hash());
2484        assert_eq!(sealed.clone().with_content_hash().hash, sealed.hash);
2485        let other_hash = MethodSchema { hash: "anything".into(), ..m.clone() };
2486        assert_eq!(other_hash.content_hash(), m.content_hash());
2487    }
2488
2489    #[test]
2490    fn returns10_content_hash_ignores_key_order_on_the_wire() {
2491        let m = sample_method().with_content_hash();
2492        let wire = serde_json::to_string(&m).unwrap();
2493        // The same method, its keys written in another order.
2494        let reordered: MethodSchema = serde_json::from_str(
2495            r#"{"returns":{"required":["id"],"properties":{"id":{"type":"string"}},"type":"object","title":"Item"},
2496                "cardinality":"one","role":{"kind":"rpc"},"http_method":"POST","bidirectional":false,
2497                "hash":"ignored","description":"Fetch one","name":"get"}"#,
2498        ).unwrap();
2499        assert_eq!(reordered.content_hash(), m.hash, "wire: {wire}");
2500    }
2501
2502    #[test]
2503    fn returns10_content_hash_moves_with_any_field() {
2504        let base = sample_method().content_hash();
2505        let variants = [
2506            ("description", MethodSchema { description: "Fetch two".into(), ..sample_method() }),
2507            ("name", MethodSchema { name: "fetch".into(), ..sample_method() }),
2508            ("cardinality", sample_method().with_cardinality(Cardinality::Many)),
2509            ("returns field", sample_method().with_returns(serde_json::from_value(serde_json::json!({
2510                "title": "Item", "type": "object",
2511                "properties": {"id": {"type": "integer"}}, "required": ["id"]
2512            })).unwrap())),
2513            ("error", sample_method().with_error(serde_json::from_value(serde_json::json!({"title": "E"})).unwrap())),
2514            ("progress", sample_method().with_progress(serde_json::from_value(serde_json::json!({"title": "P"})).unwrap())),
2515            ("http method", sample_method().with_http_method(HttpMethod::Get)),
2516            ("role", sample_method().with_role(MethodRole::StaticChild)),
2517        ];
2518        let mut seen = std::collections::HashSet::from([base.clone()]);
2519        for (what, m) in variants {
2520            assert!(seen.insert(m.content_hash()), "{what}: the hash moved to a new value");
2521        }
2522    }
2523
2524    /// RETURNS-36 (review #11): the `schema` entry is known by what every
2525    /// 0.8.x build writes alike — not by a hash recomputed with this build,
2526    /// which a peer whose plexus-core differs by a patch (a doc comment in
2527    /// `SchemaResult`, say) does not share.
2528    #[test]
2529    fn the_schema_entry_is_known_across_patches() {
2530        let ours = MethodSchema::auto_schema().with_grant("echo.schema").with_content_hash();
2531        assert!(ours.is_auto_schema());
2532        // Another patch's: the same entry, its `returns` documented otherwise.
2533        let mut theirs = MethodSchema::auto_schema().with_grant("echo.schema");
2534        let mut returns = serde_json::to_value(&theirs.returns).unwrap();
2535        returns["description"] = serde_json::json!("another patch's words");
2536        theirs.returns = serde_json::from_value(returns).unwrap();
2537        let theirs = theirs.with_content_hash();
2538        assert_ne!(theirs.hash, ours.hash);
2539        assert!(theirs.is_auto_schema(), "a 0.8.x peer's schema entry, another patch");
2540        // A method named `schema` that is not the entry: other params.
2541        let user = MethodSchema::new("schema", "mine", "").with_params(schema_for!(String)).with_content_hash();
2542        assert!(!user.is_auto_schema());
2543    }
2544
2545    #[test]
2546    fn returns10_rollup_is_sha256_of_the_hashes_one_per_line() {
2547        let a = MethodSchema::new("a", "", "aaaaaaaaaaaaaaaa");
2548        let b = MethodSchema::new("b", "", "bbbbbbbbbbbbbbbb");
2549        let leaf = PluginSchema::leaf("p", "1", "", vec![a.clone(), b.clone()]);
2550        assert_eq!(leaf.self_hash, hash16(b"aaaaaaaaaaaaaaaa\nbbbbbbbbbbbbbbbb\n"));
2551        assert_eq!(leaf.hash, hash16(format!("{}\n", leaf.self_hash).as_bytes()));
2552        assert_eq!(leaf.children_hash, None);
2553
2554        let kid = ChildSummary { namespace: "k".into(), description: "".into(), hash: "cccccccccccccccc".into() };
2555        let service = PluginSchema::hub("p", "1", "", vec![a, b], vec![kid]);
2556        assert_eq!(service.self_hash, leaf.self_hash, "children don't touch self_hash");
2557        let children_hash = hash16(b"cccccccccccccccc\n");
2558        assert_eq!(service.children_hash.as_deref(), Some(children_hash.as_str()));
2559        assert_eq!(service.hash, hash16(format!("{}\n{}\n", service.self_hash, children_hash).as_bytes()));
2560        // Pinned (computed independently with Python's hashlib): the roll-up
2561        // is a wire contract — synapse-cc locks compare it across machines —
2562        // so its bytes may not drift.
2563        assert_eq!(
2564            (leaf.self_hash.as_str(), leaf.hash.as_str(), service.hash.as_str()),
2565            ("4140cd727c96fc78", "03a069b51ff1b744", "22db23bea1fbad28")
2566        );
2567        assert_eq!(children_hash, "f631be22675d9426");
2568    }
2569
2570    // =========================================================================
2571    // IR-2 tests: MethodRole, DeprecationInfo, is_hub derived query
2572    // =========================================================================
2573
2574    /// AC #5: Deserializing a JSON `MethodSchema` with no `role` or
2575    /// `deprecation` fields yields `MethodRole::Rpc` and `None`.
2576    ///
2577    /// 0.7 (RETURNS-5): the minimal method carries the two required fields,
2578    /// `returns` and `cardinality`; everything else still defaults.
2579    #[test]
2580    fn ir2_default_role_is_rpc_on_deserialize() {
2581        // Minimal MethodSchema shape (no role, no deprecation, no error/progress)
2582        let pre_ir_json = serde_json::json!({
2583            "name": "ping",
2584            "description": "pong",
2585            "hash": "abc",
2586            "returns": {},
2587            "cardinality": "one"
2588        });
2589
2590        let schema: MethodSchema = serde_json::from_value(pre_ir_json).unwrap();
2591        assert_eq!(schema.role, MethodRole::Rpc);
2592        assert!(schema.deprecation.is_none());
2593        assert!(schema.error.is_none());
2594        assert!(schema.progress.is_none());
2595    }
2596
2597    /// AC #5: And at the PluginSchema level — a full pre-IR schema with
2598    /// multiple methods (none carrying `role`) deserializes cleanly with every
2599    /// method defaulted to `Rpc` and no deprecation.
2600    #[test]
2601    fn ir2_plugin_schema_pre_ir_json_deserializes() {
2602        let pre_ir_json = serde_json::json!({
2603            "namespace": "test",
2604            "version": "1.0",
2605            "description": "legacy schema",
2606            "self_hash": "s1",
2607            "hash": "h1",
2608            "methods": [
2609                { "name": "a", "description": "alpha", "hash": "ah", "returns": {}, "cardinality": "one" },
2610                { "name": "b", "description": "beta",  "hash": "bh", "returns": {}, "cardinality": "many" }
2611            ]
2612        });
2613
2614        let schema: PluginSchema = serde_json::from_value(pre_ir_json).unwrap();
2615        assert_eq!(schema.methods.len(), 2);
2616        for m in &schema.methods {
2617            assert_eq!(m.role, MethodRole::Rpc);
2618            assert!(m.deprecation.is_none());
2619        }
2620    }
2621
2622    /// AC #6: Serde round-trip covering all `MethodRole` variants —
2623    /// `Rpc`, `StaticChild`, and `DynamicChild { list_method, search_method }`.
2624    #[test]
2625    fn ir2_method_role_roundtrip_all_variants() {
2626        let original = PluginSchema::leaf(
2627            "rt",
2628            "1.0",
2629            "round-trip coverage",
2630            vec![
2631                MethodSchema::new("plain", "rpc", "h1"),
2632                MethodSchema::new("child_a", "static", "h2")
2633                    .with_role(MethodRole::StaticChild),
2634                MethodSchema::new("child_b", "dynamic", "h3").with_role(
2635                    MethodRole::DynamicChild {
2636                        list_method: Some("list_x".into()),
2637                        search_method: Some("search_x".into()),
2638                        child: None,
2639                    },
2640                ),
2641            ],
2642        );
2643
2644        let json = serde_json::to_string(&original).unwrap();
2645        let decoded: PluginSchema = serde_json::from_str(&json).unwrap();
2646
2647        assert_eq!(decoded.methods[0].role, MethodRole::Rpc);
2648        assert_eq!(decoded.methods[1].role, MethodRole::StaticChild);
2649        assert_eq!(
2650            decoded.methods[2].role,
2651            MethodRole::DynamicChild {
2652                list_method: Some("list_x".into()),
2653                search_method: Some("search_x".into()),
2654                child: None,
2655            }
2656        );
2657
2658        // Also survives when the DynamicChild has no list/search hints.
2659        let bare_dyn = MethodSchema::new("child_c", "dynamic-bare", "h4").with_role(
2660            MethodRole::DynamicChild {
2661                list_method: None,
2662                search_method: None,
2663                child: None,
2664            },
2665        );
2666        let j2 = serde_json::to_string(&bare_dyn).unwrap();
2667        let d2: MethodSchema = serde_json::from_str(&j2).unwrap();
2668        assert_eq!(
2669            d2.role,
2670            MethodRole::DynamicChild {
2671                list_method: None,
2672                search_method: None,
2673                child: None,
2674            }
2675        );
2676    }
2677
2678    /// AC #7: Serde round-trip for `DeprecationInfo` on a `MethodSchema`.
2679    #[test]
2680    fn ir2_deprecation_info_roundtrip() {
2681        let info = DeprecationInfo {
2682            since: "0.5".into(),
2683            removed_in: "0.6".into(),
2684            message: "use MethodRole".into(),
2685        };
2686        let method = MethodSchema::new("old", "legacy method", "hx")
2687            .with_deprecation(info.clone());
2688
2689        let json = serde_json::to_string(&method).unwrap();
2690        let decoded: MethodSchema = serde_json::from_str(&json).unwrap();
2691
2692        assert_eq!(decoded.deprecation, Some(info));
2693    }
2694
2695    /// AC #4: `PluginSchema::is_hub_by_role()` — the derived query reads only
2696    /// `methods`, not the legacy `children` field.
2697    ///
2698    /// Covers every row of the acceptance-criteria table.
2699    #[test]
2700    fn ir2_is_hub_by_role_derived_query() {
2701        // Row 1: all Rpc → false
2702        let all_rpc = PluginSchema::leaf(
2703            "p",
2704            "1.0",
2705            "all rpc",
2706            vec![
2707                MethodSchema::new("a", "d", "h1"),
2708                MethodSchema::new("b", "d", "h2"),
2709            ],
2710        );
2711        assert!(!all_rpc.is_hub_by_role());
2712        // And the back-compat `is_hub()` also returns false (no children).
2713        assert!(!all_rpc.is_hub());
2714
2715        // Row 2: at least one StaticChild → true
2716        let static_child = PluginSchema::leaf(
2717            "p",
2718            "1.0",
2719            "has static child",
2720            vec![
2721                MethodSchema::new("a", "d", "h1"),
2722                MethodSchema::new("kid", "d", "h2").with_role(MethodRole::StaticChild),
2723            ],
2724        );
2725        assert!(static_child.is_hub_by_role());
2726        assert!(static_child.is_hub());
2727
2728        // Row 3: at least one DynamicChild → true
2729        let dyn_child = PluginSchema::leaf(
2730            "p",
2731            "1.0",
2732            "has dynamic child",
2733            vec![MethodSchema::new("find", "d", "h1").with_role(
2734                MethodRole::DynamicChild {
2735                    list_method: None,
2736                    search_method: None,
2737                    child: None,
2738                },
2739            )],
2740        );
2741        assert!(dyn_child.is_hub_by_role());
2742        assert!(dyn_child.is_hub());
2743
2744        // Row 4: Mix of Rpc + StaticChild → true
2745        let mixed = PluginSchema::leaf(
2746            "p",
2747            "1.0",
2748            "mixed",
2749            vec![
2750                MethodSchema::new("a", "d", "h1"),
2751                MethodSchema::new("b", "d", "h2"),
2752                MethodSchema::new("k", "d", "h3").with_role(MethodRole::StaticChild),
2753            ],
2754        );
2755        assert!(mixed.is_hub_by_role());
2756        assert!(mixed.is_hub());
2757
2758        // Row 5: empty methods → false
2759        let empty = PluginSchema::leaf("p", "1.0", "empty", vec![]);
2760        assert!(!empty.is_hub_by_role());
2761        assert!(!empty.is_hub());
2762    }
2763
2764    /// The derived query is independent of the legacy `children` side channel
2765    /// — a `PluginSchema::hub(...)` with only `Rpc` methods reports
2766    /// `is_hub_by_role() == false` (children don't count) while `is_hub()` is
2767    /// still `true` (transition-window fallback).
2768    #[test]
2769    fn ir2_is_hub_by_role_ignores_children_field() {
2770        let hub_with_rpc_only = PluginSchema::hub(
2771            "h",
2772            "1.0",
2773            "transition",
2774            vec![MethodSchema::new("a", "d", "ah")],
2775            vec![ChildSummary {
2776                namespace: "kid".into(),
2777                description: "child".into(),
2778                hash: "kh".into(),
2779            }],
2780        );
2781
2782        // The derived query reads only methods — no child role → false.
2783        assert!(!hub_with_rpc_only.is_hub_by_role());
2784        // Back-compat `is_hub()` still reports true via the children fallback.
2785        assert!(hub_with_rpc_only.is_hub());
2786    }
2787
2788    // =========================================================================
2789    // RETURNS-5 tests: schema 0.7 — returns · error · progress · cardinality
2790    // =========================================================================
2791
2792    fn returns_5_full_method() -> MethodSchema {
2793        MethodSchema::new("import", "imports tickets", "h_import")
2794            .with_returns(schemars::json_schema!({ "type": "string", "title": "Summary" }))
2795            .with_error(schemars::json_schema!({ "type": "object", "title": "ImportError" }))
2796            .with_progress(schemars::json_schema!({ "type": "integer", "title": "Step" }))
2797            .with_cardinality(Cardinality::Many)
2798    }
2799
2800    /// AC #1: a method with all four fields round-trips through serde, with
2801    /// the names and spellings of the 0.7 table.
2802    #[test]
2803    fn returns_5_all_four_fields_roundtrip() {
2804        let method = returns_5_full_method();
2805        let json = serde_json::to_value(&method).unwrap();
2806        let obj = json.as_object().unwrap();
2807
2808        assert_eq!(obj["returns"], serde_json::json!({ "type": "string", "title": "Summary" }));
2809        assert_eq!(obj["error"], serde_json::json!({ "type": "object", "title": "ImportError" }));
2810        assert_eq!(obj["progress"], serde_json::json!({ "type": "integer", "title": "Step" }));
2811        assert_eq!(obj["cardinality"], serde_json::json!("many"));
2812
2813        let decoded: MethodSchema = serde_json::from_value(json.clone()).unwrap();
2814        assert_eq!(decoded.returns, method.returns);
2815        assert_eq!(decoded.error, method.error);
2816        assert_eq!(decoded.progress, method.progress);
2817        assert_eq!(decoded.cardinality, Cardinality::Many);
2818        assert_eq!(serde_json::to_value(&decoded).unwrap(), json);
2819    }
2820
2821    /// AC #1: `error` and `progress` are absent — not `null` — when `None`;
2822    /// `returns` and `cardinality` are always present.
2823    #[test]
2824    fn returns_5_error_and_progress_absent_when_none() {
2825        let method = MethodSchema::new("get", "gets a ticket", "h_get")
2826            .with_returns(schemars::json_schema!({ "type": "string" }));
2827        let json = serde_json::to_value(&method).unwrap();
2828        let obj = json.as_object().unwrap();
2829
2830        assert!(!obj.contains_key("error"), "error must be omitted when None, got {json}");
2831        assert!(!obj.contains_key("progress"), "progress must be omitted when None, got {json}");
2832        assert_eq!(obj["returns"], serde_json::json!({ "type": "string" }));
2833        assert_eq!(obj["cardinality"], serde_json::json!("one"));
2834
2835        let decoded: MethodSchema = serde_json::from_value(json).unwrap();
2836        assert!(decoded.error.is_none());
2837        assert!(decoded.progress.is_none());
2838        assert_eq!(decoded.cardinality, Cardinality::One);
2839    }
2840
2841    /// `MethodSchema::new` starts as one item of any value, infallible and
2842    /// progress-free.
2843    #[test]
2844    fn returns_5_new_defaults() {
2845        let method = MethodSchema::new("ping", "pong", "h_ping");
2846        assert_eq!(method.returns, schemars::Schema::default());
2847        assert!(method.error.is_none());
2848        assert!(method.progress.is_none());
2849        assert_eq!(method.cardinality, Cardinality::One);
2850        assert_eq!(
2851            serde_json::to_value(&method).unwrap()["returns"],
2852            serde_json::json!({})
2853        );
2854    }
2855
2856    /// `Cardinality` spells `"one"` / `"many"` both ways and rejects anything else.
2857    #[test]
2858    fn returns_5_cardinality_spelling() {
2859        for (c, s) in [(Cardinality::One, "\"one\""), (Cardinality::Many, "\"many\"")] {
2860            assert_eq!(serde_json::to_string(&c).unwrap(), s);
2861            assert_eq!(serde_json::from_str::<Cardinality>(s).unwrap(), c);
2862        }
2863        assert!(serde_json::from_str::<Cardinality>("\"One\"").is_err());
2864        assert!(serde_json::from_str::<Cardinality>("true").is_err());
2865    }
2866
2867    /// `returns` and `cardinality` are required: a 0.6-shaped method (no
2868    /// `cardinality`, or no `returns`) does not parse.
2869    #[test]
2870    fn returns_5_required_fields_reject_0_6_shape() {
2871        let no_cardinality = serde_json::json!({
2872            "name": "ping", "description": "pong", "hash": "h",
2873            "returns": {}, "bidirectional": false
2874        });
2875        assert!(serde_json::from_value::<MethodSchema>(no_cardinality).is_err());
2876
2877        let no_returns = serde_json::json!({
2878            "name": "ping", "description": "pong", "hash": "h",
2879            "cardinality": "one"
2880        });
2881        assert!(serde_json::from_value::<MethodSchema>(no_returns).is_err());
2882    }
2883
2884    /// The fields sit where `returns` / the old flag sat: after `params`,
2885    /// before `http_method` (where `bidirectional` sat until ASK-1) — every
2886    /// other field keeps its place on the wire.
2887    #[test]
2888    fn returns_5_field_order_on_the_wire() {
2889        let method = returns_5_full_method()
2890            .with_params(schemars::json_schema!({ "type": "object" }));
2891        let text = serde_json::to_string(&method).unwrap();
2892        let pos = |k: &str| text.find(&format!("\"{k}\":")).unwrap_or_else(|| panic!("{k} missing in {text}"));
2893        let order = ["name", "description", "hash", "params", "returns", "error", "progress", "cardinality", "http_method", "role"];
2894        for pair in order.windows(2) {
2895            assert!(pos(pair[0]) < pos(pair[1]), "{} must precede {} in {text}", pair[0], pair[1]);
2896        }
2897    }
2898
2899    // =========================================================================
2900    // IR-4 tests: derive_legacy_fields, relaxed validate_no_collisions,
2901    // deprecation markers.
2902    // =========================================================================
2903
2904    /// AC #4 (row 1): empty method list → no children, not a hub.
2905    #[test]
2906    fn ir4_derive_empty_methods() {
2907        let (children, is_hub) = PluginSchema::derive_legacy_fields(&[]);
2908        assert!(children.is_empty());
2909        assert!(!is_hub);
2910    }
2911
2912    /// AC #4 (row 2): a single `Rpc` method → no children, not a hub.
2913    #[test]
2914    fn ir4_derive_single_rpc_method() {
2915        let methods = vec![MethodSchema::new("ping", "rpc method", "h1")];
2916        let (children, is_hub) = PluginSchema::derive_legacy_fields(&methods);
2917        assert!(children.is_empty());
2918        assert!(!is_hub);
2919    }
2920
2921    /// AC #4 (row 3): one `StaticChild` method named "body" → one child named
2922    /// "body", `is_hub == true`.
2923    #[test]
2924    fn ir4_derive_single_static_child() {
2925        let methods = vec![
2926            MethodSchema::new("body", "static child", "h1")
2927                .with_role(MethodRole::StaticChild),
2928        ];
2929        let (children, is_hub) = PluginSchema::derive_legacy_fields(&methods);
2930        assert_eq!(children.len(), 1);
2931        assert_eq!(children[0].namespace, "body");
2932        assert_eq!(children[0].description, "static child");
2933        assert_eq!(children[0].hash, "");
2934        assert!(is_hub);
2935    }
2936
2937    /// AC #4 (row 4): one `DynamicChild` method named "planet" → one child
2938    /// named "planet", `is_hub == true`.
2939    #[test]
2940    fn ir4_derive_single_dynamic_child() {
2941        let methods = vec![
2942            MethodSchema::new("planet", "dynamic child", "h1").with_role(
2943                MethodRole::DynamicChild {
2944                    list_method: Some("list_planets".into()),
2945                    search_method: None,
2946                    child: None,
2947                },
2948            ),
2949        ];
2950        let (children, is_hub) = PluginSchema::derive_legacy_fields(&methods);
2951        assert_eq!(children.len(), 1);
2952        assert_eq!(children[0].namespace, "planet");
2953        assert!(is_hub);
2954    }
2955
2956    /// AC #4 (row 5): mix of Rpc + StaticChild → one child, `is_hub == true`.
2957    #[test]
2958    fn ir4_derive_mixed_roles_preserves_order() {
2959        let methods = vec![
2960            MethodSchema::new("ping", "rpc", "h1"),
2961            MethodSchema::new("kid_a", "static a", "h2")
2962                .with_role(MethodRole::StaticChild),
2963            MethodSchema::new("describe", "rpc too", "h3"),
2964            MethodSchema::new("kid_b", "static b", "h4")
2965                .with_role(MethodRole::StaticChild),
2966        ];
2967        let (children, is_hub) = PluginSchema::derive_legacy_fields(&methods);
2968        // Source-order preservation: kid_a appears before kid_b.
2969        assert_eq!(children.len(), 2);
2970        assert_eq!(children[0].namespace, "kid_a");
2971        assert_eq!(children[1].namespace, "kid_b");
2972        assert!(is_hub);
2973    }
2974
2975    /// IR-4: `derive_legacy_fields`'s `is_hub` result matches
2976    /// [`PluginSchema::is_hub_by_role`] on every method list covered by the
2977    /// acceptance-criteria table.
2978    #[test]
2979    fn ir4_derive_is_hub_matches_is_hub_by_role() {
2980        // Empty methods.
2981        let empty_schema = PluginSchema::leaf("t", "1.0", "d", vec![]);
2982        let (_, is_hub) = PluginSchema::derive_legacy_fields(&empty_schema.methods);
2983        assert_eq!(is_hub, empty_schema.is_hub_by_role());
2984
2985        // All-Rpc methods.
2986        let rpc_schema = PluginSchema::leaf(
2987            "t",
2988            "1.0",
2989            "d",
2990            vec![
2991                MethodSchema::new("a", "d", "h1"),
2992                MethodSchema::new("b", "d", "h2"),
2993            ],
2994        );
2995        let (_, is_hub) = PluginSchema::derive_legacy_fields(&rpc_schema.methods);
2996        assert_eq!(is_hub, rpc_schema.is_hub_by_role());
2997
2998        // StaticChild present.
2999        let static_schema = PluginSchema::leaf(
3000            "t",
3001            "1.0",
3002            "d",
3003            vec![
3004                MethodSchema::new("a", "d", "h1"),
3005                MethodSchema::new("kid", "d", "h2").with_role(MethodRole::StaticChild),
3006            ],
3007        );
3008        let (_, is_hub) = PluginSchema::derive_legacy_fields(&static_schema.methods);
3009        assert_eq!(is_hub, static_schema.is_hub_by_role());
3010        assert!(is_hub);
3011
3012        // DynamicChild present.
3013        let dyn_schema = PluginSchema::leaf(
3014            "t",
3015            "1.0",
3016            "d",
3017            vec![MethodSchema::new("find", "d", "h1").with_role(
3018                MethodRole::DynamicChild {
3019                    list_method: None,
3020                    search_method: None,
3021                    child: None,
3022                },
3023            )],
3024        );
3025        let (_, is_hub) = PluginSchema::derive_legacy_fields(&dyn_schema.methods);
3026        assert_eq!(is_hub, dyn_schema.is_hub_by_role());
3027        assert!(is_hub);
3028    }
3029
3030    /// IR-4 rule 2: `validate_no_collisions` no longer panics when a
3031    /// `StaticChild`-role method shares its name with a `ChildSummary` —
3032    /// that's expected by construction (two wire representations of the
3033    /// same child).
3034    #[test]
3035    fn ir4_no_collision_static_child_method_vs_summary() {
3036        // Same name on both surfaces — used to panic, now accepted.
3037        let schema = PluginSchema::hub(
3038            "hub",
3039            "1.0",
3040            "has static child",
3041            vec![
3042                MethodSchema::new("ping", "rpc", "h1"),
3043                MethodSchema::new("kid", "static child", "h2")
3044                    .with_role(MethodRole::StaticChild),
3045            ],
3046            vec![ChildSummary {
3047                namespace: "kid".into(),
3048                description: "static child".into(),
3049                hash: "kh".into(),
3050            }],
3051        );
3052        // Child stayed on the wire.
3053        #[allow(deprecated)]
3054        let kids = schema.children.as_ref().expect("hub has children");
3055        assert_eq!(kids.len(), 1);
3056        assert_eq!(kids[0].namespace, "kid");
3057        // Method kept its role tag.
3058        assert!(matches!(
3059            schema.methods.iter().find(|m| m.name == "kid").unwrap().role,
3060            MethodRole::StaticChild
3061        ));
3062    }
3063
3064    /// IR-4 rule 2: `validate_no_collisions` also tolerates DynamicChild-role
3065    /// method names that appear in the child summary list.
3066    #[test]
3067    fn ir4_no_collision_dynamic_child_method_vs_summary() {
3068        let schema = PluginSchema::hub(
3069            "hub",
3070            "1.0",
3071            "has dynamic child",
3072            vec![MethodSchema::new("body", "gate", "h1").with_role(
3073                MethodRole::DynamicChild {
3074                    list_method: Some("body_names".into()),
3075                    search_method: None,
3076                    child: None,
3077                },
3078            )],
3079            vec![ChildSummary {
3080                namespace: "body".into(),
3081                description: "gate".into(),
3082                hash: "bh".into(),
3083            }],
3084        );
3085        #[allow(deprecated)]
3086        let kids = schema.children.as_ref().unwrap();
3087        assert_eq!(kids.len(), 1);
3088    }
3089
3090    /// IR-4 rule 2: `validate_no_collisions` still panics when an `Rpc`-role
3091    /// method's name collides with a child summary — that's the case the
3092    /// validation was designed to catch.
3093    #[test]
3094    #[should_panic(expected = "method/child collision")]
3095    fn ir4_collision_rpc_method_vs_summary_still_panics() {
3096        let _ = PluginSchema::hub(
3097            "hub",
3098            "1.0",
3099            "bad hub",
3100            vec![MethodSchema::new("oops", "rpc", "h1")],
3101            vec![ChildSummary {
3102                namespace: "oops".into(),
3103                description: "shadowed".into(),
3104                hash: "oh".into(),
3105            }],
3106        );
3107    }
3108
3109    /// IR-4 AC #3 (spec): reading `PluginSchema.children` outside a
3110    /// `#[allow(deprecated)]` block emits a compiler warning. This fixture
3111    /// uses `#[allow(deprecated)]` to confirm the attribute is required —
3112    /// if it weren't, the `#[deprecated]` annotation is either missing or
3113    /// wrong.
3114    #[test]
3115    fn ir4_deprecated_field_access_requires_allow_attribute() {
3116        let schema = PluginSchema::leaf(
3117            "t",
3118            "1.0",
3119            "d",
3120            vec![MethodSchema::new("a", "b", "h")],
3121        );
3122        // Reading the deprecated field — under `#[allow(deprecated)]` from
3123        // the module-level attribute on the tests module. Removing that
3124        // allow would produce a compiler warning pointing at this line.
3125        let _children = schema.children.clone();
3126        // Calling the deprecated method — same rationale.
3127        let _is_hub = schema.is_hub();
3128    }
3129
3130    /// AUTHZ-CRED-CORE-2 AC #8: `PluginSchema::leaf` runs the
3131    /// schema-build warning hook for the framework-reserved
3132    /// `_credentials` top-level field name. The hook itself emits a
3133    /// `tracing::warn!` line, which is not directly assertable here
3134    /// without a tracing subscriber; we exercise the predicate path
3135    /// through schema construction (no panic, schema still constructed)
3136    /// and assert that the underlying check function is wired in.
3137    #[test]
3138    fn cred_core_2_ac8_leaf_constructor_does_not_panic_on_collision() {
3139        // Build a returns schema with a top-level `_credentials` field —
3140        // the framework-reserved name.
3141        let returns_collision_schema: schemars::Schema = serde_json::from_value(
3142            serde_json::json!({
3143                "type": "object",
3144                "properties": {
3145                    "user_id":      { "type": "string" },
3146                    "_credentials": { "type": "object" }
3147                }
3148            }),
3149        )
3150        .unwrap();
3151
3152        // The leaf constructor consults the warning hook but does NOT
3153        // fail — the field is shadowed at dispatch time, and the
3154        // warning is the user-visible diagnostic. Constructing the
3155        // schema must still succeed (additive behavior).
3156        let schema = PluginSchema::leaf(
3157            "auth",
3158            "1.0",
3159            "test",
3160            vec![MethodSchema::new("login", "logs in", "h1").with_returns(returns_collision_schema)],
3161        );
3162        // Plugin still built.
3163        assert_eq!(schema.namespace, "auth");
3164        assert_eq!(schema.methods.len(), 1);
3165
3166        // And the inverse: a schema without the collision does not
3167        // panic either.
3168        let no_collision_schema: schemars::Schema = serde_json::from_value(
3169            serde_json::json!({ "type": "object", "properties": { "user_id": { "type": "string" } } }),
3170        )
3171        .unwrap();
3172        let schema_clean = PluginSchema::leaf(
3173            "auth",
3174            "1.0",
3175            "test",
3176            vec![MethodSchema::new("ping", "pings", "h2").with_returns(no_collision_schema)],
3177        );
3178        assert_eq!(schema_clean.methods.len(), 1);
3179    }
3180
3181    /// IR-4 AC #8: `PluginSchema.is_hub()` (deprecated) and
3182    /// `PluginSchema::is_hub_by_role()` agree on every shape currently
3183    /// emitted by substrate activations (methods with role tags, children
3184    /// field populated via hub constructor).
3185    #[test]
3186    fn ir4_is_hub_and_is_hub_by_role_agree_on_role_tagged_methods() {
3187        // Pure-leaf, all Rpc: both false.
3188        let leaf = PluginSchema::leaf(
3189            "t",
3190            "1.0",
3191            "d",
3192            vec![MethodSchema::new("a", "d", "h1")],
3193        );
3194        assert_eq!(leaf.is_hub(), leaf.is_hub_by_role());
3195        assert!(!leaf.is_hub());
3196
3197        // Hub with role-tagged methods (today's post-IR-3 shape): both true.
3198        let hub_with_roles = PluginSchema::hub(
3199            "h",
3200            "1.0",
3201            "d",
3202            vec![MethodSchema::new("kid", "d", "h1").with_role(MethodRole::StaticChild)],
3203            vec![ChildSummary {
3204                namespace: "kid".into(),
3205                description: "d".into(),
3206                hash: "".into(),
3207            }],
3208        );
3209        assert_eq!(hub_with_roles.is_hub(), hub_with_roles.is_hub_by_role());
3210        assert!(hub_with_roles.is_hub());
3211    }
3212
3213    // =========================================================================
3214    // AUTHZ-CRED-CORE-3 tests: CredentialFieldDecl, RequiredCredential,
3215    // MethodSchema.credentials / .requires_credential projections.
3216    // =========================================================================
3217
3218    use plexus_auth_core::{
3219        AttachmentSite, CredentialFieldMarker, CredentialIssuer, CredentialKind,
3220        CredentialMetadata, CredentialScheme, HeaderName, MethodPath, Origin, Scope,
3221    };
3222
3223    fn sample_issuer() -> CredentialIssuer {
3224        CredentialIssuer::new(
3225            Origin::new("ws://localhost:4444"),
3226            MethodPath::try_new("auth.login").unwrap(),
3227        )
3228    }
3229
3230    fn sample_marker_single() -> CredentialFieldMarker {
3231        CredentialFieldMarker::new(
3232            None,
3233            "session",
3234            CredentialKind::Bearer,
3235            AttachmentSite::Header {
3236                name: HeaderName::try_new("authorization").unwrap(),
3237            },
3238            Some(CredentialScheme::new("Bearer ")),
3239            vec![Scope::new("cone.send_message")],
3240            Some(MethodPath::try_new("auth.refresh").unwrap()),
3241            Some(MethodPath::try_new("auth.logout").unwrap()),
3242        )
3243    }
3244
3245    /// AC #1: A method whose return type contains one `Credential<T>` field
3246    /// produces a `MethodSchema` whose `credentials` field has one
3247    /// `CredentialFieldDecl` entry with the correct field path and metadata.
3248    #[test]
3249    fn cred_core_3_ac1_single_credential_projection() {
3250        let marker = sample_marker_single();
3251        let decl = CredentialFieldDecl::from_marker(&marker, &[], sample_issuer());
3252
3253        // Field path is the marker's single field name.
3254        assert_eq!(decl.field_path, vec!["session".to_string()]);
3255        // No variant tag for a struct return type.
3256        assert!(decl.variant_tag.is_none());
3257        // Metadata composes correctly from the marker.
3258        assert_eq!(decl.metadata.kind, CredentialKind::Bearer);
3259        assert_eq!(
3260            decl.metadata.attach_as,
3261            AttachmentSite::Header {
3262                name: HeaderName::try_new("authorization").unwrap(),
3263            }
3264        );
3265        assert_eq!(decl.metadata.scheme, Some(CredentialScheme::new("Bearer ")));
3266        assert_eq!(decl.metadata.scopes, vec![Scope::new("cone.send_message")]);
3267        assert_eq!(
3268            decl.metadata.refresh_via,
3269            Some(MethodPath::try_new("auth.refresh").unwrap())
3270        );
3271        assert_eq!(
3272            decl.metadata.revoke_via,
3273            Some(MethodPath::try_new("auth.logout").unwrap())
3274        );
3275        assert_eq!(decl.metadata.issuer, sample_issuer());
3276
3277        // Project into a MethodSchema and confirm the field is populated.
3278        let method = MethodSchema::new("login", "logs in", "h_login").with_credentials(vec![decl]);
3279        assert_eq!(method.credentials.len(), 1);
3280        assert_eq!(method.credentials[0].field_path, vec!["session".to_string()]);
3281    }
3282
3283    /// AC #2: A method whose return type contains multiple `Credential<T>`
3284    /// fields produces a `MethodSchema` whose `credentials` field has one
3285    /// entry per credential, in stable order.
3286    #[test]
3287    fn cred_core_3_ac2_multiple_credentials_stable_order() {
3288        let m1 = CredentialFieldMarker::new(
3289            None,
3290            "access",
3291            CredentialKind::OauthAccess,
3292            AttachmentSite::Header {
3293                name: HeaderName::try_new("authorization").unwrap(),
3294            },
3295            Some(CredentialScheme::new("Bearer ")),
3296            vec![Scope::new("cone.send")],
3297            Some(MethodPath::try_new("auth.refresh").unwrap()),
3298            None,
3299        );
3300        let m2 = CredentialFieldMarker::new(
3301            None,
3302            "refresh",
3303            CredentialKind::OauthRefresh,
3304            AttachmentSite::Header {
3305                name: HeaderName::try_new("authorization").unwrap(),
3306            },
3307            None,
3308            vec![Scope::new("auth.refresh")],
3309            None,
3310            None,
3311        );
3312
3313        let decls = vec![
3314            CredentialFieldDecl::from_marker(&m1, &[], sample_issuer()),
3315            CredentialFieldDecl::from_marker(&m2, &[], sample_issuer()),
3316        ];
3317        let method = MethodSchema::new("login", "logs in", "h_oauth").with_credentials(decls);
3318
3319        // Two entries, in declaration order.
3320        assert_eq!(method.credentials.len(), 2);
3321        assert_eq!(method.credentials[0].field_path, vec!["access".to_string()]);
3322        assert_eq!(method.credentials[0].metadata.kind, CredentialKind::OauthAccess);
3323        assert_eq!(method.credentials[1].field_path, vec!["refresh".to_string()]);
3324        assert_eq!(method.credentials[1].metadata.kind, CredentialKind::OauthRefresh);
3325    }
3326
3327    /// AC #3: A method whose return type is an enum with credentials only on
3328    /// one variant produces a `MethodSchema` with the correct `variant_tag`
3329    /// set on each entry.
3330    #[test]
3331    fn cred_core_3_ac3_enum_variant_tag_set() {
3332        let marker = CredentialFieldMarker::new(
3333            Some("Issued"),
3334            "session",
3335            CredentialKind::Bearer,
3336            AttachmentSite::Header {
3337                name: HeaderName::try_new("authorization").unwrap(),
3338            },
3339            Some(CredentialScheme::new("Bearer ")),
3340            vec![Scope::new("cone.send_message")],
3341            None,
3342            None,
3343        );
3344        let decl = CredentialFieldDecl::from_marker(&marker, &[], sample_issuer());
3345        assert_eq!(decl.variant_tag, Some("Issued".to_string()));
3346        assert_eq!(decl.field_path, vec!["session".to_string()]);
3347
3348        let method = MethodSchema::new("login", "logs in", "h_login").with_credentials(vec![decl]);
3349        assert_eq!(method.credentials[0].variant_tag, Some("Issued".to_string()));
3350    }
3351
3352    /// `CredentialFieldDecl::from_marker` honors a non-empty path prefix
3353    /// (nested-field walk).
3354    #[test]
3355    fn cred_core_3_from_marker_with_nested_path_prefix() {
3356        let marker = sample_marker_single();
3357        let decl = CredentialFieldDecl::from_marker(&marker, &["auth"], sample_issuer());
3358        assert_eq!(decl.field_path, vec!["auth".to_string(), "session".to_string()]);
3359    }
3360
3361    /// AC #4: A method tagged `#[plexus::method(public)]` produces a
3362    /// `MethodSchema` whose `requires_credential` is `None`.
3363    ///
3364    /// "Public" maps to "no implicit derivation occurs"; the schema-build
3365    /// surface simply doesn't call `with_requires_credential`, leaving the
3366    /// field at its `None` default.
3367    #[test]
3368    fn cred_core_3_ac4_public_method_requires_credential_none() {
3369        let method = MethodSchema::new("auth.login", "logs in", "h_login");
3370        assert!(method.requires_credential.is_none());
3371
3372        // After round-trip the field also serializes/deserializes as None
3373        // (omitted on the wire).
3374        let json = serde_json::to_value(&method).unwrap();
3375        assert!(
3376            !json
3377                .as_object()
3378                .unwrap()
3379                .contains_key("requires_credential"),
3380            "requires_credential must be omitted from wire JSON when None, got {json}"
3381        );
3382        let decoded: MethodSchema = serde_json::from_value(json).unwrap();
3383        assert!(decoded.requires_credential.is_none());
3384    }
3385
3386    /// AC #5: A method tagged with a scope produces a `MethodSchema` whose
3387    /// `requires_credential.scopes` contains that scope and whose
3388    /// `requires_credential.kind` is `None`.
3389    #[test]
3390    fn cred_core_3_ac5_scoped_method_implicit_requires_credential() {
3391        let req = RequiredCredential::from_method_scope(Scope::new("cone.send_message"));
3392        assert!(req.kind.is_none());
3393        assert_eq!(req.scopes, vec![Scope::new("cone.send_message")]);
3394        assert!(req.site_hint.is_none());
3395
3396        let method = MethodSchema::new("send", "sends a message", "h_send")
3397            .with_requires_credential(req.clone());
3398        assert_eq!(method.requires_credential.as_ref().unwrap(), &req);
3399    }
3400
3401    /// AC #6: A method whose path appears as the `refresh_via` or
3402    /// `revoke_via` of any credential in the schema produces a `MethodSchema`
3403    /// whose `requires_credential.kind` matches the issuing credential's
3404    /// kind.
3405    #[test]
3406    fn cred_core_3_ac6_refresh_target_narrows_kind() {
3407        // The OAuth refresh flow: the access credential carries
3408        // `refresh_via = auth.refresh`. The implicit-derivation rule
3409        // narrows the requires_credential of `auth.refresh` to
3410        // `OauthRefresh`.
3411        let req = RequiredCredential::from_refresh_revoke_target(
3412            CredentialKind::OauthRefresh,
3413            vec![Scope::new("auth.refresh")],
3414        );
3415        assert_eq!(req.kind, Some(CredentialKind::OauthRefresh));
3416        assert_eq!(req.scopes, vec![Scope::new("auth.refresh")]);
3417
3418        let refresh_method =
3419            MethodSchema::new("refresh", "refreshes a token", "h_refresh")
3420                .with_requires_credential(req.clone());
3421        assert_eq!(
3422            refresh_method.requires_credential.as_ref().unwrap().kind,
3423            Some(CredentialKind::OauthRefresh)
3424        );
3425    }
3426
3427    /// AC #6 variant: site_hint can be threaded through if a build-path
3428    /// derivation step has a preferred attach site (e.g., the OAuth refresh
3429    /// path that knows the refresh token is attached via header).
3430    #[test]
3431    fn cred_core_3_required_credential_site_hint_preserved() {
3432        let mut req = RequiredCredential::from_refresh_revoke_target(
3433            CredentialKind::OauthRefresh,
3434            vec![Scope::new("auth.refresh")],
3435        );
3436        let hint = AttachmentSite::Header {
3437            name: HeaderName::try_new("authorization").unwrap(),
3438        };
3439        req.site_hint = Some(hint.clone());
3440        let method = MethodSchema::new("refresh", "refreshes", "h_refresh")
3441            .with_requires_credential(req);
3442
3443        let json = serde_json::to_string(&method).unwrap();
3444        let decoded: MethodSchema = serde_json::from_str(&json).unwrap();
3445        assert_eq!(
3446            decoded.requires_credential.as_ref().unwrap().site_hint,
3447            Some(hint)
3448        );
3449    }
3450
3451    /// AC #7: A pre-existing schema consumer (synapse IR builder,
3452    /// hub-codegen) decodes the new schema fields with their additive
3453    /// defaults and continues to function.
3454    ///
3455    /// Tested by deserializing a pre-CRED-CORE-3 JSON shape (no
3456    /// `credentials`, no `requires_credential` fields) and asserting the
3457    /// defaults are applied.
3458    ///
3459    /// 0.7 (RETURNS-5): the JSON carries the two required fields, `returns`
3460    /// and `cardinality`.
3461    #[test]
3462    fn cred_core_3_ac7_pre_ir_json_deserializes_with_empty_defaults() {
3463        let pre_ir_json = serde_json::json!({
3464            "name": "ping",
3465            "description": "pong",
3466            "hash": "abc",
3467            "returns": {},
3468            "cardinality": "one"
3469        });
3470        let schema: MethodSchema = serde_json::from_value(pre_ir_json).unwrap();
3471        assert!(schema.credentials.is_empty());
3472        assert!(schema.requires_credential.is_none());
3473    }
3474
3475    /// AC #7 variant: a pre-IR PluginSchema with multiple methods
3476    /// deserializes cleanly with every method's credential projections
3477    /// defaulted.
3478    #[test]
3479    fn cred_core_3_ac7_pre_ir_plugin_schema_deserializes() {
3480        let pre_ir_json = serde_json::json!({
3481            "namespace": "legacy",
3482            "version": "1.0",
3483            "description": "no credentials",
3484            "self_hash": "s1",
3485            "hash": "h1",
3486            "methods": [
3487                { "name": "a", "description": "alpha", "hash": "ah", "returns": {}, "cardinality": "one" },
3488                { "name": "b", "description": "beta",  "hash": "bh", "returns": {}, "cardinality": "one" }
3489            ]
3490        });
3491        let plugin: PluginSchema = serde_json::from_value(pre_ir_json).unwrap();
3492        for m in &plugin.methods {
3493            assert!(m.credentials.is_empty());
3494            assert!(m.requires_credential.is_none());
3495        }
3496    }
3497
3498    /// AC #8: The `_info` capability advertisement carries the new fields
3499    /// when populated.
3500    ///
3501    /// `_info` reads `MethodSchema`'s serde representation directly. We
3502    /// verify the wire JSON contains the new fields when populated.
3503    #[test]
3504    fn cred_core_3_ac8_info_advertisement_carries_populated_fields() {
3505        let marker = sample_marker_single();
3506        let decl = CredentialFieldDecl::from_marker(&marker, &[], sample_issuer());
3507        let req = RequiredCredential::from_method_scope(Scope::new("cone.send_message"));
3508        let method = MethodSchema::new("login", "logs in", "h_login")
3509            .with_credentials(vec![decl])
3510            .with_requires_credential(req);
3511
3512        let json = serde_json::to_value(&method).unwrap();
3513        let obj = json.as_object().unwrap();
3514        assert!(
3515            obj.contains_key("credentials"),
3516            "populated credentials must appear in wire JSON"
3517        );
3518        assert!(
3519            obj.contains_key("requires_credential"),
3520            "populated requires_credential must appear in wire JSON"
3521        );
3522        // And the entry shape is decodeable.
3523        let decoded: MethodSchema = serde_json::from_value(json).unwrap();
3524        assert_eq!(decoded.credentials.len(), 1);
3525        assert_eq!(decoded.credentials[0].field_path, vec!["session".to_string()]);
3526        assert_eq!(
3527            decoded.requires_credential.as_ref().unwrap().scopes,
3528            vec![Scope::new("cone.send_message")]
3529        );
3530    }
3531
3532    /// AC #11 (no regression): a method that does not return credentials and
3533    /// has no scope-derived requirement has identical wire JSON to a pre-IR
3534    /// schema for the same method (the new fields are omitted on the wire).
3535    #[test]
3536    fn cred_core_3_ac11_methods_without_credentials_have_unchanged_wire_shape() {
3537        let method = MethodSchema::new("ping", "pong", "h_ping");
3538        let json = serde_json::to_value(&method).unwrap();
3539        let obj = json.as_object().unwrap();
3540        // No credentials key, no requires_credential key.
3541        assert!(!obj.contains_key("credentials"));
3542        assert!(!obj.contains_key("requires_credential"));
3543
3544        // And the round-trip preserves the empty defaults.
3545        let decoded: MethodSchema = serde_json::from_value(json).unwrap();
3546        assert!(decoded.credentials.is_empty());
3547        assert!(decoded.requires_credential.is_none());
3548    }
3549
3550    /// Round-trip coverage: a full `MethodSchema` with both projections
3551    /// populated round-trips through serde without losing fields.
3552    #[test]
3553    fn cred_core_3_full_method_roundtrip_preserves_credentials_and_requires() {
3554        let marker = sample_marker_single();
3555        let decl = CredentialFieldDecl::from_marker(&marker, &[], sample_issuer());
3556        let req = RequiredCredential::from_method_scope(Scope::new("cone.send_message"));
3557        let method = MethodSchema::new("login", "logs in", "h_login")
3558            .with_credentials(vec![decl.clone()])
3559            .with_requires_credential(req.clone());
3560
3561        let json = serde_json::to_string(&method).unwrap();
3562        let decoded: MethodSchema = serde_json::from_str(&json).unwrap();
3563
3564        assert_eq!(decoded.credentials.len(), 1);
3565        assert_eq!(decoded.credentials[0], decl);
3566        assert_eq!(decoded.requires_credential.as_ref().unwrap(), &req);
3567    }
3568
3569    /// `CredentialFieldDecl` round-trips via serde — pinned independently
3570    /// of MethodSchema so consumers reading the decl in isolation (e.g.
3571    /// `AUTHZ-CRED-IR-1` Haskell decoder testing parity) have a
3572    /// trustworthy shape contract.
3573    #[test]
3574    fn cred_core_3_credential_field_decl_roundtrip() {
3575        let marker = sample_marker_single();
3576        let original = CredentialFieldDecl::from_marker(&marker, &["envelope"], sample_issuer());
3577        let json = serde_json::to_string(&original).unwrap();
3578        let parsed: CredentialFieldDecl = serde_json::from_str(&json).unwrap();
3579        assert_eq!(parsed, original);
3580    }
3581
3582    // =========================================================================
3583    // R-2 wire snapshot tests: `auth_posture` + `public` on MethodSchema
3584    // (ROLES+AP merged wave; joint AP-1).
3585    //
3586    // "old" = the pre-R-2 wire shape (no `auth_posture`, no `public` keys).
3587    // "new" = the R-2 emitter.
3588    // =========================================================================
3589
3590    /// Old-decodes-new: a schema that never sets the R-2 fields serializes to
3591    /// JSON containing neither key — byte-identical to the pre-R-2 wire, so
3592    /// old readers (synapse, hub-codegen, pinned IRs) see exactly what they
3593    /// always saw.
3594    #[test]
3595    fn r2_unset_fields_are_omitted_from_wire() {
3596        let method = MethodSchema::new("ping", "pong", "h_ping");
3597        let json = serde_json::to_value(&method).unwrap();
3598        let obj = json.as_object().unwrap();
3599        assert!(
3600            !obj.contains_key("auth_posture"),
3601            "auth_posture must be omitted when never declared, got {json}"
3602        );
3603        assert!(
3604            !obj.contains_key("public"),
3605            "public must be omitted when false, got {json}"
3606        );
3607    }
3608
3609    /// New-decodes-old: a pinned pre-R-2 JSON snapshot (no `auth_posture`,
3610    /// no `public`) decodes cleanly with the additive defaults.
3611    #[test]
3612    fn r2_pre_r2_snapshot_decodes_with_defaults() {
3613        // Pinned old-wire shape: exactly what a pre-R-2 emitter produced for
3614        // a plain method (see `r2_unset_fields_are_omitted_from_wire`).
3615        // 0.7 (RETURNS-5): `returns` + `cardinality` replace the old flag.
3616        let old_wire = r#"{"name":"ping","description":"pong","hash":"h_ping","returns":{},"cardinality":"one","bidirectional":false,"http_method":"POST","role":{"kind":"rpc"}}"#;
3617        let decoded: MethodSchema = serde_json::from_str(old_wire).unwrap();
3618        assert!(decoded.auth_posture.is_none());
3619        assert!(!decoded.public);
3620        assert!(decoded.requires_credential.is_none());
3621    }
3622
3623    /// Populated round-trip: posture + public + requires_credential all
3624    /// surface in the wire JSON and decode back losslessly.
3625    #[test]
3626    fn r2_populated_fields_roundtrip() {
3627        let gated = MethodSchema::new("send", "sends", "h_send")
3628            .with_auth_posture(AuthPosture::Required)
3629            .with_requires_credential(RequiredCredential::from_method_scope(Scope::new(
3630                "cone.send_message",
3631            )));
3632        let json = serde_json::to_value(&gated).unwrap();
3633        assert_eq!(json["auth_posture"], "required");
3634        assert_eq!(
3635            json["requires_credential"]["scopes"],
3636            serde_json::json!(["cone.send_message"])
3637        );
3638        let decoded: MethodSchema = serde_json::from_value(json).unwrap();
3639        assert_eq!(decoded.auth_posture, Some(AuthPosture::Required));
3640
3641        let public = MethodSchema::new("login", "logs in", "h_login")
3642            .with_auth_posture(AuthPosture::Mixed)
3643            .with_public(true);
3644        let json = serde_json::to_value(&public).unwrap();
3645        assert_eq!(json["auth_posture"], "mixed");
3646        assert_eq!(json["public"], true);
3647        let decoded: MethodSchema = serde_json::from_value(json).unwrap();
3648        assert_eq!(decoded.auth_posture, Some(AuthPosture::Mixed));
3649        assert!(decoded.public);
3650    }
3651
3652    /// All four posture variants serialize to their snake_case wire names
3653    /// and round-trip.
3654    #[test]
3655    fn r2_auth_posture_wire_names() {
3656        for (posture, wire) in [
3657            (AuthPosture::Required, "\"required\""),
3658            (AuthPosture::Optional, "\"optional\""),
3659            (AuthPosture::Mixed, "\"mixed\""),
3660            (AuthPosture::None, "\"none\""),
3661        ] {
3662            let s = serde_json::to_string(&posture).unwrap();
3663            assert_eq!(s, wire);
3664            let back: AuthPosture = serde_json::from_str(&s).unwrap();
3665            assert_eq!(back, posture);
3666        }
3667    }
3668
3669    /// `RequiredCredential::from_method_scopes` (R-2): multi-scope
3670    /// conjunction — kind stays `None`, scope order preserved, round-trips.
3671    #[test]
3672    fn r2_from_method_scopes_multi_scope_conjunction() {
3673        let req = RequiredCredential::from_method_scopes(vec![
3674            Scope::new("facet.write"),
3675            Scope::new("facet.admin"),
3676        ]);
3677        assert!(req.kind.is_none());
3678        assert!(req.site_hint.is_none());
3679        assert_eq!(
3680            req.scopes,
3681            vec![Scope::new("facet.write"), Scope::new("facet.admin")]
3682        );
3683
3684        let method =
3685            MethodSchema::new("update", "updates", "h_update").with_requires_credential(req.clone());
3686        let json = serde_json::to_string(&method).unwrap();
3687        let decoded: MethodSchema = serde_json::from_str(&json).unwrap();
3688        assert_eq!(decoded.requires_credential.as_ref().unwrap(), &req);
3689    }
3690
3691    /// A populated `_info`-shaped PluginSchema carries the R-2 fields on its
3692    /// methods (serde emission is the `_info` path — PluginSchema embeds
3693    /// `Vec<MethodSchema>` verbatim).
3694    #[test]
3695    fn r2_plugin_schema_info_emission_carries_fields() {
3696        let plugin = PluginSchema::leaf(
3697            "fixture",
3698            "1.0",
3699            "r2 fixture",
3700            vec![
3701                MethodSchema::new("gated", "needs scope", "h1")
3702                    .with_auth_posture(AuthPosture::Required)
3703                    .with_requires_credential(RequiredCredential::from_method_scope(
3704                        Scope::new("fixture.gated"),
3705                    )),
3706                MethodSchema::new("open", "anonymous ok", "h2")
3707                    .with_auth_posture(AuthPosture::Required)
3708                    .with_public(true),
3709            ],
3710        );
3711        let json = serde_json::to_value(&plugin).unwrap();
3712        let methods = json["methods"].as_array().unwrap();
3713        assert_eq!(methods[0]["auth_posture"], "required");
3714        assert_eq!(
3715            methods[0]["requires_credential"]["scopes"],
3716            serde_json::json!(["fixture.gated"])
3717        );
3718        assert!(methods[0].get("public").is_none());
3719        assert_eq!(methods[1]["public"], true);
3720        assert!(methods[1].get("requires_credential").is_none());
3721    }
3722
3723    /// `RequiredCredential` round-trips via serde — pinned independently
3724    /// for the same cross-stack reason as `CredentialFieldDecl`.
3725    #[test]
3726    fn cred_core_3_required_credential_roundtrip() {
3727        let req = RequiredCredential {
3728            kind: Some(CredentialKind::OauthRefresh),
3729            scopes: vec![Scope::new("auth.refresh")],
3730            site_hint: Some(AttachmentSite::Header {
3731                name: HeaderName::try_new("authorization").unwrap(),
3732            }),
3733        };
3734        let json = serde_json::to_string(&req).unwrap();
3735        let parsed: RequiredCredential = serde_json::from_str(&json).unwrap();
3736        assert_eq!(parsed, req);
3737    }
3738
3739    /// `RequiredCredential` with `kind: None, scopes: [...], site_hint:
3740    /// None` (the `from_method_scope` shape) serializes to a compact wire
3741    /// form that omits the absent fields.
3742    #[test]
3743    fn cred_core_3_required_credential_compact_wire_shape() {
3744        let req = RequiredCredential::from_method_scope(Scope::new("cone.send"));
3745        let json = serde_json::to_value(&req).unwrap();
3746        let obj = json.as_object().unwrap();
3747        // Only the scopes field is present on the wire.
3748        assert!(!obj.contains_key("kind"));
3749        assert!(obj.contains_key("scopes"));
3750        assert!(!obj.contains_key("site_hint"));
3751    }
3752
3753    /// CA-1: `fill_site_hint` fills only an ABSENT hint — an existing one
3754    /// (e.g. a future explicit override) always wins over the
3755    /// capability-derived default.
3756    #[test]
3757    fn ca1_fill_site_hint_fills_absent_and_preserves_existing() {
3758        let derived = AttachmentSite::Cookie {
3759            name: plexus_auth_core::CookieName::try_new("access_token").unwrap(),
3760        };
3761
3762        // Absent → filled.
3763        let mut req = RequiredCredential::from_method_scope(Scope::new("cone.send"));
3764        req.fill_site_hint(&derived);
3765        assert_eq!(req.site_hint.as_ref(), Some(&derived));
3766
3767        // Present → preserved.
3768        let existing = AttachmentSite::Header {
3769            name: HeaderName::try_new("authorization").unwrap(),
3770        };
3771        let mut req = RequiredCredential::from_method_scope(Scope::new("cone.send"));
3772        req.site_hint = Some(existing.clone());
3773        req.fill_site_hint(&derived);
3774        assert_eq!(req.site_hint, Some(existing));
3775    }
3776
3777    /// CA-1: the plugin-level fill never CREATES a `requires_credential` —
3778    /// methods without one keep their pre-CA-1 wire shape exactly.
3779    #[test]
3780    fn ca1_plugin_fill_never_creates_requirements() {
3781        let derived = AttachmentSite::Header {
3782            name: HeaderName::try_new("authorization").unwrap(),
3783        };
3784        let mut plugin = PluginSchema::leaf(
3785            "fixture",
3786            "1.0",
3787            "ca-1 fixture",
3788            vec![
3789                MethodSchema::new("gated", "needs scope", "h1").with_requires_credential(
3790                    RequiredCredential::from_method_scope(Scope::new("fixture.gated")),
3791                ),
3792                MethodSchema::new("open", "anonymous ok", "h2").with_public(true),
3793            ],
3794        );
3795        let before_open = serde_json::to_value(&plugin.methods[1]).unwrap();
3796
3797        plugin.fill_site_hints(&derived);
3798
3799        assert_eq!(
3800            plugin.methods[0]
3801                .requires_credential
3802                .as_ref()
3803                .unwrap()
3804                .site_hint
3805                .as_ref(),
3806            Some(&derived)
3807        );
3808        assert_eq!(
3809            serde_json::to_value(&plugin.methods[1]).unwrap(),
3810            before_open,
3811            "methods without a requirement must be byte-identical after the fill"
3812        );
3813    }
3814}