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