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 plan scores a change high when it makes a class unsatisfiable or the ABox inconsistent, and batch runs defects
FABIOTESS7234ac750420
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 49ce9c9f..eb89f225 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,26 @@ All notable changes to Open Ontologies are documented here.### Added+- **A plan says whether the change breaks the ontology, and scores it `high`+ when it does** (#336, reported by @jpsanchezcalypso). `risk_score` came from+ removal counts alone, so a change that made a named class unsatisfiable (R1:+ `Manager ⊑ Person ⊑ Agent`, `Manager ⊥ Agent`) or the ABox inconsistent (R2:+ `Machine ⊥ Person`, `alice a Machine` where `alice a Person`) removed nothing+ and scored `low`. `plan`, `batch` `plan` and `onto_plan` now carry a `logic`+ block through one function (`Planner::plan_with`): `new_defects`, the+ `defects` findings the store did not have, and `abox_consistent`, the owl-dl+ tableaux on the proposed graph under the `[reasoner]` budget, with+ `abox_consistent_before` for the store when the proposed graph is+ inconsistent. A new error- or warning-severity defect, or an inconsistency+ the store was not proven to have, sets `risk_score` to `high`, and the new+ `risk_reasons` says why. A check that ran out of budget, or a graph using a+ construct the tableaux does not model, reports `abox_consistent: null` with+ the reason, never `true`. On by default; `--no-logic-check` (CLI, `batch`) or+ `check_logic: false` (`onto_plan`) skips it and the block says+ `not_checked`. `apply` is unchanged and does not gate on the verdict, and the+ exit code of `plan` is unchanged (1 on an error only), as it already was for+ a `high` score from removals; `docs/lifecycle.md` says so. R1 and R2 now plan+ `high` on all four entry points; the benign control stays `low`.- **`defects` says how many classes are affected, and its 50-a-kind listingcan be lifted** (#341). `defect_count` counts findings, one per query row,and for `inherited_disjoint` a row is a (class, disjoint pair), so a class@@ -58,6 +78,16 @@ All notable changes to Open Ontologies are documented here.### Fixed+- **`batch` runs `defects`** (#336). It had no arm, so `batch` answered+ `{"error":"unknown batch command: 'defects'"}`, and so did the CLI `defects`+ whenever a daemon was up, since the CLI proxies it there. `defects [path]+ [--limit N]` checks the file alone, or the batch's own store when no path is+ given. The proxy coverage test now lists `defects`. The local CLI `defects`+ checked its file inside the main store, so under persistent storage it+ judged the file together with whatever the store held and left the file's+ triples behind in it; it now uses a store of its own, as the proxied form+ does. No other MCP-only check (`onto_dlp_boundary`, `onto_dl_check`) is a CLI+ command, so none is proxied and none was given a batch arm.- **`diff` and `drift` no longer hang on a symmetric blank-node graph** (#293).Both canonicalised blank nodes through oxrdf's RDFC-1.0, which sets no limiton `hash_n_degree_quads` calls, so the cost was factorial: a 7-nodediff --git a/README.md b/README.mdindex 514d220a..a9e8a6a6 100644--- a/README.md+++ b/README.md@@ -118,8 +118,9 @@ the part that survives examination.> **This is not an ontology editor.** Use Protégé to draw class hierarchies. You> run Open Ontologies on the change, before the change goes to production.>-> **The tool is like Terraform, and this is on purpose. But the plan is semantic,-> not syntactic.** A text diff is `git diff`, and you have `git diff` already.+> **The tool is like Terraform, and this is on purpose. But the plan checks what a+> change means and what it breaks, not only its text.** A text diff is `git diff`,+> and you have `git diff` already.You do not need a JVM. You do not need Protégé. The engine speaks MCP to Claude,to Cursor, and to other clients of that protocol.diff --git a/README.zh-CN.md b/README.zh-CN.mdindex df7d357a..56528201 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -110,7 +110,7 @@ new consequences 901 rule table owl-rl, in 0.04s> **这不是一个本体编辑器。**要绘制类层次结构,请使用 Protégé。你在变更进入生产环境之前,> 对这次变更运行 Open Ontologies。>-> **本工具在风格上类似 Terraform,这是刻意为之。但是这里的计划是语义层面的,不是语法层面的。**+> **本工具在风格上类似 Terraform,这是刻意为之。但是这里的计划检查变更的含义以及它会破坏什么,而不只是检查文本。**> 文本差异就是 `git diff`,而你已经有 `git diff` 了。你不需要 JVM。你不需要 Protégé。引擎通过 MCP 与 Claude、Cursor 以及该协议的其他客户端通信。diff --git a/docs/lifecycle.md b/docs/lifecycle.mdindex a55c2431..fdbcf19f 100644--- a/docs/lifecycle.md+++ b/docs/lifecycle.md@@ -33,24 +33,55 @@ therefore survive the process that computed them: `plan` and `apply` areseparate CLI invocations and separate MCP calls, and neither shares memory withthe other. The 100 most recent plans are retained.-### Conservativity: the one part of a plan that is about meaning+### Conservativity: what the change meansEverything above is about SHAPE. A change that adds one `rdfs:domain` triple addsno class, removes nothing, has a blast radius of zero and scores `low`, while-retyping every existing individual of that property. Pass-`check_conservativity: true` and the plan also reports whether the change alters-any consequence over the names the store already uses, with the rule and the-premises the base lacked behind every row.--It is opt-in because it reasons both graphs to a fixpoint, and when it is off the-`conservativity` block is still there and reads `ran: false` with the reason: a-missing block and a clean block look the same to a dashboard. It is never fatal;-a check that cannot run leaves `conservativity.skipped` set and the plan is still-returned. The verdict is a WORD rather than a boolean, and it is conservativity-with respect to a Horn rule table rather than in a description logic, which+retyping every existing individual of that property. The `conservativity` block+reports whether the change alters any consequence over the names the store+already uses, with the rule and the premises the base lacked behind every row.++It is on by default since #196 and costs a fixpoint over both graphs; skip it with+`--no-conservativity` (CLI and `batch`) or `check_conservativity: false`+(`onto_plan`). When it is off the `conservativity` block is still there and reads+`ran: false` with the reason: a missing block and a clean block look the same to a+dashboard. It is never fatal; a check that cannot run leaves+`conservativity.skipped` set and the plan is still returned. The verdict is a WORD+rather than a boolean, and it is conservativity with respect to a Horn rule table+rather than in a description logic, which[docs/modules-and-conservativity.md](modules-and-conservativity.md) states infull.+### Logic: what the change breaks++Conservativity does not see a change that breaks the ontology. Adding+`Manager rdfs:subClassOf Person` and `Manager owl:disjointWith Agent`, where+every `Person` is an `Agent`, leaves `Manager` with no possible instance; adding+`Machine owl:disjointWith Person` and `alice a Machine`, where `alice` is a+`Person`, makes the ABox inconsistent. Both remove nothing and both used to score+`low` (#336). The `logic` block answers this, relative to the store, so a defect+the store already had is never charged to the change:++| field | meaning |+|---|---|+| `new_defects` | findings of the eight `defects` kinds in the proposed graph that the store did not have; `null` if the check could not run |+| `new_defects_by_severity`, `new_defect_findings` | the same, by severity, and listed (at most 50) |+| `abox_consistent` | the owl-dl tableaux on the proposed graph: `false` on a clash it found, `true` only when the search finished and the graph uses no construct the tableaux does not model, otherwise `null` |+| `abox_consistent_before` | the same question of the store, asked only when the proposed graph is inconsistent; `null` otherwise |+| `checked_by`, `reason` | what ran, and in words why each answer is what it is; `not_checked` when skipped |++A new `error` or `warning` defect, or an inconsistency the store was not proven to+have, sets `risk_score` to `high`, and `risk_reasons` says which. An `info`+finding is listed and does not move the score. The consistency half runs under+the `[reasoner]` budget (`tableaux_test_timeout_ms` per phase, under+`classify_timeout_ms`), and a run that exhausts it reports `null` with the reason,+never `true`. Skip the whole block with `--no-logic-check` or+`check_logic: false`.++The exit code of `plan` does not change with the verdict: it is 1 on an error and+0 otherwise, as it always was for a `high` score from removals. A pipeline gates+on `risk_score` or `logic`.+## EnforceDesign pattern checks. Built-in packs: `generic` (orphan classes, missing labels), `boro` (IES4/BORO compliance), `value_partition` (disjointness). Custom SPARQL rules supported.@@ -60,6 +91,12 @@ Design pattern checks. Built-in packs: `generic` (orphan classes, missing labelsTwo modes: `safe` (write the delta) or `migrate` (same, plusowl:equivalentClass/Property bridges for consumers).+Apply does not re-judge the plan. It applies a plan whatever its `risk_score` or+`logic` block said, and the only gate is the monitor (`force` skips that too). A+change that removes terms on purpose has always been applicable at `high`, and an+apply that began refusing on a field it never read would break the pipelines+built on it without a word.+Apply writes only the triples that differ, so an unchanged graph costs nothingand a one-instance change touches one triple. `strategy` reports `delta`, or`reload` when blank nodes are present anywhere in either graph: bnode labels arediff --git a/src/batch.rs b/src/batch.rsindex 3e106024..d4d44b6a 100644--- a/src/batch.rs+++ b/src/batch.rs@@ -126,6 +126,7 @@ impl BatchRunner {"query" => self.exec_query(&cmd.args),"validate" => self.exec_validate(&cmd.args),"lint" => self.exec_lint(&cmd.args),+ "defects" => self.exec_defects(&cmd.args),"reason" => self.exec_reason(&cmd.args),"certificate-check" | "certificate_check" => self.exec_certificate_check(&cmd.args),"fol" => self.exec_fol(&cmd.args),@@ -281,6 +282,51 @@ impl BatchRunner {}}+ /// `defects [path] [--limit N]`. With a path, the file is checked alone,+ /// as the CLI subcommand checks it; without one, the batch's own store is,+ /// so `load x.ttl` then `defects` checks what was loaded. The CLI proxies+ /// `defects` here when a daemon is up, and there was no arm, so it answered+ /// `unknown batch command` and exited 1 (#336).+ fn exec_defects(&self, args: &[String]) -> Value {+ use crate::defects::Defects;+ let limit = match Self::flag_value(args, "--limit") {+ None => Defects::MAX_PER_KIND,+ Some(v) => match v.parse::<usize>() {+ Ok(n) => n,+ Err(_) => return json!({"error": format!("--limit takes a whole number, got '{v}'")}),+ },+ };+ let mut skip_next = false;+ let path = args.iter().find(|a| {+ if std::mem::take(&mut skip_next) {+ return false;+ }+ if a.as_str() == "--limit" {+ skip_next = true;+ return false;+ }+ !a.starts_with("--")+ });+ let graph = match path {+ None => self.graph.clone(),+ Some(p) => {+ let content = match crate::graph::GraphStore::read_as_turtle(p) {+ Ok(c) => c,+ Err(e) => return json!({"error": e.to_string()}),+ };+ let g = Arc::new(GraphStore::new());+ if let Err(e) = g.load_turtle(&content, None) {+ return json!({"error": e.to_string()});+ }+ g+ }+ };+ match Defects::check_with_limit(&graph, limit) {+ Ok(result) => serde_json::from_str(&result).unwrap_or(json!({"raw": result})),+ Err(e) => json!({"error": e.to_string()}),+ }+ }+fn exec_reason(&self, args: &[String]) -> Value {use crate::reason::{InferenceTarget, Reasoner};let profile = Self::flag_value(args, "--profile")@@ -960,7 +1006,12 @@ impl BatchRunner {max_rows: 1_000_000,}});- let result = planner.plan_checked(&turtle, opts)+ // The logic check (#336) is on by default for the same reason.+ let checks = crate::plan::PlanChecks {+ conservativity: opts,+ logic: !args.iter().any(|a| a == "--no-logic-check"),+ };+ let result = planner.plan_with(&turtle, checks).unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));serde_json::from_str(&result).unwrap_or(json!({"raw": result}))}diff --git a/src/inputs.rs b/src/inputs.rsindex 54aef40b..93e2b588 100644--- a/src/inputs.rs+++ b/src/inputs.rs@@ -592,8 +592,8 @@ pub struct OntoPlanInput {/// DEFAULT TRUE since #196. Pass `false` to skip it, and the plan then says/// it did not look rather than staying silent.///- /// This is the only part of a plan that is about MEANING. Everything else- /// is shape, and shape cannot see the change that matters most: adding one+ /// This asks what the change MEANS; `check_logic` asks what it breaks.+ /// Everything else is shape, and shape cannot see the change that matters most: adding one/// `rdfs:domain` triple adds no class, removes nothing, has a blast radius/// of zero and scores `low`, while retyping every existing individual of/// that property.@@ -614,6 +614,18 @@ pub struct OntoPlanInput {/// reproducible by hand. Defaults to a temporary directory.#[serde(default)]pub conservativity_out_dir: Option<String>,+ /// Also ask whether the change BREAKS something (#336): a TBox self-defect+ /// the store did not have (the eight kinds of `onto_defects`, such as a+ /// class made disjoint with its own ancestor), or a proposed graph the+ /// owl-dl tableaux proves inconsistent where the store was not. Either one+ /// makes `risk_score` `high`.+ ///+ /// DEFAULT TRUE. Pass `false` to skip it; the `logic` block then says+ /// `checked_by: "not_checked"` with every verdict `null`. The consistency+ /// half runs under the `[reasoner]` budget, and a run that exhausts it+ /// reports `abox_consistent: null` with the reason, never `true`.+ #[serde(default)]+ pub check_logic: Option<bool>,}/// Input for `onto_module_extract` — a locality module, not a slice.diff --git a/src/main.rs b/src/main.rsindex bdcbf993..1e645563 100644--- a/src/main.rs+++ b/src/main.rs@@ -840,12 +840,20 @@ enum Commands {/// Plan changes: diff current vs proposed TurtlePlan {file: String,- /// Skip the conservativity check, which is the only part of a plan- /// that is about MEANING and is ON by default since #196. It reasons+ /// Skip the conservativity check, which asks what the change MEANS+ /// and is ON by default since #196. It reasons/// both graphs to a fixpoint, about 11 microseconds an individual, so/// this is the thing to reach for on a store big enough that it hurts.#[arg(long)]no_conservativity: bool,+ /// Skip the logic check (#336): the eight TBox self-defect kinds of+ /// `defects` on the proposed graph against the store, and the owl-dl+ /// consistency of the proposed graph under the [reasoner] budget. ON by+ /// default; a new defect or an inconsistency the store did not have+ /// makes risk_score `high`. The exit code stays 0 either way: read+ /// `risk_score` and `logic` to gate on it.+ #[arg(long)]+ no_logic_check: bool,},/// Apply planned changes (safe or migrate)Apply {@@ -1400,11 +1408,14 @@ impl Commands {}cmd("ingest", a)}- Commands::Plan { file, no_conservativity } => {+ Commands::Plan { file, no_conservativity, no_logic_check } => {let mut a = vec![absolutize(file)];if *no_conservativity {a.push("--no-conservativity".into());}+ if *no_logic_check {+ a.push("--no-logic-check".into());+ }cmd("plan", a)}Commands::Apply { mode, plan_id } => {@@ -2788,7 +2799,12 @@ async fn async_main() -> anyhow::Result<()> {}Commands::Defects { input, limit } => {use open_ontologies::defects::Defects;- let (_db, graph) = setup(&cli.data_dir)?;+ // The FILE is checked, alone, in a store of its own. This used to+ // load it into the main store, so under persistent storage it was+ // checked together with whatever the store held and its triples+ // were left behind in it, while the same command proxied to a+ // daemon checked the file alone.+ let graph = std::sync::Arc::new(GraphStore::new());let raw = if input == "-" {let mut buf = String::new();std::io::Read::read_to_string(&mut std::io::stdin(), &mut buf)?;@@ -3599,7 +3615,7 @@ async fn async_main() -> anyhow::Result<()> {}// ─── Lifecycle ──────────────────────────────────────────────- Commands::Plan { file, no_conservativity } => {+ Commands::Plan { file, no_conservativity, no_logic_check } => {let (db, graph) = setup(&cli.data_dir)?;let turtle = std::fs::read_to_string(&file)?;let planner = open_ontologies::plan::Planner::new(db, graph);@@ -3616,9 +3632,17 @@ async fn async_main() -> anyhow::Result<()> {max_rows: 1_000_000,}});+ let checks = open_ontologies::plan::PlanChecks {+ conservativity: opts,+ logic: !no_logic_check,+ };let result = planner- .plan_checked(&turtle, opts)+ .plan_with(&turtle, checks).unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));+ // Exit 1 on an error only, as before. A plan is a report, and a+ // `high` risk_score has always exited 0 when it came from removals;+ // one that comes from the logic check does the same, so a pipeline+ // gates on `risk_score` / `logic` and one rule covers both.output_result_checked(&result, cli.pretty);}Commands::Apply { mode, plan_id } => {@@ -4072,7 +4096,7 @@ mod proxy_serialization_tests {#[test]fn an_absolute_path_is_left_alone() {let abs = if cfg!(windows) { r"C:\onto\proposed.ttl" } else { "/onto/proposed.ttl" };- let (_, args) = args_of(&Commands::Plan { file: abs.into(), no_conservativity: false });+ let (_, args) = args_of(&Commands::Plan { file: abs.into(), no_conservativity: false, no_logic_check: false });assert_eq!(args, vec![abs.to_string()]);}@@ -4160,7 +4184,9 @@ mod proxy_serialization_tests {Commands::History,Commands::Rollback { label: "v1".into() },Commands::Ingest { path: "x.csv".into(), format: None, mapping: None, base_iri: None },- Commands::Plan { file: "p.ttl".into(), no_conservativity: false },+ Commands::Plan { file: "p.ttl".into(), no_conservativity: false, no_logic_check: false },+ Commands::Plan { file: "p.ttl".into(), no_conservativity: true, no_logic_check: true },+ Commands::Defects { input: "x.ttl".into(), limit: 0 },Commands::Apply { mode: "safe".into(), plan_id: None },Commands::Enforce { pack: "generic".into() },Commands::Monitor,diff --git a/src/plan.rs b/src/plan.rsindex adbf6683..6b3f6704 100644--- a/src/plan.rs+++ b/src/plan.rs@@ -52,6 +52,53 @@ struct PlanState {removed_properties: Vec<String>,}+/// Which of a plan's semantic checks run.+///+/// Both are on at every entry point by default (the `plan` subcommand,+/// `batch`'s `plan`, `onto_plan`), and each has its own opt-out: conservativity+/// with `--no-conservativity` / `check_conservativity=false`, the logic check+/// with `--no-logic-check` / `check_logic=false`.+pub struct PlanChecks {+ /// Run the conservativity check with these options, or not at all.+ pub conservativity: Option<crate::conservativity::ConservativityOptions>,+ /// Run the logic check (#336): new TBox self-defects and the consistency+ /// of the proposed graph.+ pub logic: bool,+}++/// The `logic` block of a plan, and the reasons it gives for raising+/// `risk_score` to `high`, if any.+struct LogicVerdict {+ json: serde_json::Value,+ raises_risk: Vec<String>,+}++impl LogicVerdict {+ /// A block that says it did not look, with every verdict field `null`.+ fn not_checked(reason: String) -> Self {+ Self {+ json: serde_json::json!({+ "checked_by": "not_checked",+ "new_defects": null,+ "new_defects_by_severity": null,+ "new_defect_findings": null,+ "abox_consistent": null,+ "abox_consistent_before": null,+ "individuals_checked": null,+ "reason": reason,+ }),+ raises_risk: Vec::new(),+ }+ }+}++/// A three-valued consistency answer and the sentence that explains it.+struct Consistency {+ consistent: Option<bool>,+ individuals_checked: Option<usize>,+ note: String,+}+type Triple = (String, String, String);/// The triple-level difference between the store and a proposed graph.@@ -101,31 +148,45 @@ impl Planner {}/// Compute a diff plan between current store and proposed new Turtle.+ ///+ /// The logic check runs; conservativity does not. See [`Planner::plan_with`].pub fn plan(&self, new_turtle: &str) -> anyhow::Result<String> {self.plan_checked(new_turtle, None)}- /// [`Planner::plan`], optionally answering the semantic question as well as- /// the syntactic one.- ///- /// Everything else a plan reports is about SHAPE: which classes appear,- /// which disappear, how many triples move. None of it can tell you that- /// adding one `rdfs:domain` silently reclassified nine hundred existing- /// individuals, because that change adds no class and removes nothing. The- /// conservativity block is the only part of a plan that is about MEANING,- /// and it is opt-in because it reasons both graphs to a fixpoint, which is- /// seconds rather than milliseconds on a real store.- ///- /// It is never fatal. A plan whose conservativity check could not run says- /// so in `conservativity.skipped` and still returns the plan, because a- /// diagnostic that can block a plan is a diagnostic people turn off.+ /// [`Planner::plan`], optionally answering the conservativity question as+ /// well. The logic check runs; [`Planner::plan_with`] can switch it off.pub fn plan_checked(&self,new_turtle: &str,conservativity: Option<crate::conservativity::ConservativityOptions>,) -> anyhow::Result<String> {+ self.plan_with(new_turtle, PlanChecks { conservativity, logic: true })+ }++ /// The plan, with the semantic checks `checks` asks for.+ ///+ /// Everything a plan reports from the diff alone is about SHAPE: which+ /// classes appear, which disappear, how many triples move. None of it can+ /// tell you that adding one `rdfs:domain` silently reclassified nine+ /// hundred existing individuals, because that change adds no class and+ /// removes nothing. Two blocks are about MEANING, and they answer different+ /// questions:+ ///+ /// * `conservativity`: does the change alter any consequence over the+ /// names the store already uses, under a Horn rule table? It reasons+ /// both graphs to a fixpoint, which is seconds rather than milliseconds+ /// on a real store.+ /// * `logic` (#336): does the change BREAK something? A named class left+ /// with no possible instance, or an ABox that is now inconsistent. Before+ /// it existed both scored `low`, because neither removes anything.+ ///+ /// Neither is fatal. A check that could not run says so in its block and+ /// the plan is still returned, because a diagnostic that can block a plan+ /// is a diagnostic people turn off.+ pub fn plan_with(&self, new_turtle: &str, checks: PlanChecks) -> anyhow::Result<String> {let mut result: serde_json::Value = serde_json::from_str(&self.plan_inner(new_turtle)?)?;- result["conservativity"] = match conservativity {+ result["conservativity"] = match checks.conservativity {None => serde_json::json!({"ran": false,"skipped": "not requested. Pass check_conservativity=true to ask whether this \@@ -150,9 +211,222 @@ impl Planner {}}};++ let logic = if checks.logic {+ self.logic_verdict(new_turtle)+ } else {+ LogicVerdict::not_checked(+ "skipped on request (--no-logic-check, or check_logic=false). This plan does not \+ say whether the change makes a class unsatisfiable or the ABox inconsistent, and \+ risk_score is computed from the shape of the change alone."+ .to_string(),+ )+ };+ if !logic.raises_risk.is_empty() {+ result["risk_score"] = serde_json::json!("high");+ if let Some(reasons) = result["risk_reasons"].as_array_mut() {+ reasons.extend(logic.raises_risk.iter().map(|r| serde_json::json!(r)));+ }+ }+ result["logic"] = logic.json;Ok(result.to_string())}+ /// The `logic` block of a plan: what the change breaks, judged against+ /// what the store already had.+ ///+ /// Two checks, both relative to the store, because a plan is about the+ /// change and not about the ontology: a store that already had a cycle+ /// must not make every later plan look as though it caused one.+ ///+ /// 1. The eight TBox self-defect kinds of `defects`, on the proposed graph+ /// and on the store; only findings the store did not have are counted.+ /// These are SPARQL queries over the declarations and need no budget.+ /// 2. Consistency of the proposed graph by the owl-dl tableaux (TBox and+ /// ABox), under the same `[reasoner]` budget every owl-dl run uses. The+ /// store is checked only when the proposed graph is proven+ /// inconsistent, since that is the only case where its answer changes+ /// the verdict, and it is the expensive half.+ ///+ /// Three values, never two. `abox_consistent` is `false` only on a clash+ /// the tableaux found, and `true` only when the search finished AND the+ /// graph uses no construct the tableaux does not model. Anything else is+ /// `null` with the reason, because `true` would say "we looked and found+ /// nothing" about a search that stopped, or about a weaker axiom set than+ /// the one stated.+ fn logic_verdict(&self, new_turtle: &str) -> LogicVerdict {+ use crate::defects::{Defects, Finding};++ let checked_by = "defects: the eight TBox self-defect kinds, proposed graph against the \+ store; owl-dl tableaux (SHIQ): consistency of the proposed graph, and of \+ the store when the proposed graph is inconsistent, under the [reasoner] \+ budget";+ let proposed = Arc::new(GraphStore::new());+ if let Err(e) = proposed.load_turtle(new_turtle, None) {+ return LogicVerdict::not_checked(format!("the proposed graph could not be read: {e}"));+ }++ let mut notes: Vec<String> = Vec::new();+ let mut raises_risk: Vec<String> = Vec::new();++ // ── 1. New TBox self-defects ──────────────────────────────────────+ let new_findings: Option<Vec<Finding>> = match Defects::findings(&proposed) {+ Err(e) => {+ notes.push(format!("the defects check could not run on the proposed graph: {e}"));+ None+ }+ Ok(after) if after.is_empty() => Some(Vec::new()),+ Ok(after) => match Defects::findings(&self.graph) {+ Err(e) => {+ notes.push(format!(+ "the proposed graph has {} defect finding(s), and the store could not be \+ checked to tell which are new: {e}",+ after.len()+ ));+ None+ }+ Ok(before) => {+ let before: HashSet<Finding> = before.into_iter().collect();+ Some(after.into_iter().filter(|f| !before.contains(f)).collect())+ }+ },+ };+ let mut by_severity = serde_json::json!({"error": 0, "warning": 0, "info": 0});+ if let Some(found) = &new_findings {+ notes.push(format!(+ "defects: {} finding(s) in the proposed graph that the store did not have.",+ found.len()+ ));+ for f in found {+ if let Some(n) = by_severity[f.severity].as_u64() {+ by_severity[f.severity] = serde_json::json!(n + 1);+ }+ }+ // An `info` finding leaves every entailment intact and only a+ // reader uninformed, so it is listed and does not move the score.+ let serious: Vec<&Finding> =+ found.iter().filter(|f| f.severity != "info").collect();+ if !serious.is_empty() {+ let first = serious[0];+ raises_risk.push(format!(+ "the change introduces {} error- or warning-severity defect(s) the store did \+ not have, the first {} on {}",+ serious.len(),+ first.kind,+ first.subject+ ));+ }+ }++ // ── 2. Consistency ───────────────────────────────────────────────+ let after = Self::decide_consistency(&proposed);+ notes.push(format!("proposed graph: {}", after.note));+ let before = if after.consistent == Some(false) {+ let b = Self::decide_consistency(&self.graph);+ notes.push(format!("store: {}", b.note));+ if b.consistent != Some(false) {+ raises_risk.push(+ "the proposed graph is inconsistent and the store was not proven inconsistent"+ .to_string(),+ );+ }+ b.consistent+ } else {+ None+ };++ let json = serde_json::json!({+ "checked_by": checked_by,+ "new_defects": new_findings.as_ref().map(Vec::len),+ "new_defects_by_severity": new_findings.as_ref().map(|_| by_severity),+ "new_defect_findings": new_findings.as_ref().map(|found| {+ found+ .iter()+ .take(crate::defects::Defects::MAX_PER_KIND)+ .map(Finding::to_json)+ .collect::<Vec<_>>()+ }),+ "abox_consistent": after.consistent,+ "abox_consistent_before": before,+ "individuals_checked": after.individuals_checked,+ "reason": notes.join(" "),+ });+ LogicVerdict { json, raises_risk }+ }++ /// Whether `graph` is consistent, three-valued, with the reason in words.+ fn decide_consistency(graph: &Arc<GraphStore>) -> Consistency {+ use crate::tableaux::{Concept, DlReasoner};+ let reasoner = match DlReasoner::from_graph(graph) {+ Ok(r) => r,+ Err(e) => {+ return Consistency {+ consistent: None,+ individuals_checked: None,+ note: format!("not checked: the tableaux could not read the graph: {e}"),+ };+ }+ };+ let tbox = reasoner.decide_satisfiable(&Concept::Top);+ if tbox.is_unsat() {+ return Consistency {+ consistent: Some(false),+ individuals_checked: None,+ note: "inconsistent: the TBox admits no model (owl:Thing is unsatisfiable)."+ .to_string(),+ };+ }+ let abox = reasoner.check_abox();+ if !abox.consistent {+ return Consistency {+ consistent: Some(false),+ individuals_checked: Some(abox.individuals_checked),+ note: format!(+ "inconsistent: the tableaux found a clash in the ABox over {} individual(s).",+ abox.individuals_checked+ ),+ };+ }+ if tbox.is_unknown() || abox.undecided {+ let phase = if tbox.is_unknown() { "TBox consistency" } else { "ABox" };+ let by = abox.stopped_by.unwrap_or("time or steps");+ return Consistency {+ consistent: None,+ individuals_checked: Some(abox.individuals_checked),+ note: format!(+ "not decided: the {phase} check ran out of its reasoner budget (stopped by \+ {by}) before it finished, so no clash was found and none was ruled out. \+ Raise [reasoner] tableaux_test_timeout_ms or classify_timeout_ms, or pass \+ --no-logic-check to skip the check."+ ),+ };+ }+ let unmodelled = DlReasoner::unmodelled_constructs(graph);+ if !unmodelled.is_empty() {+ let names: Vec<String> =+ unmodelled.iter().map(|(k, n)| format!("{k} ({n})")).collect();+ return Consistency {+ consistent: None,+ individuals_checked: Some(abox.individuals_checked),+ note: format!(+ "not decided: the graph uses {} which the tableaux does not model, so finding \+ no clash over the remaining axioms is not a proof that the whole graph is \+ consistent.",+ names.join(", ")+ ),+ };+ }+ Consistency {+ consistent: Some(true),+ individuals_checked: Some(abox.individuals_checked),+ note: format!(+ "consistent: the search finished with no clash over {} individual(s), and the \+ graph uses no construct the tableaux does not model.",+ abox.individuals_checked+ ),+ }+ }+fn plan_inner(&self, new_turtle: &str) -> anyhow::Result<String> {let current_classes = self.extract_classes_from_store(&self.graph);let current_properties = self.extract_properties_from_store(&self.graph);@@ -212,13 +486,30 @@ impl Planner {let removes_anything = !removed_classes.is_empty()|| !removed_properties.is_empty()|| !removed_individuals.is_empty();- let risk_score = if removes_anything && triples_affected > 0 {- "high"+ let removed_terms =+ removed_classes.len() + removed_properties.len() + removed_individuals.len();+ let (risk_score, mut risk_reasons) = if removes_anything && triples_affected > 0 {+ (+ "high",+ vec![format!(+ "the change removes {removed_terms} term(s) that {triples_affected} triple(s) \+ in the store refer to"+ )],+ )} else if removes_anything {- "medium"+ (+ "medium",+ vec![format!("the change removes {removed_terms} term(s)")],+ )} else {- "low"+ ("low", Vec::new())};+ if !locked_violations.is_empty() {+ risk_reasons.push(format!(+ "the change removes {} locked IRI(s)",+ locked_violations.len()+ ));+ }// Persist the plan. It has to outlive this `Planner` — see `store_plan`.let plan_id = self.store_plan(@@ -247,6 +538,9 @@ impl Planner {},"locked_violations": locked_violations,"risk_score": risk_score,+ // Why the score is what it is, one sentence per cause. Empty when+ // it is `low`. The logic check appends its own causes.+ "risk_reasons": risk_reasons,});Ok(result.to_string())@@ -254,6 +548,16 @@ impl Planner {/// Apply the most recent plan./// Modes: "safe" (clear + reload), "force" (same but ignores monitor), "migrate" (adds bridges)+ ///+ /// Apply does not re-judge the plan. It applies what was planned whatever+ /// the plan's `risk_score` or `logic` block said, exactly as it always has+ /// for a `high` score from removals; the only gate here is the monitor. A+ /// change that removes terms on purpose, or that is meant to land while a+ /// known inconsistency is fixed in the next change, has to stay applicable,+ /// and an apply that started refusing on a field it never used to read+ /// would break every pipeline built on it without a word. The verdict is in+ /// the plan's output for the pipeline to gate on: `risk_score`,+ /// `risk_reasons`, and `logic`.pub fn apply(&self, mode: &str) -> anyhow::Result<String> {self.apply_plan(None, mode)}diff --git a/src/server.rs b/src/server.rsindex 99631692..5fd899c8 100644--- a/src/server.rs+++ b/src/server.rs@@ -2502,7 +2502,7 @@ impl OpenOntologiesServer {// ── v2: Lifecycle tools ─────────────────────────────────────────────────- #[tool(name = "onto_plan", description = "Terraform-style plan: diff current store against proposed Turtle. Shows added/removed classes/properties, blast radius, risk score, and locked IRI violations. All of that is about SHAPE. Pass check_conservativity=true for the one part that is about MEANING: whether the change alters any consequence over the names the store already uses, under the rule table in conservativity_profile. That is the check a shape diff cannot do — adding one rdfs:domain reclassifies every existing individual of that property while adding no class and removing nothing, so every other number in the plan stays green. It reasons both graphs to a fixpoint, so it is opt-in; when it is off the plan says so under `conservativity` rather than staying silent. Read the honesty note in onto_conservative_check before acting on the verdict: it is conservativity under a Horn rule table, not in a description logic.")]+ #[tool(name = "onto_plan", description = "Terraform-style plan: diff current store against proposed Turtle. Shows added/removed classes/properties, blast radius, risk score, and locked IRI violations. All of that is about SHAPE. Conservativity (on by default, check_conservativity=false skips it) asks what the change MEANS: whether the change alters any consequence over the names the store already uses, under the rule table in conservativity_profile. That is the check a shape diff cannot do — adding one rdfs:domain reclassifies every existing individual of that property while adding no class and removing nothing, so every other number in the plan stays green. It reasons both graphs to a fixpoint, which is why it can be switched off; when it is off the plan says so under `conservativity` rather than staying silent. Read the honesty note in onto_conservative_check before acting on the verdict: it is conservativity under a Horn rule table, not in a description logic. The `logic` block (on by default, check_logic=false skips it) asks whether the change BREAKS something: TBox self-defects the store did not have (the onto_defects kinds) and whether the owl-dl tableaux proves the proposed graph inconsistent where the store was not; either makes risk_score `high`, and `risk_reasons` says why. `abox_consistent` is null, never true, when the reasoner budget ran out or the graph uses a construct the tableaux does not model. onto_apply does not gate on any of this; the caller does.")]pub async fn onto_plan(&self, Parameters(input): Parameters<OntoPlanInput>) -> String {let planner = crate::plan::Planner::with_owner(self.db.clone(),@@ -2521,7 +2521,7 @@ impl OpenOntologiesServer {// microseconds an individual.//// A plan is a deliberate pre-production act, not an interactive query,- // and that cost buys the only part of a plan that is about MEANING. In+ // and that cost buys the part of a plan that asks what a change MEANS. In// the run above every shape number stayed at zero — no class added,// none removed, blast radius zero, risk low — while 901 consequences// appeared that were not there before. A safety check that is off by@@ -2551,7 +2551,13 @@ impl OpenOntologiesServer {..Default::default()}});- match planner.plan_checked(&input.new_turtle, conservativity) {+ // The logic check (#336) is on by default, like conservativity, and+ // through the same function as the CLI and batch.+ let checks = crate::plan::PlanChecks {+ conservativity,+ logic: input.check_logic.unwrap_or(true),+ };+ match planner.plan_with(&input.new_turtle, checks) {Ok(result) => {self.lineage().record(&self.session_id, "P", "plan", "computed");resultdiff --git a/tests/defects_cli_test.rs b/tests/defects_cli_test.rsindex 32dc4ef2..c59b02c7 100644--- a/tests/defects_cli_test.rs+++ b/tests/defects_cli_test.rs@@ -130,3 +130,49 @@ fn defects_limit_n_lists_n_and_reports_the_total() {assert_eq!(parsed["truncated"]["inherited_disjoint"].as_u64(), Some(80), "{parsed:#}");assert_eq!(parsed["affected_classes"].as_u64(), Some(80), "{parsed:#}");}++/// `defects x.ttl` checks the FILE. It used to load the file into the main+/// store, so under persistent storage it judged the file together with whatever+/// the store held and left the file's triples behind in it, while the same+/// command proxied to a daemon checked the file alone.+#[test]+fn defects_checks_the_file_alone_and_leaves_a_persistent_store_untouched() {+ let d = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(d.path().join("data")).unwrap();+ std::fs::write(+ d.path().join("data").join("config.toml"),+ "[storage]\nmode = 'persistent'\n",+ )+ .unwrap();+ let persistent = |args: &[&str]| -> (i32, String) {+ let out = Command::new(env!("CARGO_BIN_EXE_open-ontologies"))+ .env("OPEN_ONTOLOGIES_STORAGE_MODE", "persistent")+ .arg("--data-dir")+ .arg(d.path().join("data"))+ .arg("--no-connect")+ .args(args)+ .output()+ .expect("binary should run");+ (+ out.status.code().unwrap_or(-1),+ String::from_utf8_lossy(&out.stdout).into_owned(),+ )+ };+ let clean = write(d.path(), "good.ttl", CLEAN);+ let bad = write(d.path(), "bad.ttl", DEFECTIVE);+ let (code, out) = persistent(&["load", &clean]);+ assert_eq!(code, 0, "{out}");+ let triples = |out: &str| -> u64 {+ let v: serde_json::Value = serde_json::from_str(out.trim()).expect(out);+ v["triples"].as_u64().expect(out)+ };+ let before = triples(&persistent(&["stats"]).1);++ let (code, out) = persistent(&["defects", &bad]);+ assert_eq!(code, 0, "{out}");+ let report: serde_json::Value = serde_json::from_str(out.trim()).expect(&out);+ assert_eq!(report["defect_count"].as_u64(), Some(1), "{report:#}");++ let after = triples(&persistent(&["stats"]).1);+ assert_eq!(before, after, "checking a file must not write it into the store");+}diff --git a/tests/plan_logic_test.rs b/tests/plan_logic_test.rsnew file mode 100644index 00000000..01e9c01a--- /dev/null+++ b/tests/plan_logic_test.rs@@ -0,0 +1,358 @@+//! A plan asks whether the change is LOGICALLY safe, not only how big it is (#336).+//!+//! `risk_score` was derived from removal counts alone. A change that made a named+//! class unsatisfiable, or made the ABox inconsistent, removed nothing, touched no+//! existing triple, and scored `low`. Both checks that would have caught it worked+//! when asked (`defects` for the first, `reason --profile owl-dl` for the second);+//! the plan never asked them, and `defects` could not be asked through `batch` at+//! all, so a pipeline running `plan` and `apply` through `batch` promoted both.+//!+//! The two reproductions from the issue are R1 and R2 below. Each is run through+//! the library, the MCP handler, the CLI and `batch`, because those are four entry+//! points and the default has to be the same on all of them.+//!+//! The vocabulary is the repository's: a check that did not run, or ran out of+//! budget, reports `null` with the reason, never `true`, because `true` means "we+//! looked and found nothing".++mod common;++use open_ontologies::graph::GraphStore;+use open_ontologies::inputs::OntoPlanInput;+use open_ontologies::plan::{PlanChecks, Planner};+use open_ontologies::server::OpenOntologiesServer;+use open_ontologies::state::StateDb;+use rmcp::handler::server::wrapper::Parameters;+use std::path::Path;+use std::process::Command;+use std::sync::{Arc, Mutex};++/// The step budget is a process-wide setting, and one test here lowers it on+/// purpose. Every test that reasons holds this, so none of them runs under a+/// budget it did not ask for.+static BUDGET: Mutex<()> = Mutex::new(());++fn budget_lock() -> std::sync::MutexGuard<'static, ()> {+ BUDGET.lock().unwrap_or_else(|e| e.into_inner())+}++const BASE: &str = r#"+@prefix ex: <http://ex.org/> .+@prefix owl: <http://www.w3.org/2002/07/owl#> .+@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+ex:Agent a owl:Class .+ex:Person a owl:Class ; rdfs:subClassOf ex:Agent .+ex:hasParent a owl:ObjectProperty ; rdfs:domain ex:Person ; rdfs:range ex:Person .+ex:alice a ex:Person .+ex:bob a ex:Person .+"#;++/// R1: Manager is a Person, every Person is an Agent, and Manager is disjoint+/// from Agent. Manager can have no instances.+fn r1() -> String {+ format!(+ "{BASE}\nex:Manager a owl:Class ; rdfs:subClassOf ex:Person .\n\+ ex:Manager owl:disjointWith ex:Agent .\n"+ )+}++/// R2: alice is a Person in the base, Machine is disjoint from Person, and the+/// change says alice is a Machine. No class is unsatisfiable; the ABox is+/// inconsistent.+fn r2() -> String {+ format!(+ "{BASE}\nex:Machine a owl:Class ; owl:disjointWith ex:Person .\n\+ ex:alice a ex:Machine .\n"+ )+}++/// The control: a new subclass and a new individual, nothing contradicted.+fn benign() -> String {+ format!(+ "{BASE}\nex:Employee a owl:Class ; rdfs:subClassOf ex:Person .\n\+ ex:carol a ex:Employee .\n"+ )+}++fn planner_over(base: &str) -> (tempfile::TempDir, Planner) {+ let tmp = tempfile::tempdir().unwrap();+ let db = StateDb::open(&tmp.path().join("state.db")).unwrap();+ let graph = Arc::new(GraphStore::new());+ graph.load_turtle(base, None).unwrap();+ (tmp, Planner::new(db, graph))+}++fn plan(base: &str, proposed: &str) -> serde_json::Value {+ let _b = budget_lock();+ let (_tmp, planner) = planner_over(base);+ serde_json::from_str(&planner.plan(proposed).unwrap()).unwrap()+}++#[test]+fn r1_a_change_that_makes_a_class_unsatisfiable_is_high_risk() {+ let p = plan(BASE, &r1());+ assert_eq!(p["logic"]["new_defects"].as_u64(), Some(1), "{p:#}");+ let finding = &p["logic"]["new_defect_findings"][0];+ assert_eq!(finding["kind"], "disjoint_with_ancestor", "{p:#}");+ assert_eq!(finding["class"], "<http://ex.org/Manager>", "{p:#}");+ assert_eq!(+ p["risk_score"], "high",+ "a change that leaves a named class with no possible instance is not low risk: {p:#}"+ );+ assert!(+ p["risk_reasons"].as_array().is_some_and(|r| !r.is_empty()),+ "the plan says why the score is high: {p:#}"+ );+}++#[test]+fn r2_a_change_that_makes_the_abox_inconsistent_is_high_risk() {+ let p = plan(BASE, &r2());+ assert_eq!(p["logic"]["new_defects"].as_u64(), Some(0), "not a TBox self-defect: {p:#}");+ assert_eq!(p["logic"]["abox_consistent"], false, "{p:#}");+ assert_eq!(p["logic"]["abox_consistent_before"], true, "{p:#}");+ assert_eq!(p["risk_score"], "high", "{p:#}");+}++#[test]+fn a_benign_addition_stays_low_and_says_it_looked() {+ let p = plan(BASE, &benign());+ assert_eq!(p["logic"]["new_defects"].as_u64(), Some(0), "{p:#}");+ assert_eq!(p["logic"]["abox_consistent"], true, "{p:#}");+ assert_eq!(p["risk_score"], "low", "{p:#}");+}++#[test]+fn a_defect_the_store_already_had_is_not_new() {+ // The change did not cause it, so it must not make every later plan high.+ let broken_base = r1();+ let proposed = format!("{broken_base}\nex:Employee a owl:Class ; rdfs:subClassOf ex:Person .\n");+ let p = plan(&broken_base, &proposed);+ assert_eq!(p["logic"]["new_defects"].as_u64(), Some(0), "{p:#}");+ assert_eq!(p["risk_score"], "low", "{p:#}");+}++#[test]+fn an_inconsistency_the_store_already_had_is_not_a_flip() {+ let broken_base = r2();+ let proposed = format!("{broken_base}\nex:Employee a owl:Class ; rdfs:subClassOf ex:Person .\n");+ let p = plan(&broken_base, &proposed);+ assert_eq!(p["logic"]["abox_consistent"], false, "{p:#}");+ assert_eq!(p["logic"]["abox_consistent_before"], false, "{p:#}");+ assert_eq!(p["risk_score"], "low", "{p:#}");+}++#[test]+fn a_consistency_check_that_runs_out_of_budget_is_null_never_true() {+ let _b = budget_lock();+ let (_tmp, planner) = planner_over(BASE);+ // One step cannot finish any tableau with an individual in it.+ open_ontologies::runtime::set_tableaux_max_steps(1);+ let raw = planner.plan(&benign());+ open_ontologies::runtime::set_tableaux_max_steps(0);+ let p: serde_json::Value = serde_json::from_str(&raw.unwrap()).unwrap();+ assert!(+ p["logic"]["abox_consistent"].is_null(),+ "a check that gave up has not looked, so it must not say true: {p:#}"+ );+ assert!(+ p["logic"]["reason"].as_str().is_some_and(|r| r.contains("budget")),+ "and it says why: {p:#}"+ );+}++#[test]+fn a_construct_the_tableaux_does_not_model_makes_a_clean_answer_null() {+ // owl:sameAs is read by no tableau rule here, so finding no clash over the+ // remaining axioms is not a proof that the whole graph is consistent.+ let proposed = format!("{BASE}\nex:alice owl:sameAs ex:alicia .\n");+ let p = plan(BASE, &proposed);+ assert!(p["logic"]["abox_consistent"].is_null(), "{p:#}");+ assert!(+ p["logic"]["reason"].as_str().is_some_and(|r| r.contains("owl:sameAs")),+ "{p:#}"+ );+}++#[test]+fn the_logic_check_can_be_switched_off_and_then_says_so() {+ let _b = budget_lock();+ let (_tmp, planner) = planner_over(BASE);+ let raw = planner+ .plan_with(&r1(), PlanChecks { conservativity: None, logic: false })+ .unwrap();+ let p: serde_json::Value = serde_json::from_str(&raw).unwrap();+ assert_eq!(p["logic"]["checked_by"], "not_checked", "{p:#}");+ assert!(p["logic"]["new_defects"].is_null(), "{p:#}");+ assert!(p["logic"]["abox_consistent"].is_null(), "{p:#}");+ assert!(p["logic"]["reason"].as_str().is_some_and(|r| !r.is_empty()), "{p:#}");+ // Off means the plan is back to shape alone, and R1 removes nothing.+ assert_eq!(p["risk_score"], "low", "{p:#}");+}++// ─── MCP ────────────────────────────────────────────────────────────────────++fn mcp_plan(proposed: &str, check_logic: Option<bool>) -> serde_json::Value {+ let _b = budget_lock();+ let tmp = tempfile::tempdir().unwrap();+ let db = StateDb::open(&tmp.path().join("state.db")).unwrap();+ let graph = Arc::new(GraphStore::new());+ graph.load_turtle(BASE, None).unwrap();+ let server = OpenOntologiesServer::new_with_graph(db, graph);+ let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();+ let out = rt.block_on(server.onto_plan(Parameters(OntoPlanInput {+ new_turtle: proposed.to_string(),+ check_conservativity: Some(false),+ conservativity_profile: None,+ conservativity_out_dir: None,+ check_logic,+ })));+ serde_json::from_str(&out).unwrap()+}++#[test]+fn onto_plan_runs_the_logic_check_by_default() {+ let p = mcp_plan(&r1(), None);+ assert_eq!(p["logic"]["new_defects"].as_u64(), Some(1), "{p:#}");+ assert_eq!(p["risk_score"], "high", "{p:#}");+}++#[test]+fn onto_plan_check_logic_false_opts_out() {+ let p = mcp_plan(&r2(), Some(false));+ assert_eq!(p["logic"]["checked_by"], "not_checked", "{p:#}");+ assert!(p["logic"]["abox_consistent"].is_null(), "{p:#}");+}++// ─── CLI and batch ──────────────────────────────────────────────────────────++fn run(dir: &Path, args: &[&str]) -> (i32, String, String) {+ let out = {+ let _gate = common::exec_gate();+ Command::new(env!("CARGO_BIN_EXE_open-ontologies"))+ .env("OPEN_ONTOLOGIES_STORAGE_MODE", "persistent")+ .arg("--data-dir")+ .arg(dir.join("data"))+ .arg("--no-connect")+ .args(args)+ .output()+ .expect("binary should run")+ };+ (+ out.status.code().unwrap_or(-1),+ String::from_utf8_lossy(&out.stdout).into_owned(),+ String::from_utf8_lossy(&out.stderr).into_owned(),+ )+}++fn write(dir: &Path, name: &str, body: &str) -> String {+ let p = dir.join(name);+ std::fs::write(&p, body).unwrap();+ p.to_str().unwrap().to_string()+}++fn store_dir() -> tempfile::TempDir {+ let d = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(d.path().join("data")).unwrap();+ std::fs::write(+ d.path().join("data").join("config.toml"),+ "[storage]\nmode = 'persistent'\n",+ )+ .unwrap();+ d+}++#[test]+fn cli_plan_reports_r1_high_and_keeps_exit_0() {+ let d = store_dir();+ let base = write(d.path(), "base.ttl", BASE);+ let proposed = write(d.path(), "r1.ttl", &r1());+ let (code, out, err) = run(d.path(), &["load", &base]);+ assert_eq!(code, 0, "{out}{err}");+ let (code, out, err) = run(d.path(), &["plan", &proposed, "--no-conservativity"]);+ let p: serde_json::Value = serde_json::from_str(out.trim()).unwrap_or_else(|e| panic!("{e}: {out}{err}"));+ assert_eq!(p["risk_score"], "high", "{p:#}");+ assert_eq!(p["logic"]["new_defects"].as_u64(), Some(1), "{p:#}");+ // A plan is a report, not a gate: a high score from removals has always+ // exited 0, and a high score from logic does the same. The verdict is in+ // the output for the pipeline to read.+ assert_eq!(code, 0, "{out}{err}");+}++#[test]+fn cli_plan_no_logic_check_skips_it() {+ let d = store_dir();+ let base = write(d.path(), "base.ttl", BASE);+ let proposed = write(d.path(), "r2.ttl", &r2());+ run(d.path(), &["load", &base]);+ let (code, out, err) = run(+ d.path(),+ &["plan", &proposed, "--no-conservativity", "--no-logic-check"],+ );+ assert_eq!(code, 0, "{out}{err}");+ let p: serde_json::Value = serde_json::from_str(out.trim()).unwrap_or_else(|e| panic!("{e}: {out}{err}"));+ assert_eq!(p["logic"]["checked_by"], "not_checked", "{p:#}");+}++fn batch(d: &Path, lines: &[String]) -> (i32, Vec<serde_json::Value>) {+ let script = write(d, "script.txt", &(lines.join("\n") + "\n"));+ let (code, out, err) = run(d, &["batch", &script]);+ let results = out+ .lines()+ .filter(|l| !l.trim().is_empty())+ .map(|l| serde_json::from_str(l).unwrap_or_else(|e| panic!("{e}: {l}\n{err}")))+ .collect();+ (code, results)+}++#[test]+fn batch_plan_reports_r2_high() {+ let d = store_dir();+ let base = write(d.path(), "base.ttl", BASE);+ let proposed = write(d.path(), "r2.ttl", &r2());+ let (_, results) = batch(+ d.path(),+ &[format!("load {base}"), format!("plan {proposed} --no-conservativity")],+ );+ let p = &results[1]["result"];+ assert_eq!(p["logic"]["abox_consistent"], false, "{p:#}");+ assert_eq!(p["risk_score"], "high", "{p:#}");+}++#[test]+fn batch_plan_no_logic_check_skips_it() {+ let d = store_dir();+ let base = write(d.path(), "base.ttl", BASE);+ let proposed = write(d.path(), "r2.ttl", &r2());+ let (_, results) = batch(+ d.path(),+ &[+ format!("load {base}"),+ format!("plan {proposed} --no-conservativity --no-logic-check"),+ ],+ );+ assert_eq!(results[1]["result"]["logic"]["checked_by"], "not_checked", "{:#}", results[1]);+}++#[test]+fn batch_runs_defects_on_a_file_and_on_the_store() {+ // `defects` had no batch arm, so this answered+ // {"error":"unknown batch command: 'defects'"} and exited 1.+ let d = store_dir();+ let r1_file = write(d.path(), "r1.ttl", &r1());+ let (code, results) = batch(+ d.path(),+ &[+ format!("defects {r1_file}"),+ format!("load {r1_file}"),+ "defects --limit 0".to_string(),+ ],+ );+ assert_eq!(code, 0, "{results:#?}");+ for r in [&results[0]["result"], &results[2]["result"]] {+ assert!(r.get("error").is_none(), "{r:#}");+ assert_eq!(r["severity_counts"]["error"].as_u64(), Some(1), "{r:#}");+ assert_eq!(r["affected_classes"].as_u64(), Some(1), "{r:#}");+ }+ assert_eq!(results[2]["result"]["limit_per_kind"].as_u64(), Some(0), "{:#}", results[2]);+}diff --git a/tests/plan_mcp_test.rs b/tests/plan_mcp_test.rsindex 954ec78c..fc25e5b2 100644--- a/tests/plan_mcp_test.rs+++ b/tests/plan_mcp_test.rs@@ -37,6 +37,7 @@ fn plan_defaults() -> OntoPlanInput {check_conservativity: None,conservativity_profile: None,conservativity_out_dir: None,+ check_logic: None,}}