cortext 1.3.1

Rust bindings for the Cortext multimodal memory engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
//! Rust bindings for the Cortext multimodal memory engine.
//!
//! Shared libraries and model shards come from the
//! [`augmem/cortext.cpp`](https://github.com/augmem/cortext.cpp) GitHub Release
//! asset tarball (see [`ensure_assets`]), or from `CORTEXT_LIBRARY_PATH` /
//! `CORTEXT_ASSETS_DIR` when set explicitly.

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,
};

/// Crate version string (this package, independent of the native engine).
pub const CRATE_VERSION: &str = env!("CARGO_PKG_VERSION");

/// JSON object returned by process helpers.
pub type JsonObject = serde_json::Map<String, serde_json::Value>;

/// Optional native configuration. `None` fields keep library defaults.
#[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>,
}

/// Optional source media stored alongside a processed signal.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Media {
    pub data: Vec<u8>,
    pub mime_type: String,
}

impl Media {
    /// Construct media with Python-style `mimetype` naming.
    pub fn new(data: impl Into<Vec<u8>>, mimetype: impl Into<String>) -> Self {
        Self {
            data: data.into(),
            mime_type: mimetype.into(),
        }
    }

    /// Python `Media.mimetype`.
    pub fn mimetype(&self) -> &str {
        &self.mime_type
    }
}

/// Retention policy for process ingress.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Retention {
    #[default]
    Natural,
    Durable,
    Boundary,
    Ephemeral,
}

/// Options for JSON process result payloads.
///
/// Python uses `include_embedding: bool = True`. `omit_embedding` is the
/// inverse; if both are set, omit wins.
#[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)
    }
}

/// Embedding JSON payload.
#[derive(Clone, Debug, Default, Deserialize)]
pub struct EmbeddingResult {
    pub embedding: Vec<f32>,
    #[serde(default)]
    pub dimension: usize,
}

/// Open Cortext engine instance.
pub struct Cortext {
    ptr: *mut c_void,
    _db: Option<Box<store::DbBridge>>,
    _object: Option<Box<store::ObjectBridge>>,
}

unsafe impl Send for Cortext {}

impl Cortext {
    /// Open a Cortext instance at `db_path` (file path or `":memory:"`).
    pub fn new(db_path: impl AsRef<str>, cfg: Option<&Config>) -> Result<Self, Error> {
        Self::create(db_path.as_ref(), cfg, None, None, None)
    }

    /// Open a Cortext instance after loading `library_path` (Python `library_path=`).
    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()),
        )
    }

    /// Open using an external SQL store (Python `store=`).
    pub fn with_store(cfg: Option<&Config>, store: impl DbProvider) -> Result<Self, Error> {
        Self::create(":memory:", cfg, Some(Box::new(store)), None, None)
    }

    /// Open using external SQL and object stores.
    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,
        )
    }

    /// Open SQLite at `db_path` with an external object store.
    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,
        })
    }

    /// Close the native handle. Safe to call more than once.
    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();
    }
}

/// Native library version string, or empty if the library cannot be loaded.
pub fn version() -> String {
    if library::load_library().is_err() {
        return String::new();
    }
    library::native_version()
}

/// Last error produced by this thread's C API calls.
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");
    }
}