jpx-engine 0.3.5

JMESPath query engine with introspection, discovery, and advanced features
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
//! Engine configuration via `jpx.toml`.
//!
//! Provides declarative configuration for the jpx engine, supporting function
//! filtering, query libraries, and engine settings. Configuration is loaded
//! from multiple sources with layered overrides:
//!
//! 1. **Defaults** -- `EngineConfig::default()` (strict=false, all functions enabled)
//! 2. **Global** -- `~/.config/jpx/jpx.toml` (via `dirs::config_dir()`)
//! 3. **Project-local** -- Walk up from CWD looking for `jpx.toml`
//! 4. **Env override** -- `$JPX_CONFIG` points to a specific file
//! 5. **Programmatic** -- CLI flags, MCP args, builder calls
//!
//! # Example
//!
//! ```toml
//! [engine]
//! strict = false
//!
//! [functions]
//! disabled_categories = ["geo", "phonetic"]
//! disabled_functions = ["env"]
//!
//! [queries]
//! libraries = ["~/.config/jpx/common.jpx"]
//!
//! [queries.inline]
//! active-users = { expression = "users[?active].name", description = "Get active user names" }
//! ```

use crate::JpxEngine;
use crate::error::EngineError;
use jpx_core::query_library::QueryLibrary;
use jpx_core::{FunctionRegistry, Runtime};
use serde::Deserialize;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};

/// Top-level configuration for the jpx engine.
///
/// Parsed from `jpx.toml` files. All fields have sensible defaults.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct EngineConfig {
    /// Engine-level settings.
    pub engine: EngineSection,
    /// Function filtering settings.
    pub functions: FunctionsSection,
    /// Query library and inline query settings.
    pub queries: QueriesSection,
}

/// Engine-level settings.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct EngineSection {
    /// If true, only standard JMESPath functions are available for evaluation.
    pub strict: bool,
}

/// Function filtering configuration.
///
/// Supports two mutually exclusive approaches:
/// - **Blocklist** (default): everything enabled, opt out with `disabled_categories`/`disabled_functions`
/// - **Allowlist**: only specified categories enabled via `enabled_categories`
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct FunctionsSection {
    /// Categories to disable (blocklist approach).
    pub disabled_categories: Vec<String>,
    /// Individual functions to disable.
    pub disabled_functions: Vec<String>,
    /// If set, only these categories are enabled (allowlist approach).
    /// Mutually exclusive with `disabled_categories`.
    pub enabled_categories: Option<Vec<String>>,
}

/// Query configuration.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct QueriesSection {
    /// Paths to `.jpx` query library files to load.
    pub libraries: Vec<String>,
    /// Inline named queries.
    pub inline: HashMap<String, InlineQuery>,
}

/// An inline named query defined in the config file.
#[derive(Debug, Clone, Deserialize)]
pub struct InlineQuery {
    /// The JMESPath expression.
    pub expression: String,
    /// Optional description.
    #[serde(default)]
    pub description: Option<String>,
}

impl EngineConfig {
    /// Parses an `EngineConfig` from a TOML file.
    pub fn from_file(path: &Path) -> crate::Result<Self> {
        let content = std::fs::read_to_string(path).map_err(|e| {
            EngineError::ConfigError(format!("Failed to read {}: {}", path.display(), e))
        })?;
        toml::from_str(&content).map_err(|e| {
            EngineError::ConfigError(format!("Failed to parse {}: {}", path.display(), e))
        })
    }

    /// Discovers and merges configuration from standard locations.
    ///
    /// Loads configs in order (later overrides earlier):
    /// 1. Global: `~/.config/jpx/jpx.toml`
    /// 2. Project-local: `jpx.toml` found by walking up from CWD
    /// 3. Env override: `$JPX_CONFIG`
    pub fn discover() -> crate::Result<Self> {
        let mut config = Self::default();

        // 1. Global config
        if let Some(global_path) = global_config_path()
            && global_path.exists()
        {
            let global = Self::from_file(&global_path)?;
            config = config.merge(global);
        }

        // 2. Project-local config (walk up from CWD)
        if let Some(local_path) = find_project_config() {
            let local = Self::from_file(&local_path)?;
            config = config.merge(local);
        }

        // 3. Env override
        if let Ok(env_path) = std::env::var("JPX_CONFIG") {
            let path = PathBuf::from(&env_path);
            if path.exists() {
                let env_config = Self::from_file(&path)?;
                config = config.merge(env_config);
            }
        }

        Ok(config)
    }

    /// Merges another config into this one.
    ///
    /// Merge semantics:
    /// - Scalars (`strict`): later wins
    /// - `disabled_categories` / `disabled_functions`: union
    /// - `enabled_categories`: later replaces
    /// - `queries.libraries`: concatenate
    /// - `queries.inline`: later keys override same-name
    pub fn merge(mut self, other: Self) -> Self {
        // Engine section: later wins
        if other.engine.strict {
            self.engine.strict = true;
        }

        // Functions section
        if let Some(enabled) = other.functions.enabled_categories {
            // Allowlist: later replaces entirely
            self.functions.enabled_categories = Some(enabled);
            // Clear blocklist when switching to allowlist
            self.functions.disabled_categories.clear();
        } else {
            // Blocklist: union
            for cat in other.functions.disabled_categories {
                if !self.functions.disabled_categories.contains(&cat) {
                    self.functions.disabled_categories.push(cat);
                }
            }
        }
        for func in other.functions.disabled_functions {
            if !self.functions.disabled_functions.contains(&func) {
                self.functions.disabled_functions.push(func);
            }
        }

        // Queries section
        self.queries.libraries.extend(other.queries.libraries);
        self.queries.inline.extend(other.queries.inline);

        self
    }
}

/// Builds a `JpxEngine` from configuration with programmatic overrides.
///
/// # Example
///
/// ```rust
/// use jpx_engine::config::EngineBuilder;
///
/// let engine = EngineBuilder::new()
///     .strict(false)
///     .disable_category("geo")
///     .disable_function("env")
///     .build()
///     .unwrap();
/// ```
pub struct EngineBuilder {
    config: EngineConfig,
}

impl EngineBuilder {
    /// Creates a new builder with default configuration.
    pub fn new() -> Self {
        Self {
            config: EngineConfig::default(),
        }
    }

    /// Sets strict mode.
    pub fn strict(mut self, strict: bool) -> Self {
        self.config.engine.strict = strict;
        self
    }

    /// Adds a category to the disabled list.
    pub fn disable_category(mut self, cat: &str) -> Self {
        let cat = cat.to_string();
        if !self.config.functions.disabled_categories.contains(&cat) {
            self.config.functions.disabled_categories.push(cat);
        }
        self
    }

    /// Adds a function to the disabled list.
    pub fn disable_function(mut self, name: &str) -> Self {
        let name = name.to_string();
        if !self.config.functions.disabled_functions.contains(&name) {
            self.config.functions.disabled_functions.push(name);
        }
        self
    }

    /// Sets the allowlist of enabled categories (replaces any blocklist).
    pub fn enable_categories(mut self, cats: Vec<String>) -> Self {
        self.config.functions.enabled_categories = Some(cats);
        self.config.functions.disabled_categories.clear();
        self
    }

    /// Adds a query library path.
    pub fn load_library(mut self, path: &str) -> Self {
        self.config.queries.libraries.push(path.to_string());
        self
    }

    /// Adds an inline query.
    pub fn inline_query(mut self, name: &str, expr: &str, desc: Option<&str>) -> Self {
        self.config.queries.inline.insert(
            name.to_string(),
            InlineQuery {
                expression: expr.to_string(),
                description: desc.map(|s| s.to_string()),
            },
        );
        self
    }

    /// Applies an `EngineConfig` (merges into the builder's config).
    pub fn config(mut self, config: EngineConfig) -> Self {
        self.config = self.config.merge(config);
        self
    }

    /// Builds the `JpxEngine`.
    pub fn build(self) -> crate::Result<JpxEngine> {
        JpxEngine::from_config(self.config)
    }
}

impl Default for EngineBuilder {
    fn default() -> Self {
        Self::new()
    }
}

// =============================================================================
// Shared helpers for building Runtime + Registry from config
// =============================================================================

/// Builds a `Runtime` and `FunctionRegistry` from function configuration.
///
/// This is the shared logic used by both `JpxEngine::from_config` and the CLI's
/// `create_configured_runtime`. It handles:
/// - Registering builtin functions
/// - Applying allowlist/blocklist filtering
/// - Registering enabled extension functions on the runtime
pub fn build_runtime_from_config(
    functions_config: &FunctionsSection,
    strict: bool,
) -> (Runtime, FunctionRegistry) {
    use crate::introspection::parse_category;

    let mut runtime = Runtime::new();
    runtime.register_builtin_functions();

    let mut registry = FunctionRegistry::new();

    if let Some(ref enabled_cats) = functions_config.enabled_categories {
        // Allowlist mode: only register specified categories
        for cat_name in enabled_cats {
            if let Some(cat) = parse_category(cat_name) {
                registry.register_category(cat);
            }
        }
        // Always include Standard category
        registry.register_category(jpx_core::Category::Standard);
    } else {
        // Default: register all, then disable
        registry.register_all();

        // Disable categories
        for cat_name in &functions_config.disabled_categories {
            if let Some(cat) = parse_category(cat_name) {
                let names: Vec<String> = registry
                    .functions_in_category(cat)
                    .map(|f| f.name.to_string())
                    .collect();
                for name in &names {
                    registry.disable_function(name);
                }
            }
        }
    }

    // Disable individual functions
    for func_name in &functions_config.disabled_functions {
        registry.disable_function(func_name);
    }

    // Apply to runtime (unless strict)
    if !strict {
        registry.apply(&mut runtime);
    }

    (runtime, registry)
}

/// Loads query libraries and inline queries into a query store.
pub fn load_queries_into_store(
    queries_config: &QueriesSection,
    runtime: &Runtime,
    queries: &Arc<RwLock<crate::QueryStore>>,
) -> crate::Result<()> {
    // Load .jpx library files
    for lib_path in &queries_config.libraries {
        let expanded = expand_tilde(lib_path);
        let path = Path::new(&expanded);
        if !path.exists() {
            continue; // silently skip missing libraries
        }

        let content = std::fs::read_to_string(path).map_err(|e| {
            EngineError::ConfigError(format!("Failed to read {}: {}", path.display(), e))
        })?;

        let library = QueryLibrary::parse(&content).map_err(|e| {
            EngineError::ConfigError(format!("Failed to parse {}: {}", path.display(), e))
        })?;

        let mut store = queries
            .write()
            .map_err(|e| EngineError::Internal(e.to_string()))?;

        for named_query in library.list() {
            // Validate expression
            if runtime.compile(&named_query.expression).is_ok() {
                store.define(crate::StoredQuery {
                    name: named_query.name.clone(),
                    expression: named_query.expression.clone(),
                    description: named_query.description.clone(),
                });
            }
        }
    }

    // Load inline queries
    if !queries_config.inline.is_empty() {
        let mut store = queries
            .write()
            .map_err(|e| EngineError::Internal(e.to_string()))?;

        for (name, query) in &queries_config.inline {
            // Validate expression
            if runtime.compile(&query.expression).is_ok() {
                store.define(crate::StoredQuery {
                    name: name.clone(),
                    expression: query.expression.clone(),
                    description: query.description.clone(),
                });
            }
        }
    }

    Ok(())
}

// =============================================================================
// Path helpers
// =============================================================================

/// Returns the global config path: `~/.config/jpx/jpx.toml`
fn global_config_path() -> Option<PathBuf> {
    dirs::config_dir().map(|d| d.join("jpx").join("jpx.toml"))
}

/// Walks up from CWD looking for `jpx.toml`.
fn find_project_config() -> Option<PathBuf> {
    let cwd = std::env::current_dir().ok()?;
    let mut dir = cwd.as_path();
    loop {
        let candidate = dir.join("jpx.toml");
        if candidate.exists() {
            return Some(candidate);
        }
        dir = dir.parent()?;
    }
}

/// Expands `~` at the start of a path to the user's home directory.
fn expand_tilde(path: &str) -> String {
    if let Some(rest) = path.strip_prefix("~/")
        && let Some(home) = dirs::home_dir()
    {
        return home.join(rest).to_string_lossy().into_owned();
    }
    path.to_string()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_default_config() {
        let config = EngineConfig::default();
        assert!(!config.engine.strict);
        assert!(config.functions.disabled_categories.is_empty());
        assert!(config.functions.disabled_functions.is_empty());
        assert!(config.functions.enabled_categories.is_none());
        assert!(config.queries.libraries.is_empty());
        assert!(config.queries.inline.is_empty());
    }

    #[test]
    fn test_parse_config() {
        let toml = r#"
[engine]
strict = true

[functions]
disabled_categories = ["geo", "phonetic"]
disabled_functions = ["env"]

[queries]
libraries = ["~/.config/jpx/common.jpx"]

[queries.inline]
active-users = { expression = "users[?active].name", description = "Get active user names" }
"#;
        let config: EngineConfig = toml::from_str(toml).unwrap();
        assert!(config.engine.strict);
        assert_eq!(
            config.functions.disabled_categories,
            vec!["geo", "phonetic"]
        );
        assert_eq!(config.functions.disabled_functions, vec!["env"]);
        assert_eq!(config.queries.libraries.len(), 1);
        assert!(config.queries.inline.contains_key("active-users"));
    }

    #[test]
    fn test_merge_scalars() {
        let base = EngineConfig::default();
        let overlay = EngineConfig {
            engine: EngineSection { strict: true },
            ..Default::default()
        };
        let merged = base.merge(overlay);
        assert!(merged.engine.strict);
    }

    #[test]
    fn test_merge_disabled_union() {
        let base = EngineConfig {
            functions: FunctionsSection {
                disabled_categories: vec!["geo".to_string()],
                disabled_functions: vec!["env".to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        let overlay = EngineConfig {
            functions: FunctionsSection {
                disabled_categories: vec!["geo".to_string(), "phonetic".to_string()],
                disabled_functions: vec!["uuid".to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        let merged = base.merge(overlay);
        assert_eq!(merged.functions.disabled_categories.len(), 2); // geo + phonetic (no dups)
        assert_eq!(merged.functions.disabled_functions.len(), 2); // env + uuid
    }

    #[test]
    fn test_merge_enabled_replaces() {
        let base = EngineConfig {
            functions: FunctionsSection {
                disabled_categories: vec!["geo".to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        let overlay = EngineConfig {
            functions: FunctionsSection {
                enabled_categories: Some(vec!["string".to_string(), "math".to_string()]),
                ..Default::default()
            },
            ..Default::default()
        };
        let merged = base.merge(overlay);
        assert_eq!(
            merged.functions.enabled_categories,
            Some(vec!["string".to_string(), "math".to_string()])
        );
        assert!(merged.functions.disabled_categories.is_empty());
    }

    #[test]
    fn test_merge_queries_concat() {
        let base = EngineConfig {
            queries: QueriesSection {
                libraries: vec!["a.jpx".to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        let overlay = EngineConfig {
            queries: QueriesSection {
                libraries: vec!["b.jpx".to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        let merged = base.merge(overlay);
        assert_eq!(merged.queries.libraries, vec!["a.jpx", "b.jpx"]);
    }

    #[test]
    fn test_builder() {
        let engine = EngineBuilder::new()
            .strict(false)
            .disable_category("geo")
            .disable_function("env")
            .build()
            .unwrap();

        // Engine should work
        let result = engine
            .evaluate("length(@)", &serde_json::json!([1, 2, 3]))
            .unwrap();
        assert_eq!(result, serde_json::json!(3));
    }

    #[test]
    fn test_builder_strict() {
        let engine = EngineBuilder::new().strict(true).build().unwrap();
        assert!(engine.is_strict());
    }

    #[test]
    fn test_from_config_with_disabled_functions() {
        let config = EngineConfig {
            functions: FunctionsSection {
                disabled_functions: vec!["upper".to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        let engine = JpxEngine::from_config(config).unwrap();

        // upper should be disabled in introspection
        assert!(engine.describe_function("upper").is_none());

        // But standard functions still work
        let result = engine
            .evaluate("length(@)", &serde_json::json!([1, 2, 3]))
            .unwrap();
        assert_eq!(result, serde_json::json!(3));
    }

    #[test]
    fn test_from_config_with_inline_queries() {
        let config = EngineConfig {
            queries: QueriesSection {
                inline: {
                    let mut m = HashMap::new();
                    m.insert(
                        "count".to_string(),
                        InlineQuery {
                            expression: "length(@)".to_string(),
                            description: Some("Count items".to_string()),
                        },
                    );
                    m
                },
                ..Default::default()
            },
            ..Default::default()
        };
        let engine = JpxEngine::from_config(config).unwrap();

        let result = engine
            .run_query("count", &serde_json::json!([1, 2, 3]))
            .unwrap();
        assert_eq!(result, serde_json::json!(3));
    }

    #[test]
    fn test_expand_tilde() {
        let result = expand_tilde("/absolute/path");
        assert_eq!(result, "/absolute/path");

        let result = expand_tilde("relative/path");
        assert_eq!(result, "relative/path");

        // ~ expansion depends on home dir being available
        let result = expand_tilde("~/some/path");
        if let Some(home) = dirs::home_dir() {
            assert_eq!(result, home.join("some/path").to_string_lossy().as_ref());
        }
    }

    #[test]
    fn test_invalid_toml() {
        let bad_toml = r#"
[engine
strict = true
"#;
        let result: Result<EngineConfig, _> = toml::from_str(bad_toml);
        assert!(
            result.is_err(),
            "Parsing invalid TOML should return an error"
        );
    }

    #[test]
    fn test_from_file_missing() {
        let path = Path::new("/tmp/nonexistent_jpx_config_test_file.toml");
        let result = EngineConfig::from_file(path);
        assert!(
            result.is_err(),
            "from_file on nonexistent path should return Err"
        );
    }

    #[test]
    fn test_builder_chaining() {
        let builder = EngineBuilder::new()
            .disable_category("geo")
            .disable_category("phonetic")
            .disable_category("semver")
            .disable_function("env")
            .disable_function("upper")
            .disable_function("lower");

        let engine = builder.build().unwrap();

        // All three categories should be disabled -- geo functions should not resolve
        assert!(engine.describe_function("geo_distance").is_none());

        // All three individually disabled functions should be gone
        assert!(engine.describe_function("env").is_none());
        assert!(engine.describe_function("upper").is_none());
        assert!(engine.describe_function("lower").is_none());

        // Standard JMESPath functions still work
        let result = engine
            .evaluate("length(@)", &serde_json::json!([1, 2, 3]))
            .unwrap();
        assert_eq!(result, serde_json::json!(3));
    }

    #[test]
    fn test_builder_enable_categories() {
        let engine = EngineBuilder::new()
            .enable_categories(vec!["string".to_string(), "math".to_string()])
            .build()
            .unwrap();

        // String-category functions should be available
        assert!(
            engine.describe_function("upper").is_some(),
            "upper should be available when string category is enabled"
        );

        // Geo-category functions should NOT be available
        assert!(
            engine.describe_function("geo_distance").is_none(),
            "geo_distance should not be available when only string and math are enabled"
        );
    }

    #[test]
    fn test_builder_inline_query() {
        let engine = EngineBuilder::new()
            .inline_query("count", "length(@)", Some("Count items"))
            .inline_query("names", "people[*].name", None)
            .build()
            .unwrap();

        // First inline query should be stored and runnable
        let result = engine
            .run_query("count", &serde_json::json!([1, 2, 3]))
            .unwrap();
        assert_eq!(result, serde_json::json!(3));

        // Second inline query should also work
        let data = serde_json::json!({"people": [{"name": "alice"}, {"name": "bob"}]});
        let result = engine.run_query("names", &data).unwrap();
        assert_eq!(result, serde_json::json!(["alice", "bob"]));
    }

    #[test]
    fn test_merge_deep_both_empty() {
        let a = EngineConfig::default();
        let b = EngineConfig::default();
        let merged = a.merge(b);

        assert!(!merged.engine.strict);
        assert!(merged.functions.disabled_categories.is_empty());
        assert!(merged.functions.disabled_functions.is_empty());
        assert!(merged.functions.enabled_categories.is_none());
        assert!(merged.queries.libraries.is_empty());
        assert!(merged.queries.inline.is_empty());
    }

    #[test]
    fn test_merge_inline_queries_override() {
        let base = EngineConfig {
            queries: QueriesSection {
                inline: {
                    let mut m = HashMap::new();
                    m.insert(
                        "count".to_string(),
                        InlineQuery {
                            expression: "length(@)".to_string(),
                            description: Some("Original".to_string()),
                        },
                    );
                    m
                },
                ..Default::default()
            },
            ..Default::default()
        };
        let overlay = EngineConfig {
            queries: QueriesSection {
                inline: {
                    let mut m = HashMap::new();
                    m.insert(
                        "count".to_string(),
                        InlineQuery {
                            expression: "length(keys(@))".to_string(),
                            description: Some("Overridden".to_string()),
                        },
                    );
                    m
                },
                ..Default::default()
            },
            ..Default::default()
        };
        let merged = base.merge(overlay);

        let count_query = merged.queries.inline.get("count").unwrap();
        assert_eq!(
            count_query.expression, "length(keys(@))",
            "Later inline query should override earlier one with same name"
        );
        assert_eq!(
            count_query.description.as_deref(),
            Some("Overridden"),
            "Description should also be from the later config"
        );
    }

    #[test]
    fn test_build_runtime_strict() {
        let functions_config = FunctionsSection::default();
        let (runtime, registry) = build_runtime_from_config(&functions_config, true);

        // Registry should have extension functions registered
        assert!(
            registry.is_enabled("upper"),
            "Registry should know about upper even in strict mode"
        );

        // But the runtime should NOT have extension functions applied.
        // Compiling a standard expression should work (the parser is always available).
        assert!(
            runtime.compile("length(@)").is_ok(),
            "Compiling a standard expression should succeed"
        );

        // Evaluating with an extension function should fail because it was never
        // applied to the runtime.
        let expr = runtime.compile("upper('hello')").unwrap();
        let data = serde_json::json!("ignored");
        let result = expr.search(&data);
        assert!(
            result.is_err(),
            "upper should not be callable on the runtime in strict mode"
        );
    }

    #[test]
    fn test_build_runtime_disabled_category() {
        let functions_config = FunctionsSection {
            disabled_categories: vec!["Geo".to_string()],
            ..Default::default()
        };
        let (_runtime, registry) = build_runtime_from_config(&functions_config, false);

        // Geo functions should be disabled in the registry
        assert!(
            !registry.is_enabled("geo_distance"),
            "geo_distance should be disabled when Geo category is disabled"
        );

        // Non-geo functions should still be enabled
        assert!(
            registry.is_enabled("upper"),
            "upper should still be enabled when only Geo is disabled"
        );
    }
}