Skip to content

Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.

feat: compile cache + TTL eviction + tool exposure filter (PR #11)

FABIOTESS71c3135515a1
diff --git a/docs/cache-and-registry.md b/docs/cache-and-registry.md
new file mode 100644
index 00000000..8d2e5230
--- /dev/null
+++ b/docs/cache-and-registry.md
@@ -0,0 +1,120 @@
+# Compile cache, dynamic load/unload, and tool exposure control
+
+This document describes three operational features added to make Open
+Ontologies suitable for serving many ontologies on a memory-constrained host.
+
+## 1. Compile cache (parsed-graph reuse)
+
+When `onto_load` is called with a file path, the parsed graph is serialized
+to N-Triples and written to `[cache] dir`. Subsequent loads of the same
+source file (unchanged mtime/size/sha) read the N-Triples cache directly,
+which is significantly faster than re-parsing Turtle / RDF-XML / etc.
+
+Configuration (`config.toml`):
+
+```toml
+[cache]
+enabled = true
+dir = "~/.open-ontologies/cache"
+```
+
+Inspect with `onto_cache_status`. Bypass the cache for one call with
+`onto_load { force_recompile: true }`. Force-recompile the active
+ontology with `onto_recompile`.
+
+## 2. Idle TTL eviction (memory-saving)
+
+The registry tracks a `last_access` timestamp for the active ontology.
+A background task running every `evictor_interval_secs` seconds clears
+the in-memory store when `now - last_access >= idle_ttl_secs`. The
+on-disk N-Triples cache is preserved.
+
+```toml
+[cache]
+idle_ttl_secs = 600 # unload after 10 minutes idle
+evictor_interval_secs = 30 # check every 30 seconds
+```
+
+Set `idle_ttl_secs = 0` to disable eviction.
+
+## 3. Auto-load on query
+
+Every read tool (`onto_query`, `onto_stats`, `onto_save`, ...) calls
+`registry.ensure_loaded()` before touching the graph. If the ontology
+was evicted, it is reloaded from the N-Triples cache. The MCP client
+sees a slightly slower first query after eviction; subsequent queries
+hit warm memory.
+
+## 4. Auto-refresh on file change
+
+When `onto_load` was called with `auto_refresh: true` (or `--auto-refresh`
+was passed to the server), `ensure_loaded()` additionally checks the
+source file's mtime/size/sha on every call. If it changed, the source
+is re-parsed and the cache is rewritten before the query runs.
+
+This is opt-in for predictability — without it, running `onto_recompile`
+is the explicit way to pick up source-file edits.
+
+## 5. MCP tool exposure filter
+
+Operators can restrict which `onto_*` tools the MCP server advertises.
+
+CLI:
+
+```sh
+open-ontologies serve --tools-allow "onto_status,onto_query,@read_only"
+open-ontologies serve --tools-deny "onto_clear,onto_apply"
+```
+
+Config:
+
+```toml
+[tools]
+mode = "allow"
+list = ["onto_status", "onto_query", "onto_save"]
+groups = ["read_only"]
+```
+
+Modes: `all` (default), `allow` (only listed tools exposed), `deny`
+(all tools except listed). Groups are expanded to curated sets:
+
+- `read_only` — `onto_status`, `onto_validate`, `onto_query`, `onto_stats`,
+ `onto_diff`, `onto_lint`, `onto_history`, `onto_lineage`,
+ `onto_cache_status`, `onto_dl_check`, `onto_dl_explain`, `onto_search`,
+ `onto_similarity`
+- `mutating` — `onto_load`, `onto_clear`, `onto_save`, `onto_convert`,
+ `onto_pull`, `onto_import`, `onto_marketplace`, `onto_version`,
+ `onto_rollback`, `onto_ingest`, `onto_map`, `onto_shacl`, `onto_reason`,
+ `onto_extend`, `onto_unload`, `onto_recompile`
+- `governance` — `onto_plan`, `onto_apply`, `onto_lock`, `onto_drift`,
+ `onto_enforce`, `onto_monitor`, `onto_monitor_clear`, `onto_align`,
+ `onto_align_feedback`, `onto_lint_feedback`, `onto_enforce_feedback`
+- `remote` — `onto_pull`, `onto_push`, `onto_marketplace`, `onto_import`
+- `embeddings` — `onto_embed`, `onto_search`, `onto_similarity`
+
+Removed tools are not advertised via `tools/list` and cannot be invoked
+via `tools/call`.
+
+## New tools added by this feature
+
+| Tool | Description |
+| ---- | ----------- |
+| `onto_unload` | Unload from memory. With `name`: targets that named entry (clears in-memory store if it is the active slot). Without `name`: operates on the active ontology. `delete_cache=true` also removes the on-disk file. |
+| `onto_recompile` | Re-parse the source. With `name`: rebuilds that cached entry — if it is not the active slot, the in-memory store is left untouched (safe background refresh). Without `name`: recompiles the active ontology and reloads it. |
+| `onto_cache_status` | Active slot, all cache rows, and effective config. |
+| `onto_cache_list` | Lighter alternative to `onto_cache_status` — returns just the array of cached ontologies with metadata and `is_active`/`in_memory` flags. |
+| `onto_cache_remove` | Remove a cached ontology by name. If it is the active slot, the in-memory store is unloaded first. By default the on-disk N-Triples file is also deleted; pass `delete_file=false` to keep it. |
+
+### Managing multiple cached ontologies
+
+Although the registry holds a single *active* slot at a time, the on-disk
+compile cache is keyed by `name` and supports many entries. The combination
+of `onto_load`, `onto_cache_list`, `onto_cache_remove`, and per-name
+`onto_recompile`/`onto_unload` lets operators:
+
+- maintain a set of pre-compiled N-Triples caches for many ontologies,
+- swap which one is currently active by calling `onto_load` with the
+ matching path (cache will be reused since the source is unchanged),
+- refresh background ontologies' caches *without* disturbing the active
+ in-memory ontology by calling `onto_recompile { name: "other" }`,
+- clean up obsolete entries with `onto_cache_remove`.
diff --git a/src/cache.rs b/src/cache.rs
new file mode 100644
index 00000000..1a1d8ae3
--- /dev/null
+++ b/src/cache.rs
@@ -0,0 +1,387 @@
+//! Compile cache for ontology files.
+//!
+//! A loaded ontology is serialized as N-Triples (the simplest, fastest-to-parse
+//! RDF format) and written to `<cache_dir>/<sha>.nt`. Metadata is stored in
+//! the `ontology_cache` SQLite table so we can quickly answer "is the cache
+//! still valid for this source file?" without re-parsing.
+//!
+//! Validity key: `(source_path, mtime_secs, size, sha256(prefix))`.
+//! For most workflows the (mtime, size) pair is sufficient and avoids hashing
+//! large files; the sha256 of the first 64 KiB is also stored as a tie-breaker.
+use anyhow::{anyhow, Context, Result};
+use std::fs;
+use std::io::Read;
+use std::path::{Path, PathBuf};
+use std::time::UNIX_EPOCH;
+
+use rusqlite::params;
+
+use crate::state::StateDb;
+
+const HASH_PREFIX_BYTES: usize = 64 * 1024;
+
+/// Information about a source ontology file used as the cache validity key.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct SourceFingerprint {
+ pub mtime_secs: i64,
+ pub size: u64,
+ pub sha_prefix: String,
+}
+
+impl SourceFingerprint {
+ /// Compute a fingerprint for `path` (mtime, size, sha256 of first 64 KiB).
+ pub fn from_path(path: &Path) -> Result<Self> {
+ let meta = fs::metadata(path)
+ .with_context(|| format!("stat({})", path.display()))?;
+ let size = meta.len();
+ let mtime_secs = meta
+ .modified()
+ .ok()
+ .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
+ .map(|d| d.as_secs() as i64)
+ .unwrap_or(0);
+
+ // Read up to 64 KiB for hashing — enough to differentiate files
+ // with identical mtime/size (rare but possible with `cp -p`).
+ let mut file = fs::File::open(path)
+ .with_context(|| format!("open({})", path.display()))?;
+ let mut buf = vec![0u8; HASH_PREFIX_BYTES.min(size as usize)];
+ let n = file.read(&mut buf)?;
+ buf.truncate(n);
+ let sha_prefix = sha256_hex(&buf);
+
+ Ok(Self { mtime_secs, size, sha_prefix })
+ }
+}
+
+/// A small, dependency-free SHA-256 implementation (FIPS 180-4).
+///
+/// Why not use the `sha2` crate? The cache only uses this hash as a
+/// **non-security** content-fingerprint (combined with mtime+size) to detect
+/// when a parsed source file is stale. Mis-hashing causes a re-parse, never
+/// a security failure. We therefore prefer a self-contained ~80-line
+/// implementation over adding a new dependency tree just for the cache key.
+/// If this hash is ever reused for an authenticity-sensitive purpose,
+/// switch the call sites to `sha2` first.
+fn sha256_hex(input: &[u8]) -> String {
+ let digest = sha256(input);
+ let mut s = String::with_capacity(64);
+ for b in digest.iter() {
+ s.push_str(&format!("{:02x}", b));
+ }
+ s
+}
+
+fn sha256(input: &[u8]) -> [u8; 32] {
+ const K: [u32; 64] = [
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
+ ];
+ let mut h: [u32; 8] = [
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
+ 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
+ ];
+
+ // Pre-processing: padding
+ let bit_len = (input.len() as u64).wrapping_mul(8);
+ let mut msg = Vec::with_capacity(input.len() + 64);
+ msg.extend_from_slice(input);
+ msg.push(0x80);
+ while msg.len() % 64 != 56 {
+ msg.push(0);
+ }
+ msg.extend_from_slice(&bit_len.to_be_bytes());
+
+ for chunk in msg.chunks(64) {
+ let mut w = [0u32; 64];
+ for (i, word) in chunk.chunks(4).enumerate() {
+ w[i] = u32::from_be_bytes([word[0], word[1], word[2], word[3]]);
+ }
+ for i in 16..64 {
+ let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
+ let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
+ w[i] = w[i - 16]
+ .wrapping_add(s0)
+ .wrapping_add(w[i - 7])
+ .wrapping_add(s1);
+ }
+
+ let (mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh) =
+ (h[0], h[1], h[2], h[3], h[4], h[5], h[6], h[7]);
+
+ for i in 0..64 {
+ let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
+ let ch = (e & f) ^ ((!e) & g);
+ let temp1 = hh.wrapping_add(s1).wrapping_add(ch).wrapping_add(K[i]).wrapping_add(w[i]);
+ let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
+ let maj = (a & b) ^ (a & c) ^ (b & c);
+ let temp2 = s0.wrapping_add(maj);
+
+ hh = g;
+ g = f;
+ f = e;
+ e = d.wrapping_add(temp1);
+ d = c;
+ c = b;
+ b = a;
+ a = temp1.wrapping_add(temp2);
+ }
+
+ h[0] = h[0].wrapping_add(a);
+ h[1] = h[1].wrapping_add(b);
+ h[2] = h[2].wrapping_add(c);
+ h[3] = h[3].wrapping_add(d);
+ h[4] = h[4].wrapping_add(e);
+ h[5] = h[5].wrapping_add(f);
+ h[6] = h[6].wrapping_add(g);
+ h[7] = h[7].wrapping_add(hh);
+ }
+
+ let mut out = [0u8; 32];
+ for (i, word) in h.iter().enumerate() {
+ out[i * 4..(i + 1) * 4].copy_from_slice(&word.to_be_bytes());
+ }
+ out
+}
+
+/// One row from the `ontology_cache` table.
+#[derive(Debug, Clone)]
+pub struct CacheEntry {
+ pub name: String,
+ pub source_path: String,
+ pub source_mtime: i64,
+ pub source_size: u64,
+ pub source_sha: String,
+ pub cache_path: String,
+ pub triple_count: usize,
+ pub compiled_at: String,
+ pub last_access_at: String,
+}
+
+/// Manages the on-disk N-Triples cache plus its SQLite metadata.
+pub struct CacheManager {
+ cache_dir: PathBuf,
+ db: StateDb,
+}
+
+impl CacheManager {
+ pub fn new(cache_dir: PathBuf, db: StateDb) -> Result<Self> {
+ fs::create_dir_all(&cache_dir)
+ .with_context(|| format!("create cache dir {}", cache_dir.display()))?;
+ Ok(Self { cache_dir, db })
+ }
+
+ pub fn cache_dir(&self) -> &Path {
+ &self.cache_dir
+ }
+
+ /// Look up a cache entry by ontology name.
+ pub fn get(&self, name: &str) -> Result<Option<CacheEntry>> {
+ let conn = self.db.conn();
+ let mut stmt = conn.prepare(
+ "SELECT name, source_path, source_mtime, source_size, source_sha, \
+ cache_path, triple_count, compiled_at, last_access_at \
+ FROM ontology_cache WHERE name = ?1",
+ )?;
+ let mut rows = stmt.query(params![name])?;
+ if let Some(row) = rows.next()? {
+ Ok(Some(CacheEntry {
+ name: row.get(0)?,
+ source_path: row.get(1)?,
+ source_mtime: row.get(2)?,
+ source_size: row.get::<_, i64>(3)? as u64,
+ source_sha: row.get(4)?,
+ cache_path: row.get(5)?,
+ triple_count: row.get::<_, i64>(6)? as usize,
+ compiled_at: row.get(7)?,
+ last_access_at: row.get(8)?,
+ }))
+ } else {
+ Ok(None)
+ }
+ }
+
+ /// Determine whether `entry` is still valid for the on-disk source file.
+ /// Returns `Ok(true)` only if the source's fingerprint matches.
+ pub fn is_fresh(&self, entry: &CacheEntry) -> Result<bool> {
+ let path = Path::new(&entry.source_path);
+ if !path.exists() {
+ return Ok(false);
+ }
+ let fp = SourceFingerprint::from_path(path)?;
+ Ok(fp.mtime_secs == entry.source_mtime
+ && fp.size == entry.source_size
+ && fp.sha_prefix == entry.source_sha)
+ }
+
+ /// Build a cache file path for a given source key.
+ pub fn cache_path_for(&self, name: &str, sha: &str) -> PathBuf {
+ // Use both the name and the sha so renames don't collide and we can
+ // garbage-collect stale entries by `name`.
+ let safe = name
+ .chars()
+ .map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' })
+ .collect::<String>();
+ self.cache_dir.join(format!("{}.{}.nt", safe, &sha[..sha.len().min(16)]))
+ }
+
+ /// Atomically write `content` to `path` (writes to `<path>.tmp` then renames).
+ pub fn atomic_write(path: &Path, content: &str) -> Result<()> {
+ if let Some(parent) = path.parent() {
+ fs::create_dir_all(parent).ok();
+ }
+ let tmp = path.with_extension("nt.tmp");
+ fs::write(&tmp, content)
+ .with_context(|| format!("write {}", tmp.display()))?;
+ fs::rename(&tmp, path)
+ .with_context(|| format!("rename {} -> {}", tmp.display(), path.display()))?;
+ Ok(())
+ }
+
+ /// Insert or update a cache entry.
+ pub fn upsert(
+ &self,
+ name: &str,
+ source_path: &str,
+ fp: &SourceFingerprint,
+ cache_path: &Path,
+ triple_count: usize,
+ ) -> Result<()> {
+ let conn = self.db.conn();
+ conn.execute(
+ "INSERT INTO ontology_cache \
+ (name, source_path, source_mtime, source_size, source_sha, cache_path, \
+ triple_count, compiled_at, last_access_at) \
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, datetime('now'), datetime('now')) \
+ ON CONFLICT(name) DO UPDATE SET \
+ source_path = excluded.source_path, \
+ source_mtime = excluded.source_mtime, \
+ source_size = excluded.source_size, \
+ source_sha = excluded.source_sha, \
+ cache_path = excluded.cache_path, \
+ triple_count = excluded.triple_count, \
+ compiled_at = excluded.compiled_at, \
+ last_access_at = excluded.last_access_at",
+ params![
+ name,
+ source_path,
+ fp.mtime_secs,
+ fp.size as i64,
+ fp.sha_prefix,
+ cache_path.to_string_lossy(),
+ triple_count as i64,
+ ],
+ )?;
+ Ok(())
+ }
+
+ /// Touch `last_access_at` for an entry.
+ pub fn touch(&self, name: &str) -> Result<()> {
+ let conn = self.db.conn();
+ conn.execute(
+ "UPDATE ontology_cache SET last_access_at = datetime('now') WHERE name = ?1",
+ params![name],
+ )?;
+ Ok(())
+ }
+
+ /// Remove a cache entry and its on-disk file.
+ pub fn remove(&self, name: &str) -> Result<()> {
+ let entry = self.get(name)?;
+ if let Some(e) = &entry {
+ let _ = fs::remove_file(&e.cache_path);
+ }
+ let conn = self.db.conn();
+ conn.execute("DELETE FROM ontology_cache WHERE name = ?1", params![name])?;
+ Ok(())
+ }
+
+ /// List all cache entries.
+ pub fn list(&self) -> Result<Vec<CacheEntry>> {
+ let conn = self.db.conn();
+ let mut stmt = conn.prepare(
+ "SELECT name, source_path, source_mtime, source_size, source_sha, \
+ cache_path, triple_count, compiled_at, last_access_at \
+ FROM ontology_cache ORDER BY last_access_at DESC",
+ )?;
+ let mut rows = stmt.query([])?;
+ let mut out = Vec::new();
+ while let Some(row) = rows.next()? {
+ out.push(CacheEntry {
+ name: row.get(0)?,
+ source_path: row.get(1)?,
+ source_mtime: row.get(2)?,
+ source_size: row.get::<_, i64>(3)? as u64,
+ source_sha: row.get(4)?,
+ cache_path: row.get(5)?,
+ triple_count: row.get::<_, i64>(6)? as usize,
+ compiled_at: row.get(7)?,
+ last_access_at: row.get(8)?,
+ });
+ }
+ Ok(out)
+ }
+}
+
+/// Convenience: derive a default ontology name from a source path
+/// (basename without extension), used when the caller doesn't supply one.
+pub fn derive_name(path: &str) -> String {
+ Path::new(path)
+ .file_stem()
+ .and_then(|s| s.to_str())
+ .map(|s| s.to_string())
+ .unwrap_or_else(|| "default".to_string())
+}
+
+/// Validate a shape used by tests and the registry.
+pub fn require_path(path: &Option<String>) -> Result<&str> {
+ match path {
+ Some(p) if !p.is_empty() => Ok(p),
+ _ => Err(anyhow!("path required")),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn sha256_known_vector() {
+ // FIPS 180-2 example: "abc" -> ba7816bf...
+ assert_eq!(
+ sha256_hex(b"abc"),
+ "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
+ );
+ assert_eq!(
+ sha256_hex(b""),
+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ );
+ }
+
+ #[test]
+ fn fingerprint_changes_when_content_changes() {
+ let dir = tempfile::tempdir().unwrap();
+ let p = dir.path().join("x.ttl");
+ fs::write(&p, "@prefix : <http://example.org/> . :a a :B .").unwrap();
+ let fp1 = SourceFingerprint::from_path(&p).unwrap();
+ // Sleep just enough to bump mtime; on filesystems with 1s resolution
+ // we also rewrite different content so size/sha differs even at same mtime.
+ std::thread::sleep(std::time::Duration::from_millis(1100));
+ fs::write(&p, "@prefix : <http://example.org/> . :a a :C .").unwrap();
+ let fp2 = SourceFingerprint::from_path(&p).unwrap();
+ assert_ne!(fp1, fp2);
+ }
+
+ #[test]
+ fn derive_name_strips_extension() {
+ assert_eq!(derive_name("/tmp/foo.ttl"), "foo");
+ assert_eq!(derive_name("foo.bar.ttl"), "foo.bar");
+ assert_eq!(derive_name(""), "default");
+ }
+}
diff --git a/src/config.rs b/src/config.rs
index 36560aaf..54f8e70f 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -8,6 +8,8 @@ use std::path::Path;
pub struct Config {
pub general: GeneralConfig,
pub embeddings: EmbeddingsConfig,
+ pub cache: CacheConfig,
+ pub tools: ToolsConfig,
}
@@ -50,6 +52,50 @@ pub struct EmbeddingsConfig {
pub model_name: Option<String>,
}
+/// Configuration for the on-disk N-Triples compile cache and TTL eviction.
+#[derive(Debug, Deserialize, Clone)]
+#[serde(default)]
+pub struct CacheConfig {
+ /// Master switch for the compile cache. When false, every load re-parses
+ /// from source and no metadata is recorded.
+ pub enabled: bool,
+ /// Directory where N-Triples cache files are stored.
+ pub dir: String,
+ /// If > 0, the active ontology will be unloaded from memory after this
+ /// many seconds without access. The cache file is preserved and reloaded
+ /// automatically on the next query.
+ pub idle_ttl_secs: u64,
+ /// How often the background evictor checks idle entries (seconds).
+ pub evictor_interval_secs: u64,
+ /// When true, every read tool checks the source file's mtime/sha and
+ /// recompiles if it changed. Off by default for predictability.
+ pub auto_refresh: bool,
+}
+
+impl Default for CacheConfig {
+ fn default() -> Self {
+ Self {
+ enabled: true,
+ dir: "~/.open-ontologies/cache".into(),
+ idle_ttl_secs: 0,
+ evictor_interval_secs: 30,
+ auto_refresh: false,
+ }
+ }
+}
+
+/// Configuration for limiting which MCP tools are exposed.
+#[derive(Debug, Deserialize, Clone, Default)]
+#[serde(default)]
+pub struct ToolsConfig {
+ /// "all" (default), "allow", or "deny".
+ pub mode: String,
+ /// Explicit tool names included by the filter.
+ pub list: Vec<String>,
+ /// Group names (e.g. "read_only") expanded into tool names.
+ pub groups: Vec<String>,
+}
+
/// Expand a leading `~` in a path to the user's home directory.
pub fn expand_tilde(path: &str) -> String {
if (path.starts_with("~/") || path == "~")
diff --git a/src/inputs.rs b/src/inputs.rs
index 6ab9a676..5f1ea1a5 100644
--- a/src/inputs.rs
+++ b/src/inputs.rs
@@ -27,6 +27,49 @@ pub struct OntoLoadInput {
pub path: Option<String>,
/// Inline Turtle content to load (alternative to path)
pub turtle: Option<String>,
+ /// Optional name for this ontology in the registry. Defaults to the file
+ /// stem of `path`. When omitted for inline turtle, defaults to "default".
+ pub name: Option<String>,
+ /// When true, every subsequent read tool checks the source file's mtime
+ /// and recompiles if it changed. Has no effect for inline turtle.
+ pub auto_refresh: Option<bool>,
+ /// When true, ignore the on-disk compile cache and re-parse from source.
+ pub force_recompile: Option<bool>,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoUnloadInput {
+ /// When true, also delete the on-disk compile cache file.
+ pub delete_cache: Option<bool>,
+ /// Optional ontology name. When omitted, operates on the currently active
+ /// ontology. When provided, targets that named cache entry — if it is the
+ /// active slot the in-memory store is cleared; otherwise only the on-disk
+ /// cache is touched (and only when `delete_cache` is true).
+ pub name: Option<String>,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoRecompileInput {
+ /// Optional ontology name. When omitted, recompiles the active ontology.
+ /// When provided, recompiles that cached entry from its recorded source
+ /// path; if the entry is not active, the active in-memory store is left
+ /// untouched.
+ pub name: Option<String>,
+}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoCacheStatusInput {}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoCacheListInput {}
+
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoCacheRemoveInput {
+ /// Name of the cached ontology to remove.
+ pub name: String,
+ /// When true (default), also delete the on-disk N-Triples cache file.
+ /// When false, only the metadata row is removed.
+ pub delete_file: Option<bool>,
}
#[derive(Deserialize, JsonSchema)]
diff --git a/src/lib.rs b/src/lib.rs
index ffcbce30..f3f7374c 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,4 +1,5 @@
pub mod batch;
+pub mod cache;
pub mod error;
pub mod align;
pub mod config;
@@ -17,12 +18,14 @@ pub mod mapping;
pub mod marketplace;
pub mod ontology;
pub mod reason;
+pub mod registry;
pub mod server;
pub mod shacl;
pub mod state;
pub mod schema;
pub mod socket;
pub mod tableaux;
+pub mod toolfilter;
#[cfg(feature = "embeddings")]
pub mod poincare;
#[cfg(feature = "embeddings")]
diff --git a/src/main.rs b/src/main.rs
index b4322215..0b736c57 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -10,6 +10,28 @@ use open_ontologies::state::StateDb;
const DEFAULT_CONFIG: &str = r#"[general]
data_dir = "~/.open-ontologies"
+# [cache]
+# Compile-cache: parsed ontologies are written to N-Triples files for fast reload.
+# enabled = true
+# dir = "~/.open-ontologies/cache"
+# # Idle TTL in seconds before the active ontology is unloaded from memory.
+# # Set to 0 to disable eviction. The on-disk cache file is always preserved
+# # across evictions; the next query reloads it transparently.
+# idle_ttl_secs = 0
+# # How often the background evictor runs (seconds).
+# evictor_interval_secs = 30
+# # When true, every read tool checks the source file's mtime/sha and
+# # recompiles if it changed.
+# auto_refresh = false
+
+# [tools]
+# Restrict which MCP tools are exposed by this server.
+# mode = "all" | "allow" | "deny"
+# list = ["onto_status", "onto_query", "onto_load"]
+# # Groups: read_only, mutating, governance, remote, embeddings.
+# groups = ["read_only"]
+# mode = "all"
+
# [embeddings]
# Paths to a local ONNX model and tokenizer (loaded at runtime)
# model_path = "~/.open-ontologies/models/bge-small-en-v1.5.onnx"
@@ -67,6 +89,18 @@ enum Commands {
/// Interval in seconds between monitor sweeps (default: 30)
#[arg(long, default_value = "30")]
watch_interval: u64,
+ /// Comma-separated list of tools (or `@group`) to allow. Mutually exclusive with --tools-deny.
+ #[arg(long)]
+ tools_allow: Option<String>,
+ /// Comma-separated list of tools (or `@group`) to deny.
+ #[arg(long)]
+ tools_deny: Option<String>,
+ /// Idle TTL in seconds before the active ontology is unloaded from memory. 0 disables eviction.
+ #[arg(long)]
+ idle_ttl_secs: Option<u64>,
+ /// When set, every read tool checks the source file for changes and recompiles.
+ #[arg(long)]
+ auto_refresh: bool,
},
/// Start the MCP server (Streamable HTTP transport)
ServeHttp {
@@ -90,6 +124,18 @@ enum Commands {
/// Interval in seconds between monitor sweeps (default: 30)
#[arg(long, default_value = "30")]
watch_interval: u64,
+ /// Comma-separated list of tools (or `@group`) to allow.
+ #[arg(long)]
+ tools_allow: Option<String>,
+ /// Comma-separated list of tools (or `@group`) to deny.
+ #[arg(long)]
+ tools_deny: Option<String>,
+ /// Idle TTL in seconds before the active ontology is unloaded from memory.
+ #[arg(long)]
+ idle_ttl_secs: Option<u64>,
+ /// When set, every read tool checks the source file for changes and recompiles.
+ #[arg(long)]
+ auto_refresh: bool,
},
/// Start unix socket server for Tardygrada fact grounding
@@ -382,6 +428,55 @@ fn output_result(result: &str, pretty: bool) {
}
}
+/// Compose the effective cache configuration from `[cache]` in config + CLI overrides.
+fn build_cache_config(
+ cfg: &Config,
+ idle_ttl_secs: Option<u64>,
+ auto_refresh: bool,
+) -> open_ontologies::config::CacheConfig {
+ let mut cc = cfg.cache.clone();
+ if let Some(ttl) = idle_ttl_secs {
+ cc.idle_ttl_secs = ttl;
+ }
+ if auto_refresh {
+ cc.auto_refresh = true;
+ }
+ cc
+}
+
+/// Compose the effective tool filter from `[tools]` in config + CLI flags.
+/// CLI `--tools-allow` / `--tools-deny` override `[tools]` when present.
+fn build_tool_filter(
+ cfg: &Config,
+ cli_allow: Option<&str>,
+ cli_deny: Option<&str>,
+) -> anyhow::Result<open_ontologies::toolfilter::ToolFilter> {
+ use open_ontologies::toolfilter::{Mode, ToolFilter, parse_csv};
+
+ if cli_allow.is_some() && cli_deny.is_some() {
+ anyhow::bail!("--tools-allow and --tools-deny are mutually exclusive");
+ }
+ if let Some(spec) = cli_allow {
+ let (list, groups) = parse_csv(spec);
+ return Ok(ToolFilter { mode: Mode::Allow, list, groups });
+ }
+ if let Some(spec) = cli_deny {
+ let (list, groups) = parse_csv(spec);
+ return Ok(ToolFilter { mode: Mode::Deny, list, groups });
+ }
+ // Fall back to config file.
+ let mode = if cfg.tools.mode.is_empty() {
+ Mode::All
+ } else {
+ Mode::parse(&cfg.tools.mode).map_err(|e| anyhow::anyhow!(e))?
+ };
+ Ok(ToolFilter {
+ mode,
+ list: cfg.tools.list.clone(),
+ groups: cfg.tools.groups.clone(),
+ })
+}
+
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let cli = Cli::parse();
@@ -454,7 +549,7 @@ async fn main() -> anyhow::Result<()> {
println!("\nOpen Ontologies initialized successfully!");
}
- Commands::Serve { config: config_path, governance_webhook, watch, watch_interval } => {
+ Commands::Serve { config: config_path, governance_webhook, watch, watch_interval, tools_allow, tools_deny, idle_ttl_secs, auto_refresh } => {
let config_path = expand_tilde(&config_path);
let cfg = match Config::load(std::path::Path::new(&config_path)) {
Ok(c) => c,
@@ -486,11 +581,21 @@ async fn main() -> anyhow::Result<()> {
None
};
- let server = OpenOntologiesServer::new_with_full_options(db, graph, governance_webhook, cfg.embeddings);
+ let cache_config = build_cache_config(&cfg, idle_ttl_secs, auto_refresh);
+ let tool_filter = build_tool_filter(&cfg, tools_allow.as_deref(), tools_deny.as_deref())?;
+ let server = OpenOntologiesServer::new_with_registry_options(
+ db,
+ graph,
+ governance_webhook,
+ cfg.embeddings,
+ cache_config,
+ tool_filter,
+ );
+ let _evictor = open_ontologies::registry::spawn_evictor(server.registry());
let service = server.serve(rmcp::transport::stdio()).await?;
service.waiting().await?;
}
- Commands::ServeHttp { config: config_path, host, port, token, governance_webhook, watch, watch_interval } => {
+ Commands::ServeHttp { config: config_path, host, port, token, governance_webhook, watch, watch_interval, tools_allow, tools_deny, idle_ttl_secs, auto_refresh } => {
use rmcp::transport::streamable_http_server::{
StreamableHttpServerConfig, StreamableHttpService,
session::local::LocalSessionManager,
@@ -541,12 +646,35 @@ async fn main() -> anyhow::Result<()> {
let shared_graph_for_service = shared_graph.clone();
let gw_for_service = governance_webhook.clone();
let embed_config = cfg.embeddings.clone();
+ let cache_config = build_cache_config(&cfg, idle_ttl_secs, auto_refresh);
+ let tool_filter = build_tool_filter(&cfg, tools_allow.as_deref(), tools_deny.as_deref())?;
+ // Spawn a single evictor backed by a registry over the shared graph.
+ // Each per-session server constructs its own registry (active slot
+ // is per-session anyway), but the shared one drives memory cleanup.
+ {
+ let evictor_db = StateDb::open(&db_path_owned)?;
+ let shared_registry = Arc::new(open_ontologies::registry::OntologyRegistry::new(
+ shared_graph.clone(),
+ evictor_db,
+ cache_config.clone(),
+ )?);
+ let _evictor = open_ontologies::registry::spawn_evictor(shared_registry);
+ }
+ let cache_for_service = cache_config.clone();
+ let filter_for_service = tool_filter.clone();
let service: StreamableHttpService<_, LocalSessionManager> =
StreamableHttpService::new(
move || {
let db = StateDb::open(&db_path_owned)
.map_err(std::io::Error::other)?;
- Ok(OpenOntologiesServer::new_with_full_options(db, shared_graph_for_service.clone(), gw_for_service.clone(), embed_config.clone()))
+ Ok(OpenOntologiesServer::new_with_registry_options(
+ db,
+ shared_graph_for_service.clone(),
+ gw_for_service.clone(),
+ embed_config.clone(),
+ cache_for_service.clone(),
+ filter_for_service.clone(),
+ ))
},
Default::default(),
http_config,
diff --git a/src/registry.rs b/src/registry.rs
new file mode 100644
index 00000000..02333ea2
--- /dev/null
+++ b/src/registry.rs
@@ -0,0 +1,481 @@
+//! Ontology registry with TTL-based eviction and on-demand reload.
+//!
+//! The registry tracks the *currently loaded* ontology (a single active slot
+//! at a time) along with the metadata needed to reload it cheaply from the
+//! N-Triples compile cache.
+//!
+//! Lifecycle:
+//! 1. `load_file(path, name, opts)` — parses (or reads cache), populates
+//! `Arc<GraphStore>`, records active entry.
+//! 2. `touch()` — called by every read tool (`onto_query`, `onto_stats`, ...)
+//! to keep the active entry alive.
+//! 3. Background `evictor_tick()` clears the in-memory store if the active
+//! entry has been idle for longer than `idle_ttl_secs`.
+//! 4. `ensure_loaded()` — called by every read tool *before* using the graph;
+//! if the store was evicted, it reloads from the cache (or from source if
+//! `auto_refresh` detected a change).
+use anyhow::{anyhow, Context, Result};
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use crate::cache::{CacheManager, SourceFingerprint};
+use crate::config::CacheConfig;
+use crate::graph::GraphStore;
+use crate::state::StateDb;
+
+/// Options accepted by `OntologyRegistry::load_file`.
+#[derive(Debug, Clone, Default)]
+pub struct LoadOptions {
+ pub name: Option<String>,
+ /// Re-parse the source on every `ensure_loaded` if its mtime/sha changed.
+ pub auto_refresh: bool,
+ /// Bypass the cache and re-parse from source unconditionally.
+ pub force_recompile: bool,
+}
+
+/// Outcome of a load operation, returned to callers (and surfaced in tool JSON).
+#[derive(Debug, Clone)]
+pub struct LoadResult {
+ pub name: String,
+ pub source_path: String,
+ pub triple_count: usize,
+ /// "cache" if loaded from N-Triples cache, "source" if re-parsed.
+ pub origin: &'static str,
+ pub cache_path: String,
+}
+
+#[derive(Debug)]
+struct ActiveEntry {
+ name: String,
+ source_path: String,
+ fingerprint: SourceFingerprint,
+ cache_path: PathBuf,
+ auto_refresh: bool,
+ /// `Mutex<Instant>` to allow `&self`-touch from many threads.
+ last_access: Mutex<Instant>,
+ /// True after the in-memory store has been cleared by the evictor.
+ /// Read tools must reload before using the graph.
+ evicted: Mutex<bool>,
+}
+
+/// Registry of the active ontology. Wrapped in `Arc` and shared with the server.
+pub struct OntologyRegistry {
+ graph: Arc<GraphStore>,
+ cache: CacheManager,
+ config: CacheConfig,
+ /// `Mutex<Option<ActiveEntry>>` — at most one entry is "active" at a time
+ /// in this minimal model. Multi-slot extension is future work.
+ active: Mutex<Option<ActiveEntry>>,
+ /// Per-name reload mutex to prevent thundering-herd reloads.
+ reload_lock: Mutex<()>,
+}
+
+impl OntologyRegistry {
+ pub fn new(graph: Arc<GraphStore>, db: StateDb, config: CacheConfig) -> Result<Self> {
+ let cache_dir = PathBuf::from(crate::config::expand_tilde(&config.dir));
+ let cache = CacheManager::new(cache_dir, db)?;
+ Ok(Self {
+ graph,
+ cache,
+ config,
+ active: Mutex::new(None),
+ reload_lock: Mutex::new(()),
+ })
+ }
+
+ pub fn config(&self) -> &CacheConfig {
+ &self.config
+ }
+
+ pub fn cache(&self) -> &CacheManager {
+ &self.cache
+ }
+
+ /// Load an RDF file into the graph, using the compile cache when valid.
+ pub fn load_file(&self, path: &str, opts: LoadOptions) -> Result<LoadResult> {
+ let path_obj = Path::new(path);
+ if !path_obj.exists() {
+ return Err(anyhow!("file not found: {}", path));
+ }
+ let name = opts.name.clone().unwrap_or_else(|| crate::cache::derive_name(path));
+ let fp = SourceFingerprint::from_path(path_obj)?;
+
+ // Decide load strategy: cache vs source.
+ let existing = self.cache.get(&name)?;
+ let cache_is_fresh = !opts.force_recompile
+ && self.config.enabled
+ && existing
+ .as_ref()
+ .map(|e| {
+ e.source_path == path
+ && e.source_mtime == fp.mtime_secs
+ && e.source_size == fp.size
+ && e.source_sha == fp.sha_prefix
+ && Path::new(&e.cache_path).exists()
+ })
+ .unwrap_or(false);
+
+ // Always start from a clean store for a fresh load.
+ self.graph.clear()?;
+
+ let (triple_count, origin, cache_path) = if cache_is_fresh {
+ let entry = existing.unwrap();
+ let nt = std::fs::read_to_string(&entry.cache_path)
+ .with_context(|| format!("read cache {}", entry.cache_path))?;
+ let count = self.graph.load_ntriples(&nt)?;
+ self.cache.touch(&name)?;
+ (count, "cache", PathBuf::from(entry.cache_path))
+ } else {
+ let count = self
+ .graph
+ .load_file(path)
+ .with_context(|| format!("parse source {}", path))?;
+ let cache_path = if self.config.enabled {
+ let cp = self.cache.cache_path_for(&name, &fp.sha_prefix);
+ let nt = self.graph.serialize("ntriples")?;
+ CacheManager::atomic_write(&cp, &nt)?;
+ self.cache.upsert(&name, path, &fp, &cp, count)?;
+ cp
+ } else {
+ PathBuf::new()
+ };
+ (count, "source", cache_path)
+ };
+
+ // Record active entry.
+ let mut active = self.active.lock().unwrap();
+ *active = Some(ActiveEntry {
+ name: name.clone(),
+ source_path: path.to_string(),
+ fingerprint: fp,
+ cache_path: cache_path.clone(),
+ auto_refresh: opts.auto_refresh,
+ last_access: Mutex::new(Instant::now()),
+ evicted: Mutex::new(false),
+ });
+
+ Ok(LoadResult {
+ name,
+ source_path: path.to_string(),
+ triple_count,
+ origin,
+ cache_path: cache_path.to_string_lossy().into_owned(),
+ })
+ }
+
+ /// Update `last_access` if there is an active entry.
+ pub fn touch(&self) {
+ if let Some(entry) = &*self.active.lock().unwrap() {
+ *entry.last_access.lock().unwrap() = Instant::now();
+ }
+ }
+
+ /// Make sure the in-memory store reflects the active entry.
+ /// If the store was evicted, reload from cache (or source on refresh).
+ /// No-op if no active entry exists.
+ pub fn ensure_loaded(&self) -> Result<()> {
+ // Single-flight guard.
+ let _g = self.reload_lock.lock().unwrap();
+
+ // Snapshot needed fields (avoid holding the active lock across reload).
+ let needs_reload;
+ let auto_refresh;
+ let source_path;
+ let stored_fp;
+ let cache_path;
+ let name;
+ {
+ let active_guard = self.active.lock().unwrap();
+ let Some(entry) = active_guard.as_ref() else {
+ return Ok(());
+ };
+ // Touch first.
+ *entry.last_access.lock().unwrap() = Instant::now();
+ needs_reload = *entry.evicted.lock().unwrap();
+ auto_refresh = entry.auto_refresh;
+ source_path = entry.source_path.clone();
+ stored_fp = entry.fingerprint.clone();
+ cache_path = entry.cache_path.clone();
+ name = entry.name.clone();
+ }
+
+ // Auto-refresh: if the source file changed, recompile (even if not evicted).
+ let mut refreshed = false;
+ if auto_refresh && Path::new(&source_path).exists() {
+ let cur = SourceFingerprint::from_path(Path::new(&source_path))?;
+ if cur != stored_fp {
+ // Source changed — re-parse and rewrite cache.
+ self.graph.clear()?;
+ let count = self.graph.load_file(&source_path)?;
+ let new_cache = self.cache.cache_path_for(&name, &cur.sha_prefix);
+ let nt = self.graph.serialize("ntriples")?;
+ CacheManager::atomic_write(&new_cache, &nt)?;
+ self.cache.upsert(&name, &source_path, &cur, &new_cache, count)?;
+
+ let mut active_guard = self.active.lock().unwrap();
+ if let Some(entry) = active_guard.as_mut() {
+ entry.fingerprint = cur;
+ entry.cache_path = new_cache;
+ *entry.evicted.lock().unwrap() = false;
+ }
+ refreshed = true;
+ }
+ }
+
+ if needs_reload && !refreshed {
+ // Reload from N-Triples cache; fall back to source if cache file
+ // is missing for some reason.
+ if cache_path.exists() {
+ let nt = std::fs::read_to_string(&cache_path)?;
+ self.graph.clear()?;
+ self.graph.load_ntriples(&nt)?;
+ } else if Path::new(&source_path).exists() {
+ self.graph.clear()?;
+ self.graph.load_file(&source_path)?;
+ } else {
+ return Err(anyhow!(
+ "ontology '{}' was evicted but neither cache file '{}' nor source '{}' exists",
+ name, cache_path.display(), source_path
+ ));
+ }
+ let active_guard = self.active.lock().unwrap();
+ if let Some(entry) = active_guard.as_ref() {
+ *entry.evicted.lock().unwrap() = false;
+ }
+ self.cache.touch(&name)?;
+ }
+
+ Ok(())
+ }
+
+ /// Evict the active entry if idle longer than `idle_ttl_secs`.
+ /// Returns `true` when an eviction took place.
+ pub fn evictor_tick(&self) -> Result<bool> {
+ if !self.config.enabled || self.config.idle_ttl_secs == 0 {
+ return Ok(false);
+ }
+ let ttl = Duration::from_secs(self.config.idle_ttl_secs);
+ let active = self.active.lock().unwrap();
+ let Some(entry) = active.as_ref() else { return Ok(false) };
+ let already = *entry.evicted.lock().unwrap();
+ if already {
+ return Ok(false);
+ }
+ let elapsed = entry.last_access.lock().unwrap().elapsed();
+ if elapsed >= ttl {
+ // Clear the in-memory store to release memory; cache file remains.
+ self.graph.clear()?;
+ *entry.evicted.lock().unwrap() = true;
+ return Ok(true);
+ }
+ Ok(false)
+ }
+
+ /// Manually unload the active ontology (clear graph + drop active slot).
+ /// The cache file is preserved unless `delete_cache` is true.
+ pub fn unload(&self, delete_cache: bool) -> Result<Option<String>> {
+ let mut active = self.active.lock().unwrap();
+ let Some(entry) = active.take() else { return Ok(None) };
+ self.graph.clear()?;
+ if delete_cache {
+ self.cache.remove(&entry.name)?;
+ }
+ Ok(Some(entry.name))
+ }
+
+ /// Unload a specific named ontology.
+ /// - If `name` matches the active slot, behaves like `unload(delete_cache)`.
+ /// - If `name` is in the cache but not active, only the on-disk cache is
+ /// touched (since it was never in memory). With `delete_cache=true` the
+ /// cache file and DB row are removed; otherwise this is a no-op.
+ /// Returns `Ok(true)` if anything was actually changed.
+ pub fn unload_named(&self, name: &str, delete_cache: bool) -> Result<bool> {
+ let active_name = self.active.lock().unwrap().as_ref().map(|e| e.name.clone());
+ if active_name.as_deref() == Some(name) {
+ return Ok(self.unload(delete_cache)?.is_some());
+ }
+ // Not active. The graph isn't holding it, so there's nothing to clear
+ // in memory. Touch the cache only if requested.
+ if delete_cache {
+ if self.cache.get(name)?.is_none() {
+ return Err(anyhow!("no cached ontology named '{}'", name));
+ }
+ self.cache.remove(name)?;
+ return Ok(true);
+ }
+ // Verify the entry exists at least, so callers get a clear error
+ // when they pass a typo.
+ if self.cache.get(name)?.is_none() {
+ return Err(anyhow!("no cached ontology named '{}'", name));
+ }
+ Ok(false)
+ }
+
+ /// Force recompile the active ontology from source (used by `onto_recompile`).
+ pub fn recompile(&self) -> Result<LoadResult> {
+ let (path, name, auto_refresh) = {
+ let active = self.active.lock().unwrap();
+ let entry = active
+ .as_ref()
+ .ok_or_else(|| anyhow!("no active ontology to recompile"))?;
+ (entry.source_path.clone(), entry.name.clone(), entry.auto_refresh)
+ };
+ self.load_file(
+ &path,
+ LoadOptions {
+ name: Some(name),
+ auto_refresh,
+ force_recompile: true,
+ },
+ )
+ }
+
+ /// Recompile a specific named ontology from its recorded source path.
+ ///
+ /// - If `name` is the active slot, this re-parses and replaces both the
+ /// in-memory store and the on-disk cache (same effect as `recompile()`).
+ /// - If `name` is a non-active cache entry, the source is parsed into a
+ /// *temporary* `GraphStore`, the new N-Triples cache file is written
+ /// atomically, the metadata row is updated, and the active slot is
+ /// left completely untouched. This makes it safe to refresh background
+ /// ontologies without disturbing whatever is currently being queried.
+ pub fn recompile_named(&self, name: &str) -> Result<LoadResult> {
+ let active_name = self.active.lock().unwrap().as_ref().map(|e| e.name.clone());
+ if active_name.as_deref() == Some(name) {
+ return self.recompile();
+ }
+ let entry = self
+ .cache
+ .get(name)?
+ .ok_or_else(|| anyhow!("no cached ontology named '{}'", name))?;
+ let path = Path::new(&entry.source_path);
+ if !path.exists() {
+ return Err(anyhow!(
+ "source file '{}' for cached ontology '{}' is missing",
+ entry.source_path, name
+ ));
+ }
+ // Parse into an isolated graph so we don't disturb the active slot.
+ let isolated_graph = GraphStore::new();
+ let count = isolated_graph
+ .load_file(&entry.source_path)
+ .with_context(|| format!("parse source {}", entry.source_path))?;
+ let fp = SourceFingerprint::from_path(path)?;
+ let cache_path = self.cache.cache_path_for(name, &fp.sha_prefix);
+ let nt = isolated_graph.serialize("ntriples")?;
+ CacheManager::atomic_write(&cache_path, &nt)?;
+ // If the sha-prefix changed, the new cache_path differs from the old
+ // one. Remove the old file to avoid leaking stale .nt files.
+ if entry.cache_path != cache_path.to_string_lossy() {
+ let _ = std::fs::remove_file(&entry.cache_path);
+ }
+ self.cache.upsert(name, &entry.source_path, &fp, &cache_path, count)?;
+ Ok(LoadResult {
+ name: name.to_string(),
+ source_path: entry.source_path,
+ triple_count: count,
+ origin: "source",
+ cache_path: cache_path.to_string_lossy().into_owned(),
+ })
+ }
+
+ /// Return all cached ontologies, with extra runtime flags
+ /// (`is_active`, `in_memory`) so callers can present a single rich list.
+ pub fn list_cached(&self) -> Result<Vec<serde_json::Value>> {
+ let active_guard = self.active.lock().unwrap();
+ let active_name = active_guard.as_ref().map(|e| e.name.clone());
+ let evicted = active_guard
+ .as_ref()
+ .map(|e| *e.evicted.lock().unwrap())
+ .unwrap_or(false);
+ drop(active_guard);
+
+ let entries = self.cache.list()?;
+ let out = entries
+ .into_iter()
+ .map(|e| {
+ let is_active = active_name.as_deref() == Some(e.name.as_str());
+ let in_memory = is_active && !evicted;
+ serde_json::json!({
+ "name": e.name,
+ "source_path": e.source_path,
+ "cache_path": e.cache_path,
+ "triple_count": e.triple_count,
+ "source_mtime": e.source_mtime,
+ "source_size": e.source_size,
+ "compiled_at": e.compiled_at,
+ "last_access_at": e.last_access_at,
+ "is_active": is_active,
+ "in_memory": in_memory,
+ })
+ })
+ .collect();
+ Ok(out)
+ }
+
+ /// Status snapshot for `onto_cache_status`.
+ pub fn status(&self) -> serde_json::Value {
+ let active = self.active.lock().unwrap();
+ let active_json = if let Some(entry) = active.as_ref() {
+ let evicted = *entry.evicted.lock().unwrap();
+ let last_access_secs = entry.last_access.lock().unwrap().elapsed().as_secs();
+ serde_json::json!({
+ "name": entry.name,
+ "source_path": entry.source_path,
+ "cache_path": entry.cache_path.to_string_lossy(),
+ "auto_refresh": entry.auto_refresh,
+ "evicted": evicted,
+ "idle_seconds": last_access_secs,
+ "in_memory_triples": self.graph.triple_count(),
+ })
+ } else {
+ serde_json::Value::Null
+ };
+ let entries: Vec<_> = self
+ .cache
+ .list()
+ .unwrap_or_default()
+ .into_iter()
+ .map(|e| {
+ serde_json::json!({
+ "name": e.name,
+ "source_path": e.source_path,
+ "cache_path": e.cache_path,
+ "triple_count": e.triple_count,
+ "compiled_at": e.compiled_at,
+ "last_access_at": e.last_access_at,
+ })
+ })
+ .collect();
+ serde_json::json!({
+ "active": active_json,
+ "cache_entries": entries,
+ "config": {
+ "enabled": self.config.enabled,
+ "dir": self.config.dir,
+ "idle_ttl_secs": self.config.idle_ttl_secs,
+ "auto_refresh": self.config.auto_refresh,
+ }
+ })
+ }
+}
+
+/// Spawn the background evictor task. Returns a `JoinHandle` that callers can
+/// keep alive; dropping it does NOT abort (the task is detached but will exit
+/// with the runtime).
+pub fn spawn_evictor(registry: Arc<OntologyRegistry>) -> tokio::task::JoinHandle<()> {
+ let interval_secs = registry.config().evictor_interval_secs.max(1);
+ tokio::spawn(async move {
+ let mut ticker =
+ tokio::time::interval(Duration::from_secs(interval_secs));
+ // Skip the immediate tick so we don't evict before any access happens.
+ ticker.tick().await;
+ loop {
+ ticker.tick().await;
+ if let Err(e) = registry.evictor_tick() {
+ tracing::warn!("ontology evictor tick failed: {}", e);
+ }
+ }
+ })
+}
diff --git a/src/server.rs b/src/server.rs
index 941324c0..b0ad28cf 100644
--- a/src/server.rs
+++ b/src/server.rs
@@ -27,6 +27,8 @@ pub struct OpenOntologiesServer {
graph: Arc<GraphStore>,
session_id: String,
governance_webhook: Option<String>,
+ /// Registry tracking the active ontology + compile cache + TTL eviction.
+ registry: Arc<crate::registry::OntologyRegistry>,
#[cfg(feature = "embeddings")]
vecstore: Arc<std::sync::Mutex<crate::vecstore::VecStore>>,
#[cfg(feature = "embeddings")]
@@ -56,10 +58,56 @@ impl OpenOntologiesServer {
graph: Arc<GraphStore>,
governance_webhook: Option<String>,
_embed_config: crate::config::EmbeddingsConfig,
+ ) -> Self {
+ Self::new_with_registry_options(
+ db,
+ graph,
+ governance_webhook,
+ _embed_config,
+ crate::config::CacheConfig::default(),
+ crate::toolfilter::ToolFilter::default(),
+ )
+ }
+
+ /// Full constructor, including cache configuration and tool filter.
+ pub fn new_with_registry_options(
+ db: StateDb,
+ graph: Arc<GraphStore>,
+ governance_webhook: Option<String>,
+ _embed_config: crate::config::EmbeddingsConfig,
+ cache_config: crate::config::CacheConfig,
+ tool_filter: crate::toolfilter::ToolFilter,
) -> Self {
let lineage = crate::lineage::LineageLog::with_governance_webhook(db.clone(), governance_webhook.clone());
let session_id = lineage.new_session();
+ // Build the registry. If construction fails (e.g. cache dir cannot be
+ // created) fall back to a disabled registry so the server still starts.
+ let registry = match crate::registry::OntologyRegistry::new(
+ graph.clone(),
+ db.clone(),
+ cache_config.clone(),
+ ) {
+ Ok(r) => Arc::new(r),
+ Err(e) => {
+ tracing::warn!("ontology registry init failed: {}; cache disabled", e);
+ let mut disabled = cache_config.clone();
+ disabled.enabled = false;
+ disabled.dir = std::env::temp_dir().to_string_lossy().to_string();
+ Arc::new(
+ crate::registry::OntologyRegistry::new(graph.clone(), db.clone(), disabled)
+ .expect("temp_dir registry"),
+ )
+ }
+ };
+
+ // Apply tool filter by removing routes from the router.
+ let mut tool_router = Self::tool_router();
+ let removed = tool_filter.apply(&mut tool_router);
+ if !removed.is_empty() {
+ tracing::info!("tool filter removed {} tools: {:?}", removed.len(), removed);
+ }
+
#[cfg(feature = "embeddings")]
let (vecstore, text_embedder) = {
let mut vs = crate::vecstore::VecStore::new(db.clone());
@@ -91,12 +139,13 @@ impl OpenOntologiesServer {
};
Self {
- tool_router: Self::tool_router(),
+ tool_router,
prompt_router: Self::prompt_router(),
db,
graph,
session_id,
governance_webhook,
+ registry,
#[cfg(feature = "embeddings")]
vecstore,
#[cfg(feature = "embeddings")]
@@ -109,6 +158,11 @@ impl OpenOntologiesServer {
self.tool_router.list_all()
}
+ /// Access the ontology registry (for tests and the HTTP server eviction loop).
+ pub fn registry(&self) -> Arc<crate::registry::OntologyRegistry> {
+ self.registry.clone()
+ }
+
fn lineage(&self) -> crate::lineage::LineageLog {
crate::lineage::LineageLog::with_governance_webhook(self.db.clone(), self.governance_webhook.clone())
}
@@ -173,31 +227,50 @@ impl OpenOntologiesServer {
}
}
- #[tool(name = "onto_load", description = "Load an RDF file or inline Turtle content into the in-memory ontology store for querying")]
+ #[tool(name = "onto_load", description = "Load an RDF file or inline Turtle content into the in-memory ontology store. When given a file path, the parsed graph is also written to a fast N-Triples compile cache (in `[cache] dir`) so subsequent loads from the same source skip parsing. Optional `name`, `auto_refresh`, and `force_recompile` flags control caching/refresh behavior.")]
async fn onto_load(&self, Parameters(input): Parameters<OntoLoadInput>) -> String {
if let Some(turtle) = input.turtle {
+ // Inline turtle bypasses the registry/cache (no source file).
match self.graph.load_turtle(&turtle, None) {
Ok(count) => format!(r#"{{"ok":true,"triples_loaded":{},"source":"inline"}}"#, count),
Err(e) => format!(r#"{{"error":"{}"}}"#, e),
}
} else if let Some(path) = input.path {
let path = expand_tilde(&path);
- match self.graph.load_file(&path) {
- Ok(count) => format!(r#"{{"ok":true,"triples_loaded":{},"path":"{}"}}"#, count, path),
- Err(e) => format!(r#"{{"error":"{}"}}"#, e),
+ let opts = crate::registry::LoadOptions {
+ name: input.name,
+ auto_refresh: input.auto_refresh.unwrap_or(false),
+ force_recompile: input.force_recompile.unwrap_or(false),
+ };
+ match self.registry.load_file(&path, opts) {
+ Ok(res) => serde_json::json!({
+ "ok": true,
+ "triples_loaded": res.triple_count,
+ "path": res.source_path,
+ "name": res.name,
+ "origin": res.origin,
+ "cache_path": res.cache_path,
+ }).to_string(),
+ Err(e) => format!(r#"{{"error":"{}"}}"#, e.to_string().replace('"', "'")),
}
} else {
r#"{"error":"Either 'path' or 'turtle' must be provided"}"#.to_string()
}
}
- #[tool(name = "onto_query", description = "Run a SPARQL query against the loaded ontology store")]
+ #[tool(name = "onto_query", description = "Run a SPARQL query against the loaded ontology store. If the active ontology has been evicted from memory (idle TTL), it is transparently reloaded from the compile cache before the query runs.")]
async fn onto_query(&self, Parameters(input): Parameters<OntoQueryInput>) -> String {
+ if let Err(e) = self.registry.ensure_loaded() {
+ return format!(r#"{{"error":"ensure_loaded: {}"}}"#, e.to_string().replace('"', "'"));
+ }
self.graph.sparql_select(&input.query).unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e))
}
#[tool(name = "onto_save", description = "Save the current ontology store to a file")]
async fn onto_save(&self, Parameters(input): Parameters<OntoSaveInput>) -> String {
+ if let Err(e) = self.registry.ensure_loaded() {
+ return format!(r#"{{"error":"ensure_loaded: {}"}}"#, e.to_string().replace('"', "'"));
+ }
let format = input.format.as_deref().unwrap_or("turtle");
let path = expand_tilde(&input.path);
match self.graph.save_file(&path, format) {
@@ -208,6 +281,9 @@ impl OpenOntologiesServer {
#[tool(name = "onto_stats", description = "Get statistics about the loaded ontology (triple count, classes, properties, individuals)")]
fn onto_stats(&self) -> String {
+ if let Err(e) = self.registry.ensure_loaded() {
+ return format!(r#"{{"error":"ensure_loaded: {}"}}"#, e.to_string().replace('"', "'"));
+ }
self.graph.get_stats().unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e))
}
@@ -239,14 +315,96 @@ impl OpenOntologiesServer {
OntologyService::lint_with_feedback(&content, Some(&self.db)).unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e))
}
- #[tool(name = "onto_clear", description = "Clear all triples from the in-memory ontology store")]
+ #[tool(name = "onto_clear", description = "Clear all triples from the in-memory ontology store and unload the active registry slot (cache file is preserved)")]
fn onto_clear(&self) -> String {
+ // Drop the active registry entry; this also clears the graph.
+ let _ = self.registry.unload(false);
match self.graph.clear() {
Ok(_) => r#"{"ok":true,"message":"Store cleared"}"#.to_string(),
Err(e) => format!(r#"{{"error":"{}"}}"#, e),
}
}
+ #[tool(name = "onto_unload", description = "Unload an ontology from memory. With no `name`, operates on the active ontology. With `name`, targets that cached entry — clears in-memory store if it is currently active. The on-disk compile cache is preserved unless `delete_cache=true`.")]
+ fn onto_unload(&self, Parameters(input): Parameters<OntoUnloadInput>) -> String {
+ let del = input.delete_cache.unwrap_or(false);
+ if let Some(name) = input.name.as_deref() {
+ return match self.registry.unload_named(name, del) {
+ Ok(true) => serde_json::json!({
+ "ok": true,
+ "unloaded": name,
+ "deleted_cache": del,
+ }).to_string(),
+ Ok(false) => serde_json::json!({
+ "ok": true,
+ "unloaded": null,
+ "name": name,
+ "message": "entry exists in cache but was not in memory; pass delete_cache=true to remove it",
+ }).to_string(),
+ Err(e) => format!(r#"{{"error":"{}"}}"#, e.to_string().replace('"', "'")),
+ };
+ }
+ match self.registry.unload(del) {
+ Ok(Some(name)) => serde_json::json!({"ok": true, "unloaded": name, "deleted_cache": del}).to_string(),
+ Ok(None) => r#"{"ok":true,"unloaded":null,"message":"no active ontology"}"#.to_string(),
+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),
+ }
+ }
+
+ #[tool(name = "onto_recompile", description = "Force-recompile an ontology from its source file, ignoring the on-disk cache. With no `name`, recompiles the active ontology (and reloads it into memory). With `name`, recompiles that cached entry; if it is not the active slot, the in-memory store is left untouched.")]
+ fn onto_recompile(&self, Parameters(input): Parameters<OntoRecompileInput>) -> String {
+ let res = match input.name.as_deref() {
+ Some(name) => self.registry.recompile_named(name),
+ None => self.registry.recompile(),
+ };
+ match res {
+ Ok(res) => serde_json::json!({
+ "ok": true,
+ "name": res.name,
+ "triples_loaded": res.triple_count,
+ "origin": res.origin,
+ "cache_path": res.cache_path,
+ }).to_string(),
+ Err(e) => format!(r#"{{"error":"{}"}}"#, e.to_string().replace('"', "'")),
+ }
+ }
+
+ #[tool(name = "onto_cache_status", description = "Inspect the compile cache: active ontology, all cached entries, and the cache configuration (TTL, auto_refresh, dir).")]
+ fn onto_cache_status(&self, Parameters(_input): Parameters<OntoCacheStatusInput>) -> String {
+ self.registry.status().to_string()
+ }
+
+ #[tool(name = "onto_cache_list", description = "List all cached ontologies with metadata (name, source_path, triple_count, source_mtime, source_size, cache_path, compiled_at, last_access_at) and runtime flags (is_active, in_memory). Lighter than onto_cache_status when you only need the list.")]
+ fn onto_cache_list(&self, Parameters(_input): Parameters<OntoCacheListInput>) -> String {
+ match self.registry.list_cached() {
+ Ok(entries) => serde_json::json!({
+ "ok": true,
+ "count": entries.len(),
+ "entries": entries,
+ }).to_string(),
+ Err(e) => format!(r#"{{"error":"{}"}}"#, e.to_string().replace('"', "'")),
+ }
+ }
+
+ #[tool(name = "onto_cache_remove", description = "Remove a cached ontology by name. If it is the active slot, the in-memory store is unloaded first. By default the on-disk N-Triples cache file is also deleted; pass delete_file=false to keep it on disk.")]
+ fn onto_cache_remove(&self, Parameters(input): Parameters<OntoCacheRemoveInput>) -> String {
+ let delete_file = input.delete_file.unwrap_or(true);
+ match self.registry.unload_named(&input.name, delete_file) {
+ Ok(true) => serde_json::json!({
+ "ok": true,
+ "removed": input.name,
+ "deleted_file": delete_file,
+ }).to_string(),
+ Ok(false) => serde_json::json!({
+ "ok": true,
+ "removed": null,
+ "name": input.name,
+ "message": "entry was found but delete_file=false and it was not active, so nothing changed",
+ }).to_string(),
+ Err(e) => format!(r#"{{"error":"{}"}}"#, e.to_string().replace('"', "'")),
+ }
+ }
+
#[tool(name = "onto_pull", description = "Fetch an ontology from a remote URL or SPARQL endpoint and load it into the store")]
async fn onto_pull(&self, Parameters(input): Parameters<OntoPullInput>) -> String {
use crate::graph::GraphStore;
diff --git a/src/state.rs b/src/state.rs
index 25878a0a..b1415d61 100644
--- a/src/state.rs
+++ b/src/state.rs
@@ -104,6 +104,20 @@ CREATE TABLE IF NOT EXISTS embeddings (
struct_dim INTEGER NOT NULL,
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
+
+-- Compile cache for loaded ontology files. One row per ontology `name`.
+-- See src/cache.rs for the validity policy.
+CREATE TABLE IF NOT EXISTS ontology_cache (
+ name TEXT PRIMARY KEY,
+ source_path TEXT NOT NULL,
+ source_mtime INTEGER NOT NULL,
+ source_size INTEGER NOT NULL,
+ source_sha TEXT NOT NULL,
+ cache_path TEXT NOT NULL,
+ triple_count INTEGER NOT NULL,
+ compiled_at TEXT NOT NULL DEFAULT (datetime('now')),
+ last_access_at TEXT NOT NULL DEFAULT (datetime('now'))
+);
";
/// Minimal SQLite state store for ontology versioning.
diff --git a/src/toolfilter.rs b/src/toolfilter.rs
new file mode 100644
index 00000000..ff33b7e2
--- /dev/null
+++ b/src/toolfilter.rs
@@ -0,0 +1,269 @@
+//! Tool exposure filter for the MCP server.
+//!
+//! This lets operators restrict which `onto_*` tools are advertised over MCP
+//! (and which can actually be invoked) via configuration or CLI flags.
+//!
+//! Three modes:
+//! - `Mode::All` — all registered tools exposed (default).
+//! - `Mode::Allow` — only tools in `list` (or expanded from `groups`) exposed.
+//! - `Mode::Deny` — all tools except those in `list` (or `groups`) exposed.
+//!
+//! Implementation: applied by removing routes from the rmcp `ToolRouter`
+//! before the server is constructed. Removed tools are not advertised via
+//! `tools/list` and cannot be invoked via `tools/call`.
+
+use serde::Deserialize;
+use std::collections::HashSet;
+
+use rmcp::handler::server::tool::ToolRouter;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Mode {
+ All,
+ Allow,
+ Deny,
+}
+
+impl Default for Mode {
+ fn default() -> Self {
+ Mode::All
+ }
+}
+
+impl Mode {
+ pub fn parse(s: &str) -> Result<Self, String> {
+ match s.to_ascii_lowercase().as_str() {
+ "all" | "" => Ok(Mode::All),
+ "allow" | "allowlist" | "whitelist" => Ok(Mode::Allow),
+ "deny" | "denylist" | "blacklist" => Ok(Mode::Deny),
+ other => Err(format!("unknown tool filter mode: {}", other)),
+ }
+ }
+}
+
+/// User-facing filter spec.
+#[derive(Debug, Clone, Default)]
+pub struct ToolFilter {
+ pub mode: Mode,
+ /// Explicit tool names.
+ pub list: Vec<String>,
+ /// Group names that expand to a curated set of tool names.
+ pub groups: Vec<String>,
+}
+
+impl ToolFilter {
+ pub fn all() -> Self {
+ Self::default()
+ }
+
+ pub fn allow_only(names: impl IntoIterator<Item = String>) -> Self {
+ Self {
+ mode: Mode::Allow,
+ list: names.into_iter().collect(),
+ groups: vec![],
+ }
+ }
+
+ pub fn deny(names: impl IntoIterator<Item = String>) -> Self {
+ Self {
+ mode: Mode::Deny,
+ list: names.into_iter().collect(),
+ groups: vec![],
+ }
+ }
+
+ /// Resolve the effective set of explicit names (list ∪ expand(groups)).
+ fn resolved_names(&self) -> HashSet<String> {
+ let mut out: HashSet<String> = self.list.iter().cloned().collect();
+ for g in &self.groups {
+ for n in expand_group(g) {
+ out.insert(n.to_string());
+ }
+ }
+ out
+ }
+
+ /// Decide whether `tool_name` should be exposed.
+ pub fn allows(&self, tool_name: &str) -> bool {
+ let names = self.resolved_names();
+ match self.mode {
+ Mode::All => true,
+ Mode::Allow => names.contains(tool_name),
+ Mode::Deny => !names.contains(tool_name),
+ }
+ }
+
+ /// Apply the filter to a `ToolRouter` by removing disallowed routes.
+ /// Returns the list of removed tool names (for logging/inspection).
+ pub fn apply<S>(&self, router: &mut ToolRouter<S>) -> Vec<String>
+ where
+ S: Send + Sync + 'static,
+ {
+ if self.mode == Mode::All {
+ return Vec::new();
+ }
+ let names = self.resolved_names();
+ let all: Vec<String> = router
+ .list_all()
+ .into_iter()
+ .map(|t| t.name.to_string())
+ .collect();
+ let mut removed = Vec::new();
+ for name in all {
+ let keep = match self.mode {
+ Mode::All => true,
+ Mode::Allow => names.contains(&name),
+ Mode::Deny => !names.contains(&name),
+ };
+ if !keep {
+ router.remove_route(&name);
+ removed.push(name);
+ }
+ }
+ removed
+ }
+}
+
+/// Curated tool groups. Tool names must match the ones registered with
+/// `#[tool(name = "...")]` in `src/server.rs`.
+pub fn expand_group(name: &str) -> &'static [&'static str] {
+ match name {
+ // Read-only inspection tools (safe to expose to untrusted callers).
+ "read_only" | "read" => &[
+ "onto_status",
+ "onto_validate",
+ "onto_query",
+ "onto_stats",
+ "onto_diff",
+ "onto_lint",
+ "onto_history",
+ "onto_lineage",
+ "onto_cache_status",
+ "onto_cache_list",
+ "onto_dl_check",
+ "onto_dl_explain",
+ "onto_search",
+ "onto_similarity",
+ ],
+ // Tools that mutate the in-memory store but not external systems.
+ "mutating" | "write" => &[
+ "onto_load",
+ "onto_clear",
+ "onto_save",
+ "onto_convert",
+ "onto_pull",
+ "onto_import",
+ "onto_marketplace",
+ "onto_version",
+ "onto_rollback",
+ "onto_ingest",
+ "onto_map",
+ "onto_shacl",
+ "onto_reason",
+ "onto_extend",
+ "onto_unload",
+ "onto_recompile",
+ "onto_cache_remove",
+ ],
+ // Tools that change governance / lifecycle state.
+ "governance" => &[
+ "onto_plan",
+ "onto_apply",
+ "onto_lock",
+ "onto_drift",
+ "onto_enforce",
+ "onto_monitor",
+ "onto_monitor_clear",
+ "onto_align",
+ "onto_align_feedback",
+ "onto_lint_feedback",
+ "onto_enforce_feedback",
+ ],
+ // Tools that talk to external systems.
+ "remote" => &[
+ "onto_pull",
+ "onto_push",
+ "onto_marketplace",
+ "onto_import",
+ ],
+ // Embedding / semantic search tools.
+ "embeddings" => &[
+ "onto_embed",
+ "onto_search",
+ "onto_similarity",
+ ],
+ _ => &[],
+ }
+}
+
+/// Parse a comma-separated list of tool/group identifiers into (names, groups).
+/// Identifiers prefixed with `@` are treated as group names.
+pub fn parse_csv(spec: &str) -> (Vec<String>, Vec<String>) {
+ let mut names = Vec::new();
+ let mut groups = Vec::new();
+ for raw in spec.split(',') {
+ let item = raw.trim();
+ if item.is_empty() {
+ continue;
+ }
+ if let Some(g) = item.strip_prefix('@') {
+ groups.push(g.to_string());
+ } else {
+ names.push(item.to_string());
+ }
+ }
+ (names, groups)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn mode_parse() {
+ assert_eq!(Mode::parse("all").unwrap(), Mode::All);
+ assert_eq!(Mode::parse("ALLOW").unwrap(), Mode::Allow);
+ assert_eq!(Mode::parse("deny").unwrap(), Mode::Deny);
+ assert!(Mode::parse("nope").is_err());
+ }
+
+ #[test]
+ fn allow_filter_only_lets_listed_tools_through() {
+ let f = ToolFilter::allow_only(vec!["onto_status".to_string(), "onto_query".to_string()]);
+ assert!(f.allows("onto_status"));
+ assert!(f.allows("onto_query"));
+ assert!(!f.allows("onto_load"));
+ }
+
+ #[test]
+ fn deny_filter_blocks_listed_tools() {
+ let f = ToolFilter::deny(vec!["onto_clear".to_string()]);
+ assert!(f.allows("onto_status"));
+ assert!(!f.allows("onto_clear"));
+ }
+
+ #[test]
+ fn group_expansion() {
+ let f = ToolFilter {
+ mode: Mode::Allow,
+ list: vec![],
+ groups: vec!["read_only".to_string()],
+ };
+ assert!(f.allows("onto_status"));
+ assert!(f.allows("onto_query"));
+ assert!(!f.allows("onto_load"));
+ }
+
+ #[test]
+ fn csv_parser_splits_names_and_groups() {
+ let (n, g) = parse_csv("onto_status, onto_query, @read_only, ");
+ assert_eq!(n, vec!["onto_status", "onto_query"]);
+ assert_eq!(g, vec!["read_only"]);
+ }
+
+ #[test]
+ fn unknown_group_expands_to_empty() {
+ assert!(expand_group("does-not-exist").is_empty());
+ }
+}
diff --git a/tests/cache_management_test.rs b/tests/cache_management_test.rs
new file mode 100644
index 00000000..43cfab3f
--- /dev/null
+++ b/tests/cache_management_test.rs
@@ -0,0 +1,346 @@
+//! Tests for per-name cache management:
+//! - `OntologyRegistry::list_cached`
+//! - `OntologyRegistry::unload_named`
+//! - `OntologyRegistry::recompile_named`
+//!
+//! These complement `tests/registry_test.rs` (which exercises the active-slot
+//! lifecycle) by covering operations on cache entries that are not the
+//! currently-active ontology.
+
+use std::path::PathBuf;
+use std::sync::Arc;
+use std::thread::sleep;
+use std::time::Duration;
+
+use open_ontologies::config::CacheConfig;
+use open_ontologies::graph::GraphStore;
+use open_ontologies::registry::{LoadOptions, OntologyRegistry};
+use open_ontologies::state::StateDb;
+
+const TTL_A: &str = r#"
+@prefix owl: <http://www.w3.org/2002/07/owl#> .
+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+@prefix ex: <http://example.org/a#> .
+ex:A1 a owl:Class ; rdfs:label "A1" .
+ex:A2 a owl:Class ; rdfs:label "A2" .
+"#;
+
+const TTL_B: &str = r#"
+@prefix owl: <http://www.w3.org/2002/07/owl#> .
+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+@prefix ex: <http://example.org/b#> .
+ex:B1 a owl:Class ; rdfs:label "B1" .
+ex:B2 a owl:Class ; rdfs:label "B2" .
+ex:B3 a owl:Class ; rdfs:label "B3" .
+"#;
+
+const TTL_B_V2: &str = r#"
+@prefix owl: <http://www.w3.org/2002/07/owl#> .
+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+@prefix ex: <http://example.org/b#> .
+ex:B1 a owl:Class ; rdfs:label "B1" .
+ex:B2 a owl:Class ; rdfs:label "B2" .
+ex:B3 a owl:Class ; rdfs:label "B3" .
+ex:B4 a owl:Class ; rdfs:label "B4" .
+ex:B5 a owl:Class ; rdfs:label "B5" .
+"#;
+
+struct TestHarness {
+ _tmp: tempfile::TempDir,
+ pub path_a: PathBuf,
+ pub path_b: PathBuf,
+ pub registry: Arc<OntologyRegistry>,
+ pub graph: Arc<GraphStore>,
+}
+
+fn setup() -> TestHarness {
+ let tmp = tempfile::tempdir().unwrap();
+ let path_a = tmp.path().join("a.ttl");
+ let path_b = tmp.path().join("b.ttl");
+ std::fs::write(&path_a, TTL_A).unwrap();
+ std::fs::write(&path_b, TTL_B).unwrap();
+ let db = StateDb::open(&tmp.path().join("s.db")).unwrap();
+ let graph = Arc::new(GraphStore::new());
+ let cfg = CacheConfig {
+ enabled: true,
+ dir: tmp.path().join("cache").to_string_lossy().into_owned(),
+ idle_ttl_secs: 0,
+ evictor_interval_secs: 30,
+ auto_refresh: false,
+ };
+ let registry = Arc::new(OntologyRegistry::new(graph.clone(), db, cfg).unwrap());
+ TestHarness { _tmp: tmp, path_a, path_b, registry, graph }
+}
+
+/// Load A then B so B is active, A is cached but not active.
+fn populate_two(h: &TestHarness) {
+ h.registry
+ .load_file(h.path_a.to_str().unwrap(), LoadOptions::default())
+ .unwrap();
+ h.registry
+ .load_file(h.path_b.to_str().unwrap(), LoadOptions::default())
+ .unwrap();
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// list_cached
+// ────────────────────────────────────────────────────────────────────────────
+
+#[test]
+fn list_cached_empty_when_nothing_loaded() {
+ let h = setup();
+ let list = h.registry.list_cached().unwrap();
+ assert!(list.is_empty());
+}
+
+#[test]
+fn list_cached_includes_all_loaded_ontologies() {
+ let h = setup();
+ populate_two(&h);
+ let list = h.registry.list_cached().unwrap();
+ assert_eq!(list.len(), 2, "both A and B should be cached");
+ let names: Vec<&str> = list
+ .iter()
+ .map(|e| e["name"].as_str().unwrap())
+ .collect();
+ assert!(names.contains(&"a"));
+ assert!(names.contains(&"b"));
+}
+
+#[test]
+fn list_cached_flags_active_and_in_memory() {
+ let h = setup();
+ populate_two(&h);
+ let list = h.registry.list_cached().unwrap();
+ let b = list.iter().find(|e| e["name"] == "b").unwrap();
+ let a = list.iter().find(|e| e["name"] == "a").unwrap();
+ assert_eq!(b["is_active"], true, "B is the most-recently-loaded -> active");
+ assert_eq!(b["in_memory"], true);
+ assert_eq!(a["is_active"], false, "A is cached but not active");
+ assert_eq!(a["in_memory"], false);
+}
+
+#[test]
+fn list_cached_marks_in_memory_false_after_eviction() {
+ let tmp = tempfile::tempdir().unwrap();
+ let path = tmp.path().join("a.ttl");
+ std::fs::write(&path, TTL_A).unwrap();
+ let db = StateDb::open(&tmp.path().join("s.db")).unwrap();
+ let graph = Arc::new(GraphStore::new());
+ let cfg = CacheConfig {
+ enabled: true,
+ dir: tmp.path().join("cache").to_string_lossy().into_owned(),
+ idle_ttl_secs: 1,
+ evictor_interval_secs: 30,
+ auto_refresh: false,
+ };
+ let reg = OntologyRegistry::new(graph, db, cfg).unwrap();
+ reg.load_file(path.to_str().unwrap(), LoadOptions::default()).unwrap();
+ sleep(Duration::from_millis(1100));
+ assert!(reg.evictor_tick().unwrap());
+ let list = reg.list_cached().unwrap();
+ assert_eq!(list.len(), 1);
+ assert_eq!(list[0]["is_active"], true, "still the active slot");
+ assert_eq!(list[0]["in_memory"], false, "but evicted from memory");
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// unload_named
+// ────────────────────────────────────────────────────────────────────────────
+
+#[test]
+fn unload_named_unknown_returns_error() {
+ let h = setup();
+ populate_two(&h);
+ let err = h.registry.unload_named("does-not-exist", false).unwrap_err();
+ assert!(
+ err.to_string().contains("does-not-exist"),
+ "error message should mention the name; got: {}",
+ err
+ );
+}
+
+#[test]
+fn unload_named_non_active_with_delete_removes_only_that_entry() {
+ let h = setup();
+ populate_two(&h);
+ let active_triples = h.graph.triple_count();
+ assert!(active_triples > 0);
+
+ // A is non-active. Delete it; B (active) must be unaffected.
+ let changed = h.registry.unload_named("a", true).unwrap();
+ assert!(changed);
+
+ assert_eq!(
+ h.graph.triple_count(),
+ active_triples,
+ "removing a non-active entry must NOT touch the in-memory active store"
+ );
+
+ let list = h.registry.list_cached().unwrap();
+ assert_eq!(list.len(), 1);
+ assert_eq!(list[0]["name"], "b");
+}
+
+#[test]
+fn unload_named_non_active_without_delete_is_noop_but_validates_name() {
+ let h = setup();
+ populate_two(&h);
+ // A is non-active. With delete_cache=false there is nothing to do
+ // (it's not in memory and we are told not to touch the cache file).
+ let changed = h.registry.unload_named("a", false).unwrap();
+ assert!(!changed);
+ // But the entry is still present.
+ let list = h.registry.list_cached().unwrap();
+ assert_eq!(list.len(), 2);
+}
+
+#[test]
+fn unload_named_active_unloads_and_optionally_deletes() {
+ let h = setup();
+ populate_two(&h);
+ // B is active. Unload it WITHOUT deleting cache.
+ let changed = h.registry.unload_named("b", false).unwrap();
+ assert!(changed);
+ assert_eq!(h.graph.triple_count(), 0);
+
+ let list = h.registry.list_cached().unwrap();
+ assert_eq!(list.len(), 2, "cache file for B should still exist");
+ let b = list.iter().find(|e| e["name"] == "b").unwrap();
+ assert_eq!(b["is_active"], false);
+}
+
+#[test]
+fn unload_named_active_with_delete_removes_db_row_and_file() {
+ let h = setup();
+ populate_two(&h);
+ let b_cache = h
+ .registry
+ .list_cached()
+ .unwrap()
+ .into_iter()
+ .find(|e| e["name"] == "b")
+ .unwrap()["cache_path"]
+ .as_str()
+ .unwrap()
+ .to_string();
+ assert!(std::path::Path::new(&b_cache).exists());
+
+ h.registry.unload_named("b", true).unwrap();
+ assert_eq!(h.graph.triple_count(), 0);
+ assert!(!std::path::Path::new(&b_cache).exists(), "cache file deleted");
+
+ let list = h.registry.list_cached().unwrap();
+ assert_eq!(list.len(), 1);
+ assert_eq!(list[0]["name"], "a");
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// recompile_named
+// ────────────────────────────────────────────────────────────────────────────
+
+#[test]
+fn recompile_named_unknown_returns_error() {
+ let h = setup();
+ let err = h.registry.recompile_named("nope").unwrap_err();
+ assert!(err.to_string().contains("nope"));
+}
+
+#[test]
+fn recompile_named_active_behaves_like_recompile() {
+ let h = setup();
+ populate_two(&h);
+ // B is active. Modify its source.
+ sleep(Duration::from_millis(1100));
+ std::fs::write(&h.path_b, TTL_B_V2).unwrap();
+ let res = h.registry.recompile_named("b").unwrap();
+ assert_eq!(res.origin, "source");
+ assert_eq!(res.name, "b");
+ // Active in-memory store reflects v2.
+ assert!(h.graph.triple_count() > 0);
+ let list = h.registry.list_cached().unwrap();
+ let b = list.iter().find(|e| e["name"] == "b").unwrap();
+ assert!(b["triple_count"].as_u64().unwrap() > 5);
+}
+
+#[test]
+fn recompile_named_non_active_does_not_touch_active_memory() {
+ let h = setup();
+ populate_two(&h);
+ let active_count_before = h.graph.triple_count();
+
+ // Modify A (non-active) and recompile by name.
+ sleep(Duration::from_millis(1100));
+ std::fs::write(&h.path_a, TTL_B_V2).unwrap(); // give A more triples
+ let res = h.registry.recompile_named("a").unwrap();
+ assert_eq!(res.origin, "source");
+ assert_eq!(res.name, "a");
+
+ // The active in-memory store (B) must be untouched.
+ assert_eq!(
+ h.graph.triple_count(),
+ active_count_before,
+ "active in-memory store must not be disturbed by recompiling a non-active entry"
+ );
+ // A's cache row reflects the new content.
+ let list = h.registry.list_cached().unwrap();
+ let a = list.iter().find(|e| e["name"] == "a").unwrap();
+ assert_eq!(a["is_active"], false);
+ // v2 has more classes than the original A (which had 2).
+ assert!(
+ a["triple_count"].as_u64().unwrap() > 2,
+ "A's cached triple count should have grown after recompile"
+ );
+}
+
+#[test]
+fn recompile_named_missing_source_returns_clear_error() {
+ let h = setup();
+ populate_two(&h);
+ // Delete A's source file.
+ std::fs::remove_file(&h.path_a).unwrap();
+ let err = h.registry.recompile_named("a").unwrap_err();
+ assert!(
+ err.to_string().contains("missing") || err.to_string().contains("source"),
+ "error should mention the missing source; got: {}",
+ err
+ );
+ // Active store still untouched.
+ assert!(h.graph.triple_count() > 0);
+}
+
+#[test]
+fn recompile_named_garbage_collects_old_cache_file_when_sha_changes() {
+ let h = setup();
+ populate_two(&h);
+ let old_a_cache = h
+ .registry
+ .list_cached()
+ .unwrap()
+ .into_iter()
+ .find(|e| e["name"] == "a")
+ .unwrap()["cache_path"]
+ .as_str()
+ .unwrap()
+ .to_string();
+ assert!(std::path::Path::new(&old_a_cache).exists());
+
+ sleep(Duration::from_millis(1100));
+ std::fs::write(&h.path_a, TTL_B_V2).unwrap(); // very different content -> different sha
+ h.registry.recompile_named("a").unwrap();
+
+ let new_a_cache = h
+ .registry
+ .list_cached()
+ .unwrap()
+ .into_iter()
+ .find(|e| e["name"] == "a")
+ .unwrap()["cache_path"]
+ .as_str()
+ .unwrap()
+ .to_string();
+ assert_ne!(new_a_cache, old_a_cache, "new cache file path expected");
+ assert!(!std::path::Path::new(&old_a_cache).exists(),
+ "old cache file should be cleaned up");
+ assert!(std::path::Path::new(&new_a_cache).exists());
+}
diff --git a/tests/registry_test.rs b/tests/registry_test.rs
new file mode 100644
index 00000000..7b973417
--- /dev/null
+++ b/tests/registry_test.rs
@@ -0,0 +1,429 @@
+//! Integration tests for the compile cache (`src/cache.rs`) and the
+//! ontology registry (`src/registry.rs`).
+//!
+//! These exercise features 1–4 from the task statement:
+//! 1. compile/cache of loaded ontologies
+//! 2. TTL-based eviction from memory
+//! 3. transparent reload-on-query
+//! 4. auto-refresh when source file changes
+
+use std::path::PathBuf;
+use std::sync::Arc;
+use std::thread::sleep;
+use std::time::Duration;
+
+use open_ontologies::cache::{CacheManager, SourceFingerprint};
+use open_ontologies::config::CacheConfig;
+use open_ontologies::graph::GraphStore;
+use open_ontologies::registry::{LoadOptions, OntologyRegistry};
+use open_ontologies::state::StateDb;
+
+const SAMPLE_TTL: &str = r#"
+@prefix owl: <http://www.w3.org/2002/07/owl#> .
+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+@prefix ex: <http://example.org/test#> .
+
+ex:Animal a owl:Class ;
+ rdfs:label "Animal" .
+
+ex:Dog a owl:Class ;
+ rdfs:subClassOf ex:Animal ;
+ rdfs:label "Dog" .
+"#;
+
+const SAMPLE_TTL_V2: &str = r#"
+@prefix owl: <http://www.w3.org/2002/07/owl#> .
+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+@prefix ex: <http://example.org/test#> .
+
+ex:Animal a owl:Class ;
+ rdfs:label "Animal" .
+
+ex:Dog a owl:Class ;
+ rdfs:subClassOf ex:Animal ;
+ rdfs:label "Dog" .
+
+ex:Cat a owl:Class ;
+ rdfs:subClassOf ex:Animal ;
+ rdfs:label "Cat" .
+
+ex:Bird a owl:Class ;
+ rdfs:subClassOf ex:Animal ;
+ rdfs:label "Bird" .
+"#;
+
+struct Harness {
+ _tmp: tempfile::TempDir,
+ pub source_path: PathBuf,
+ pub cache_dir: PathBuf,
+ pub registry: Arc<OntologyRegistry>,
+ pub graph: Arc<GraphStore>,
+}
+
+fn setup(idle_ttl_secs: u64) -> Harness {
+ let tmp = tempfile::tempdir().unwrap();
+ let source_path = tmp.path().join("sample.ttl");
+ std::fs::write(&source_path, SAMPLE_TTL).unwrap();
+ let cache_dir = tmp.path().join("cache");
+ let db_path = tmp.path().join("state.db");
+ let db = StateDb::open(&db_path).unwrap();
+
+ let graph = Arc::new(GraphStore::new());
+ let cfg = CacheConfig {
+ enabled: true,
+ dir: cache_dir.to_string_lossy().into_owned(),
+ idle_ttl_secs,
+ evictor_interval_secs: 1,
+ auto_refresh: false,
+ };
+ let registry = Arc::new(OntologyRegistry::new(graph.clone(), db, cfg).unwrap());
+ Harness {
+ _tmp: tmp,
+ source_path,
+ cache_dir,
+ registry,
+ graph,
+ }
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// Feature 1 — compile cache
+// ────────────────────────────────────────────────────────────────────────────
+
+#[test]
+fn first_load_writes_cache_file() {
+ let h = setup(0);
+ let res = h
+ .registry
+ .load_file(
+ h.source_path.to_str().unwrap(),
+ LoadOptions::default(),
+ )
+ .unwrap();
+ assert_eq!(res.origin, "source", "first load should be from source");
+ assert!(res.triple_count > 0);
+ assert!(
+ std::path::Path::new(&res.cache_path).exists(),
+ "cache file should exist on disk"
+ );
+ // Cache directory should contain at least one .nt file.
+ let entries: Vec<_> = std::fs::read_dir(&h.cache_dir)
+ .unwrap()
+ .filter_map(|e| e.ok())
+ .filter(|e| {
+ e.path()
+ .extension()
+ .and_then(|s| s.to_str())
+ .map(|s| s == "nt")
+ .unwrap_or(false)
+ })
+ .collect();
+ assert!(!entries.is_empty(), "expected an .nt file in cache dir");
+}
+
+#[test]
+fn second_load_uses_cache_when_unchanged() {
+ let h = setup(0);
+ let r1 = h
+ .registry
+ .load_file(h.source_path.to_str().unwrap(), LoadOptions::default())
+ .unwrap();
+ assert_eq!(r1.origin, "source");
+
+ // Re-load: the source file is unchanged so we should hit the cache.
+ let r2 = h
+ .registry
+ .load_file(h.source_path.to_str().unwrap(), LoadOptions::default())
+ .unwrap();
+ assert_eq!(r2.origin, "cache");
+ assert_eq!(r1.triple_count, r2.triple_count);
+}
+
+#[test]
+fn force_recompile_bypasses_cache() {
+ let h = setup(0);
+ h.registry
+ .load_file(h.source_path.to_str().unwrap(), LoadOptions::default())
+ .unwrap();
+ // Even with a fresh cache, force_recompile=true must re-parse from source.
+ let r = h
+ .registry
+ .load_file(
+ h.source_path.to_str().unwrap(),
+ LoadOptions {
+ force_recompile: true,
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ assert_eq!(r.origin, "source");
+}
+
+#[test]
+fn changing_source_invalidates_cache() {
+ let h = setup(0);
+ let r1 = h
+ .registry
+ .load_file(h.source_path.to_str().unwrap(), LoadOptions::default())
+ .unwrap();
+ let initial = r1.triple_count;
+
+ // Modify source. Sleep > 1s so mtime resolution doesn't mask the change.
+ sleep(Duration::from_millis(1100));
+ std::fs::write(&h.source_path, SAMPLE_TTL_V2).unwrap();
+
+ let r2 = h
+ .registry
+ .load_file(h.source_path.to_str().unwrap(), LoadOptions::default())
+ .unwrap();
+ assert_eq!(r2.origin, "source", "modified source should bypass cache");
+ assert!(r2.triple_count > initial, "v2 has more triples than v1");
+}
+
+#[test]
+fn cache_disabled_skips_ondisk_cache() {
+ let tmp = tempfile::tempdir().unwrap();
+ let source_path = tmp.path().join("sample.ttl");
+ std::fs::write(&source_path, SAMPLE_TTL).unwrap();
+ let db_path = tmp.path().join("state.db");
+ let db = StateDb::open(&db_path).unwrap();
+ let graph = Arc::new(GraphStore::new());
+ let cfg = CacheConfig {
+ enabled: false,
+ dir: tmp.path().join("cache").to_string_lossy().into_owned(),
+ idle_ttl_secs: 0,
+ evictor_interval_secs: 30,
+ auto_refresh: false,
+ };
+ let registry = OntologyRegistry::new(graph, db, cfg).unwrap();
+ let r = registry
+ .load_file(source_path.to_str().unwrap(), LoadOptions::default())
+ .unwrap();
+ assert_eq!(r.origin, "source");
+ assert!(r.cache_path.is_empty(), "no cache path when disabled");
+}
+
+#[test]
+fn fingerprint_round_trips_through_cache_manager() {
+ let tmp = tempfile::tempdir().unwrap();
+ let f = tmp.path().join("f.txt");
+ std::fs::write(&f, b"hello").unwrap();
+ let fp = SourceFingerprint::from_path(&f).unwrap();
+ assert_eq!(fp.size, 5);
+ assert!(!fp.sha_prefix.is_empty());
+}
+
+#[test]
+fn cache_manager_upsert_and_get_round_trip() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = StateDb::open(&tmp.path().join("s.db")).unwrap();
+ let cm = CacheManager::new(tmp.path().to_path_buf(), db).unwrap();
+ let f = tmp.path().join("a.ttl");
+ std::fs::write(&f, b"ignored").unwrap();
+ let fp = SourceFingerprint::from_path(&f).unwrap();
+ let cp = cm.cache_path_for("a", &fp.sha_prefix);
+ CacheManager::atomic_write(&cp, "<a> <b> <c> .\n").unwrap();
+ cm.upsert("a", f.to_str().unwrap(), &fp, &cp, 1).unwrap();
+
+ let got = cm.get("a").unwrap().expect("entry present");
+ assert_eq!(got.name, "a");
+ assert_eq!(got.triple_count, 1);
+ assert!(cm.is_fresh(&got).unwrap());
+
+ // Modifying the source invalidates freshness.
+ sleep(Duration::from_millis(1100));
+ std::fs::write(&f, b"different content").unwrap();
+ let got2 = cm.get("a").unwrap().unwrap();
+ assert!(!cm.is_fresh(&got2).unwrap());
+
+ // Removal cleans up disk + row.
+ cm.remove("a").unwrap();
+ assert!(cm.get("a").unwrap().is_none());
+ assert!(!cp.exists());
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// Feature 2 + 3 — TTL eviction + auto-reload-on-query
+// ────────────────────────────────────────────────────────────────────────────
+
+#[test]
+fn evictor_unloads_idle_ontology_and_keeps_cache() {
+ let h = setup(/* idle_ttl_secs */ 1);
+ let _ = h
+ .registry
+ .load_file(h.source_path.to_str().unwrap(), LoadOptions::default())
+ .unwrap();
+ assert!(h.graph.triple_count() > 0);
+
+ // Wait past the TTL, then invoke the evictor.
+ sleep(Duration::from_millis(1100));
+ let evicted = h.registry.evictor_tick().unwrap();
+ assert!(evicted, "evictor should have unloaded the idle ontology");
+ assert_eq!(h.graph.triple_count(), 0, "graph should be empty");
+
+ // Status should report `evicted: true`.
+ let status = h.registry.status();
+ assert_eq!(status["active"]["evicted"], true);
+}
+
+#[test]
+fn ensure_loaded_reloads_after_eviction() {
+ let h = setup(1);
+ let r1 = h
+ .registry
+ .load_file(h.source_path.to_str().unwrap(), LoadOptions::default())
+ .unwrap();
+ let original = r1.triple_count;
+
+ // Evict.
+ sleep(Duration::from_millis(1100));
+ assert!(h.registry.evictor_tick().unwrap());
+ assert_eq!(h.graph.triple_count(), 0);
+
+ // Simulate a query: ensure_loaded must transparently reload.
+ h.registry.ensure_loaded().unwrap();
+ assert_eq!(
+ h.graph.triple_count(),
+ original,
+ "store should be reloaded with the same triple count"
+ );
+
+ // Active entry should be marked not-evicted again.
+ let status = h.registry.status();
+ assert_eq!(status["active"]["evicted"], false);
+}
+
+#[test]
+fn touch_postpones_eviction() {
+ let h = setup(2);
+ h.registry
+ .load_file(h.source_path.to_str().unwrap(), LoadOptions::default())
+ .unwrap();
+ // Less than TTL: touch resets the access timestamp.
+ sleep(Duration::from_millis(800));
+ h.registry.touch();
+ sleep(Duration::from_millis(800));
+ let evicted = h.registry.evictor_tick().unwrap();
+ assert!(!evicted, "touch should keep the entry alive");
+ assert!(h.graph.triple_count() > 0);
+}
+
+#[test]
+fn unload_drops_active_entry() {
+ let h = setup(0);
+ h.registry
+ .load_file(h.source_path.to_str().unwrap(), LoadOptions::default())
+ .unwrap();
+ let name = h.registry.unload(false).unwrap();
+ assert!(name.is_some());
+ assert_eq!(h.graph.triple_count(), 0);
+
+ // ensure_loaded with no active entry is a no-op.
+ h.registry.ensure_loaded().unwrap();
+ assert_eq!(h.graph.triple_count(), 0);
+}
+
+#[test]
+fn unload_with_delete_cache_removes_file() {
+ let h = setup(0);
+ let r = h
+ .registry
+ .load_file(h.source_path.to_str().unwrap(), LoadOptions::default())
+ .unwrap();
+ let cache_path = std::path::PathBuf::from(&r.cache_path);
+ assert!(cache_path.exists());
+ h.registry.unload(true).unwrap();
+ assert!(!cache_path.exists(), "delete_cache should remove the .nt file");
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// Feature 4 — auto-refresh when source file changes
+// ────────────────────────────────────────────────────────────────────────────
+
+#[test]
+fn auto_refresh_picks_up_changes_on_ensure_loaded() {
+ let h = setup(0);
+ let r1 = h
+ .registry
+ .load_file(
+ h.source_path.to_str().unwrap(),
+ LoadOptions {
+ auto_refresh: true,
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ let v1 = r1.triple_count;
+
+ // Modify source.
+ sleep(Duration::from_millis(1100));
+ std::fs::write(&h.source_path, SAMPLE_TTL_V2).unwrap();
+
+ // ensure_loaded should detect the change and recompile.
+ h.registry.ensure_loaded().unwrap();
+ let v2 = h.graph.triple_count();
+ assert!(
+ v2 > v1,
+ "auto_refresh should pick up the larger v2 ontology (v1={}, v2={})",
+ v1,
+ v2
+ );
+}
+
+#[test]
+fn no_auto_refresh_keeps_old_data_until_explicit_recompile() {
+ let h = setup(0);
+ let r1 = h
+ .registry
+ .load_file(
+ h.source_path.to_str().unwrap(),
+ LoadOptions {
+ auto_refresh: false,
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ let v1 = r1.triple_count;
+
+ sleep(Duration::from_millis(1100));
+ std::fs::write(&h.source_path, SAMPLE_TTL_V2).unwrap();
+
+ h.registry.ensure_loaded().unwrap();
+ assert_eq!(
+ h.graph.triple_count(),
+ v1,
+ "without auto_refresh, ensure_loaded must NOT reload from changed source"
+ );
+
+ // Manual recompile picks up the change.
+ let r2 = h.registry.recompile().unwrap();
+ assert!(r2.triple_count > v1);
+ assert_eq!(r2.origin, "source");
+}
+
+#[test]
+fn auto_refresh_after_eviction_uses_new_source() {
+ let h = setup(1);
+ h.registry
+ .load_file(
+ h.source_path.to_str().unwrap(),
+ LoadOptions {
+ auto_refresh: true,
+ ..Default::default()
+ },
+ )
+ .unwrap();
+ let v1 = h.graph.triple_count();
+
+ // Evict, then change source.
+ sleep(Duration::from_millis(1100));
+ assert!(h.registry.evictor_tick().unwrap());
+ std::fs::write(&h.source_path, SAMPLE_TTL_V2).unwrap();
+
+ // ensure_loaded should:
+ // - notice that the source changed (auto_refresh)
+ // - recompile from the new source rather than reload the stale cache
+ h.registry.ensure_loaded().unwrap();
+ let v2 = h.graph.triple_count();
+ assert!(v2 > v1, "expected refreshed (larger) ontology after change");
+}
diff --git a/tests/toolfilter_test.rs b/tests/toolfilter_test.rs
new file mode 100644
index 00000000..d203a8af
--- /dev/null
+++ b/tests/toolfilter_test.rs
@@ -0,0 +1,182 @@
+//! Integration tests for the MCP tool exposure filter (`src/toolfilter.rs`)
+//! and its application to `OpenOntologiesServer`.
+//!
+//! Covers feature 5: limiting which `onto_*` tools the MCP server advertises.
+
+use std::sync::Arc;
+
+use open_ontologies::config::{CacheConfig, EmbeddingsConfig};
+use open_ontologies::graph::GraphStore;
+use open_ontologies::server::OpenOntologiesServer;
+use open_ontologies::state::StateDb;
+use open_ontologies::toolfilter::{Mode, ToolFilter, parse_csv};
+
+fn fresh_db() -> (tempfile::TempDir, StateDb) {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = StateDb::open(&tmp.path().join("s.db")).unwrap();
+ (tmp, db)
+}
+
+fn build_server(filter: ToolFilter) -> (tempfile::TempDir, OpenOntologiesServer) {
+ let (tmp, db) = fresh_db();
+ let graph = Arc::new(GraphStore::new());
+ let cache = CacheConfig {
+ enabled: true,
+ dir: tmp.path().join("cache").to_string_lossy().into_owned(),
+ idle_ttl_secs: 0,
+ evictor_interval_secs: 30,
+ auto_refresh: false,
+ };
+ let server = OpenOntologiesServer::new_with_registry_options(
+ db,
+ graph,
+ None,
+ EmbeddingsConfig::default(),
+ cache,
+ filter,
+ );
+ (tmp, server)
+}
+
+fn tool_names(server: &OpenOntologiesServer) -> Vec<String> {
+ server
+ .list_tool_definitions()
+ .into_iter()
+ .map(|t| t.name.to_string())
+ .collect()
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// Default — all tools exposed
+// ────────────────────────────────────────────────────────────────────────────
+
+#[test]
+fn default_filter_exposes_everything() {
+ let (_tmp, server) = build_server(ToolFilter::default());
+ let names = tool_names(&server);
+ // Sanity: a handful of well-known tools are present.
+ for must in &[
+ "onto_status",
+ "onto_load",
+ "onto_query",
+ "onto_save",
+ "onto_clear",
+ "onto_unload",
+ "onto_recompile",
+ "onto_cache_status",
+ ] {
+ assert!(names.contains(&must.to_string()), "missing {}", must);
+ }
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// Allowlist
+// ────────────────────────────────────────────────────────────────────────────
+
+#[test]
+fn allow_filter_exposes_only_listed_tools() {
+ let filter = ToolFilter::allow_only(vec![
+ "onto_status".to_string(),
+ "onto_query".to_string(),
+ "onto_stats".to_string(),
+ ]);
+ let (_tmp, server) = build_server(filter);
+ let names = tool_names(&server);
+ assert_eq!(names.len(), 3);
+ assert!(names.contains(&"onto_status".to_string()));
+ assert!(names.contains(&"onto_query".to_string()));
+ assert!(names.contains(&"onto_stats".to_string()));
+ assert!(!names.contains(&"onto_load".to_string()));
+ assert!(!names.contains(&"onto_clear".to_string()));
+}
+
+#[test]
+fn allow_filter_with_unknown_name_yields_empty_set() {
+ let filter = ToolFilter::allow_only(vec!["nope_no_such_tool".to_string()]);
+ let (_tmp, server) = build_server(filter);
+ assert_eq!(tool_names(&server).len(), 0);
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// Denylist
+// ────────────────────────────────────────────────────────────────────────────
+
+#[test]
+fn deny_filter_blocks_listed_tools() {
+ let filter = ToolFilter::deny(vec![
+ "onto_clear".to_string(),
+ "onto_load".to_string(),
+ ]);
+ let (_tmp, server) = build_server(filter);
+ let names = tool_names(&server);
+ assert!(!names.contains(&"onto_clear".to_string()));
+ assert!(!names.contains(&"onto_load".to_string()));
+ // Other tools are still exposed.
+ assert!(names.contains(&"onto_status".to_string()));
+ assert!(names.contains(&"onto_query".to_string()));
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// Group expansion
+// ────────────────────────────────────────────────────────────────────────────
+
+#[test]
+fn allow_filter_with_read_only_group() {
+ let filter = ToolFilter {
+ mode: Mode::Allow,
+ list: vec![],
+ groups: vec!["read_only".to_string()],
+ };
+ let (_tmp, server) = build_server(filter);
+ let names = tool_names(&server);
+ // read_only group must include status & query.
+ assert!(names.contains(&"onto_status".to_string()));
+ assert!(names.contains(&"onto_query".to_string()));
+ // and must exclude write tools.
+ assert!(!names.contains(&"onto_load".to_string()));
+ assert!(!names.contains(&"onto_clear".to_string()));
+}
+
+#[test]
+fn deny_filter_with_governance_group() {
+ let filter = ToolFilter {
+ mode: Mode::Deny,
+ list: vec![],
+ groups: vec!["governance".to_string()],
+ };
+ let (_tmp, server) = build_server(filter);
+ let names = tool_names(&server);
+ assert!(!names.contains(&"onto_apply".to_string()));
+ assert!(!names.contains(&"onto_plan".to_string()));
+ assert!(names.contains(&"onto_status".to_string()));
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// CSV parsing
+// ────────────────────────────────────────────────────────────────────────────
+
+#[test]
+fn parse_csv_handles_groups_and_names() {
+ let (n, g) = parse_csv("onto_status,@read_only,onto_query");
+ assert_eq!(n, vec!["onto_status", "onto_query"]);
+ assert_eq!(g, vec!["read_only"]);
+}
+
+#[test]
+fn parse_csv_trims_whitespace_and_skips_empty() {
+ let (n, g) = parse_csv(" onto_status , , @read_only ,, onto_query ");
+ assert_eq!(n, vec!["onto_status", "onto_query"]);
+ assert_eq!(g, vec!["read_only"]);
+}
+
+// ────────────────────────────────────────────────────────────────────────────
+// Mode parsing
+// ────────────────────────────────────────────────────────────────────────────
+
+#[test]
+fn mode_parse_is_case_insensitive_and_supports_aliases() {
+ assert_eq!(Mode::parse("ALL").unwrap(), Mode::All);
+ assert_eq!(Mode::parse("allowlist").unwrap(), Mode::Allow);
+ assert_eq!(Mode::parse("denylist").unwrap(), Mode::Deny);
+ assert!(Mode::parse("garbage").is_err());
+}