Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.
Rust ai-nativedescription-logicsformal-verificationinfrastructure-as-codeisabelle-languageknowledge-graphleanlean4mcpmcp-serverontologyowlowl2reasoningrustshaclsparqltheorem-proving
A named profile hands a client one job's worth of the tool surface (#263)
Fabio Rovaidc957f7fed8b
diff --git a/docs/tool-reference.md b/docs/tool-reference.mdindex 459996c4..128d72d2 100644--- a/docs/tool-reference.md+++ b/docs/tool-reference.md@@ -11,6 +11,69 @@ who meets a catalogue first cannot tell what it is for. Everything below keepsits code and its own documentation; it loses its place above the fold.+## Tool profiles++A profile is a named subset of this catalogue sized for one job. A client that+is aligning two vocabularies has no use for most of what is listed below, and+every tool it has no use for is one more chance to call the wrong one. Select+one with `--tool-profile <name>` on `serve` or `serve-http`, with+`OPEN_ONTOLOGIES_TOOL_PROFILE`, or with `profile` under `[tools]` in+`config.toml`, in that order of precedence. The default is `full`, which is+every tool this build can serve, so a deployment that selects nothing keeps+exactly the surface it has today.++- `full`: every tool this build can serve. The default.+- `authoring`: write and edit an ontology. Validate, lint, enforce patterns,+ version, extract modules, and pull in vocabularies to build on.+- `validation`: judge data against an ontology. SHACL shapes, closed-world+ vocabulary checks, shape induction, what the rule table can see, and the+ provenance of what the graph claims.+- `reasoning`: derive consequences and produce the artefacts that can be+ checked. Certificates, justifications, first-order export and proof checking,+ DL tableaux, model finding.+- `alignment`: relate two vocabularies. Alignment candidates and their feedback+ loop, clinical crosswalks, and the embeddings the scorer uses.+- `governance`: change an ontology in production and answer for it afterwards.+ Plan, apply, lock, drift, monitor, policy, packs, conservativity and the+ lineage trail.+- `data`: land external data in the graph and keep it there. File and SQL+ ingest, schema induction, mapping, CDC watermarks, and the two temporal+ clocks.+- `planning`: act on the graph under laws. Registered actions, BC+ invariants+ and defaults, PDDL compilation and plan validation.+- `retrieval`: ground a model on the graph. Neighbourhood slices, modules,+ community skeletons, schema-guided extraction, and whether a slice kept what+ the answer rests on.+- `evaluation`: score the thing rather than run it. Competency questions, mmRAG+ and OAEI metrics, and the borderline-verdict loop.++Every profile carries the same floor: `onto_status`, `onto_validate`,+`onto_load`, `onto_query`, `onto_stats` and `onto_clear`. Nothing else in any+profile can do anything until a graph is loaded, and a client that cannot check+what it loaded or clear a bad load is stuck inside its own profile.++An unknown profile name refuses to start rather than falling back to `full`.+Publishing the whole catalogue to a deployment that asked for one job's worth of+it, silently, because someone mistyped a flag, is the one failure worth+declining to boot over.++The older `--tools-allow` and `--tools-deny` axis still works and is applied+after the profile. Both axes only ever narrow, so naming a tool in+`--tools-allow` that the selected profile does not carry does not bring it back.+The two ask different questions: a profile asks what a client is here to do, and+the allow/deny groups ask what a caller may be trusted to do.++The profiles are defined in `src/toolfilter.rs`. No size is written on this+page, and that is deliberate: `tests/toolfilter_profiles_test.rs` measures them+from the router and fails if any registered tool belongs to no profile, so the+next tool added to `src/server.rs` carries a failing test until its author files+it. A size typed here would be a second copy of a number nothing derives.+Selecting a profile and calling `onto_status` reports the one in force and what+it withheld.++## Every tool++121 tools.| Tool | What it does |diff --git a/src/config.rs b/src/config.rsindex b5045f3f..523c07cc 100644--- a/src/config.rs+++ b/src/config.rs@@ -365,6 +365,35 @@ pub fn resolve_storage_mode_from(}}+/// The tool profile in force.+///+/// Precedence is the one every other setting in this file uses: CLI > env >+/// config > default. An empty string at any level means "not set" and falls+/// through, and the default is `full`, so an untouched deployment is unaffected.+pub fn resolve_tool_profile(cfg: &ToolsConfig, cli: Option<&str>) -> String {+ let from_env = std::env::var("OPEN_ONTOLOGIES_TOOL_PROFILE").ok();+ resolve_tool_profile_from(cfg, cli, from_env.as_deref())+}++/// The pure half of [`resolve_tool_profile`], for the same reason+/// [`resolve_storage_mode_from`] exists: the environment is shared mutable+/// state, `set_var` is `unsafe` in edition 2024, and cargo runs the tests in+/// one binary on parallel threads. Every branch is exercised through this+/// function so no test has to touch the process environment.+pub fn resolve_tool_profile_from(+ cfg: &ToolsConfig,+ cli: Option<&str>,+ env: Option<&str>,+) -> String {+ [cli, env, Some(cfg.profile.as_str())]+ .into_iter()+ .flatten()+ .map(str::trim)+ .find(|s| !s.is_empty())+ .unwrap_or(crate::toolfilter::FULL)+ .to_string()+}+/// Configuration for limiting which MCP tools are exposed.#[derive(Debug, Deserialize, Clone, Default)]#[serde(default)]@@ -375,6 +404,10 @@ pub struct ToolsConfig {pub list: Vec<String>,/// Group names (e.g. "read_only") expanded into tool names.pub groups: Vec<String>,+ /// Task profile: `full` (default) or one of the names `toolfilter::profiles()`+ /// lists. Empty means `full`. Override with `--tool-profile` or+ /// `OPEN_ONTOLOGIES_TOOL_PROFILE`.+ pub profile: String,}/// Expand a leading `~` in a path to the user's home directory.diff --git a/src/main.rs b/src/main.rsindex e18e587c..d7f08a5d 100644--- a/src/main.rs+++ b/src/main.rs@@ -46,12 +46,23 @@ data_dir = "~/.open-ontologies"# mode = "memory"# [tools]-# Restrict which MCP tools are exposed by this server.+# Restrict which MCP tools this server advertises. Two axes, both of which only+# ever narrow.+#+# profile - a named subset sized for one job, so a client sees the tools it+# needs instead of the whole catalogue. Default "full" (everything this build+# can serve), which is what every existing client already gets. Override with+# --tool-profile or OPEN_ONTOLOGIES_TOOL_PROFILE. An unknown name refuses to+# start rather than quietly falling back to "full".+# profile = "full" # authoring | validation | reasoning | alignment |+# # governance | data | planning | retrieval | evaluation+#+# mode/list/groups - the older allow/deny axis, which asks what a caller may be+# trusted to do rather than what it is here to do. Applied after the profile.# mode = "all" | "allow" | "deny"# list = ["onto_status", "onto_query", "onto_load"]-# # Groups: read_only, mutating, governance, remote, embeddings.+# # Groups: read_only, mutating, governance, remote, embeddings, sql.# groups = ["read_only"]-# mode = "all"# [embeddings]# Provider selects how text embeddings are computed. Override at runtime@@ -236,6 +247,13 @@ enum Commands {/// Comma-separated list of tools (or `@group`) to deny.#[arg(long)]tools_deny: Option<String>,+ /// Task profile: the named subset of the tool surface to advertise.+ /// `full` (default, every tool) or one of `authoring`, `validation`,+ /// `reasoning`, `alignment`, `governance`, `data`, `planning`,+ /// `retrieval`, `evaluation`. An unknown name refuses to start.+ /// CLI > `OPEN_ONTOLOGIES_TOOL_PROFILE` env > `[tools] profile`.+ #[arg(long)]+ tool_profile: Option<String>,/// Idle TTL in seconds before the active ontology is unloaded from memory. 0 disables eviction.#[arg(long)]idle_ttl_secs: Option<u64>,@@ -281,6 +299,13 @@ enum Commands {/// Comma-separated list of tools (or `@group`) to deny.#[arg(long)]tools_deny: Option<String>,+ /// Task profile: the named subset of the tool surface to advertise.+ /// `full` (default, every tool) or one of `authoring`, `validation`,+ /// `reasoning`, `alignment`, `governance`, `data`, `planning`,+ /// `retrieval`, `evaluation`. An unknown name refuses to start.+ /// CLI > `OPEN_ONTOLOGIES_TOOL_PROFILE` env > `[tools] profile`.+ #[arg(long)]+ tool_profile: Option<String>,/// Idle TTL in seconds before the active ontology is unloaded from memory.#[arg(long)]idle_ttl_secs: Option<u64>,@@ -1554,24 +1579,46 @@ fn init_tracing(cfg: &open_ontologies::config::LoggingConfig) {let _ = result;}-/// Compose the effective tool filter from `[tools]` in config + CLI flags.-/// CLI `--tools-allow` / `--tools-deny` override `[tools]` when present.+/// Compose the effective tool filter from `[tools]` in config + env + CLI flags.+///+/// Two independent axes, resolved separately and then combined. The PROFILE+/// comes from `--tool-profile`, then `OPEN_ONTOLOGIES_TOOL_PROFILE`, then+/// `[tools] profile`, then `full`. The allow/deny MODE comes from+/// `--tools-allow` / `--tools-deny` when present and from `[tools]` otherwise,+/// exactly as before.+///+/// An unknown profile name is a startup ERROR. Falling back to `full` on a typo+/// would publish the whole catalogue to a deployment that asked for one job's+/// worth of it, silently, which is the one failure worth refusing to boot over.fn build_tool_filter(cfg: &Config,cli_allow: Option<&str>,cli_deny: Option<&str>,+ cli_profile: Option<&str>,) -> anyhow::Result<open_ontologies::toolfilter::ToolFilter> {- use open_ontologies::toolfilter::{Mode, ToolFilter, parse_csv};+ use open_ontologies::toolfilter::{self, Mode, ToolFilter, parse_csv};if cli_allow.is_some() && cli_deny.is_some() {anyhow::bail!("--tools-allow and --tools-deny are mutually exclusive");}++ let name = open_ontologies::config::resolve_tool_profile(&cfg.tools, cli_profile);+ if !toolfilter::is_profile(&name) {+ anyhow::bail!(+ "unknown tool profile {:?}; known: {}",+ name,+ toolfilter::profiles().join(", ")+ );+ }+ let profile = Some(name);+if let Some(spec) = cli_allow {let (list, groups) = parse_csv(spec);return Ok(ToolFilter {mode: Mode::Allow,list,groups,+ profile,});}if let Some(spec) = cli_deny {@@ -1580,6 +1627,7 @@ fn build_tool_filter(mode: Mode::Deny,list,groups,+ profile,});}// Fall back to config file.@@ -1592,6 +1640,7 @@ fn build_tool_filter(mode,list: cfg.tools.list.clone(),groups: cfg.tools.groups.clone(),+ profile,})}@@ -1781,6 +1830,7 @@ async fn async_main() -> anyhow::Result<()> {watch_interval,tools_allow,tools_deny,+ tool_profile,idle_ttl_secs,auto_refresh,storage_mode,@@ -1842,8 +1892,12 @@ async fn async_main() -> anyhow::Result<()> {};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 tool_filter = build_tool_filter(+ &cfg,+ tools_allow.as_deref(),+ tools_deny.as_deref(),+ tool_profile.as_deref(),+ )?;let ontology_dirs =open_ontologies::config::resolve_ontology_dirs(&cfg.general.ontology_dirs);for d in &ontology_dirs {@@ -1886,6 +1940,7 @@ async fn async_main() -> anyhow::Result<()> {watch_interval,tools_allow,tools_deny,+ tool_profile,idle_ttl_secs,auto_refresh,storage_mode,@@ -2006,8 +2061,12 @@ async fn async_main() -> anyhow::Result<()> {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())?;+ let tool_filter = build_tool_filter(+ &cfg,+ tools_allow.as_deref(),+ tools_deny.as_deref(),+ tool_profile.as_deref(),+ )?;let ontology_dirs =open_ontologies::config::resolve_ontology_dirs(&cfg.general.ontology_dirs);for d in &ontology_dirs {diff --git a/src/server.rs b/src/server.rsindex c7319426..b80fed8c 100644--- a/src/server.rs+++ b/src/server.rs@@ -33,6 +33,11 @@ pub struct OpenOntologiesServer {/// Empty when none are configured. Used by `onto_repo_list` //// `onto_repo_load`.ontology_dirs: Arc<Vec<std::path::PathBuf>>,+ /// What the operator's filter did to this server's surface, so `onto_status`+ /// can name the profile in force and the count it withheld. A user hunting a+ /// tool that is not advertised has to be able to read the reason out of the+ /// server rather than infer it from the deployment.+ tool_surface: Arc<crate::toolfilter::ToolSurface>,#[cfg(feature = "embeddings")]vecstore: Arc<std::sync::Mutex<crate::vecstore::VecStore>>,#[cfg(feature = "embeddings")]@@ -136,6 +141,7 @@ impl OpenOntologiesServer {// behind a Cargo feature whose absence turns every call into// "Compiled without X feature". See `toolfilter::FEATURE_GATED_TOOLS`.let mut tool_router = Self::tool_router();+ let compiled_in = tool_router.list_all().len();let unavailable = crate::toolfilter::remove_unavailable(&mut tool_router);if !unavailable.is_empty() {tracing::info!(@@ -149,10 +155,26 @@ impl OpenOntologiesServer {);}+ // Counted after the feature gate and before the operator's filter, so+ // `withheld_by_filter` is about the filter and nothing else.+ let servable = tool_router.list_all().len();+// Apply tool filter by removing routes from the router.let removed = tool_filter.apply(&mut tool_router);+ let tool_surface = Arc::new(tool_filter.describe(+ compiled_in,+ servable,+ servable.saturating_sub(removed.len()),+ ));if !removed.is_empty() {- tracing::info!("tool filter removed {} tools: {:?}", removed.len(), removed);+ tracing::info!(+ "tool profile {:?}: advertising {} of {} servable tools, {} withheld: {:?}",+ tool_surface.profile,+ tool_surface.exposed,+ tool_surface.servable_in_this_build,+ tool_surface.withheld_by_filter,+ removed+ );}#[cfg(feature = "embeddings")]@@ -200,6 +222,7 @@ impl OpenOntologiesServer {governance_webhook,registry,ontology_dirs: Arc::new(ontology_dirs),+ tool_surface,#[cfg(feature = "embeddings")]vecstore,#[cfg(feature = "embeddings")]@@ -212,6 +235,27 @@ impl OpenOntologiesServer {self.tool_router.list_all()}+ /// The body of `onto_status`, callable without going through MCP.+ ///+ /// `onto_status` is a private `#[tool]` method, so a test that wants to+ /// assert on what a client is TOLD would otherwise assert on the fields one+ /// by one and could pass while the JSON said something else.+ pub fn status_json(&self) -> String {+ serde_json::json!({+ "status": "ok",+ "version": env!("CARGO_PKG_VERSION"),+ "tools": self.tool_router.list_all().len(),+ "triples_loaded": self.graph.triple_count(),+ // Always present and always naming the profile, even under `full`.+ // Reporting it only when something was withheld would mean the+ // absence of the field had to be read as "nothing was withheld",+ // and a field that must be read by its absence gets missed.+ "tool_surface": &*self.tool_surface,+ "tool_profiles_available": crate::toolfilter::profiles(),+ })+ .to_string()+ }+/// Access the ontology registry (for tests and the HTTP server eviction loop).pub fn registry(&self) -> Arc<crate::registry::OntologyRegistry> {self.registry.clone()@@ -237,17 +281,9 @@ impl OpenOntologiesServer {// ── Status ──────────────────────────────────────────────────────────────- #[tool(name = "onto_status", description = "Returns health status of the Open Ontologies server")]+ #[tool(name = "onto_status", description = "Returns health status of the Open Ontologies server, including which tool profile is in force and how many tools it withheld. If a tool you expected is missing from tools/list, `tool_surface` is where the reason is: the operator can re-run with `--tool-profile full` (the default) or name the profile that carries it.")]fn onto_status(&self) -> String {- let tool_count = self.tool_router.list_all().len();- let triple_count = self.graph.triple_count();- serde_json::json!({- "status": "ok",- "version": env!("CARGO_PKG_VERSION"),- "tools": tool_count,- "triples_loaded": triple_count,- })- .to_string()+ self.status_json()}// ── Ontology ────────────────────────────────────────────────────────────@@ -3369,11 +3405,24 @@ impl ServerHandler for OpenOntologiesServer {.join(", "))};+ // Telling a client it has every tool while advertising one profile's+ // worth is a false claim to the one reader that cannot check.+ let s = &*self.tool_surface;+ let profile_tail = if s.withheld_by_filter > 0 {+ format!(+ " This server is running the \"{}\" tool profile, so {} of the {} tools this \+ build can serve are NOT advertised. Call onto_status for the profile and the \+ counts; the operator can select another profile or \"full\".",+ s.profile, s.withheld_by_filter, s.servable_in_this_build+ )+ } else {+ String::new()+ };ServerInfo::new(ServerCapabilities::builder().enable_tools().enable_prompts().build()).with_instructions(format!("Open Ontologies: AI-native ontology engine, an RDF/OWL/SPARQL MCP server with \{advertised} tools and 6 workflow prompts for ontology engineering, validation, \- comparison, alignment, data ingestion, and exploration.{tail}"+ comparison, alignment, data ingestion, and exploration.{tail}{profile_tail}"))}}diff --git a/src/toolfilter.rs b/src/toolfilter.rsindex 6b3221e9..bef61a8f 100644--- a/src/toolfilter.rs+++ b/src/toolfilter.rs@@ -3,10 +3,29 @@//! 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.+//! TWO AXES, AND THEY COMPOSE.+//!+//! The first axis is the PROFILE: a named subset of the tool surface sized for+//! one job. A client that is aligning two vocabularies has no use for most of+//! what `src/server.rs` registers, and every tool it has no use for is one more+//! chance to call the wrong one. `expand_profile` is the table and `profiles()`+//! lists the names. No count is written here on purpose: the total is measured+//! from the router by `tests/toolfilter_profiles_test.rs` and stated in+//! `docs/tool-reference.md`, which is the one document allowed to state it.+//!+//! The second axis is the MODE, which is the older mechanism and is unchanged:+//! - `Mode::All` — every tool the profile left standing (default).+//! - `Mode::Allow` — only tools in `list` (or expanded from `groups`).+//! - `Mode::Deny` — all but the tools in `list` (or `groups`).+//!+//! The profile narrows FIRST and the mode narrows what is left, so+//! `--tool-profile alignment --tools-deny onto_push` is the alignment profile+//! minus one tool and neither axis can widen the other. The `groups` on the+//! mode axis (`read_only`, `mutating`, …) cut along a different line: they+//! answer what a caller may be trusted to do, not what it is here to do.+//!+//! THE DEFAULT DOES NOT MOVE. No profile means `full`, which is every tool this+//! build can serve, which is what every existing client already sees.//!//! Implementation: applied by removing routes from the rmcp `ToolRouter`//! before the server is constructed. Removed tools are not advertised via@@ -45,6 +64,9 @@ pub struct ToolFilter {pub list: Vec<String>,/// Group names that expand to a curated set of tool names.pub groups: Vec<String>,+ /// Task profile. `None` and `Some("full")` both mean every tool, which is+ /// the default and what every client saw before profiles existed.+ pub profile: Option<String>,}impl ToolFilter {@@ -57,6 +79,7 @@ impl ToolFilter {mode: Mode::Allow,list: names.into_iter().collect(),groups: vec![],+ profile: None,}}@@ -65,6 +88,7 @@ impl ToolFilter {mode: Mode::Deny,list: names.into_iter().collect(),groups: vec![],+ profile: None,}}@@ -79,9 +103,82 @@ impl ToolFilter {out}+ /// A filter that exposes exactly one profile. Errors on an unknown name+ /// rather than falling back to `full`.+ pub fn with_profile(name: &str) -> Result<Self, String> {+ if !is_profile(name) {+ return Err(format!(+ "unknown tool profile {:?}; known: {}",+ name,+ profiles().join(", ")+ ));+ }+ Ok(Self {+ profile: Some(name.to_string()),+ ..Default::default()+ })+ }++ /// The profile in force, `full` when none was chosen.+ pub fn profile_name(&self) -> &str {+ self.profile.as_deref().unwrap_or(FULL)+ }++ /// Whether the PROFILE axis alone lets `tool_name` through.+ fn profile_allows(&self, tool_name: &str) -> bool {+ match self.profile.as_deref() {+ None | Some(FULL) => true,+ Some(p) => match expand_profile(p) {+ Some(names) => names.contains(&tool_name),+ // Unreachable through the CLI, the env var and the config file,+ // all three of which refuse an unknown name at startup. Reached+ // only by building the struct by hand, and the conservative+ // reading of a name nobody recognises is that it names nothing.+ None => false,+ },+ }+ }++ /// What a client is looking at, for `onto_status` and the startup log.+ ///+ /// `servable` is counted AFTER `remove_unavailable` and `compiled_in`+ /// before it, because in a default build eight of the registered tools are+ /// behind a Cargo feature and are already gone by the time the operator's+ /// filter runs. Folding the two into one number would report the feature+ /// gate as something the profile withheld, and the field a user reads to+ /// answer "why can I not see it" would name the wrong cause.+ pub fn describe(&self, compiled_in: usize, servable: usize, exposed: usize) -> ToolSurface {+ ToolSurface {+ profile: self.profile_name().to_string(),+ mode: match self.mode {+ Mode::All => "all",+ Mode::Allow => "allow",+ Mode::Deny => "deny",+ },+ compiled_in,+ servable_in_this_build: servable,+ exposed,+ withheld_by_filter: servable.saturating_sub(exposed),+ }+ }+/// Decide whether `tool_name` should be exposed.+ ///+ /// The profile narrows first and the mode narrows what is left, so naming a+ /// tool in `--tools-allow` that the profile does not carry does not bring it+ /// back.pub fn allows(&self, tool_name: &str) -> bool {- let names = self.resolved_names();+ self.allows_given(&self.resolved_names(), tool_name)+ }++ /// `allows` with the resolved name set supplied, so `apply` builds it once+ /// for the whole router instead of once per tool. The DECISION lives here+ /// and nowhere else: `apply` used to carry its own copy of the match, which+ /// is two places for one rule to be changed in.+ fn allows_given(&self, names: &HashSet<String>, tool_name: &str) -> bool {+ if !self.profile_allows(tool_name) {+ return false;+ }match self.mode {Mode::All => true,Mode::Allow => names.contains(tool_name),@@ -99,7 +196,9 @@ impl ToolFilter {whereS: Send + Sync + 'static,{- if self.mode == Mode::All {+ // The fast path is the DEFAULT path and it has to stay exact: no+ // profile and `Mode::All` must remove nothing at all.+ if self.mode == Mode::All && matches!(self.profile.as_deref(), None | Some(FULL)) {return Vec::new();}let names = self.resolved_names();@@ -110,12 +209,7 @@ impl ToolFilter {.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 {+ if !self.allows_given(&names, &name) {router.remove_route(&name);removed.push(name);}@@ -124,6 +218,214 @@ impl ToolFilter {}}+/// The filtered surface as reported to clients.+#[derive(Debug, Clone, serde::Serialize)]+pub struct ToolSurface {+ /// `full` when nothing was selected.+ pub profile: String,+ /// The second axis: `all`, `allow` or `deny`.+ pub mode: &'static str,+ /// Tools the binary registers, whatever this build can serve.+ pub compiled_in: usize,+ /// Of those, the ones this feature set can actually serve.+ pub servable_in_this_build: usize,+ /// Of those, the ones that survived the operator's filter.+ pub exposed: usize,+ /// The filter's own doing. Non-zero here is the answer to "why can I not+ /// see it", and `compiled_in - servable_in_this_build` is the other answer.+ pub withheld_by_filter: usize,+}++/// The name that means "everything".+pub const FULL: &str = "full";++/// Tools present in EVERY profile.+///+/// Not a category, a floor. Nothing else in any profile can do anything until a+/// graph is loaded, and a client that cannot check what it loaded or clear a+/// bad load is stuck inside its own profile. Six tools is the price of every+/// profile being self-sufficient, and a profile that is not self-sufficient+/// sends the user back to `full`, which defeats the exercise.+pub const SPINE: &[&str] = &[+ "onto_status",+ "onto_validate",+ "onto_load",+ "onto_query",+ "onto_stats",+ "onto_clear",+];++/// The task-oriented profiles, each the tools for one job, on top of `SPINE`.+///+/// Read off what the tools do in `src/server.rs`, which is why they OVERLAP:+/// `onto_shacl` belongs to judging data and to landing it, `onto_module_extract`+/// to authoring, reasoning and retrieval, and forcing a partition would have+/// left one of those jobs a tool short. The only rule the set has to satisfy is+/// COVERAGE, enforced by+/// `tests/toolfilter_profiles_test.rs::every_registered_tool_is_in_some_profile`:+/// a tool added later and filed under nothing fails the build rather than+/// becoming reachable only from `full` and therefore never missed.+const PROFILES: &[(&str, &str, &[&str])] = &[+ (+ "authoring",+ "Write and edit an ontology: validate, lint, enforce patterns, version, \+ extract modules, and pull in vocabularies to build on.",+ &[+ "onto_save", "onto_convert", "onto_diff", "onto_lint", "onto_lint_feedback",+ "onto_defects", "onto_dl_check", "onto_dl_explain", "onto_version", "onto_history",+ "onto_rollback", "onto_marketplace", "onto_import", "onto_pull", "onto_push",+ "onto_repo_list", "onto_repo_load", "onto_unload", "onto_recompile",+ "onto_cache_status", "onto_cache_list", "onto_cache_remove", "onto_enforce",+ "onto_enforce_feedback", "onto_ossie_import", "onto_import_schema",+ "onto_plugin_list", "onto_plugin_call", "onto_induce", "onto_module_extract",+ "onto_conservative_check",+ ],+ ),+ (+ "validation",+ "Judge data against an ontology: SHACL shapes, closed-world vocabulary \+ checks, shape induction, what the rule table can see, and the \+ provenance of what the graph claims.",+ &[+ "onto_shacl", "onto_shacl_check", "onto_vocab_check", "onto_lint", "onto_defects",+ "onto_dlp_boundary", "onto_justify", "onto_coevolve_dependency_graph",+ "onto_owl_shacl_coevolve_check", "onto_owl_shacl_coevolve_incremental",+ "onto_shape_induce", "onto_shape_combinatorics", "onto_ingest", "onto_map",+ "onto_extend", "onto_support_check", "onto_support_verdict", "onto_support_report",+ "onto_plugin_list", "onto_plugin_call",+ ],+ ),+ (+ "reasoning",+ "Derive consequences and produce the artefacts that can be checked: \+ certificates, justifications, first-order export and proof checking, \+ DL tableaux, model finding.",+ &[+ "onto_reason", "onto_reason_incremental", "onto_rules_import", "onto_defects",+ "onto_dlp_boundary", "onto_justify", "onto_provenance", "onto_classify_el",+ "onto_dl_check", "onto_dl_explain", "onto_fol_export", "onto_fol_model",+ "onto_fol_prove", "onto_closure_diff", "onto_module_extract",+ "graph_projection_entailment_check", "graph_projection_lossy_check", "onto_extend",+ ],+ ),+ (+ "alignment",+ "Relate two vocabularies: alignment candidates and their feedback loop, \+ clinical crosswalks, and the embeddings the scorer uses.",+ &[+ "onto_align", "onto_align_feedback", "onto_align_fuzzy", "onto_align_flora",+ "onto_eval_alignment", "onto_diff", "onto_crosswalk", "onto_enrich",+ "onto_validate_clinical", "onto_embed", "onto_search", "onto_similarity",+ "onto_hnsw_build", "borderline_partition", "borderline_record_verdict",+ ],+ ),+ (+ "governance",+ "Change an ontology in production and answer for it afterwards: plan, \+ apply, lock, drift, monitor, policy, packs, conservativity and the \+ lineage trail.",+ &[+ "onto_plan", "onto_apply", "onto_lock", "onto_drift", "onto_enforce",+ "onto_enforce_feedback", "onto_monitor", "onto_monitor_clear", "onto_lineage",+ "onto_provenance", "onto_conservative_check", "onto_version", "onto_history",+ "onto_rollback", "onto_pack", "onto_unpack", "onto_policy_register",+ "onto_policy_list", "onto_policy_check", "onto_support_report",+ "onto_temporal_snapshot", "onto_temporal_query", "onto_temporal_conflicts",+ ],+ ),+ (+ "data",+ "Land external data in the graph and keep it there: file and SQL \+ ingest, schema induction, mapping, CDC watermarks, and the two \+ temporal clocks.",+ &[+ "onto_ingest", "onto_induce", "onto_map", "onto_extend", "onto_convert",+ "onto_sql_ingest", "onto_import_schema", "onto_sql_sync_state",+ "onto_sql_sync_reset", "onto_sql_sync_states_list", "onto_pull", "onto_push",+ "onto_shacl", "onto_vocab_check", "onto_temporal_snapshot", "onto_temporal_query",+ "onto_temporal_conflicts",+ ],+ ),+ (+ "planning",+ "Act on the graph under laws: registered actions, BC+ invariants and \+ defaults, PDDL compilation and plan validation.",+ &[+ "onto_action_register", "onto_action_list", "onto_action_applicable",+ "onto_action_apply", "onto_action_apply_concurrent", "onto_certify_action",+ "onto_invariant_register", "onto_invariant_list", "onto_invariant_remove",+ "onto_invariant_check", "onto_default_register", "onto_default_apply",+ "onto_plan_classical", "onto_plan_compile_pddl", "onto_plan_validate",+ "onto_policy_check", "onto_lineage",+ ],+ ),+ (+ "retrieval",+ "Ground a model on the graph: neighbourhood slices, modules, community \+ skeletons, schema-guided extraction, and whether a slice kept what the \+ answer rests on.",+ &[+ "onto_segment_retrieve", "onto_communities", "onto_extract_scaffold",+ "onto_extract_validate", "onto_module_extract", "onto_embed", "onto_search",+ "onto_similarity", "onto_hnsw_build", "graph_projection_lossy_check",+ "graph_projection_entailment_check", "onto_closure_diff",+ ],+ ),+ (+ "evaluation",+ "Score the thing rather than run it: competency questions, mmRAG and \+ OAEI metrics, and the borderline-verdict loop.",+ &[+ "onto_cq_run", "onto_verify_cq", "onto_cq_verdicts_list", "eval_rag",+ "eval_rag_mmrag", "onto_eval_alignment", "borderline_partition",+ "borderline_record_verdict", "onto_shape_induce", "onto_shape_combinatorics",+ "onto_diff",+ ],+ ),+];++/// Every profile name, `full` first. `full` is not in `PROFILES` because it is+/// not a subset: it is the absence of one. Giving it a list would mean a tool+/// added to `src/server.rs` had to be added to `full` by hand to stay visible,+/// which is the unreachability this whole exercise is against.+pub fn profiles() -> Vec<&'static str> {+ let mut out = vec![FULL];+ out.extend(PROFILES.iter().map(|(n, _, _)| *n));+ out+}++/// One line saying what a profile is for, or `None` if the name is unknown.+pub fn profile_description(name: &str) -> Option<&'static str> {+ if name == FULL {+ return Some(+ "Every tool this build can serve. The default, and what every \+ client saw before profiles existed.",+ );+ }+ PROFILES.iter().find(|(n, _, _)| *n == name).map(|(_, d, _)| *d)+}++/// The tools a profile exposes: `SPINE` plus its own, deduplicated and sorted.+///+/// `None` for an unknown name, and the distinction matters: a typo must be an+/// error at startup and must NOT fall back to exposing everything, which is the+/// one wrong answer a misspelled `--tool-profile` could give.+pub fn expand_profile(name: &str) -> Option<Vec<&'static str>> {+ if name == FULL {+ return None;+ }+ let (_, _, own) = PROFILES.iter().find(|(n, _, _)| *n == name)?;+ let mut out: Vec<&'static str> = SPINE.iter().copied().chain(own.iter().copied()).collect();+ out.sort_unstable();+ out.dedup();+ Some(out)+}++/// Whether `name` names a profile, `full` included.+pub fn is_profile(name: &str) -> bool {+ name == FULL || PROFILES.iter().any(|(n, _, _)| *n == name)+}+// ───────────────────────────────────────────────────────────────────────────// Tools this build cannot serve// ───────────────────────────────────────────────────────────────────────────@@ -325,6 +627,7 @@ mod tests {mode: Mode::Allow,list: vec![],groups: vec!["read_only".to_string()],+ profile: None,};assert!(f.allows("onto_status"));assert!(f.allows("onto_query"));diff --git a/tests/toolfilter_profiles_test.rs b/tests/toolfilter_profiles_test.rsnew file mode 100644index 00000000..01de14dc--- /dev/null+++ b/tests/toolfilter_profiles_test.rs@@ -0,0 +1,324 @@+//! Task profiles: the named subsets of the tool surface, and the one property+//! that has to hold for ever.+//!+//! THE COVERAGE TEST IS THE POINT. The profile table in `src/toolfilter.rs` is+//! a hand-maintained list of names next to a router that grows on its own, and+//! the failure mode is not a wrong grouping: it is a tool added to+//! `src/server.rs` next year, filed under nothing, reachable only from `full`,+//! and never missed, because a tool that is never advertised is never missed.+//! `every_registered_tool_is_in_some_profile` turns that into a failure on the+//! commit that causes it, which is the only moment anyone can fix it.+//!+//! The rest pins what makes profiles safe to ship: the default does not move, a+//! profile only narrows, the spine is in all of them, and an unknown name is+//! refused rather than widened to `full`.++use std::collections::BTreeSet;+use std::sync::Arc;++use open_ontologies::config::{+ CacheConfig, EmbeddingsConfig, ToolsConfig, resolve_tool_profile_from,+};+use open_ontologies::graph::GraphStore;+use open_ontologies::server::OpenOntologiesServer;+use open_ontologies::state::StateDb;+use open_ontologies::toolfilter::{+ self, FEATURE_GATED_TOOLS, FULL, Mode, SPINE, ToolFilter, expand_profile, is_profile,+ profile_description, profiles,+};++fn build_server(filter: ToolFilter) -> (tempfile::TempDir, OpenOntologiesServer) {+ let tmp = tempfile::tempdir().unwrap();+ let db = StateDb::open(&tmp.path().join("s.db")).unwrap();+ 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,+ hash_prefix_bytes: 64 * 1024,+ };+ let server = OpenOntologiesServer::new_with_registry_options(+ db,+ Arc::new(GraphStore::new()),+ None,+ EmbeddingsConfig::default(),+ cache,+ filter,+ );+ (tmp, server)+}++fn tool_names(server: &OpenOntologiesServer) -> BTreeSet<String> {+ server.list_tool_definitions().into_iter().map(|t| t.name.to_string()).collect()+}++/// Every tool THIS build advertises by default, read off the router. A list+/// written here would be the same hand-maintained thing the test exists to+/// police.+fn advertised_by_default() -> BTreeSet<String> {+ let (_tmp, server) = build_server(ToolFilter::default());+ tool_names(&server)+}++/// Every tool the binary registers, feature-gated ones included.+///+/// `remove_unavailable` runs before the operator's filter, so in a default+/// build the router has already lost the eight tools behind a Cargo feature.+/// The union is what a profile name is legitimately allowed to be: CI runs+/// `cargo test` with default features and again with `--all-features`, and a+/// ghost test that read only the router would call `onto_embed` a dead string+/// in the first job and not the second.+fn nameable() -> BTreeSet<String> {+ let mut out = advertised_by_default();+ out.extend(FEATURE_GATED_TOOLS.iter().map(|(t, _)| t.to_string()));+ out+}++#[test]+fn every_registered_tool_is_in_some_profile() {+ let mut covered: BTreeSet<String> = BTreeSet::new();+ for name in profiles() {+ if name == FULL {+ continue;+ }+ for t in expand_profile(name).expect("a listed profile expands") {+ covered.insert(t.to_string());+ }+ }+ let registered = nameable();+ let orphans: Vec<&String> = registered.difference(&covered).collect();+ assert!(+ orphans.is_empty(),+ "{} registered tool(s) belong to no profile, so a client that selects any \+ profile can never reach them: {:?}\nAdd each one to a profile in \+ src/toolfilter.rs. `full` does not count: it is the absence of a profile, \+ not a home for orphans.",+ orphans.len(),+ orphans+ );+}++#[test]+fn no_profile_names_a_tool_that_does_not_exist() {+ // The other direction. A renamed tool leaves a dead string behind, the+ // profile silently shrinks by one, and nothing says so.+ let registered = nameable();+ let mut ghosts = Vec::new();+ for name in profiles() {+ if name == FULL {+ continue;+ }+ for t in expand_profile(name).unwrap() {+ if !registered.contains(t) {+ ghosts.push(format!("{name}: {t}"));+ }+ }+ }+ assert!(+ ghosts.is_empty(),+ "profile(s) name tools that are not registered, so the profile is quietly \+ smaller than it reads: {ghosts:?}"+ );+}++#[test]+fn the_default_is_still_every_tool() {+ let (_tmp, server) = build_server(ToolFilter::default());+ let status: serde_json::Value = serde_json::from_str(&server.status_json()).unwrap();+ assert_eq!(+ status["tool_surface"]["exposed"], status["tool_surface"]["servable_in_this_build"],+ "the default filter must advertise every tool this build can serve. Existing \+ clients were built against that surface and shrinking it under them is worse \+ than the discoverability problem profiles are for."+ );+ assert_eq!(status["tool_surface"]["withheld_by_filter"], 0);+ assert_eq!(status["tool_surface"]["profile"], "full");+ // The three counters have to stay three. Folding `servable_in_this_build`+ // into `compiled_in` leaves the assertions above still passing, because+ // both sides move together when the filter withholds nothing, so the+ // default case needs the invariant stated against the feature gate+ // directly: what this build can serve is what it compiled in MINUS what+ // the Cargo features took away, and `tools` is the router length the same+ // call reports. Without these two the collapse the plan warns about is+ // caught only by the profile test, and a default-features CI job would+ // publish a false servable count.+ assert_eq!(status["tools"], status["tool_surface"]["exposed"]);+ let compiled = status["tool_surface"]["compiled_in"].as_u64().unwrap();+ let gated = toolfilter::unavailable_in_this_build().len() as u64;+ assert_eq!(+ status["tool_surface"]["servable_in_this_build"].as_u64().unwrap(),+ compiled - gated,+ "servable must be counted AFTER remove_unavailable and compiled_in before it"+ );+}++#[test]+fn full_is_the_same_surface_as_no_profile_at_all() {+ let (_a, default_server) = build_server(ToolFilter::default());+ let (_b, full_server) = build_server(ToolFilter::with_profile(FULL).unwrap());+ assert_eq!(tool_names(&default_server), tool_names(&full_server));+}++#[test]+fn every_profile_is_smaller_than_full_and_bigger_than_the_spine() {+ let total = advertised_by_default().len();+ for name in profiles() {+ if name == FULL {+ continue;+ }+ let (_tmp, server) = build_server(ToolFilter::with_profile(name).unwrap());+ let n = tool_names(&server).len();+ assert!(+ n < total,+ "profile {name:?} advertises {n} of {total}. A profile that is not smaller \+ is not a profile; a smaller surface is the whole point."+ );+ assert!(+ n > SPINE.len(),+ "profile {name:?} advertises {n} tools, which is the spine and almost \+ nothing else. It cannot do the job it is named for."+ );+ }+}++#[test]+fn every_profile_carries_the_spine() {+ for name in profiles() {+ if name == FULL {+ continue;+ }+ let (_tmp, server) = build_server(ToolFilter::with_profile(name).unwrap());+ let exposed = tool_names(&server);+ for t in SPINE {+ assert!(+ exposed.contains(*t),+ "profile {name:?} is missing {t}, so a client cannot load a graph or see \+ what it loaded and is stuck inside its profile"+ );+ }+ }+}++#[test]+fn every_profile_says_what_it_is_for() {+ for name in profiles() {+ let d = profile_description(name).unwrap_or_else(|| panic!("{name} has no description"));+ assert!(d.len() > 40, "profile {name:?} description is a stub: {d:?}");+ }+}++#[test]+fn a_selected_profile_is_visible_in_the_servers_own_reporting() {+ let (_tmp, server) = build_server(ToolFilter::with_profile("alignment").unwrap());+ let status: serde_json::Value = serde_json::from_str(&server.status_json()).unwrap();+ assert_eq!(status["tool_surface"]["profile"], "alignment");+ let exposed = status["tool_surface"]["exposed"].as_u64().unwrap();+ let servable = status["tool_surface"]["servable_in_this_build"].as_u64().unwrap();+ let withheld = status["tool_surface"]["withheld_by_filter"].as_u64().unwrap();+ assert!(withheld > 0 && exposed + withheld == servable);+ // `tools` is the count a client sees in tools/list and it has to match the+ // surface the same call describes, or the report is about a different server+ // than the one answering.+ assert_eq!(status["tools"].as_u64().unwrap(), exposed);+ // The way out is printed, so a user missing a tool does not have to find the+ // documentation to learn that profiles exist.+ let available = status["tool_profiles_available"].as_array().unwrap();+ assert!(available.iter().any(|v| v == "full"));+}++#[test]+fn allow_list_cannot_add_back_a_tool_the_profile_dropped() {+ // `onto_plan_classical` is in `planning` and not in `alignment`. Naming it in+ // --tools-allow must not resurrect it: both axes narrow, and a mode that+ // could widen a profile would make the profile advisory.+ let filter = ToolFilter {+ mode: Mode::Allow,+ list: vec!["onto_plan_classical".to_string(), "onto_align".to_string()],+ groups: vec![],+ profile: Some("alignment".to_string()),+ };+ let (_tmp, server) = build_server(filter);+ let exposed = tool_names(&server);+ assert!(!exposed.contains("onto_plan_classical"));+ assert!(exposed.contains("onto_align"));+}++#[test]+fn deny_narrows_a_profile_further() {+ let filter = ToolFilter {+ mode: Mode::Deny,+ list: vec!["onto_align".to_string()],+ groups: vec![],+ profile: Some("alignment".to_string()),+ };+ let (_tmp, server) = build_server(filter);+ let exposed = tool_names(&server);+ assert!(!exposed.contains("onto_align"));+ assert!(exposed.contains("onto_crosswalk"));+ assert!(exposed.contains("onto_status"));+}++#[test]+fn an_unknown_profile_is_an_error_and_not_a_silent_full() {+ let err = ToolFilter::with_profile("authorring").unwrap_err();+ assert!(err.contains("authorring"), "{err}");+ assert!(err.contains("authoring"), "the error must list the real names: {err}");+ assert!(!is_profile("authorring"));+ assert!(expand_profile("authorring").is_none());+}++#[test]+fn a_filter_holding_an_unknown_profile_exposes_nothing_rather_than_everything() {+ // Not reachable through the CLI, which refuses to start. Pinned because the+ // conservative reading of a name nobody recognises is "no tools" and the+ // dangerous reading is "all of them".+ let filter = ToolFilter { profile: Some("nonsense".to_string()), ..Default::default() };+ assert!(!filter.allows("onto_status"));+ let (_tmp, server) = build_server(filter);+ assert!(tool_names(&server).is_empty());+}++#[test]+fn profile_resolution_is_cli_then_env_then_config_then_full() {+ // Through the pure resolver: the process environment is shared mutable+ // state and cargo runs these tests on parallel threads, which is why+ // config.rs has a `_from` half at all.+ let cfg = ToolsConfig { profile: "governance".to_string(), ..Default::default() };+ assert_eq!(resolve_tool_profile_from(&cfg, Some("reasoning"), Some("data")), "reasoning");+ assert_eq!(resolve_tool_profile_from(&cfg, None, Some("data")), "data");+ assert_eq!(resolve_tool_profile_from(&cfg, None, None), "governance");+ // An empty string at any level is "not set", not "the empty profile".+ assert_eq!(resolve_tool_profile_from(&cfg, Some(" "), None), "governance");+ assert_eq!(resolve_tool_profile_from(&ToolsConfig::default(), None, Some("")), FULL);+ // Every name the resolver can return has to be one the filter accepts.+ for n in [+ resolve_tool_profile_from(&cfg, None, None),+ resolve_tool_profile_from(&ToolsConfig::default(), None, None),+ ] {+ assert!(is_profile(&n), "{n} resolved but is not a profile");+ }+}++#[test]+fn the_older_group_mechanism_still_works_with_no_profile() {+ let filter = ToolFilter {+ mode: Mode::Allow,+ list: vec![],+ groups: vec!["read_only".to_string()],+ profile: None,+ };+ let (_tmp, server) = build_server(filter);+ let exposed = tool_names(&server);+ assert!(exposed.contains("onto_query"));+ assert!(!exposed.contains("onto_push"));+ let gated: BTreeSet<&str> = FEATURE_GATED_TOOLS.iter().map(|(t, _)| *t).collect();+ for t in toolfilter::expand_group("read_only") {+ // `onto_search` and `onto_similarity` are in the group and are not in a+ // default build, and the group mechanism is not what removed them.+ if gated.contains(t) && !advertised_by_default().contains(*t) {+ continue;+ }+ assert!(exposed.contains(*t), "{t} dropped from the read_only group");+ }+}diff --git a/tests/toolfilter_test.rs b/tests/toolfilter_test.rsindex dacdbbcf..9c724723 100644--- a/tests/toolfilter_test.rs+++ b/tests/toolfilter_test.rs@@ -127,6 +127,7 @@ fn allow_filter_with_read_only_group() {mode: Mode::Allow,list: vec![],groups: vec!["read_only".to_string()],+ profile: None,};let (_tmp, server) = build_server(filter);let names = tool_names(&server);@@ -144,6 +145,7 @@ fn deny_filter_with_governance_group() {mode: Mode::Deny,list: vec![],groups: vec!["governance".to_string()],+ profile: None,};let (_tmp, server) = build_server(filter);let names = tool_names(&server);