Skip to main content

lean_ctx/core/ocla/
invocation.rs

1//! Common invocation and measurement envelopes for OCLA capability adapters.
2
3use std::collections::BTreeMap;
4
5use lean_ctx_protocol::CapabilityManifestV1;
6use serde::{Deserialize, Serialize};
7
8use super::{OclaError, OclaResult};
9
10/// Version of the public observation shape emitted by native adapters.
11pub const CAPABILITY_OBSERVATION_SCHEMA_VERSION: u32 = 1;
12
13/// Input accepted by a capability adapter.
14#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
15#[serde(rename_all = "snake_case")]
16pub enum CapabilityInput {
17    ContextRequest {
18        paths: Vec<String>,
19        mode: String,
20        budget_tokens: Option<u64>,
21    },
22    ShellCommand {
23        command: String,
24        workdir: Option<String>,
25    },
26    ModelRequest {
27        prompt: String,
28        model: Option<String>,
29    },
30}
31
32impl CapabilityInput {
33    /// Returns the payload measured by the common token envelope.
34    #[must_use]
35    pub fn payload(&self) -> &str {
36        match self {
37            Self::ContextRequest { paths, .. } => paths.first().map(String::as_str).unwrap_or(""),
38            Self::ShellCommand { command, .. } => command,
39            Self::ModelRequest { prompt, .. } => prompt,
40        }
41    }
42}
43
44/// Policy limits applied uniformly before and after adapter execution.
45#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
46#[serde(default)]
47pub struct PolicyConstraints {
48    pub max_input_tokens: Option<u64>,
49    pub max_output_tokens: Option<u64>,
50    pub max_latency_ms: Option<u64>,
51    pub allowed_models: Vec<String>,
52    pub allowed_paths: Vec<String>,
53    pub allowed_data_classifications: Vec<String>,
54    pub allow_remote: bool,
55    pub require_deterministic: bool,
56    pub require_reversible: bool,
57}
58
59impl PolicyConstraints {
60    /// Validate internal policy invariants.
61    pub fn validate(&self) -> OclaResult<()> {
62        if self
63            .allowed_models
64            .iter()
65            .chain(self.allowed_paths.iter())
66            .chain(self.allowed_data_classifications.iter())
67            .any(|value| value.trim().is_empty())
68        {
69            return Err(OclaError::InvalidRequest(
70                "policy constraint lists must not contain empty values".into(),
71            ));
72        }
73        Ok(())
74    }
75
76    /// Apply the model/path portions of policy to an invocation.
77    pub fn check_input(&self, input: &CapabilityInput) -> OclaResult<()> {
78        self.validate()?;
79        match input {
80            CapabilityInput::ContextRequest { paths, .. } => {
81                if !self.allowed_paths.is_empty()
82                    && paths
83                        .iter()
84                        .any(|path| !self.allowed_paths.iter().any(|allowed| path == allowed))
85                {
86                    return Err(OclaError::InvalidRequest(
87                        "context path is outside policy allowlist".into(),
88                    ));
89                }
90            }
91            CapabilityInput::ModelRequest { model, .. } => {
92                if !self.allowed_models.is_empty()
93                    && model.as_ref().is_none_or(|model| {
94                        !self.allowed_models.iter().any(|allowed| allowed == model)
95                    })
96                {
97                    return Err(OclaError::InvalidRequest(
98                        "model is outside policy allowlist".into(),
99                    ));
100                }
101            }
102            CapabilityInput::ShellCommand { .. } => {}
103        }
104        Ok(())
105    }
106}
107
108/// A single capability invocation with task and policy lineage attached.
109#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
110#[serde(deny_unknown_fields)]
111pub struct CapabilityInvocation {
112    pub task_id: String,
113    pub capability_id: String,
114    pub capability_version: String,
115    pub input: CapabilityInput,
116    pub policy_constraints: PolicyConstraints,
117    pub timeout_ms: u64,
118}
119
120impl CapabilityInvocation {
121    /// Validate identity and policy fields before dispatch.
122    pub fn validate(&self) -> OclaResult<()> {
123        for (label, value) in [
124            ("task_id", &self.task_id),
125            ("capability_id", &self.capability_id),
126            ("capability_version", &self.capability_version),
127        ] {
128            if value.trim().is_empty() {
129                return Err(OclaError::InvalidRequest(format!("{label} is required")));
130            }
131        }
132        self.policy_constraints.check_input(&self.input)
133    }
134}
135
136/// Failure taxonomy shared by all adapters.
137#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
138#[serde(rename_all = "snake_case")]
139pub enum CapabilityFailureMode {
140    Timeout,
141    Unavailable,
142    RejectedByPolicy,
143    InvalidOutput,
144    Partial,
145    FallbackToNative,
146    Internal,
147}
148
149/// Comparable, payload-free measurement emitted for one invocation.
150#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
151#[serde(deny_unknown_fields)]
152pub struct CapabilityObservationV1 {
153    pub schema_version: u32,
154    pub task_id: String,
155    pub capability_id: String,
156    pub capability_version: String,
157    pub success: bool,
158    pub input_tokens: u64,
159    pub output_tokens: u64,
160    pub latency_ms: u64,
161    pub failure_mode: Option<CapabilityFailureMode>,
162    pub output_ref: Option<String>,
163    pub metrics: BTreeMap<String, u64>,
164}
165
166impl CapabilityObservationV1 {
167    /// Build the successful observation shared by native adapters.
168    #[must_use]
169    pub fn success(
170        invocation: &CapabilityInvocation,
171        input_tokens: u64,
172        output_tokens: u64,
173        latency_ms: u64,
174        output_ref: Option<String>,
175    ) -> Self {
176        Self {
177            schema_version: CAPABILITY_OBSERVATION_SCHEMA_VERSION,
178            task_id: invocation.task_id.clone(),
179            capability_id: invocation.capability_id.clone(),
180            capability_version: invocation.capability_version.clone(),
181            success: true,
182            input_tokens,
183            output_tokens,
184            latency_ms,
185            failure_mode: None,
186            output_ref,
187            metrics: BTreeMap::new(),
188        }
189    }
190}
191
192/// Result returned by every adapter through the common invocation path.
193#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
194#[serde(deny_unknown_fields)]
195pub struct CapabilityResult {
196    pub success: bool,
197    pub output_tokens: u64,
198    pub latency_ms: u64,
199    pub observation: CapabilityObservationV1,
200    pub evidence_ref: Option<String>,
201}
202
203/// Adapter boundary shared by native, reference, and enterprise capabilities.
204pub trait CapabilityAdapter: Send + Sync {
205    fn manifest(&self) -> &CapabilityManifestV1;
206    fn invoke(&self, invocation: CapabilityInvocation) -> OclaResult<CapabilityResult>;
207    fn health_check(&self) -> OclaResult<bool>;
208}
209
210/// Create a stable content-addressed evidence reference without exposing data.
211#[must_use]
212pub(crate) fn evidence_ref(content: &str) -> String {
213    format!("blake3:{}", blake3::hash(content.as_bytes()).to_hex())
214}
215
216/// Enforce the invocation timeout after a synchronous adapter operation.
217pub(crate) fn check_timeout(start: std::time::Instant, timeout_ms: u64) -> OclaResult<u64> {
218    let elapsed_ms = start.elapsed().as_millis() as u64;
219    if timeout_ms != 0 && elapsed_ms > timeout_ms {
220        return Err(OclaError::InvalidRequest(format!(
221            "capability invocation exceeded timeout ({elapsed_ms}ms > {timeout_ms}ms)"
222        )));
223    }
224    Ok(elapsed_ms)
225}