Skip to main content

evorule_plugin_kit/
gateway.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2// Copyright (C) 2026 EvoRule Project
3// This file is part of EvoRule, licensed under GNU Affero General Public License v3 or later.
4//! Mechanism gateway: the single injection point for canonical mechanism
5//! execution (meta-instruction evaluation) into plugin families.
6//!
7//! The plugin-kit crate deliberately carries **no** dependency on the
8//! canonical repo (`evorule-tcb` / `evorule-reactor`). Mechanism-dependent
9//! services (e.g. the inference family's forward simulation) obtain their
10//! meta-instruction executor exclusively through this gateway, which the
11//! host process registers at startup:
12//!
13//! - **Hosts** (the canonical consumer of the mechanism layer, e.g.
14//!   `evorule-server`) implement [`MechanismGateway`] and call
15//!   [`register_mechanism_gateway`] during plugin loading. This keeps the
16//!   service entry point (`evorule-server`) as the only legitimate consumer
17//!   of canonical mechanism capabilities.
18//! - **Guests** (wasm32 family modules) ship **without** a gateway: their
19//!   compile graph contains no canonical crates at all, and any
20//!   mechanism-dependent call fails visibly with
21//!   [`GATEWAY_UNAVAILABLE_ERR`] (never a silent fallback, never a stub
22//!   impersonating the real mechanism).
23//!
24//! # Failure semantics (fail-visible)
25//!
26//! [`require_mechanism_gateway`] returns a self-describing error when no
27//! gateway has been registered. Callers surface this error through their
28//! regular business-error channel; nothing degrades silently.
29//!
30//! # Result mirroring
31//!
32//! [`MetaOutcome`] mirrors the canonical executor's result enum arm-for-arm
33//! (state / io-required / halted). The host-side implementation performs a
34//! mechanical three-arm mapping; no semantic reinterpretation happens on
35//! either side of the boundary.
36
37#![forbid(unsafe_code)]
38
39use std::sync::{Arc, OnceLock};
40
41use crate::reexports::JsonValue;
42
43/// Canonical fail-visible error for mechanism calls without a registered
44/// gateway. Byte-stable by design: host-side and guest-side runs must
45/// produce the identical error text so downstream golden vectors and
46/// parity comparisons stay deterministic.
47pub const GATEWAY_UNAVAILABLE_ERR: &str = "mechanism gateway not available in this runtime \
48     (guest runtimes ship without a mechanism gateway by design; hosts must register one via \
49     register_mechanism_gateway at startup)";
50
51/// Outcome of one meta-instruction execution, mirrored arm-for-arm from the
52/// canonical executor's result type (state / io-required / halted).
53///
54/// This mirror lives in plugin-kit (not in the primitive-types layer) on
55/// purpose: it carries mechanism semantics, which must not leak into the
56/// base value-domain crate.
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub enum MetaOutcome {
59    /// Execution produced an updated state document.
60    State(JsonValue),
61    /// I/O request signal (propagates immediately; no further instructions
62    /// execute within the step).
63    IoRequired {
64        /// I/O type (e.g. `call_external`, `query_db`).
65        io_type: String,
66        /// I/O request parameters (path references already resolved to
67        /// concrete values).
68        params: JsonValue,
69    },
70    /// Enforce-primitive hit: pure halt signal, no state attached; any
71    /// state modification made before the hit is discarded by the
72    /// canonical transition layer.
73    Halted {
74        /// Violation description (enforce `params.reason`, echoed for
75        /// violation-fact audit).
76        reason: String,
77    },
78}
79
80/// Host-side mechanism executor: synchronous pure-function view over the
81/// canonical meta-instruction state machine.
82pub trait MechanismGateway: Send + Sync {
83    /// Execute one meta instruction against `state` at nesting `depth`,
84    /// returning the mirrored outcome. Errors are plain strings (the host
85    /// implementation flattens the canonical error type via `Display`).
86    ///
87    /// # Errors
88    ///
89    /// Budget exhaustion, depth overrun, or an invalid instruction tree —
90    /// passed through verbatim from the canonical executor.
91    fn execute_meta_instruction(
92        &self,
93        instr: &JsonValue,
94        state: JsonValue,
95        depth: usize,
96    ) -> Result<MetaOutcome, String>;
97}
98
99static GATEWAY: OnceLock<Arc<dyn MechanismGateway>> = OnceLock::new();
100
101/// Register the process-wide mechanism gateway (host startup / plugin
102/// loading path).
103///
104/// # Errors
105///
106/// A gateway is already registered — fail-fast, no silent replacement (the
107/// first registration wins for the lifetime of the process).
108pub fn register_mechanism_gateway(gateway: Arc<dyn MechanismGateway>) -> Result<(), String> {
109    GATEWAY.set(gateway).map_err(|_| {
110        "a mechanism gateway is already registered - fail-fast, no silent replacement \
111         (register_mechanism_gateway must be called exactly once per process)"
112            .to_string()
113    })
114}
115
116/// Registered gateway, if any. Hosts register at startup; guests never do.
117pub fn mechanism_gateway() -> Option<&'static Arc<dyn MechanismGateway>> {
118    GATEWAY.get()
119}
120
121/// Fail-visible accessor: the registered gateway or
122/// [`GATEWAY_UNAVAILABLE_ERR`]. Mechanism-dependent services must go through
123/// this accessor (never silently degrade when [`mechanism_gateway`] is
124/// `None`).
125///
126/// # Errors
127///
128/// No gateway registered in this runtime (guest case, or a host that missed
129/// its startup registration).
130pub fn require_mechanism_gateway() -> Result<&'static Arc<dyn MechanismGateway>, String> {
131    GATEWAY
132        .get()
133        .ok_or_else(|| GATEWAY_UNAVAILABLE_ERR.to_string())
134}