mod assets;
mod error;
mod ffi;
mod library;
mod model;
mod store;
use std::ffi::{c_void, CString};
use std::path::Path;
use std::ptr;
use serde::Deserialize;
pub use assets::{
assets_dir, assets_version, ensure_assets, package_assets_ready, ASSETS_VERSION,
};
pub use error::Error;
pub use library::{library_path, load_library, load_library_from};
pub use model::{clear_materialize_cache, materialize_model, resolve_aist_model};
pub use store::{DbProvider, DbRow, DbValue, ObjectStoreProvider, ProviderTransaction};
use ffi::{
NativeConfig, NativeMedia, NativeProcessOptions, RETENTION_BOUNDARY, RETENTION_DURABLE,
RETENTION_EPHEMERAL, RETENTION_NATURAL,
};
pub const CRATE_VERSION: &str = env!("CARGO_PKG_VERSION");
pub type JsonObject = serde_json::Map<String, serde_json::Value>;
#[derive(Clone, Debug, Default)]
pub struct Config {
pub focus: Option<f64>,
pub sensitivity: Option<f64>,
pub stability: Option<f64>,
pub affect_interrupt: Option<bool>,
pub affect_retrieval: Option<bool>,
pub reinforcement_enabled: Option<bool>,
pub procedural_enabled: Option<bool>,
pub sequential_edges_enabled: Option<bool>,
pub signal_filter_audio: Option<bool>,
pub signal_filter_image: Option<bool>,
pub signal_filter_text: Option<bool>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Media {
pub data: Vec<u8>,
pub mime_type: String,
}
impl Media {
pub fn new(data: impl Into<Vec<u8>>, mimetype: impl Into<String>) -> Self {
Self {
data: data.into(),
mime_type: mimetype.into(),
}
}
pub fn mimetype(&self) -> &str {
&self.mime_type
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Retention {
#[default]
Natural,
Durable,
Boundary,
Ephemeral,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ProcessOptions {
pub include_embedding: bool,
pub omit_embedding: bool,
pub retention: Retention,
}
impl Default for ProcessOptions {
fn default() -> Self {
Self {
include_embedding: true,
omit_embedding: false,
retention: Retention::Natural,
}
}
}
impl ProcessOptions {
fn include_embedding_c(&self) -> i32 {
i32::from(self.include_embedding && !self.omit_embedding)
}
}
#[derive(Clone, Debug, Default, Deserialize)]
pub struct EmbeddingResult {
pub embedding: Vec<f32>,
#[serde(default)]
pub dimension: usize,
}
pub struct Cortext {
ptr: *mut c_void,
_db: Option<Box<store::DbBridge>>,
_object: Option<Box<store::ObjectBridge>>,
}
unsafe impl Send for Cortext {}
impl Cortext {
pub fn new(db_path: impl AsRef<str>, cfg: Option<&Config>) -> Result<Self, Error> {
Self::create(db_path.as_ref(), cfg, None, None, None)
}
pub fn with_library_path(
db_path: impl AsRef<str>,
cfg: Option<&Config>,
library_path: impl AsRef<Path>,
) -> Result<Self, Error> {
Self::create(
db_path.as_ref(),
cfg,
None,
None,
Some(library_path.as_ref()),
)
}
pub fn with_store(cfg: Option<&Config>, store: impl DbProvider) -> Result<Self, Error> {
Self::create(":memory:", cfg, Some(Box::new(store)), None, None)
}
pub fn with_store_and_object(
cfg: Option<&Config>,
store: impl DbProvider,
object_store: impl ObjectStoreProvider,
) -> Result<Self, Error> {
Self::create(
":memory:",
cfg,
Some(Box::new(store)),
Some(Box::new(object_store)),
None,
)
}
pub fn with_object_store(
db_path: impl AsRef<str>,
cfg: Option<&Config>,
object_store: impl ObjectStoreProvider,
) -> Result<Self, Error> {
Self::create(
db_path.as_ref(),
cfg,
None,
Some(Box::new(object_store)),
None,
)
}
fn create(
db_path: &str,
cfg: Option<&Config>,
store: Option<Box<dyn DbProvider>>,
object_store: Option<Box<dyn ObjectStoreProvider>>,
library_path: Option<&Path>,
) -> Result<Self, Error> {
if store.is_some() && db_path != ":memory:" {
return Err(Error::new("db_path and store are mutually exclusive"));
}
if let Some(path) = library_path {
library::load_library_from(path)?;
} else {
library::load_library()?;
}
ensure_model_env()?;
let mut native = NativeConfig {
struct_size: std::mem::size_of::<NativeConfig>(),
focus: 0.0,
sensitivity: 0.0,
stability: 0.0,
affect_interrupt: 0,
affect_retrieval: 0,
reinforcement_enabled: 0,
procedural_enabled: 0,
sequential_edges_enabled: 0,
signal_filter_audio_enabled: 0,
signal_filter_image_enabled: 0,
signal_filter_text_enabled: 0,
};
library::config_init(&mut native)?;
if let Some(cfg) = cfg {
apply_config(&mut native, cfg);
}
let db_bridge = store.map(|s| Box::new(store::DbBridge::new(s)));
let object_bridge = object_store.map(|s| Box::new(store::ObjectBridge::new(s)));
let ptr = match (&db_bridge, &object_bridge) {
(Some(db), Some(object)) => library::create_with_store_and_object(
&native,
db.callbacks(),
db.user_data(),
object.callbacks(),
object.user_data(),
)?,
(Some(db), None) => {
library::create_with_store(&native, db.callbacks(), db.user_data())?
}
(None, Some(object)) => {
let db = c_string(db_path, "db_path")?;
library::create_with_config_and_object(
&native,
&db,
object.callbacks(),
object.user_data(),
)?
}
(None, None) => {
let db = c_string(db_path, "db_path")?;
library::create_with_config(&native, &db)?
}
};
if ptr.is_null() {
return Err(library::last_error_as_error());
}
Ok(Self {
ptr,
_db: db_bridge,
_object: object_bridge,
})
}
pub fn close(&mut self) {
if !self.ptr.is_null() {
library::free_handle(self.ptr);
self.ptr = ptr::null_mut();
}
}
pub fn process_text_json(&self, text: &str, source_id: &str) -> Result<Vec<u8>, Error> {
self.process_text_json_with_options(text, source_id, None)
}
pub fn process_text_json_with_options(
&self,
text: &str,
source_id: &str,
options: Option<ProcessOptions>,
) -> Result<Vec<u8>, Error> {
self.require()?;
let text = c_string(text, "text")?;
let source_id = c_string(source_id, "source_id")?;
let native_options = make_native_process_options(options)?;
let raw = library::process_text_json_opts(self.ptr, &text, &source_id, &native_options)?;
library::take_json_string(raw)
}
pub fn process_text(&self, text: &str, source_id: &str) -> Result<JsonObject, Error> {
decode_json_object(self.process_text_json(text, source_id)?)
}
pub fn process_text_with_options(
&self,
text: &str,
source_id: &str,
options: Option<ProcessOptions>,
) -> Result<JsonObject, Error> {
decode_json_object(self.process_text_json_with_options(text, source_id, options)?)
}
pub fn process_text_with_media_json(
&self,
text: &str,
source_id: &str,
media: Option<&Media>,
) -> Result<Vec<u8>, Error> {
self.process_text_with_media_json_with_options(text, source_id, media, None)
}
pub fn process_text_with_media_json_with_options(
&self,
text: &str,
source_id: &str,
media: Option<&Media>,
options: Option<ProcessOptions>,
) -> Result<Vec<u8>, Error> {
self.require()?;
if !library::has_process_text_media() {
return Err(Error::new(
"native library does not support text media processing",
));
}
let text = c_string(text, "text")?;
let source_id = c_string(source_id, "source_id")?;
let keep = keep_native_media(media)?;
let native_media = keep.native();
let native_options = make_native_process_options(options)?;
let raw = library::process_text_media_opts(
self.ptr,
&text,
&source_id,
&native_media,
&native_options,
)?;
library::take_json_string(raw)
}
pub fn process_text_with_media(
&self,
text: &str,
source_id: &str,
media: Option<&Media>,
) -> Result<JsonObject, Error> {
decode_json_object(self.process_text_with_media_json(text, source_id, media)?)
}
pub fn process_text_with_media_and_options(
&self,
text: &str,
source_id: &str,
media: Option<&Media>,
options: Option<ProcessOptions>,
) -> Result<JsonObject, Error> {
decode_json_object(
self.process_text_with_media_json_with_options(text, source_id, media, options)?,
)
}
pub fn embed_text_json(&self, text: &str) -> Result<Vec<u8>, Error> {
self.require()?;
let text = c_string(text, "text")?;
let raw = library::embed_text_json(self.ptr, &text)?;
library::take_json_string(raw)
}
pub fn embed_text(&self, text: &str) -> Result<Vec<f32>, Error> {
Ok(decode_embedding_result(&self.embed_text_json(text)?)?.embedding)
}
pub fn process_audio_json(&self, pcm: &[f32], source_id: &str) -> Result<Vec<u8>, Error> {
self.process_audio_json_with_options(pcm, source_id, None)
}
pub fn process_audio_json_with_options(
&self,
pcm: &[f32],
source_id: &str,
options: Option<ProcessOptions>,
) -> Result<Vec<u8>, Error> {
self.require()?;
let source_id = c_string(source_id, "source_id")?;
let native_options = make_native_process_options(options)?;
let raw = library::process_audio_json_opts(
self.ptr,
pcm_ptr(pcm),
pcm.len(),
&source_id,
&native_options,
)?;
library::take_json_string(raw)
}
pub fn process_audio_with_media_json(
&self,
pcm: &[f32],
source_id: &str,
media: Option<&Media>,
) -> Result<Vec<u8>, Error> {
self.process_audio_with_media_json_with_options(pcm, source_id, media, None)
}
pub fn process_audio_with_media_json_with_options(
&self,
pcm: &[f32],
source_id: &str,
media: Option<&Media>,
options: Option<ProcessOptions>,
) -> Result<Vec<u8>, Error> {
self.require()?;
let source_id = c_string(source_id, "source_id")?;
let keep = keep_native_media(media)?;
let native_media = keep.native();
let native_options = make_native_process_options(options)?;
let raw = library::process_audio_media_opts(
self.ptr,
pcm_ptr(pcm),
pcm.len(),
&source_id,
&native_media,
&native_options,
)?;
library::take_json_string(raw)
}
pub fn process_audio(&self, pcm: &[f32], source_id: &str) -> Result<JsonObject, Error> {
decode_json_object(self.process_audio_json(pcm, source_id)?)
}
pub fn process_audio_with_options(
&self,
pcm: &[f32],
source_id: &str,
options: Option<ProcessOptions>,
) -> Result<JsonObject, Error> {
decode_json_object(self.process_audio_json_with_options(pcm, source_id, options)?)
}
pub fn process_audio_with_media(
&self,
pcm: &[f32],
source_id: &str,
media: Option<&Media>,
) -> Result<JsonObject, Error> {
decode_json_object(self.process_audio_with_media_json(pcm, source_id, media)?)
}
pub fn process_audio_with_media_and_options(
&self,
pcm: &[f32],
source_id: &str,
media: Option<&Media>,
options: Option<ProcessOptions>,
) -> Result<JsonObject, Error> {
decode_json_object(
self.process_audio_with_media_json_with_options(pcm, source_id, media, options)?,
)
}
pub fn embed_audio_json(&self, pcm: &[f32]) -> Result<Vec<u8>, Error> {
self.require()?;
let raw = library::embed_audio_json(self.ptr, pcm_ptr(pcm), pcm.len())?;
library::take_json_string(raw)
}
pub fn embed_audio(&self, pcm: &[f32]) -> Result<Vec<f32>, Error> {
Ok(decode_embedding_result(&self.embed_audio_json(pcm)?)?.embedding)
}
pub fn process_image_json(
&self,
data: &[u8],
width: i32,
height: i32,
channels: i32,
source_id: &str,
) -> Result<Vec<u8>, Error> {
self.process_image_json_with_options(data, width, height, channels, source_id, None)
}
pub fn process_image_json_with_options(
&self,
data: &[u8],
width: i32,
height: i32,
channels: i32,
source_id: &str,
options: Option<ProcessOptions>,
) -> Result<Vec<u8>, Error> {
self.require()?;
validate_image_buffer(data, width, height, channels)?;
let source_id = c_string(source_id, "source_id")?;
let native_options = make_native_process_options(options)?;
let raw = library::process_image_json_opts(
self.ptr,
data_ptr(data),
width,
height,
channels,
&source_id,
&native_options,
)?;
library::take_json_string(raw)
}
pub fn process_image_with_media_json(
&self,
data: &[u8],
width: i32,
height: i32,
channels: i32,
source_id: &str,
media: Option<&Media>,
) -> Result<Vec<u8>, Error> {
self.process_image_with_media_json_with_options(
data, width, height, channels, source_id, media, None,
)
}
pub fn process_image_with_media_json_with_options(
&self,
data: &[u8],
width: i32,
height: i32,
channels: i32,
source_id: &str,
media: Option<&Media>,
options: Option<ProcessOptions>,
) -> Result<Vec<u8>, Error> {
self.require()?;
validate_image_buffer(data, width, height, channels)?;
let source_id = c_string(source_id, "source_id")?;
let keep = keep_native_media(media)?;
let native_media = keep.native();
let native_options = make_native_process_options(options)?;
let raw = library::process_image_media_opts(
self.ptr,
data_ptr(data),
width,
height,
channels,
&source_id,
&native_media,
&native_options,
)?;
library::take_json_string(raw)
}
pub fn process_image(
&self,
data: &[u8],
width: i32,
height: i32,
channels: i32,
source_id: &str,
) -> Result<JsonObject, Error> {
decode_json_object(self.process_image_json(data, width, height, channels, source_id)?)
}
pub fn process_image_with_options(
&self,
data: &[u8],
width: i32,
height: i32,
channels: i32,
source_id: &str,
options: Option<ProcessOptions>,
) -> Result<JsonObject, Error> {
decode_json_object(
self.process_image_json_with_options(
data, width, height, channels, source_id, options,
)?,
)
}
pub fn process_image_with_media(
&self,
data: &[u8],
width: i32,
height: i32,
channels: i32,
source_id: &str,
media: Option<&Media>,
) -> Result<JsonObject, Error> {
decode_json_object(
self.process_image_with_media_json(data, width, height, channels, source_id, media)?,
)
}
pub fn process_image_with_media_and_options(
&self,
data: &[u8],
width: i32,
height: i32,
channels: i32,
source_id: &str,
media: Option<&Media>,
options: Option<ProcessOptions>,
) -> Result<JsonObject, Error> {
decode_json_object(self.process_image_with_media_json_with_options(
data, width, height, channels, source_id, media, options,
)?)
}
pub fn embed_image_json(
&self,
data: &[u8],
width: i32,
height: i32,
channels: i32,
) -> Result<Vec<u8>, Error> {
self.require()?;
validate_image_buffer(data, width, height, channels)?;
let raw = library::embed_image_json(self.ptr, data_ptr(data), width, height, channels)?;
library::take_json_string(raw)
}
pub fn embed_image(
&self,
data: &[u8],
width: i32,
height: i32,
channels: i32,
) -> Result<Vec<f32>, Error> {
Ok(decode_embedding_result(&self.embed_image_json(data, width, height, channels)?)?.embedding)
}
pub fn consolidate_json(&self) -> Result<Vec<u8>, Error> {
self.require()?;
library::take_json_string(library::consolidate_json(self.ptr)?)
}
pub fn consolidate(&self) -> Result<JsonObject, Error> {
decode_json_object(self.consolidate_json()?)
}
pub fn flush(&self) -> Result<(), Error> {
self.require()?;
if library::flush(self.ptr)? != 0 {
return Err(library::last_error_as_error());
}
Ok(())
}
pub fn reset(&self) -> Result<(), Error> {
self.require()?;
if library::reset(self.ptr)? != 0 {
return Err(library::last_error_as_error());
}
Ok(())
}
fn require(&self) -> Result<(), Error> {
if self.ptr.is_null() {
Err(Error::new("cortext handle is closed"))
} else {
Ok(())
}
}
}
impl Drop for Cortext {
fn drop(&mut self) {
self.close();
}
}
pub fn version() -> String {
if library::load_library().is_err() {
return String::new();
}
library::native_version()
}
pub fn last_error() -> String {
if let Err(err) = library::load_library() {
return err.to_string();
}
library::native_last_error()
}
fn apply_config(native: &mut NativeConfig, cfg: &Config) {
if let Some(v) = cfg.focus {
native.focus = v;
}
if let Some(v) = cfg.sensitivity {
native.sensitivity = v;
}
if let Some(v) = cfg.stability {
native.stability = v;
}
if let Some(v) = cfg.affect_interrupt {
native.affect_interrupt = bool_to_c(v);
}
if let Some(v) = cfg.affect_retrieval {
native.affect_retrieval = bool_to_c(v);
}
if let Some(v) = cfg.reinforcement_enabled {
native.reinforcement_enabled = bool_to_c(v);
}
if let Some(v) = cfg.procedural_enabled {
native.procedural_enabled = bool_to_c(v);
}
if let Some(v) = cfg.sequential_edges_enabled {
native.sequential_edges_enabled = bool_to_c(v);
}
if let Some(v) = cfg.signal_filter_audio {
native.signal_filter_audio_enabled = bool_to_c(v);
}
if let Some(v) = cfg.signal_filter_image {
native.signal_filter_image_enabled = bool_to_c(v);
}
if let Some(v) = cfg.signal_filter_text {
native.signal_filter_text_enabled = bool_to_c(v);
}
}
fn bool_to_c(value: bool) -> i32 {
i32::from(value)
}
fn c_string(value: &str, field: &str) -> Result<CString, Error> {
CString::new(value).map_err(|_| Error::new(format!("{field} contains an interior NUL")))
}
fn pcm_ptr(pcm: &[f32]) -> *const f32 {
if pcm.is_empty() {
ptr::null()
} else {
pcm.as_ptr()
}
}
fn data_ptr(data: &[u8]) -> *const u8 {
if data.is_empty() {
ptr::null()
} else {
data.as_ptr()
}
}
struct KeptMedia {
data: Vec<u8>,
mime: CString,
}
impl KeptMedia {
fn native(&self) -> NativeMedia {
if self.data.is_empty() {
NativeMedia {
data: ptr::null(),
size: 0,
mimetype: ptr::null(),
}
} else {
NativeMedia {
data: self.data.as_ptr(),
size: self.data.len(),
mimetype: self.mime.as_ptr(),
}
}
}
}
fn keep_native_media(media: Option<&Media>) -> Result<KeptMedia, Error> {
match media {
None => Ok(KeptMedia {
data: Vec::new(),
mime: CString::new("").expect("empty mime"),
}),
Some(media) if media.data.is_empty() => Ok(KeptMedia {
data: Vec::new(),
mime: CString::new("").expect("empty mime"),
}),
Some(media) => Ok(KeptMedia {
data: media.data.clone(),
mime: c_string(&media.mime_type, "mime_type")?,
}),
}
}
fn make_native_process_options(
options: Option<ProcessOptions>,
) -> Result<NativeProcessOptions, Error> {
let mut native = NativeProcessOptions {
struct_size: std::mem::size_of::<NativeProcessOptions>(),
include_embedding: 1,
retention: RETENTION_NATURAL,
reserved: 0,
};
library::process_json_options_init(&mut native)?;
if let Some(options) = options {
native.include_embedding = options.include_embedding_c();
native.retention = match options.retention {
Retention::Natural => RETENTION_NATURAL,
Retention::Durable => RETENTION_DURABLE,
Retention::Boundary => RETENTION_BOUNDARY,
Retention::Ephemeral => RETENTION_EPHEMERAL,
};
}
Ok(native)
}
fn decode_json_object(payload: Vec<u8>) -> Result<JsonObject, Error> {
let value: serde_json::Value = serde_json::from_slice(&payload)?;
match value {
serde_json::Value::Object(map) => Ok(map),
_ => Err(Error::new("process result was not a JSON object")),
}
}
fn decode_embedding_result(payload: &[u8]) -> Result<EmbeddingResult, Error> {
Ok(serde_json::from_slice(payload)?)
}
fn validate_image_buffer(data: &[u8], width: i32, height: i32, channels: i32) -> Result<(), Error> {
if width <= 0 || height <= 0 || channels <= 0 {
return Err(Error::new("width, height, and channels must be positive"));
}
let width_u = usize::try_from(width)
.map_err(|_| Error::new("image dimensions exceed the native int range"))?;
let height_u = usize::try_from(height)
.map_err(|_| Error::new("image dimensions exceed the native int range"))?;
let channels_u = usize::try_from(channels)
.map_err(|_| Error::new("image dimensions exceed the native int range"))?;
let expected = width_u
.checked_mul(height_u)
.and_then(|v| v.checked_mul(channels_u))
.ok_or_else(|| Error::new("image dimensions overflow addressable memory"))?;
if data.len() < expected {
return Err(Error::new(
"image buffer is smaller than width * height * channels",
));
}
Ok(())
}
fn ensure_model_env() -> Result<(), Error> {
const KEY: &str = "CORTEXT_AIST_MODEL_PATH";
let Ok(path) = std::env::var(KEY) else {
return Ok(());
};
if path.trim().is_empty() {
return Ok(());
}
if !PathExists::is_file(&path) {
return Err(Error::new(format!(
"CORTEXT_AIST_MODEL_PATH is missing or not a file: {path}"
)));
}
Ok(())
}
struct PathExists;
impl PathExists {
fn is_file(path: &str) -> bool {
std::path::Path::new(path).is_file()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ffi::NativeMedia;
#[test]
fn platform_tag_is_nonempty() {
let tag = library::platform_tag();
assert!(!tag.is_empty(), "empty platform tag");
assert!(tag.contains('-'));
}
#[test]
fn validate_image_buffer_accepts_and_rejects() {
assert!(validate_image_buffer(&vec![0; 12], 2, 2, 3).is_ok());
assert!(validate_image_buffer(&vec![0; 10], 1000, 1000, 3).is_err());
assert!(validate_image_buffer(&[], 0, 1, 3).is_err());
}
#[test]
fn keep_native_media_preserves_bytes_and_mime() {
let media = Media {
data: vec![0x00, 0xff, 0x01, 0x7f],
mime_type: "application/octet-stream".into(),
};
let keep = keep_native_media(Some(&media)).unwrap();
let native: NativeMedia = keep.native();
assert!(!native.data.is_null());
assert_eq!(native.size, 4);
let got = unsafe { std::slice::from_raw_parts(native.data, native.size) };
assert_eq!(got, media.data.as_slice());
let mime = unsafe { std::ffi::CStr::from_ptr(native.mimetype) };
assert_eq!(mime.to_str().unwrap(), "application/octet-stream");
}
#[test]
fn config_fields_distinguish_omitted_and_explicit_zero() {
let cfg = Config {
focus: Some(0.0),
affect_interrupt: Some(false),
..Config::default()
};
assert_eq!(cfg.focus, Some(0.0));
assert_eq!(cfg.affect_interrupt, Some(false));
assert!(cfg.sensitivity.is_none());
}
#[test]
fn crate_version_matches_package() {
assert_eq!(CRATE_VERSION, "1.3.1");
assert_eq!(ASSETS_VERSION, "1.3.0");
}
#[test]
fn process_options_include_and_omit() {
let default = ProcessOptions::default();
assert!(default.include_embedding);
assert!(!default.omit_embedding);
assert_eq!(default.include_embedding_c(), 1);
let omit = ProcessOptions {
include_embedding: true,
omit_embedding: true,
retention: Retention::Natural,
};
assert_eq!(omit.include_embedding_c(), 0);
let exclude = ProcessOptions {
include_embedding: false,
omit_embedding: false,
retention: Retention::Durable,
};
assert_eq!(exclude.include_embedding_c(), 0);
}
#[test]
fn media_mimetype_alias() {
let media = Media::new(vec![1, 2], "audio/ogg");
assert_eq!(media.mimetype(), "audio/ogg");
assert_eq!(media.mime_type, "audio/ogg");
}
#[test]
fn store_and_db_path_are_exclusive() {
struct Dummy;
impl DbProvider for Dummy {
fn execute(
&self,
_query: &str,
_params: &[DbValue],
_transaction: Option<&ProviderTransaction>,
) -> Result<Vec<DbRow>, Error> {
Ok(Vec::new())
}
fn begin(
&self,
_parent: Option<&ProviderTransaction>,
) -> Result<ProviderTransaction, Error> {
Ok(ProviderTransaction::new(()))
}
fn commit(&self, _transaction: &ProviderTransaction) -> Result<(), Error> {
Ok(())
}
fn rollback(&self, _transaction: &ProviderTransaction) -> Result<(), Error> {
Ok(())
}
}
match Cortext::create("memory.db", None, Some(Box::new(Dummy)), None, None) {
Ok(_) => panic!("expected mutually exclusive error"),
Err(err) => assert!(err.to_string().contains("mutually exclusive")),
}
}
}
#[cfg(test)]
mod smoke {
use super::*;
fn native_present() -> bool {
if std::env::var("CORTEXT_LIBRARY_PATH")
.ok()
.is_some_and(|p| std::path::Path::new(&p).is_file())
{
return true;
}
if let Ok(dir) = std::env::var("CORTEXT_ASSETS_DIR") {
return crate::assets::validate_assets_root(std::path::Path::new(&dir)).is_ok();
}
false
}
#[test]
fn process_text_and_embed_when_native_present() {
if !native_present() {
eprintln!(
"skipping native smoke test (set CORTEXT_ASSETS_DIR or CORTEXT_LIBRARY_PATH)"
);
return;
}
library::reset_library_for_test();
let engine = Cortext::new(":memory:", None).expect("Cortext::new");
let ctx = engine
.process_text("Bailey likes tennis balls.", "chat/main")
.expect("process_text");
assert!(
ctx.contains_key("should_interrupt") || !ctx.is_empty(),
"process_text returned empty object"
);
let without_emb = engine
.process_text_with_options(
"omit embedding",
"chat/main",
Some(ProcessOptions {
include_embedding: false,
omit_embedding: false,
retention: Retention::Natural,
}),
)
.expect("process_text include_embedding=false");
assert!(
!without_emb.contains_key("embedding"),
"include_embedding=false still returned embedding"
);
if library::has_process_text_media() {
let media = Media {
data: vec![0x00, 0xff, 0x01],
mime_type: "audio/ogg".into(),
};
engine
.process_text_with_media("Bailey sent a voice note.", "chat/main", Some(&media))
.expect("process_text_with_media");
}
let embedding = engine
.embed_text("embed without storing")
.expect("embed_text");
assert!(!embedding.is_empty());
let ver = version();
assert!(!ver.is_empty(), "native version empty");
}
}