lean_ctx/core/ocla/adapters/
native_context.rs1use std::path::{Path, PathBuf};
4use std::sync::OnceLock;
5use std::time::Instant;
6
7use lean_ctx_protocol::CapabilityManifestV1;
8use sha2::{Digest, Sha256};
9
10use super::read_context_paths;
11use crate::core::compressor;
12use crate::core::ocla::invocation::{
13 CapabilityAdapter, CapabilityInput, CapabilityInvocation, CapabilityObservationV1,
14 CapabilityResult, evidence_ref,
15};
16use crate::core::ocla::{OclaError, OclaResult};
17use crate::core::tokens;
18
19pub const MANIFEST_PATH: &str =
21 "docs/contracts/ocla/capability-manifests/leanctx/context-optimization-v1.json";
22const MANIFEST_JSON: &str = include_str!(concat!(
23 env!("CARGO_MANIFEST_DIR"),
24 "/assets/ocla/capability-manifests/leanctx/context-optimization-v1.json"
25));
26
27fn manifest() -> &'static CapabilityManifestV1 {
28 static MANIFEST: OnceLock<CapabilityManifestV1> = OnceLock::new();
29 MANIFEST.get_or_init(|| {
30 let manifest: CapabilityManifestV1 =
31 serde_json::from_str(MANIFEST_JSON).expect("native context manifest is valid JSON");
32 manifest
33 .validate()
34 .expect("native context manifest satisfies the protocol");
35 manifest
36 })
37}
38
39pub struct NativeContextAdapter {
41 root: PathBuf,
42 #[cfg(test)]
43 materialized_test_control: Option<std::sync::Arc<MaterializedTestControl>>,
44}
45
46#[cfg(test)]
47pub(crate) struct MaterializedTestControl {
48 pub(crate) release: std::sync::Barrier,
49 pub(crate) completed: std::sync::Barrier,
50}
51
52#[cfg(test)]
53impl MaterializedTestControl {
54 pub(crate) fn new() -> Self {
55 Self {
56 release: std::sync::Barrier::new(2),
57 completed: std::sync::Barrier::new(2),
58 }
59 }
60}
61
62#[allow(dead_code)]
68pub(crate) struct NativeContextInvocationResult {
69 pub result: CapabilityResult,
70 pub input_digest: String,
71 pub output_digest: String,
72 pub(crate) output: Vec<u8>,
76}
77
78#[derive(Debug)]
83pub(crate) enum NativeContextInvocationFailure {
84 SourceUnavailable(String),
85 ResourceLimit(String),
86 UnsupportedInput,
87 InvalidRequest(String),
88}
89
90impl NativeContextInvocationFailure {
91 fn into_ocla_error(self) -> OclaError {
92 let message = match self {
93 Self::SourceUnavailable(message)
94 | Self::ResourceLimit(message)
95 | Self::InvalidRequest(message) => message,
96 Self::UnsupportedInput => {
97 "native context optimization accepts ContextRequest only".to_owned()
98 }
99 };
100 OclaError::InvalidRequest(message)
101 }
102}
103
104impl NativeContextAdapter {
105 #[must_use]
106 pub fn new() -> Self {
107 Self {
108 root: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
109 #[cfg(test)]
110 materialized_test_control: None,
111 }
112 }
113
114 #[must_use]
115 pub fn with_root(root: impl AsRef<Path>) -> Self {
116 Self {
117 root: root.as_ref().to_path_buf(),
118 #[cfg(test)]
119 materialized_test_control: None,
120 }
121 }
122
123 #[cfg(test)]
124 pub(crate) fn with_materialized_test_control(
125 mut self,
126 control: std::sync::Arc<MaterializedTestControl>,
127 ) -> Self {
128 self.materialized_test_control = Some(control);
129 self
130 }
131
132 #[must_use]
133 pub fn root(&self) -> &Path {
134 &self.root
135 }
136
137 fn optimize(&self, content: &str, paths: &[String], mode: &str) -> String {
138 if matches!(mode, "full" | "raw" | "passthrough") {
139 return content.to_owned();
140 }
141
142 let extension = paths
143 .first()
144 .and_then(|path| Path::new(path).extension())
145 .and_then(|extension| extension.to_str());
146 compressor::aggressive_compress(content, extension)
147 }
148
149 fn invoke_context(
150 &self,
151 invocation: &CapabilityInvocation,
152 paths: &[String],
153 mode: &str,
154 budget_tokens: Option<u64>,
155 start: Instant,
156 ) -> Result<NativeContextInvocationResult, NativeContextInvocationFailure> {
157 let input = read_context_paths(&self.root, paths).map_err(|error| {
158 NativeContextInvocationFailure::SourceUnavailable(error.to_string())
159 })?;
160 self.invoke_materialized_context(invocation, paths, mode, budget_tokens, start, &input)
161 }
162
163 fn invoke_materialized_context(
164 &self,
165 invocation: &CapabilityInvocation,
166 paths: &[String],
167 mode: &str,
168 budget_tokens: Option<u64>,
169 start: Instant,
170 input: &str,
171 ) -> Result<NativeContextInvocationResult, NativeContextInvocationFailure> {
172 let input_tokens = tokens::count_tokens(&input) as u64;
173 if let Some(max) = invocation.policy_constraints.max_input_tokens
174 && input_tokens > max
175 {
176 return Err(NativeContextInvocationFailure::ResourceLimit(format!(
177 "input exceeds policy token limit ({input_tokens} > {max})"
178 )));
179 }
180
181 let optimized = self.optimize(&input, paths, mode);
182 let output = match budget_tokens {
183 Some(budget) => truncate_to_tokens(&optimized, budget),
184 None => optimized,
185 };
186 let output_tokens = tokens::count_tokens(&output) as u64;
187 if let Some(max) = invocation.policy_constraints.max_output_tokens
188 && output_tokens > max
189 {
190 return Err(NativeContextInvocationFailure::ResourceLimit(format!(
191 "output exceeds policy token limit ({output_tokens} > {max})"
192 )));
193 }
194
195 let latency_ms = super::super::invocation::check_timeout(start, invocation.timeout_ms)
196 .map_err(|error| NativeContextInvocationFailure::ResourceLimit(error.to_string()))?;
197 if let Some(max) = invocation.policy_constraints.max_latency_ms
198 && latency_ms > max
199 {
200 return Err(NativeContextInvocationFailure::ResourceLimit(format!(
201 "capability latency exceeds policy limit ({latency_ms} > {max})"
202 )));
203 }
204 let output_ref = evidence_ref(&output);
205 let mut observation = CapabilityObservationV1::success(
206 invocation,
207 input_tokens,
208 output_tokens,
209 latency_ms,
210 Some(output_ref.clone()),
211 );
212 observation.metrics.insert(
213 "compression_saved_tokens".into(),
214 input_tokens.saturating_sub(output_tokens),
215 );
216 observation.metrics.insert(
217 "compression_rate_milli".into(),
218 compression_rate_milli(input_tokens, output_tokens),
219 );
220 Ok(NativeContextInvocationResult {
221 result: CapabilityResult {
222 success: true,
223 output_tokens,
224 latency_ms,
225 observation,
226 evidence_ref: Some(output_ref),
227 },
228 input_digest: format!(
229 "sha256:{}",
230 crate::core::agent_identity::hex_encode(&Sha256::digest(input.as_bytes()))
231 ),
232 output_digest: format!(
233 "sha256:{}",
234 crate::core::agent_identity::hex_encode(&Sha256::digest(output.as_bytes()))
235 ),
236 output: output.into_bytes(),
237 })
238 }
239
240 pub(crate) fn invoke_with_output_identity(
243 &self,
244 invocation: &CapabilityInvocation,
245 ) -> Result<NativeContextInvocationResult, NativeContextInvocationFailure> {
246 self.validate_engine_invocation(invocation)?;
247 let start = Instant::now();
248 match &invocation.input {
249 CapabilityInput::ContextRequest {
250 paths,
251 mode,
252 budget_tokens,
253 } => self.invoke_context(invocation, paths, mode, *budget_tokens, start),
254 CapabilityInput::ShellCommand { .. } | CapabilityInput::ModelRequest { .. } => {
255 Err(NativeContextInvocationFailure::UnsupportedInput)
256 }
257 }
258 }
259
260 fn invoke_materialized_with_output_identity(
264 &self,
265 invocation: &CapabilityInvocation,
266 input: &str,
267 ) -> Result<NativeContextInvocationResult, NativeContextInvocationFailure> {
268 self.validate_engine_invocation(invocation)?;
269 let start = Instant::now();
270 match &invocation.input {
271 CapabilityInput::ContextRequest {
272 paths,
273 mode,
274 budget_tokens,
275 } => self.invoke_materialized_context(
276 invocation,
277 paths,
278 mode,
279 *budget_tokens,
280 start,
281 input,
282 ),
283 CapabilityInput::ShellCommand { .. } | CapabilityInput::ModelRequest { .. } => {
284 Err(NativeContextInvocationFailure::UnsupportedInput)
285 }
286 }
287 }
288
289 pub(crate) fn invoke_materialized_bounded(
293 &self,
294 invocation: CapabilityInvocation,
295 input: String,
296 ) -> Result<NativeContextInvocationResult, NativeContextInvocationFailure> {
297 if invocation.timeout_ms == 0 {
298 return Err(NativeContextInvocationFailure::ResourceLimit(
299 "native context deadline expired before dispatch".to_owned(),
300 ));
301 }
302 let timeout = std::time::Duration::from_millis(invocation.timeout_ms);
303 let adapter = Self::with_root(&self.root);
304 #[cfg(test)]
305 let adapter = {
306 let mut adapter = adapter;
307 adapter.materialized_test_control = self.materialized_test_control.clone();
308 adapter
309 };
310 let (tx, rx) = std::sync::mpsc::sync_channel(1);
311 std::thread::Builder::new()
312 .name("native-context-engine".to_owned())
313 .spawn(move || {
314 #[cfg(test)]
315 if let Some(control) = adapter.materialized_test_control.as_ref() {
316 control.release.wait();
317 }
318 let result = adapter.invoke_materialized_with_output_identity(&invocation, &input);
319 #[cfg(test)]
320 if let Some(control) = adapter.materialized_test_control.as_ref() {
321 control.completed.wait();
322 }
323 let _ = tx.send(result);
324 })
325 .map_err(|error| {
326 NativeContextInvocationFailure::InvalidRequest(format!(
327 "start native context worker: {error}"
328 ))
329 })?;
330 rx.recv_timeout(timeout).map_err(|error| match error {
331 std::sync::mpsc::RecvTimeoutError::Timeout => {
332 NativeContextInvocationFailure::ResourceLimit(
333 "native context execution exceeded its deadline".to_owned(),
334 )
335 }
336 std::sync::mpsc::RecvTimeoutError::Disconnected => {
337 NativeContextInvocationFailure::InvalidRequest(
338 "native context worker disconnected".to_owned(),
339 )
340 }
341 })?
342 }
343
344 fn validate_engine_invocation(
345 &self,
346 invocation: &CapabilityInvocation,
347 ) -> Result<(), NativeContextInvocationFailure> {
348 invocation
349 .validate()
350 .map_err(|error| NativeContextInvocationFailure::InvalidRequest(error.to_string()))?;
351 if invocation.capability_id != self.manifest().capability_id.as_str()
352 || invocation.capability_version != self.manifest().version
353 {
354 return Err(NativeContextInvocationFailure::InvalidRequest(
355 "invocation capability identity does not match adapter manifest".into(),
356 ));
357 }
358 Ok(())
359 }
360}
361
362impl Default for NativeContextAdapter {
363 fn default() -> Self {
364 Self::new()
365 }
366}
367
368impl CapabilityAdapter for NativeContextAdapter {
369 fn manifest(&self) -> &CapabilityManifestV1 {
370 manifest()
371 }
372
373 fn invoke(&self, invocation: CapabilityInvocation) -> OclaResult<CapabilityResult> {
374 self.invoke_with_output_identity(&invocation)
375 .map(|result| result.result)
376 .map_err(NativeContextInvocationFailure::into_ocla_error)
377 }
378
379 fn health_check(&self) -> OclaResult<bool> {
380 Ok(self.root.is_dir() && self.manifest().validate().is_ok())
381 }
382}
383
384fn truncate_to_tokens(content: &str, budget: u64) -> String {
385 if budget == 0 {
386 return String::new();
387 }
388 if tokens::count_tokens(content) as u64 <= budget {
389 return content.to_owned();
390 }
391 content
392 .split_whitespace()
393 .take(budget as usize)
394 .collect::<Vec<_>>()
395 .join(" ")
396}
397
398fn compression_rate_milli(input_tokens: u64, output_tokens: u64) -> u64 {
399 if input_tokens == 0 {
400 return 0;
401 }
402 input_tokens
403 .saturating_sub(output_tokens)
404 .saturating_mul(1000)
405 .checked_div(input_tokens)
406 .unwrap_or(0)
407 .min(1000)
408}
409
410#[cfg(test)]
411mod tests {
412 use super::*;
413 use crate::core::ocla::invocation::{CapabilityAdapter, PolicyConstraints};
414
415 #[test]
416 fn manifest_is_pinned_to_native_path() {
417 assert!(MANIFEST_PATH.ends_with("context-optimization-v1.json"));
418 assert_eq!(manifest().provider, "leanctx");
419 }
420
421 #[test]
422 fn rejects_non_context_inputs() {
423 let adapter = NativeContextAdapter::new();
424 let invocation = CapabilityInvocation {
425 task_id: "task-1".into(),
426 capability_id: adapter.manifest().capability_id.as_str().into(),
427 capability_version: adapter.manifest().version.clone(),
428 input: CapabilityInput::ShellCommand {
429 command: "printf test".into(),
430 workdir: None,
431 },
432 policy_constraints: PolicyConstraints::default(),
433 timeout_ms: 100,
434 };
435 assert!(adapter.invoke(invocation).is_err());
436 }
437
438 #[test]
439 fn internal_output_identity_is_canonical_sha256_without_payload() {
440 let root = tempfile::tempdir().expect("temporary adapter root");
441 std::fs::write(root.path().join("fixture.md"), "hello context").expect("fixture write");
442 let adapter = NativeContextAdapter::with_root(root.path());
443 let invocation = CapabilityInvocation {
444 task_id: "task-1".into(),
445 capability_id: adapter.manifest().capability_id.as_str().into(),
446 capability_version: adapter.manifest().version.clone(),
447 input: CapabilityInput::ContextRequest {
448 paths: vec!["fixture.md".into()],
449 mode: "raw".into(),
450 budget_tokens: None,
451 },
452 policy_constraints: PolicyConstraints::default(),
453 timeout_ms: 0,
454 };
455
456 let result = adapter
457 .invoke_with_output_identity(&invocation)
458 .expect("native invocation succeeds");
459 assert_eq!(
460 result.output_digest,
461 format!(
462 "sha256:{}",
463 crate::core::agent_identity::hex_encode(&Sha256::digest(b"hello context"))
464 )
465 );
466 assert!(result.result.evidence_ref.is_some());
467 }
468}