Skip to main content

hyprstream_core/mac/
dispatch_labels.rs

1//! **Typed RPC dispatch labels** — the focused #1499 boot-labeling slice.
2//!
3//! The mandatory RPC dispatch PEP (`hyprstream_rpc::auth::mac::dispatch_pep`)
4//! evaluates a **typed declared `(service, leaf/method)` object identity** plus
5//! a **deliberate service subject clearance**. This module supplies both, keyed
6//! on the dispatch plane's own coordinates:
7//!
8//! - [`DispatchMethodId`] — the typed object identity: the canonical service
9//!   name plus the canonical request-union discriminant (the leaf/method),
10//!   decoded once from the verified payload by the dispatch pipeline. It is
11//!   **never** a VFS path, and bare service domains are never routed through
12//!   the VFS object-label adapter (`CompositeObjectLabelResolver`'s
13//!   `RpcObjectLabelResolver` impl now serves the VFS plane only).
14//! - [`ServiceSubjectClearance`] — the deliberate clearance a declared
15//!   bootstrap service holds as a *caller*, the dispatch-plane seed of the
16//!   v16 `ServiceEnrollmentManifest` clearance. The assurance axis is clamped
17//!   by the cryptographically verified key material at evaluation time, so the
18//!   declaration can never outrun what the envelope signature proved.
19//!
20//! ## Deny-by-default
21//!
22//! There is no wildcard, catch-all, prefix rule, or permissive default. An
23//! unknown service, an unknown leaf on a known service, a bare/VFS-shaped
24//! alias (`"/srv/policy"`, `"srv/policy"`), and a call whose payload carries
25//! no canonical method identity all resolve to `None` ⇒ `UnlabeledObject` ⇒
26//! deny before handler entry. A caller with no declared service clearance —
27//! including an anonymous caller, for whom the activation floor would
28//! otherwise suffice against a floor-labeled row — denies `NoClearance`. The
29//! permit of a declared bootstrap call is therefore justified by the
30//! *declared pair* (typed object + deliberate clearance), never by a
31//! fabricated anonymous/public clearance.
32//!
33//! ## Relationship to #1507 (v16)
34//!
35//! This is the smallest deny-by-default representation the production PEP can
36//! evaluate today. #1507 replaces the hand-maintained tables with the
37//! generated full-method inventory (transitional/target label columns, scope
38//! and signature policy) without changing the PEP contract: typed `(service,
39//! leaf)` resolution, declared subject clearance, activation-gated selection,
40//! and intrinsic lattice dominance all stay. Object labels here are
41//! deliberately the lattice floor (`SecurityLabel::bottom()`): the bootstrap
42//! identity-lifecycle leaves precede identity standing and must remain
43//! reachable under the permanent narrow-to-floor incident control
44//! (`FloorOnly`); every raising above the floor is #1507's reviewed
45//! transitional/target column work, not this slice.
46
47use hyprstream_rpc::auth::mac::{
48    Assurance, CompartmentSet, Level, MacDecision, MacDenyReason, MacDispatchPep,
49    RpcObjectLabelResolver, SecurityContext, SecurityLabel,
50};
51use hyprstream_rpc::service::EnvelopeContext;
52
53/// Subject-name prefix of a verified service identity (`service:{name}`).
54///
55/// Service JWTs minted by the CA carry `sub = "service:{name}"`
56/// (`crates/hyprstream-rpc-std/schema/policy.capnp`), so the verified subject
57/// produced by claims verification has this exact shape.
58pub const SERVICE_SUBJECT_PREFIX: &str = "service:";
59
60/// Canonical `PolicyRequest` union discriminants (the leaf/method axis of
61/// [`DispatchMethodId`]).
62///
63/// The values are the Cap'n Proto union discriminant ordinals — 0-based
64/// declaration order in `hyprstream-rpc-std/schema/policy.capnp`, which
65/// assigns no explicit discriminants. The drift test in this module decodes
66/// real serialized requests and pins these values to the schema; changing the
67/// union order fails CI rather than silently relabeling the dispatch plane.
68pub mod policy_methods {
69    /// `check` — an authenticated service asks the PolicyService to evaluate
70    /// its own authorization request. The handler derives caller identity and
71    /// domain from the verified envelope; this declaration adds no anonymous
72    /// or tokenless exception.
73    pub const CHECK: u16 = 0;
74    /// `issueToken` — PolicyService mints a session-bound credential. Its
75    /// schema declares `internal:pq-hybrid`; only the verified hybrid OAuth
76    /// authority receives the corresponding scoped dispatch clearance.
77    pub const ISSUE_TOKEN: u16 = 1;
78    /// `getPolicy` — read the local control-plane policy.
79    pub const GET_POLICY: u16 = 3;
80    /// `applyTemplate` — install a reviewed bootstrap template.
81    pub const APPLY_TEMPLATE: u16 = 4;
82    /// `applyDraft` — commit a local policy draft.
83    pub const APPLY_DRAFT: u16 = 5;
84    /// `rollback` — restore a local policy revision.
85    pub const ROLLBACK: u16 = 6;
86    /// `getHistory` — inspect local policy revisions.
87    pub const GET_HISTORY: u16 = 7;
88    /// `getDiff` — inspect a local policy draft.
89    pub const GET_DIFF: u16 = 8;
90    /// `getDraftStatus` — inspect local draft state.
91    pub const GET_DRAFT_STATUS: u16 = 9;
92    /// `addGrouping` — add a local role assignment.
93    pub const ADD_GROUPING: u16 = 10;
94    /// `removeGrouping` — remove a local role assignment.
95    pub const REMOVE_GROUPING: u16 = 11;
96    /// `registerServiceKey` — a keyed service installs its identity with the
97    /// CA. Bootstrap-critical: it precedes identity standing.
98    pub const REGISTER_SERVICE_KEY: u16 = 18;
99    /// `refreshServiceToken` — a registered service renews the identity the
100    /// registration created. Same bootstrap identity-lifecycle class; without
101    /// a declared row the first hourly renewal would deny on any live node.
102    pub const REFRESH_SERVICE_TOKEN: u16 = 19;
103}
104
105/// Canonical `DiscoveryRequest` union discriminants used by native startup.
106pub mod discovery_methods {
107    /// `announce @9` is union discriminant 8, not wire field ordinal 9.
108    pub const ANNOUNCE: u16 = 8;
109}
110
111/// Canonical `InferenceRequest` union discriminants.
112///
113/// The values are the Cap'n Proto union discriminants: 0-based DECLARATION
114/// order of the members in `hyprstream-rpc-std/schema/inference.capnp` — NOT
115/// the members' explicit `@N` field ordinals (generateStream is `@1` on the
116/// wire-field axis but carries union discriminant 0). Every member declares
117/// `$dispatchMac("internal:pq-hybrid")`, so every row these constants index
118/// carries the schema-declared hybrid label. The drift test in this module
119/// decodes real serialized requests and pins representative values to the
120/// schema; changing the union order fails CI rather than silently relabeling
121/// the dispatch plane.
122pub mod inference_methods {
123    /// `generateStream` — tenant-authorized streaming generation.
124    pub const GENERATE_STREAM: u16 = 0;
125    pub const MODEL_INFO: u16 = 1;
126    pub const IS_READY: u16 = 2;
127    pub const APPLY_CHAT_TEMPLATE: u16 = 3;
128    pub const CREATE_LORA: u16 = 4;
129    pub const LOAD_LORA: u16 = 5;
130    pub const SAVE_LORA: u16 = 6;
131    pub const UNLOAD_LORA: u16 = 7;
132    pub const HAS_LORA: u16 = 8;
133    pub const SET_SESSION: u16 = 9;
134    pub const CLEAR_SESSION: u16 = 10;
135    pub const RELEASE_SESSION: u16 = 11;
136    pub const HEALTH_CHECK: u16 = 12;
137    /// `shutdown` — engine lifecycle management (`$scope(manage)`).
138    pub const SHUTDOWN: u16 = 13;
139    pub const TTT_WRITEBACK: u16 = 14;
140    pub const TTT_EVICT: u16 = 15;
141    pub const TRAIN_STEP: u16 = 16;
142    pub const TTT_ZERO: u16 = 17;
143    pub const GET_DELTA_STATUS: u16 = 18;
144    pub const SAVE_ADAPTATION: u16 = 19;
145    pub const SNAPSHOT_DELTA: u16 = 20;
146    pub const TRAIN_STEP_STREAM: u16 = 21;
147    pub const EXPORT_PEFT_ADAPTER: u16 = 22;
148    pub const MERGE_LORA: u16 = 23;
149    pub const CREATE_LORA_STREAM: u16 = 24;
150    pub const LOAD_LORA_STREAM: u16 = 25;
151    pub const SAVE_LORA_STREAM: u16 = 26;
152    pub const SAVE_ADAPTATION_STREAM: u16 = 27;
153    pub const SNAPSHOT_DELTA_STREAM: u16 = 28;
154    pub const EXPORT_PEFT_ADAPTER_STREAM: u16 = 29;
155    pub const MERGE_LORA_STREAM: u16 = 30;
156    pub const EMBED: u16 = 31;
157    pub const GET_LAYER_PROFILE: u16 = 32;
158}
159
160/// Clearance for the narrow local Policy bootstrap authority and classical
161/// test fixtures. Enrolled native services use the hybrid ceiling below.
162/// The assurance axis is a *ceiling*, not a grant — evaluation clamps it
163/// to the cryptographically verified key material (#548), so a caller whose
164/// envelope proved less derives less.
165pub const BOOTSTRAP_SERVICE_CLEARANCE: SecurityLabel = SecurityLabel {
166    level: Level::Internal,
167    assurance: Assurance::Classical,
168    compartments: CompartmentSet::EMPTY,
169};
170
171/// Schema-declared label of `PolicyRequest.issueToken`.
172///
173/// The issuing authority crosses a signing boundary and is explicitly marked
174/// `$dispatchMac("internal:pq-hybrid")` in `policy.capnp`; it is therefore not
175/// a floor-labelled bootstrap operation. The only staging caller cleared for
176/// this row is `service:oauth`, whose verified hybrid envelope is additionally
177/// checked by the regular PolicyService authorization and issuance guards.
178pub const OAUTH_ISSUANCE_LABEL: SecurityLabel = SecurityLabel {
179    level: Level::Internal,
180    assurance: Assurance::PqHybrid,
181    compartments: CompartmentSet::EMPTY,
182};
183
184/// Schema-declared label of every `InferenceRequest` member.
185///
186/// All `inference.capnp` members are annotated
187/// `$dispatchMac("internal:pq-hybrid")`; the schema is the security contract,
188/// so the declared rows carry the hybrid label rather than the bootstrap
189/// floor. Callers are the hybrid-enrolled internal services (`model`, `oai`)
190/// whose tenant/user authorization runs at their own layer; the verified
191/// PqHybrid key material of those envelopes is what lets them dominate this
192/// label.
193pub const INFERENCE_METHOD_LABEL: SecurityLabel = SecurityLabel {
194    level: Level::Internal,
195    assurance: Assurance::PqHybrid,
196    compartments: CompartmentSet::EMPTY,
197};
198
199/// Service subject clearance for the hybrid-enrolled runtime services whose
200/// RPC surfaces are schema-declared `internal:pq-hybrid` (`model`, `oai`,
201/// `inference`). Identical in value to [`OAUTH_ISSUANCE_LABEL`] and
202/// [`INFERENCE_METHOD_LABEL`]; the distinct names keep each declaration's
203/// review intent legible.
204pub const HYBRID_SERVICE_CLEARANCE: SecurityLabel = SecurityLabel {
205    level: Level::Internal,
206    assurance: Assurance::PqHybrid,
207    compartments: CompartmentSet::EMPTY,
208};
209
210/// Typed dispatch object identity: canonical service name + canonical
211/// request-union discriminant. Never a VFS path; never interpreted by another
212/// plane's resolver.
213#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
214pub struct DispatchMethodId {
215    /// The canonical registered service name (`policy`, `discovery`, …).
216    pub service: &'static str,
217    /// The canonical request-union discriminant of the method leaf.
218    pub method: u16,
219}
220
221/// One declared `(service, leaf/method)` policy row: the typed object label
222/// for exactly one RPC method on exactly one service.
223#[derive(Debug, Clone, Copy)]
224pub struct DispatchMethodPolicy {
225    /// The typed object identity this row labels.
226    pub id: DispatchMethodId,
227    /// The symbolic leaf name (`registerServiceKey`) — audit and drift-test
228    /// evidence; resolution is by the numeric identity only.
229    pub method_name: &'static str,
230    /// The declared object label. Bootstrap rows are the lattice floor; see
231    /// the module docs for why no row may rise above it in this slice.
232    pub label: SecurityLabel,
233    /// Why this row exists and why its label is correct (reviewed text).
234    pub justification: &'static str,
235}
236
237/// The deliberate MAC clearance a declared service holds as a dispatch
238/// *caller* — the dispatch-plane seed of the v16 `ServiceEnrollmentManifest`
239/// service clearance.
240#[derive(Debug, Clone, Copy)]
241pub struct ServiceSubjectClearance {
242    /// The canonical service name (the `service:{name}` subject suffix).
243    pub service: &'static str,
244    /// The declared clearance. Assurance is clamped to the verified key
245    /// material at evaluation time.
246    pub clearance: SecurityLabel,
247    /// Why this clearance is correct for this service (reviewed text).
248    pub justification: &'static str,
249}
250
251/// The declared dispatch table: a closed, deny-by-default set of typed
252/// `(service, leaf/method)` object labels plus the deliberate per-service
253/// subject clearances. Consumed by [`DeclaredDispatchPep`]; replaceable by
254/// #1507's generated inventory without changing the PEP contract.
255#[derive(Debug, Clone, Copy)]
256pub struct DeclaredDispatchTable {
257    methods: &'static [DispatchMethodPolicy],
258    clearances: &'static [ServiceSubjectClearance],
259}
260
261impl DeclaredDispatchTable {
262    /// The production staging-bootstrap declarations (#1499).
263    ///
264    /// Object rows cover the fresh-state
265    /// `service start --services event,policy,discovery,registry,model,oai,oauth` boot
266    /// graph plus the PolicyService authority's local policy-control-plane
267    /// commands. The production wrapper further restricts those local commands
268    /// to the verified, tokenless `service:policy` authority. Subject rows
269    /// declare the deliberate caller clearance for all seven bootstrap services.
270    #[must_use]
271    pub fn production() -> &'static Self {
272        &PRODUCTION_TABLE
273    }
274
275    /// Construct a table from explicit rows (test fixtures). Production uses
276    /// [`Self::production`].
277    #[must_use]
278    pub const fn from_rows(
279        methods: &'static [DispatchMethodPolicy],
280        clearances: &'static [ServiceSubjectClearance],
281    ) -> Self {
282        Self {
283            methods,
284            clearances,
285        }
286    }
287
288    /// Every declared method row (table-driven test and audit evidence).
289    #[must_use]
290    pub fn methods(&self) -> &'static [DispatchMethodPolicy] {
291        self.methods
292    }
293
294    /// Every declared service subject clearance row.
295    #[must_use]
296    pub fn clearances(&self) -> &'static [ServiceSubjectClearance] {
297        self.clearances
298    }
299
300    /// Resolve the declared policy row for a typed `(service, leaf)` call.
301    ///
302    /// Exact match only: `method` must be `Some` (the canonical discriminant
303    /// committed by the verified payload) and the pair must be declared.
304    /// Unknown services, unknown leaves, VFS-shaped aliases, and calls with
305    /// no committed method identity all return `None` ⇒ deny.
306    #[must_use]
307    pub fn resolve_row(
308        &self,
309        service_domain: &str,
310        method: Option<&[u16]>,
311    ) -> Option<&DispatchMethodPolicy> {
312        // Existing declarations name top-level leaves only. A nested path must
313        // not inherit the row of either its first or last discriminant.
314        let [method] = method? else {
315            return None;
316        };
317        self.methods
318            .iter()
319            .find(|row| row.id.service == service_domain && row.id.method == *method)
320    }
321
322    /// The deliberate clearance declared for a service caller, if any.
323    ///
324    /// `service` is the canonical service name (the `service:` subject prefix
325    /// is stripped by the caller). Exact match; no declaration ⇒ `None` ⇒ the
326    /// caller has no dispatch authority (deny `NoClearance`).
327    #[must_use]
328    pub fn service_clearance(&self, service: &str) -> Option<SecurityLabel> {
329        self.clearances
330            .iter()
331            .find(|row| row.service == service)
332            .map(|row| row.clearance)
333    }
334}
335
336impl RpcObjectLabelResolver for DeclaredDispatchTable {
337    /// Typed dispatch-plane resolution. No path splitting, no prefix
338    /// matching, no VFS adapter: an exact declared `(service, leaf)` row or
339    /// `None` (deny).
340    fn resolve(&self, service_domain: &str, method: Option<&[u16]>) -> Option<SecurityLabel> {
341        self.resolve_row(service_domain, method)
342            .map(|row| row.label)
343    }
344}
345
346/// The production dispatch PEP over the declared table.
347///
348/// Decision procedure (every missing input denies; no permissive mode):
349///
350/// 1. **Activation-selected context** — the coverage-gated operator control
351///    (`FloorOnly` ⇒ anonymous floor; `IdentityAware` ⇒ the verified
352///    Claims × VerifiedKeyMaterial derivation). `None` ⇒ `NoClearance`. The
353///    activation gate and the narrow-to-floor kill-switch are unchanged: a
354///    narrowed process still evaluates every dispatch, and only floor-labeled
355///    (bootstrap-critical) rows remain reachable.
356/// 2. **Deliberate service subject clearance** — the verified subject must be
357///    a `service:{name}` identity with a real authenticated envelope signer
358///    key AND a declared clearance in the table. The declared clearance is
359///    composed with the crypto-derived assurance (`SecurityContext::
360///    from_clearance` clamps down, never up). No declaration ⇒ `NoClearance`
361///    — an anonymous or undeclared caller can never ride the activation floor
362///    into a declared row.
363/// 3. **Typed object identity** — an exact declared `(service, leaf)` row.
364///    `None` ⇒ `UnlabeledObject`.
365/// 4. **Dominance** — BOTH the activation-selected context and the deliberate
366///    declared-service context must dominate the declared object label
367///    (`can_access`). Otherwise `FloorDeny`.
368///
369/// Like the genesis PEP it replaces at the install seam, this PEP performs no
370/// permit caching and holds no permissive state.
371pub struct DeclaredDispatchPep {
372    table: &'static DeclaredDispatchTable,
373    activation_controlled: bool,
374}
375
376impl DeclaredDispatchPep {
377    /// Construct over a declared table.
378    ///
379    /// Direct unit-test and embedding constructors keep the historical
380    /// identity-aware behavior (the verified context is used as-is);
381    /// production installs with [`Self::with_activation_control`].
382    #[must_use]
383    pub fn new(table: &'static DeclaredDispatchTable) -> Self {
384        Self {
385            table,
386            activation_controlled: false,
387        }
388    }
389
390    /// Select subject contexts through the process-global coverage gate.
391    /// Production's install path opts in explicitly.
392    #[must_use]
393    pub fn with_activation_control(mut self) -> Self {
394        self.activation_controlled = true;
395        self
396    }
397
398    /// The declared table this PEP evaluates.
399    #[must_use]
400    pub fn table(&self) -> &'static DeclaredDispatchTable {
401        self.table
402    }
403
404    /// Evaluate an already-established subject context against the typed table.
405    ///
406    /// This remains crate-private so production callers cannot substitute an
407    /// arbitrary clearance for an unverified envelope. The local policy
408    /// bootstrap wrapper uses it only after proving its exact bearerless,
409    /// non-federated root authority and derives this context from the
410    /// authenticated service clearance.
411    pub(crate) fn check_with_explicit_context(
412        &self,
413        ctx: &EnvelopeContext,
414        service_domain: &str,
415        method: Option<&[u16]>,
416        selected: SecurityContext,
417    ) -> MacDecision {
418        hyprstream_rpc::auth::mac::remember_verified_subject(ctx);
419        self.check_selected_context(ctx, service_domain, method, selected)
420    }
421
422    fn check_selected_context(
423        &self,
424        ctx: &EnvelopeContext,
425        service_domain: &str,
426        method: Option<&[u16]>,
427        selected: SecurityContext,
428    ) -> MacDecision {
429        let Some(service_name) = declared_service_subject(ctx) else {
430            return MacDecision::Deny(MacDenyReason::NoClearance);
431        };
432        let Some(declared_clearance) = self.table.service_clearance(&service_name) else {
433            return MacDecision::Deny(MacDenyReason::NoClearance);
434        };
435        let service_ctx =
436            SecurityContext::from_clearance(declared_clearance, ctx.verified_key_material());
437
438        let Some(row) = self.table.resolve_row(service_domain, method) else {
439            return MacDecision::Deny(MacDenyReason::UnlabeledObject);
440        };
441
442        if selected.can_access(&row.label) && service_ctx.can_access(&row.label) {
443            MacDecision::Permit
444        } else {
445            MacDecision::Deny(MacDenyReason::FloorDeny)
446        }
447    }
448}
449
450/// Extract the canonical service name from a verified service subject.
451///
452/// The declared clearance attaches only to a `service:{name}` identity backed
453/// by a real authenticated envelope signer key — never to an anonymous
454/// subject and never to a keyless internal callback context
455/// (`EnvelopeContext::from_callback_service` zeroes `cnf`, so
456/// `authenticated_signer_key` refuses it).
457fn declared_service_subject(ctx: &EnvelopeContext) -> Option<String> {
458    ctx.authenticated_signer_key()?;
459    let subject = ctx.subject();
460    let name = subject.name()?;
461    name.strip_prefix(SERVICE_SUBJECT_PREFIX)
462        .filter(|suffix| !suffix.is_empty())
463        .map(str::to_owned)
464}
465
466impl MacDispatchPep for DeclaredDispatchPep {
467    fn check(
468        &self,
469        ctx: &EnvelopeContext,
470        service_domain: &str,
471        method: Option<&[u16]>,
472    ) -> MacDecision {
473        // Preserve the verified context for the direct VFS/CAS/MoQ PEPs, whose
474        // low-level APIs carry Subject but not the full verified envelope.
475        // (Parity with DefaultMacDispatchPep.)
476        hyprstream_rpc::auth::mac::remember_verified_subject(ctx);
477
478        // 1. Activation-selected subject context (floor-only or verified
479        //    identity-aware). The operator gate is unchanged by this PEP.
480        let selected = if self.activation_controlled {
481            hyprstream_rpc::auth::mac::global_mac_activation_control()
482                .select_context(ctx.security_context())
483        } else {
484            ctx.security_context()
485        };
486        let Some(selected) = selected else {
487            return MacDecision::Deny(MacDenyReason::NoClearance);
488        };
489
490        // 2. Deliberate declared service subject clearance. The assurance axis
491        //    is clamped to the verified key material; the declaration cannot
492        //    outrun the crypto.
493        self.check_selected_context(ctx, service_domain, method, selected)
494    }
495}
496
497// ── Production declarations (the staging bootstrap set, #1499) ─────────────
498
499static BOOTSTRAP_METHODS: &[DispatchMethodPolicy] = &[
500    DispatchMethodPolicy {
501        id: DispatchMethodId {
502            service: "discovery",
503            method: discovery_methods::ANNOUNCE,
504        },
505        method_name: "announce",
506        label: HYBRID_SERVICE_CLEARANCE,
507        justification: "native endpoint publication requires the schema-declared internal:pq-hybrid context; Discovery additionally verifies the service credential, signer binding, and accepted current identity state",
508    },
509    DispatchMethodPolicy {
510        id: DispatchMethodId {
511            service: "inference",
512            method: inference_methods::GENERATE_STREAM,
513        },
514        method_name: "generateStream",
515        label: INFERENCE_METHOD_LABEL,
516        justification: "tenant-authorized generation/embedding against the admitted engine; the handler enforces tenant binding, model admission, and the spend ledger (infer scope; schema-declared internal:pq-hybrid)",
517    },
518    DispatchMethodPolicy {
519        id: DispatchMethodId {
520            service: "inference",
521            method: inference_methods::MODEL_INFO,
522        },
523        method_name: "modelInfo",
524        label: INFERENCE_METHOD_LABEL,
525        justification: "read-only introspection of the admitted engine; the handler retains tenant binding and readiness gating (query scope; schema-declared internal:pq-hybrid)",
526    },
527    DispatchMethodPolicy {
528        id: DispatchMethodId {
529            service: "inference",
530            method: inference_methods::IS_READY,
531        },
532        method_name: "isReady",
533        label: INFERENCE_METHOD_LABEL,
534        justification: "read-only introspection of the admitted engine; the handler retains tenant binding and readiness gating (query scope; schema-declared internal:pq-hybrid)",
535    },
536    DispatchMethodPolicy {
537        id: DispatchMethodId {
538            service: "inference",
539            method: inference_methods::APPLY_CHAT_TEMPLATE,
540        },
541        method_name: "applyChatTemplate",
542        label: INFERENCE_METHOD_LABEL,
543        justification: "read-only introspection of the admitted engine; the handler retains tenant binding and readiness gating (query scope; schema-declared internal:pq-hybrid)",
544    },
545    DispatchMethodPolicy {
546        id: DispatchMethodId {
547            service: "inference",
548            method: inference_methods::CREATE_LORA,
549        },
550        method_name: "createLora",
551        label: INFERENCE_METHOD_LABEL,
552        justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
553    },
554    DispatchMethodPolicy {
555        id: DispatchMethodId {
556            service: "inference",
557            method: inference_methods::LOAD_LORA,
558        },
559        method_name: "loadLora",
560        label: INFERENCE_METHOD_LABEL,
561        justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
562    },
563    DispatchMethodPolicy {
564        id: DispatchMethodId {
565            service: "inference",
566            method: inference_methods::SAVE_LORA,
567        },
568        method_name: "saveLora",
569        label: INFERENCE_METHOD_LABEL,
570        justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
571    },
572    DispatchMethodPolicy {
573        id: DispatchMethodId {
574            service: "inference",
575            method: inference_methods::UNLOAD_LORA,
576        },
577        method_name: "unloadLora",
578        label: INFERENCE_METHOD_LABEL,
579        justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
580    },
581    DispatchMethodPolicy {
582        id: DispatchMethodId {
583            service: "inference",
584            method: inference_methods::HAS_LORA,
585        },
586        method_name: "hasLora",
587        label: INFERENCE_METHOD_LABEL,
588        justification: "read-only introspection of the admitted engine; the handler retains tenant binding and readiness gating (query scope; schema-declared internal:pq-hybrid)",
589    },
590    DispatchMethodPolicy {
591        id: DispatchMethodId {
592            service: "inference",
593            method: inference_methods::SET_SESSION,
594        },
595        method_name: "setSession",
596        label: INFERENCE_METHOD_LABEL,
597        justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
598    },
599    DispatchMethodPolicy {
600        id: DispatchMethodId {
601            service: "inference",
602            method: inference_methods::CLEAR_SESSION,
603        },
604        method_name: "clearSession",
605        label: INFERENCE_METHOD_LABEL,
606        justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
607    },
608    DispatchMethodPolicy {
609        id: DispatchMethodId {
610            service: "inference",
611            method: inference_methods::RELEASE_SESSION,
612        },
613        method_name: "releaseSession",
614        label: INFERENCE_METHOD_LABEL,
615        justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
616    },
617    DispatchMethodPolicy {
618        id: DispatchMethodId {
619            service: "inference",
620            method: inference_methods::HEALTH_CHECK,
621        },
622        method_name: "healthCheck",
623        label: INFERENCE_METHOD_LABEL,
624        justification: "read-only introspection of the admitted engine; the handler retains tenant binding and readiness gating (query scope; schema-declared internal:pq-hybrid)",
625    },
626    DispatchMethodPolicy {
627        id: DispatchMethodId {
628            service: "inference",
629            method: inference_methods::SHUTDOWN,
630        },
631        method_name: "shutdown",
632        label: INFERENCE_METHOD_LABEL,
633        justification: "engine lifecycle management restricted to the verified hybrid model-service authority; the handler retains its own admission checks (manage scope; schema-declared internal:pq-hybrid)",
634    },
635    DispatchMethodPolicy {
636        id: DispatchMethodId {
637            service: "inference",
638            method: inference_methods::TTT_WRITEBACK,
639        },
640        method_name: "tttWriteback",
641        label: INFERENCE_METHOD_LABEL,
642        justification: "TTT training/adaptation step against the tenant-bound engine; the handler enforces tenant binding (train scope; schema-declared internal:pq-hybrid)",
643    },
644    DispatchMethodPolicy {
645        id: DispatchMethodId {
646            service: "inference",
647            method: inference_methods::TTT_EVICT,
648        },
649        method_name: "tttEvict",
650        label: INFERENCE_METHOD_LABEL,
651        justification: "TTT training/adaptation step against the tenant-bound engine; the handler enforces tenant binding (train scope; schema-declared internal:pq-hybrid)",
652    },
653    DispatchMethodPolicy {
654        id: DispatchMethodId {
655            service: "inference",
656            method: inference_methods::TRAIN_STEP,
657        },
658        method_name: "trainStep",
659        label: INFERENCE_METHOD_LABEL,
660        justification: "TTT training/adaptation step against the tenant-bound engine; the handler enforces tenant binding (train scope; schema-declared internal:pq-hybrid)",
661    },
662    DispatchMethodPolicy {
663        id: DispatchMethodId {
664            service: "inference",
665            method: inference_methods::TTT_ZERO,
666        },
667        method_name: "tttZero",
668        label: INFERENCE_METHOD_LABEL,
669        justification: "engine lifecycle management restricted to the verified hybrid model-service authority; the handler retains its own admission checks (manage scope; schema-declared internal:pq-hybrid)",
670    },
671    DispatchMethodPolicy {
672        id: DispatchMethodId {
673            service: "inference",
674            method: inference_methods::GET_DELTA_STATUS,
675        },
676        method_name: "getDeltaStatus",
677        label: INFERENCE_METHOD_LABEL,
678        justification: "read-only introspection of the admitted engine; the handler retains tenant binding and readiness gating (query scope; schema-declared internal:pq-hybrid)",
679    },
680    DispatchMethodPolicy {
681        id: DispatchMethodId {
682            service: "inference",
683            method: inference_methods::SAVE_ADAPTATION,
684        },
685        method_name: "saveAdaptation",
686        label: INFERENCE_METHOD_LABEL,
687        justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
688    },
689    DispatchMethodPolicy {
690        id: DispatchMethodId {
691            service: "inference",
692            method: inference_methods::SNAPSHOT_DELTA,
693        },
694        method_name: "snapshotDelta",
695        label: INFERENCE_METHOD_LABEL,
696        justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
697    },
698    DispatchMethodPolicy {
699        id: DispatchMethodId {
700            service: "inference",
701            method: inference_methods::TRAIN_STEP_STREAM,
702        },
703        method_name: "trainStepStream",
704        label: INFERENCE_METHOD_LABEL,
705        justification: "TTT training/adaptation step against the tenant-bound engine; the handler enforces tenant binding (train scope; schema-declared internal:pq-hybrid)",
706    },
707    DispatchMethodPolicy {
708        id: DispatchMethodId {
709            service: "inference",
710            method: inference_methods::EXPORT_PEFT_ADAPTER,
711        },
712        method_name: "exportPeftAdapter",
713        label: INFERENCE_METHOD_LABEL,
714        justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
715    },
716    DispatchMethodPolicy {
717        id: DispatchMethodId {
718            service: "inference",
719            method: inference_methods::MERGE_LORA,
720        },
721        method_name: "mergeLora",
722        label: INFERENCE_METHOD_LABEL,
723        justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
724    },
725    DispatchMethodPolicy {
726        id: DispatchMethodId {
727            service: "inference",
728            method: inference_methods::CREATE_LORA_STREAM,
729        },
730        method_name: "createLoraStream",
731        label: INFERENCE_METHOD_LABEL,
732        justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
733    },
734    DispatchMethodPolicy {
735        id: DispatchMethodId {
736            service: "inference",
737            method: inference_methods::LOAD_LORA_STREAM,
738        },
739        method_name: "loadLoraStream",
740        label: INFERENCE_METHOD_LABEL,
741        justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
742    },
743    DispatchMethodPolicy {
744        id: DispatchMethodId {
745            service: "inference",
746            method: inference_methods::SAVE_LORA_STREAM,
747        },
748        method_name: "saveLoraStream",
749        label: INFERENCE_METHOD_LABEL,
750        justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
751    },
752    DispatchMethodPolicy {
753        id: DispatchMethodId {
754            service: "inference",
755            method: inference_methods::SAVE_ADAPTATION_STREAM,
756        },
757        method_name: "saveAdaptationStream",
758        label: INFERENCE_METHOD_LABEL,
759        justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
760    },
761    DispatchMethodPolicy {
762        id: DispatchMethodId {
763            service: "inference",
764            method: inference_methods::SNAPSHOT_DELTA_STREAM,
765        },
766        method_name: "snapshotDeltaStream",
767        label: INFERENCE_METHOD_LABEL,
768        justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
769    },
770    DispatchMethodPolicy {
771        id: DispatchMethodId {
772            service: "inference",
773            method: inference_methods::EXPORT_PEFT_ADAPTER_STREAM,
774        },
775        method_name: "exportPeftAdapterStream",
776        label: INFERENCE_METHOD_LABEL,
777        justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
778    },
779    DispatchMethodPolicy {
780        id: DispatchMethodId {
781            service: "inference",
782            method: inference_methods::MERGE_LORA_STREAM,
783        },
784        method_name: "mergeLoraStream",
785        label: INFERENCE_METHOD_LABEL,
786        justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
787    },
788    DispatchMethodPolicy {
789        id: DispatchMethodId {
790            service: "inference",
791            method: inference_methods::EMBED,
792        },
793        method_name: "embed",
794        label: INFERENCE_METHOD_LABEL,
795        justification: "tenant-authorized generation/embedding against the admitted engine; the handler enforces tenant binding, model admission, and the spend ledger (infer scope; schema-declared internal:pq-hybrid)",
796    },
797    DispatchMethodPolicy {
798        id: DispatchMethodId {
799            service: "inference",
800            method: inference_methods::GET_LAYER_PROFILE,
801        },
802        method_name: "getLayerProfile",
803        label: INFERENCE_METHOD_LABEL,
804        justification: "read-only introspection of the admitted engine; the handler retains tenant binding and readiness gating (query scope; schema-declared internal:pq-hybrid)",
805    },
806    DispatchMethodPolicy {
807        id: DispatchMethodId { service: "policy", method: policy_methods::CHECK },
808        method_name: "check",
809        label: SecurityLabel::bottom(),
810        justification: "authenticated declared services mediate PolicyService authorization checks; the handler derives subject and domain from the verified envelope and Casbin retains the federation decision",
811    },
812    DispatchMethodPolicy {
813        id: DispatchMethodId { service: "policy", method: policy_methods::ISSUE_TOKEN },
814        method_name: "issueToken",
815        label: OAUTH_ISSUANCE_LABEL,
816        justification: "the OAuth authority mints a session-bound credential through the schema-declared internal:pq-hybrid signing boundary; only a verified hybrid service:oauth envelope can dominate this row, while PolicyService retains target-tenant policy:IssueToken/manage, subject, tenant, audience, scope, session, client, confirmation, and signing checks",
817    },
818    DispatchMethodPolicy {
819        id: DispatchMethodId { service: "policy", method: policy_methods::GET_POLICY },
820        method_name: "getPolicy",
821        label: SecurityLabel::bottom(),
822        justification: "verified local PolicyService control-plane read; only the tokenless policy authority reaches this row",
823    },
824    DispatchMethodPolicy {
825        id: DispatchMethodId { service: "policy", method: policy_methods::APPLY_TEMPLATE },
826        method_name: "applyTemplate",
827        label: SecurityLabel::bottom(),
828        justification: "verified local PolicyService installs a reviewed bootstrap template; the handler still enforces Casbin writeback",
829    },
830    DispatchMethodPolicy {
831        id: DispatchMethodId { service: "policy", method: policy_methods::APPLY_DRAFT },
832        method_name: "applyDraft",
833        label: SecurityLabel::bottom(),
834        justification: "verified local PolicyService commits a local draft; the handler still enforces Casbin writeback",
835    },
836    DispatchMethodPolicy {
837        id: DispatchMethodId { service: "policy", method: policy_methods::ROLLBACK },
838        method_name: "rollback",
839        label: SecurityLabel::bottom(),
840        justification: "verified local PolicyService restores a local revision; the handler still enforces Casbin writeback",
841    },
842    DispatchMethodPolicy {
843        id: DispatchMethodId { service: "policy", method: policy_methods::GET_HISTORY },
844        method_name: "getHistory",
845        label: SecurityLabel::bottom(),
846        justification: "verified local PolicyService control-plane history read; only the tokenless policy authority reaches this row",
847    },
848    DispatchMethodPolicy {
849        id: DispatchMethodId { service: "policy", method: policy_methods::GET_DIFF },
850        method_name: "getDiff",
851        label: SecurityLabel::bottom(),
852        justification: "verified local PolicyService control-plane draft inspection; only the tokenless policy authority reaches this row",
853    },
854    DispatchMethodPolicy {
855        id: DispatchMethodId { service: "policy", method: policy_methods::GET_DRAFT_STATUS },
856        method_name: "getDraftStatus",
857        label: SecurityLabel::bottom(),
858        justification: "verified local PolicyService draft-state inspection; only the tokenless policy authority reaches this row",
859    },
860    DispatchMethodPolicy {
861        id: DispatchMethodId { service: "policy", method: policy_methods::ADD_GROUPING },
862        method_name: "addGrouping",
863        label: SecurityLabel::bottom(),
864        justification: "verified local PolicyService role update; the handler still enforces Casbin writeback",
865    },
866    DispatchMethodPolicy {
867        id: DispatchMethodId { service: "policy", method: policy_methods::REMOVE_GROUPING },
868        method_name: "removeGrouping",
869        label: SecurityLabel::bottom(),
870        justification: "verified local PolicyService role removal; the handler still enforces Casbin writeback",
871    },
872    DispatchMethodPolicy {
873        id: DispatchMethodId {
874            service: "policy",
875            method: policy_methods::REGISTER_SERVICE_KEY,
876        },
877        method_name: "registerServiceKey",
878        label: SecurityLabel::bottom(),
879        justification: "a keyed service installs its identity with the CA; \
880             bootstrap-critical (it precedes identity standing) and reachable \
881             only by declared service subjects; handler-level CA-JWT, subject, \
882             and cnf binding checks are unchanged",
883    },
884    DispatchMethodPolicy {
885        id: DispatchMethodId {
886            service: "policy",
887            method: policy_methods::REFRESH_SERVICE_TOKEN,
888        },
889        method_name: "refreshServiceToken",
890        label: SecurityLabel::bottom(),
891        justification: "a registered service renews the identity registration \
892             created; same bootstrap identity-lifecycle class — the handler \
893             re-binds cnf to the verified caller key and requires prior \
894             registration",
895    },
896];
897
898static BOOTSTRAP_SERVICE_CLEARANCES: &[ServiceSubjectClearance] = &[
899    ServiceSubjectClearance {
900        service: "discovery",
901        clearance: HYBRID_SERVICE_CLEARANCE,
902        justification: "the hybrid-enrolled discovery identity publishes its accepted native endpoint; verified envelope material clamps assurance",
903    },
904    ServiceSubjectClearance {
905        service: "event",
906        clearance: HYBRID_SERVICE_CLEARANCE,
907        justification: "the hybrid-enrolled event service publishes its accepted native endpoint; verified envelope material clamps assurance",
908    },
909    ServiceSubjectClearance {
910        service: "inference",
911        clearance: HYBRID_SERVICE_CLEARANCE,
912        justification: "the hybrid-enrolled engine service answers the declared \
913             internal:pq-hybrid inference rows; its handler retains tenant \
914             binding, admission, and spend-ledger checks",
915    },
916    ServiceSubjectClearance {
917        service: "model",
918        clearance: HYBRID_SERVICE_CLEARANCE,
919        justification: "the hybrid-enrolled model service mediates tenant- \
920             authorized generation to the schema-declared internal:pq-hybrid \
921             inference surface; its load/tenant admission checks are unchanged",
922    },
923    ServiceSubjectClearance {
924        service: "oai",
925        clearance: HYBRID_SERVICE_CLEARANCE,
926        justification: "the hybrid-enrolled OpenAI-compatible API bridges \
927             verified browser sessions to the schema-declared internal:pq- \
928             hybrid model/inference surfaces; session and tenant authorization \
929             run at this layer",
930    },
931    ServiceSubjectClearance {
932        service: "oauth",
933        clearance: OAUTH_ISSUANCE_LABEL,
934        justification: "the verified hybrid OAuth authority performs the declared internal:pq-hybrid session-token issuance boundary; its exact typed row and PolicyService authorization remain mandatory",
935    },
936    ServiceSubjectClearance {
937        service: "policy",
938        clearance: HYBRID_SERVICE_CLEARANCE,
939        justification: "the CA itself; its local control-plane rows are separately \
940             restricted to the verified tokenless service:policy authority",
941    },
942    ServiceSubjectClearance {
943        service: "registry",
944        clearance: HYBRID_SERVICE_CLEARANCE,
945        justification: "service/model registration is part of boot; registry \
946             registers its key at boot",
947    },
948    ServiceSubjectClearance {
949        service: "streams",
950        clearance: HYBRID_SERVICE_CLEARANCE,
951        justification: "the hybrid-enrolled streams service publishes its accepted native endpoint; stream authorization remains in its handler",
952    },
953];
954
955static PRODUCTION_TABLE: DeclaredDispatchTable =
956    DeclaredDispatchTable::from_rows(BOOTSTRAP_METHODS, BOOTSTRAP_SERVICE_CLEARANCES);
957
958#[cfg(test)]
959#[allow(clippy::unwrap_used, clippy::expect_used)]
960mod tests {
961    use super::*;
962
963    // ── fixtures ────────────────────────────────────────────────────────
964
965    fn service_subject_ctx(service: &str, key_byte: u8) -> EnvelopeContext {
966        let signer = ed25519_dalek::SigningKey::from_bytes(&[key_byte; 32]);
967        let claims = hyprstream_rpc::auth::Claims::new(format!("service:{service}"), 1, i64::MAX)
968            .with_clearance(BOOTSTRAP_SERVICE_CLEARANCE);
969        EnvelopeContext::for_test_authenticated_subject_with_claims(
970            hyprstream_rpc::Subject::new(format!("service:{service}")),
971            "test-tenant",
972            signer.verifying_key(),
973            claims,
974        )
975    }
976
977    fn user_subject_ctx() -> EnvelopeContext {
978        let signer = ed25519_dalek::SigningKey::from_bytes(&[0x77; 32]);
979        EnvelopeContext::for_test_authenticated_subject(
980            hyprstream_rpc::Subject::new("did:web:alice"),
981            signer.verifying_key(),
982        )
983    }
984
985    /// The production PEP exactly as the daemon installs it (identity-aware
986    /// activation control, production table).
987    fn production_pep() -> DeclaredDispatchPep {
988        DeclaredDispatchPep::new(DeclaredDispatchTable::production()).with_activation_control()
989    }
990
991    // ── table coverage: every declared (service, leaf) + clearance ──────
992
993    #[test]
994    fn every_declared_call_resolves_to_the_intended_typed_label_and_clearance() {
995        let table = DeclaredDispatchTable::production();
996
997        // The fresh boot graph declares the local PolicyService control-plane
998        // operations plus authenticated authorization checks, registration,
999        // and renewal. Every declared row resolves to the intended typed label
1000        // — the lattice floor, deliberate and reviewed.
1001        let expected: &[(u16, &str)] = &[
1002            (policy_methods::CHECK, "check"),
1003            (policy_methods::ISSUE_TOKEN, "issueToken"),
1004            (policy_methods::GET_POLICY, "getPolicy"),
1005            (policy_methods::APPLY_TEMPLATE, "applyTemplate"),
1006            (policy_methods::APPLY_DRAFT, "applyDraft"),
1007            (policy_methods::ROLLBACK, "rollback"),
1008            (policy_methods::GET_HISTORY, "getHistory"),
1009            (policy_methods::GET_DIFF, "getDiff"),
1010            (policy_methods::GET_DRAFT_STATUS, "getDraftStatus"),
1011            (policy_methods::ADD_GROUPING, "addGrouping"),
1012            (policy_methods::REMOVE_GROUPING, "removeGrouping"),
1013            (policy_methods::REGISTER_SERVICE_KEY, "registerServiceKey"),
1014            (policy_methods::REFRESH_SERVICE_TOKEN, "refreshServiceToken"),
1015        ];
1016        assert!(
1017            table.methods().len() > expected.len(),
1018            "the table must also carry the inference surface declared below"
1019        );
1020        for (method, name) in expected {
1021            let row = table
1022                .resolve_row("policy", Some(&[*method]))
1023                .unwrap_or_else(|| panic!("declared row for policy.{name} must resolve"));
1024            assert_eq!(row.method_name, *name);
1025            assert_eq!(row.id.service, "policy");
1026            let expected_label = if *method == policy_methods::ISSUE_TOKEN {
1027                OAUTH_ISSUANCE_LABEL
1028            } else {
1029                SecurityLabel::bottom()
1030            };
1031            assert_eq!(
1032                row.label, expected_label,
1033                "declared row {name} must retain its reviewed schema/bootstrap label"
1034            );
1035            assert!(!row.justification.is_empty());
1036        }
1037
1038        // Every schema-declared inference member resolves to the hybrid label.
1039        const INFERENCE_EXPECTED: &[(u16, &str)] = &[
1040            (inference_methods::GENERATE_STREAM, "generateStream"),
1041            (inference_methods::MODEL_INFO, "modelInfo"),
1042            (inference_methods::IS_READY, "isReady"),
1043            (inference_methods::APPLY_CHAT_TEMPLATE, "applyChatTemplate"),
1044            (inference_methods::CREATE_LORA, "createLora"),
1045            (inference_methods::LOAD_LORA, "loadLora"),
1046            (inference_methods::SAVE_LORA, "saveLora"),
1047            (inference_methods::UNLOAD_LORA, "unloadLora"),
1048            (inference_methods::HAS_LORA, "hasLora"),
1049            (inference_methods::SET_SESSION, "setSession"),
1050            (inference_methods::CLEAR_SESSION, "clearSession"),
1051            (inference_methods::RELEASE_SESSION, "releaseSession"),
1052            (inference_methods::HEALTH_CHECK, "healthCheck"),
1053            (inference_methods::SHUTDOWN, "shutdown"),
1054            (inference_methods::TTT_WRITEBACK, "tttWriteback"),
1055            (inference_methods::TTT_EVICT, "tttEvict"),
1056            (inference_methods::TRAIN_STEP, "trainStep"),
1057            (inference_methods::TTT_ZERO, "tttZero"),
1058            (inference_methods::GET_DELTA_STATUS, "getDeltaStatus"),
1059            (inference_methods::SAVE_ADAPTATION, "saveAdaptation"),
1060            (inference_methods::SNAPSHOT_DELTA, "snapshotDelta"),
1061            (inference_methods::TRAIN_STEP_STREAM, "trainStepStream"),
1062            (inference_methods::EXPORT_PEFT_ADAPTER, "exportPeftAdapter"),
1063            (inference_methods::MERGE_LORA, "mergeLora"),
1064            (inference_methods::CREATE_LORA_STREAM, "createLoraStream"),
1065            (inference_methods::LOAD_LORA_STREAM, "loadLoraStream"),
1066            (inference_methods::SAVE_LORA_STREAM, "saveLoraStream"),
1067            (
1068                inference_methods::SAVE_ADAPTATION_STREAM,
1069                "saveAdaptationStream",
1070            ),
1071            (
1072                inference_methods::SNAPSHOT_DELTA_STREAM,
1073                "snapshotDeltaStream",
1074            ),
1075            (
1076                inference_methods::EXPORT_PEFT_ADAPTER_STREAM,
1077                "exportPeftAdapterStream",
1078            ),
1079            (inference_methods::MERGE_LORA_STREAM, "mergeLoraStream"),
1080            (inference_methods::EMBED, "embed"),
1081            (inference_methods::GET_LAYER_PROFILE, "getLayerProfile"),
1082        ];
1083        for (method, name) in INFERENCE_EXPECTED {
1084            let row = table
1085                .resolve_row("inference", Some(&[*method]))
1086                .unwrap_or_else(|| panic!("declared row for inference.{name} must resolve"));
1087            assert_eq!(row.method_name, *name);
1088            assert_eq!(row.id.service, "inference");
1089            assert_eq!(
1090                row.label, INFERENCE_METHOD_LABEL,
1091                "inference.{name} must retain its schema-declared hybrid label"
1092            );
1093            assert!(!row.justification.is_empty());
1094        }
1095
1096        // The seven staging bootstrap services each hold the deliberate
1097        // service subject clearance, and each declared caller's clearance
1098        // dominates every declared object label (the boot calls evaluate).
1099        let mut services: Vec<&str> = table.clearances().iter().map(|row| row.service).collect();
1100        services.sort_unstable();
1101        assert_eq!(
1102            services,
1103            [
1104                "discovery",
1105                "event",
1106                "inference",
1107                "model",
1108                "oai",
1109                "oauth",
1110                "policy",
1111                "registry",
1112                "streams"
1113            ]
1114        );
1115        // Hybrid-enrolled runtime services hold the hybrid clearance; the
1116        // bootstrap identity-lifecycle services stay at the floor.
1117        const HYBRID_SERVICES: &[&str] = &[
1118            "discovery",
1119            "event",
1120            "inference",
1121            "model",
1122            "oai",
1123            "oauth",
1124            "policy",
1125            "registry",
1126            "streams",
1127        ];
1128        for row in table.clearances() {
1129            let is_hybrid = HYBRID_SERVICES.contains(&row.service);
1130            let expected_clearance = match row.service {
1131                "oauth" => OAUTH_ISSUANCE_LABEL,
1132                "discovery" | "event" | "model" | "oai" | "inference" | "policy" | "registry"
1133                | "streams" => HYBRID_SERVICE_CLEARANCE,
1134                _ => BOOTSTRAP_SERVICE_CLEARANCE,
1135            };
1136            assert_eq!(row.clearance, expected_clearance);
1137            assert_eq!(
1138                table.service_clearance(row.service),
1139                Some(row.clearance),
1140                "clearance lookup by canonical name"
1141            );
1142            assert!(!row.justification.is_empty());
1143            for method in table.methods() {
1144                let ctx = SecurityContext::from_clearance(
1145                    row.clearance,
1146                    if is_hybrid {
1147                        hyprstream_rpc::auth::mac::VerifiedKeyMaterial::PqHybrid
1148                    } else {
1149                        hyprstream_rpc::auth::mac::VerifiedKeyMaterial::Classical
1150                    },
1151                );
1152                // Hybrid-enrolled services dominate every declared row
1153                // (verified PqHybrid key material x hybrid clearance); floor
1154                // services dominate only the floor-labelled bootstrap rows —
1155                // never the schema-declared hybrid rows (issueToken,
1156                // inference.*).
1157                let expected = is_hybrid || method.label == SecurityLabel::bottom();
1158                assert_eq!(
1159                    ctx.can_access(&method.label),
1160                    expected,
1161                    "{} against {} ({})",
1162                    row.service,
1163                    method.label,
1164                    method.method_name
1165                );
1166            }
1167        }
1168    }
1169
1170    #[test]
1171    fn table_has_no_duplicate_or_unsorted_rows() {
1172        let table = DeclaredDispatchTable::production();
1173        let ids: Vec<DispatchMethodId> = table.methods().iter().map(|row| row.id).collect();
1174        let mut sorted = ids.clone();
1175        sorted.sort();
1176        sorted.dedup();
1177        assert_eq!(ids, sorted, "method rows must be sorted and unique");
1178        let services: Vec<&str> = table.clearances().iter().map(|row| row.service).collect();
1179        let mut sorted_services = services.clone();
1180        sorted_services.sort_unstable();
1181        sorted_services.dedup();
1182        assert_eq!(
1183            services, sorted_services,
1184            "clearance rows must be sorted and unique"
1185        );
1186    }
1187
1188    #[test]
1189    fn native_announce_row_matches_schema_and_requires_hybrid_identity() {
1190        let mut message = capnp::message::Builder::new_default();
1191        message
1192            .init_root::<hyprstream_rpc_std::discovery_capnp::discovery_request::Builder>()
1193            .init_announce();
1194        let bytes = capnp::serialize::write_message_to_words(&message);
1195        let method =
1196            hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap();
1197        assert_eq!(method, discovery_methods::ANNOUNCE);
1198        let table = DeclaredDispatchTable::production();
1199        let row = table.resolve_row("discovery", Some(&[method])).unwrap();
1200        assert_eq!(row.method_name, "announce");
1201        assert_eq!(row.label, HYBRID_SERVICE_CLEARANCE);
1202        let pep = DeclaredDispatchPep::new(table);
1203        for service in [
1204            "policy",
1205            "discovery",
1206            "registry",
1207            "event",
1208            "streams",
1209            "model",
1210            "oai",
1211            "oauth",
1212        ] {
1213            let clearance = table.service_clearance(service).unwrap();
1214            assert!(SecurityContext::from_clearance(
1215                clearance,
1216                hyprstream_rpc::auth::mac::VerifiedKeyMaterial::PqHybrid
1217            )
1218            .can_access(&row.label));
1219            assert!(!SecurityContext::from_clearance(
1220                clearance,
1221                hyprstream_rpc::auth::mac::VerifiedKeyMaterial::Classical
1222            )
1223            .can_access(&row.label));
1224            let ctx = EnvelopeContext::for_test_authenticated_subject(
1225                hyprstream_rpc::Subject::new(format!("service:{service}")),
1226                ed25519_dalek::SigningKey::from_bytes(&[0x31; 32]).verifying_key(),
1227            );
1228            assert_eq!(
1229                pep.check(&ctx, "discovery", Some(&[method])),
1230                MacDecision::Deny(MacDenyReason::NoClearance),
1231                "bearerless identity cannot announce"
1232            );
1233        }
1234        assert!(table.resolve_row("discovery", Some(&[method, 0])).is_none());
1235        assert!(table.resolve_row("discovery", Some(&[u16::MAX])).is_none());
1236    }
1237
1238    // ── deny-by-default: unknown service / leaf / VFS alias ─────────────
1239
1240    #[test]
1241    fn unknown_service_unknown_leaf_and_vfs_alias_resolve_to_none() {
1242        let table = DeclaredDispatchTable::production();
1243
1244        // Unknown service, even with a declared method number.
1245        assert!(table
1246            .resolve_row("ghost", Some(&[policy_methods::REGISTER_SERVICE_KEY]))
1247            .is_none());
1248        // Unknown leaf on a known service: resolveServiceKey (17) is a real
1249        // policy method but NOT declared — declaration, not schema, is the
1250        // authority.
1251        assert!(table.resolve_row("policy", Some(&[17])).is_none());
1252        // Out-of-schema leaf on a known service.
1253        assert!(table.resolve_row("policy", Some(&[u16::MAX])).is_none());
1254        // No committed method identity (a payload without a canonical
1255        // discriminant) matches no declared row, even on a known service.
1256        assert!(table.resolve_row("policy", None).is_none());
1257        // Bare/VFS-shaped aliases never enter the VFS adapter and never match.
1258        for alias in ["/srv/policy", "srv/policy", "/policy", "policy/", "/"] {
1259            assert!(
1260                table
1261                    .resolve_row(alias, Some(&[policy_methods::REGISTER_SERVICE_KEY]))
1262                    .is_none(),
1263                "VFS-shaped alias {alias:?} must not resolve"
1264            );
1265        }
1266        // Case and whitespace variants are not canonical names.
1267        assert!(table
1268            .resolve_row("Policy", Some(&[policy_methods::REGISTER_SERVICE_KEY]))
1269            .is_none());
1270        assert!(table
1271            .resolve_row(" policy", Some(&[policy_methods::REGISTER_SERVICE_KEY]))
1272            .is_none());
1273        // Undeclared service clearance.
1274        assert!(table.service_clearance("ghost").is_none());
1275        assert!(table.service_clearance("metrics").is_none());
1276
1277        // The RpcObjectLabelResolver view agrees (None ⇒ deny).
1278        let resolver: &dyn RpcObjectLabelResolver = table;
1279        assert!(resolver
1280            .resolve("policy", Some(&[policy_methods::REGISTER_SERVICE_KEY]))
1281            .is_some());
1282        assert!(resolver.resolve("policy", Some(&[17])).is_none());
1283        assert!(resolver
1284            .resolve("/srv/policy", Some(&[policy_methods::REGISTER_SERVICE_KEY]))
1285            .is_none());
1286    }
1287
1288    // ── causal PEP pair over the production table ───────────────────────
1289
1290    #[test]
1291    fn declared_call_permits_and_identical_undeclared_call_denies() {
1292        let pep = production_pep();
1293        let caller = service_subject_ctx("discovery", 0x61);
1294
1295        // Positive: the exact fresh-boot call — discovery registering its key.
1296        let declared = pep.check(
1297            &caller,
1298            "policy",
1299            Some(&[policy_methods::REGISTER_SERVICE_KEY]),
1300        );
1301        assert_eq!(
1302            declared,
1303            MacDecision::Permit,
1304            "declared (policy, registerServiceKey) from declared discovery must permit"
1305        );
1306
1307        // Causal twin: identical caller, identical service, undeclared leaf.
1308        let undeclared = pep.check(&caller, "policy", Some(&[17]));
1309        assert_eq!(
1310            undeclared,
1311            MacDecision::Deny(MacDenyReason::UnlabeledObject),
1312            "an otherwise identical undeclared call must deny UnlabeledObject"
1313        );
1314
1315        // Unknown service denies the same way.
1316        assert_eq!(
1317            pep.check(
1318                &caller,
1319                "ghost",
1320                Some(&[policy_methods::REGISTER_SERVICE_KEY])
1321            ),
1322            MacDecision::Deny(MacDenyReason::UnlabeledObject)
1323        );
1324
1325        // VFS-shaped alias of a declared pair denies (never routed through the
1326        // VFS adapter).
1327        assert_eq!(
1328            pep.check(
1329                &caller,
1330                "/srv/policy",
1331                Some(&[policy_methods::REGISTER_SERVICE_KEY])
1332            ),
1333            MacDecision::Deny(MacDenyReason::UnlabeledObject)
1334        );
1335
1336        // No committed method identity ⇒ no declared row ⇒ deny.
1337        assert_eq!(
1338            pep.check(&caller, "policy", None),
1339            MacDecision::Deny(MacDenyReason::UnlabeledObject)
1340        );
1341    }
1342
1343    #[test]
1344    fn authenticated_oauth_policy_methods_require_exact_declared_hybrid_authority() {
1345        let pep = production_pep();
1346        let oauth = service_subject_ctx("oauth", 0x66);
1347
1348        // The PAR registration path is an authenticated service:oauth call to
1349        // PolicyRequest.check (union ordinal zero). It must resolve through
1350        // the normal declared-service PEP, not a tokenless policy exception.
1351        assert_eq!(
1352            pep.check(&oauth, "policy", Some(&[policy_methods::CHECK])),
1353            MacDecision::Permit,
1354            "verified service:oauth must reach the declared policy.check leaf"
1355        );
1356
1357        // The real production client test below verifies a hybrid envelope;
1358        // this classical fixture intentionally cannot dominate issueToken's
1359        // schema-declared internal:pq-hybrid label.
1360        assert_eq!(
1361            pep.check(&oauth, "policy", Some(&[policy_methods::ISSUE_TOKEN])),
1362            MacDecision::Deny(MacDenyReason::FloorDeny),
1363            "a classical envelope must not reach the PQ-hybrid token issuer"
1364        );
1365
1366        // The same floor-labelled object remains unavailable to an
1367        // undeclared service, a non-service subject, and a keyless callback.
1368        // Adding the row therefore cannot fabricate an anonymous clearance.
1369        let ghost = service_subject_ctx("ghost", 0x67);
1370        assert_eq!(
1371            pep.check(&ghost, "policy", Some(&[policy_methods::CHECK])),
1372            MacDecision::Deny(MacDenyReason::NoClearance)
1373        );
1374        let user = user_subject_ctx();
1375        assert_eq!(
1376            pep.check(&user, "policy", Some(&[policy_methods::CHECK])),
1377            MacDecision::Deny(MacDenyReason::NoClearance)
1378        );
1379        let callback = EnvelopeContext::from_callback_service(1, "oauth");
1380        assert_eq!(
1381            pep.check(&callback, "policy", Some(&[policy_methods::CHECK])),
1382            MacDecision::Deny(MacDenyReason::NoClearance)
1383        );
1384    }
1385
1386    #[test]
1387    fn permit_requires_the_deliberate_service_clearance_not_the_anonymous_floor() {
1388        let pep = production_pep();
1389
1390        // An undeclared service subject denies even for a declared object row:
1391        // the activation floor alone must NOT carry a caller into the table —
1392        // that is the fabricated-anonymous-clearance hole this slice closes.
1393        let ghost = service_subject_ctx("ghost", 0x62);
1394        assert_eq!(
1395            pep.check(
1396                &ghost,
1397                "policy",
1398                Some(&[policy_methods::REGISTER_SERVICE_KEY])
1399            ),
1400            MacDecision::Deny(MacDenyReason::NoClearance),
1401            "undeclared service subject must deny NoClearance"
1402        );
1403
1404        // A non-service (user) identity has no service clearance.
1405        let user = user_subject_ctx();
1406        assert_eq!(
1407            pep.check(
1408                &user,
1409                "policy",
1410                Some(&[policy_methods::REGISTER_SERVICE_KEY])
1411            ),
1412            MacDecision::Deny(MacDenyReason::NoClearance)
1413        );
1414
1415        // A keyless internal callback context (zeroed cnf) asserting a service
1416        // subject has no authenticated signer key and must not inherit the
1417        // declared clearance.
1418        let callback = EnvelopeContext::from_callback_service(1, "discovery");
1419        assert_eq!(
1420            pep.check(
1421                &callback,
1422                "policy",
1423                Some(&[policy_methods::REGISTER_SERVICE_KEY])
1424            ),
1425            MacDecision::Deny(MacDenyReason::NoClearance),
1426            "keyless callback contexts must not claim a service clearance"
1427        );
1428
1429        // Every declared bootstrap service caller permits the boot
1430        // registration call (deliberate clearance composed with verified key
1431        // material).
1432        for service in [
1433            "discovery",
1434            "event",
1435            "model",
1436            "oai",
1437            "oauth",
1438            "policy",
1439            "registry",
1440        ] {
1441            let ctx = service_subject_ctx(service, 0x63);
1442            assert_eq!(
1443                pep.check(
1444                    &ctx,
1445                    "policy",
1446                    Some(&[policy_methods::REGISTER_SERVICE_KEY])
1447                ),
1448                MacDecision::Permit,
1449                "declared service:{service} must permit the declared bootstrap call"
1450            );
1451        }
1452    }
1453
1454    #[test]
1455    fn floor_deny_when_declared_clearance_cannot_dominate_the_label() {
1456        // Fixture table: a declared row above the declared clearance. Both
1457        // dominance checks must hold; here the declared service context
1458        // (Internal) cannot dominate a Secret object label.
1459        static SECRET_ROW: &[DispatchMethodPolicy] = &[DispatchMethodPolicy {
1460            id: DispatchMethodId {
1461                service: "policy",
1462                method: 7,
1463            },
1464            method_name: "fixture",
1465            label: SecurityLabel {
1466                level: Level::Secret,
1467                assurance: Assurance::Unverified,
1468                compartments: CompartmentSet::EMPTY,
1469            },
1470            justification: "test fixture: label deliberately above the declared clearance",
1471        }];
1472        static TABLE: DeclaredDispatchTable =
1473            DeclaredDispatchTable::from_rows(SECRET_ROW, BOOTSTRAP_SERVICE_CLEARANCES);
1474        let pep = DeclaredDispatchPep::new(&TABLE).with_activation_control();
1475        let caller = service_subject_ctx("discovery", 0x64);
1476        assert_eq!(
1477            pep.check(&caller, "policy", Some(&[7])),
1478            MacDecision::Deny(MacDenyReason::FloorDeny),
1479            "a label above the declared clearance must FloorDeny"
1480        );
1481    }
1482
1483    // ── installed-PEP causal pair ───────────────────────────────────────
1484    //
1485    // The process-global install + "the PEP stayed installed" assertion lives
1486    // in the integration binary `tests/mac_dispatch_boot_labeling.rs`, which
1487    // owns its own globals; lib tests share this binary's global PEP slot with
1488    // the `install_explicit_test_dispatch_pep` plumbing fixtures and cannot
1489    // serialize against them.
1490
1491    // ── drift: declared discriminants == real schema discriminants ──────
1492
1493    #[test]
1494    fn declared_policy_discriminants_match_the_serialized_schema() {
1495        use capnp::message::Builder;
1496
1497        // check
1498        let mut message = Builder::new_default();
1499        {
1500            let mut req =
1501                message.init_root::<hyprstream_rpc_std::policy_capnp::policy_request::Builder>();
1502            req.set_id(1);
1503            let mut check = req.reborrow().init_check();
1504            check.set_subject("service:oauth");
1505            check.set_domain("");
1506            check.set_resource("federation:register:https://signup.example.test");
1507            check.set_operation("check");
1508        }
1509        let bytes = capnp::serialize::write_message_to_words(&message);
1510        assert_eq!(
1511            hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1512            policy_methods::CHECK,
1513            "the declared check discriminant must match the schema union ordinal"
1514        );
1515
1516        // issueToken
1517        let mut message = Builder::new_default();
1518        {
1519            let mut req =
1520                message.init_root::<hyprstream_rpc_std::policy_capnp::policy_request::Builder>();
1521            req.set_id(1);
1522            req.reborrow().init_issue_token();
1523        }
1524        let bytes = capnp::serialize::write_message_to_words(&message);
1525        assert_eq!(
1526            hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1527            policy_methods::ISSUE_TOKEN,
1528            "the declared issueToken discriminant must match the schema union ordinal"
1529        );
1530
1531        // getPolicy
1532        let mut message = Builder::new_default();
1533        {
1534            let mut req =
1535                message.init_root::<hyprstream_rpc_std::policy_capnp::policy_request::Builder>();
1536            req.set_id(1);
1537            req.set_get_policy(());
1538        }
1539        let bytes = capnp::serialize::write_message_to_words(&message);
1540        assert_eq!(
1541            hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1542            policy_methods::GET_POLICY,
1543            "the declared getPolicy discriminant must match the schema union ordinal"
1544        );
1545
1546        // applyTemplate
1547        let mut message = Builder::new_default();
1548        {
1549            let mut req =
1550                message.init_root::<hyprstream_rpc_std::policy_capnp::policy_request::Builder>();
1551            req.set_id(1);
1552            req.reborrow().init_apply_template().set_name("public-read");
1553        }
1554        let bytes = capnp::serialize::write_message_to_words(&message);
1555        assert_eq!(
1556            hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1557            policy_methods::APPLY_TEMPLATE,
1558            "the declared applyTemplate discriminant must match the schema union ordinal"
1559        );
1560
1561        // applyDraft
1562        let mut message = Builder::new_default();
1563        {
1564            let mut req =
1565                message.init_root::<hyprstream_rpc_std::policy_capnp::policy_request::Builder>();
1566            req.set_id(1);
1567            req.reborrow().init_apply_draft();
1568        }
1569        let bytes = capnp::serialize::write_message_to_words(&message);
1570        assert_eq!(
1571            hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1572            policy_methods::APPLY_DRAFT,
1573            "the declared applyDraft discriminant must match the schema union ordinal"
1574        );
1575
1576        // rollback
1577        let mut message = Builder::new_default();
1578        {
1579            let mut req =
1580                message.init_root::<hyprstream_rpc_std::policy_capnp::policy_request::Builder>();
1581            req.set_id(1);
1582            req.reborrow().init_rollback().set_git_ref("HEAD");
1583        }
1584        let bytes = capnp::serialize::write_message_to_words(&message);
1585        assert_eq!(
1586            hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1587            policy_methods::ROLLBACK,
1588            "the declared rollback discriminant must match the schema union ordinal"
1589        );
1590
1591        // getHistory
1592        let mut message = Builder::new_default();
1593        {
1594            let mut req =
1595                message.init_root::<hyprstream_rpc_std::policy_capnp::policy_request::Builder>();
1596            req.set_id(1);
1597            req.reborrow().init_get_history().set_count(1);
1598        }
1599        let bytes = capnp::serialize::write_message_to_words(&message);
1600        assert_eq!(
1601            hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1602            policy_methods::GET_HISTORY,
1603            "the declared getHistory discriminant must match the schema union ordinal"
1604        );
1605
1606        // getDiff
1607        let mut message = Builder::new_default();
1608        {
1609            let mut req =
1610                message.init_root::<hyprstream_rpc_std::policy_capnp::policy_request::Builder>();
1611            req.set_id(1);
1612            req.reborrow().init_get_diff();
1613        }
1614        let bytes = capnp::serialize::write_message_to_words(&message);
1615        assert_eq!(
1616            hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1617            policy_methods::GET_DIFF,
1618            "the declared getDiff discriminant must match the schema union ordinal"
1619        );
1620
1621        // getDraftStatus
1622        let mut message = Builder::new_default();
1623        {
1624            let mut req =
1625                message.init_root::<hyprstream_rpc_std::policy_capnp::policy_request::Builder>();
1626            req.set_id(1);
1627            req.set_get_draft_status(());
1628        }
1629        let bytes = capnp::serialize::write_message_to_words(&message);
1630        assert_eq!(
1631            hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1632            policy_methods::GET_DRAFT_STATUS,
1633            "the declared getDraftStatus discriminant must match the schema union ordinal"
1634        );
1635
1636        // addGrouping
1637        let mut message = Builder::new_default();
1638        {
1639            let mut req =
1640                message.init_root::<hyprstream_rpc_std::policy_capnp::policy_request::Builder>();
1641            req.set_id(1);
1642            let mut call = req.reborrow().init_add_grouping();
1643            call.set_user("bootstrap-user");
1644            call.set_role("viewer");
1645        }
1646        let bytes = capnp::serialize::write_message_to_words(&message);
1647        assert_eq!(
1648            hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1649            policy_methods::ADD_GROUPING,
1650            "the declared addGrouping discriminant must match the schema union ordinal"
1651        );
1652
1653        // removeGrouping
1654        let mut message = Builder::new_default();
1655        {
1656            let mut req =
1657                message.init_root::<hyprstream_rpc_std::policy_capnp::policy_request::Builder>();
1658            req.set_id(1);
1659            let mut call = req.reborrow().init_remove_grouping();
1660            call.set_user("bootstrap-user");
1661            call.set_role("viewer");
1662        }
1663        let bytes = capnp::serialize::write_message_to_words(&message);
1664        assert_eq!(
1665            hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1666            policy_methods::REMOVE_GROUPING,
1667            "the declared removeGrouping discriminant must match the schema union ordinal"
1668        );
1669
1670        // registerServiceKey
1671        let mut message = Builder::new_default();
1672        {
1673            let mut req =
1674                message.init_root::<hyprstream_rpc_std::policy_capnp::policy_request::Builder>();
1675            req.set_id(1);
1676            let mut call = req.reborrow().init_register_service_key();
1677            call.set_service_name("discovery");
1678            call.set_verifying_key(&[0x42; 32]);
1679            call.set_service_jwt("header.payload.signature");
1680        }
1681        let bytes = capnp::serialize::write_message_to_words(&message);
1682        assert_eq!(
1683            hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1684            policy_methods::REGISTER_SERVICE_KEY,
1685            "the declared registerServiceKey discriminant must match the schema union ordinal"
1686        );
1687
1688        // refreshServiceToken
1689        let mut message = Builder::new_default();
1690        {
1691            let mut req =
1692                message.init_root::<hyprstream_rpc_std::policy_capnp::policy_request::Builder>();
1693            req.set_id(1);
1694            req.reborrow()
1695                .init_refresh_service_token()
1696                .set_ttl_seconds(2_592_000);
1697        }
1698        let bytes = capnp::serialize::write_message_to_words(&message);
1699        assert_eq!(
1700            hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1701            policy_methods::REFRESH_SERVICE_TOKEN,
1702            "the declared refreshServiceToken discriminant must match the schema union ordinal"
1703        );
1704
1705        // inference.generateStream — lowest declared ordinal (schema assigns
1706        // no @0 member; the union starts at @1).
1707        let mut message = Builder::new_default();
1708        {
1709            let mut req = message
1710                .init_root::<hyprstream_rpc_std::inference_capnp::inference_request::Builder>();
1711            req.set_id(1);
1712            req.reborrow().init_generate_stream();
1713        }
1714        let bytes = capnp::serialize::write_message_to_words(&message);
1715        assert_eq!(
1716            hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1717            inference_methods::GENERATE_STREAM,
1718            "the declared generateStream discriminant must match the schema union ordinal"
1719        );
1720
1721        // inference.healthCheck — mid-table ordinal 13.
1722        let mut message = Builder::new_default();
1723        {
1724            let mut req = message
1725                .init_root::<hyprstream_rpc_std::inference_capnp::inference_request::Builder>();
1726            req.set_id(1);
1727            req.set_health_check(());
1728        }
1729        let bytes = capnp::serialize::write_message_to_words(&message);
1730        assert_eq!(
1731            hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1732            inference_methods::HEALTH_CHECK,
1733            "the declared healthCheck discriminant must match the schema union ordinal"
1734        );
1735
1736        // inference.embed — high ordinal 32.
1737        let mut message = Builder::new_default();
1738        {
1739            let mut req = message
1740                .init_root::<hyprstream_rpc_std::inference_capnp::inference_request::Builder>();
1741            req.set_id(1);
1742            req.reborrow().init_embed();
1743        }
1744        let bytes = capnp::serialize::write_message_to_words(&message);
1745        assert_eq!(
1746            hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1747            inference_methods::EMBED,
1748            "the declared embed discriminant must match the schema union ordinal"
1749        );
1750
1751        // inference.getLayerProfile — highest declared ordinal 33.
1752        let mut message = Builder::new_default();
1753        {
1754            let mut req = message
1755                .init_root::<hyprstream_rpc_std::inference_capnp::inference_request::Builder>();
1756            req.set_id(1);
1757            req.set_get_layer_profile(());
1758        }
1759        let bytes = capnp::serialize::write_message_to_words(&message);
1760        assert_eq!(
1761            hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1762            inference_methods::GET_LAYER_PROFILE,
1763            "the declared getLayerProfile discriminant must match the schema union ordinal"
1764        );
1765    }
1766
1767    // ── drift: declared services exist in the factory inventory ─────────
1768
1769    #[test]
1770    fn declared_bootstrap_services_are_registered_factories() {
1771        let registered: Vec<&str> = hyprstream_service::list_factories()
1772            .map(|factory| factory.name)
1773            .collect();
1774        for row in DeclaredDispatchTable::production().clearances() {
1775            assert!(
1776                registered.contains(&row.service),
1777                "declared bootstrap service {} must be a registered service factory",
1778                row.service
1779            );
1780        }
1781        for row in DeclaredDispatchTable::production().methods() {
1782            assert!(
1783                registered.contains(&row.id.service),
1784                "declared dispatch target {} must be a registered service factory",
1785                row.id.service
1786            );
1787        }
1788    }
1789}