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
fix(plan): make apply work at all, see the ABox, and stop fabricating bridges
FABIOTESS9e323256e498
diff --git a/docs/lifecycle.md b/docs/lifecycle.mdindex de0f421c..4719c6c6 100644--- a/docs/lifecycle.md+++ b/docs/lifecycle.md@@ -19,7 +19,19 @@ flowchart LR## Plan-Diffs current vs proposed ontology. Reports added/removed classes, blast radius, risk score (`low`/`medium`/`high`). Locked IRIs (`onto_lock`) prevent accidental removal.+Diffs current vs proposed ontology. Reports added/removed classes, properties+and **individuals**, the triple-level delta, blast radius, and a risk score+(`low`/`medium`/`high`). Locked IRIs (`onto_lock`) prevent accidental removal.++The proposed Turtle is the complete desired state, as in Terraform: anything+absent from it is removed. The plan therefore reports instance data as well as+the TBox, because an apply deletes both — a removal of any kind is at least+`medium` risk, and `high` once other triples reference it.++Every plan is persisted in the state database and returned as a `plan_id`. Plans+therefore survive the process that computed them: `plan` and `apply` are+separate CLI invocations and separate MCP calls, and neither shares memory with+the other. The 100 most recent plans are retained.## Enforce@@ -27,7 +39,35 @@ Design pattern checks. Built-in packs: `generic` (orphan classes, missing labels## Apply-Two modes: `safe` (clear + reload) or `migrate` (add owl:equivalentClass/Property bridges for consumers).+Two modes: `safe` (write the delta) or `migrate` (same, plus+owl:equivalentClass/Property bridges for consumers).++Apply writes only the triples that differ, so an unchanged graph costs nothing+and a one-instance change touches one triple. `strategy` reports `delta`, or+`reload` when blank nodes are present anywhere in either graph: bnode labels are+store-local, so a set difference over them is meaningless and `DELETE DATA` /+`INSERT DATA` cannot carry them at all. The result is the same either way.++Applies the most recent plan by default. Pass a `plan_id` (`--plan-id` on the+CLI, `plan_id` to `onto_apply`) to apply a specific one; an id that does not+match a stored plan is an error rather than a silent fall-back to the latest.++```bash+oo plan proposed.ttl # prints plan_id+oo apply safe --plan-id plan-0a1b2c3d… # or just: oo apply safe+```++### Rename bridges++`migrate` pairs each removed term with a replacement using `DriftDetector`, the+same calibrated rename detector `onto_drift` uses, assigned one-to-one so no+addition can be declared the replacement for two different removals. Pairs below+a name/label similarity of 0.6 are declined.++`owl:equivalentClass` is a hard logical assertion, so a wrong bridge is worse+than a missing one. Every bridge is reported with its similarity score in+`bridges`, and every removal the matcher declined is named in+`unbridged_removals` — check both before trusting a migration.## Monitordiff --git a/src/batch.rs b/src/batch.rsindex da2c63d9..4b13e19a 100644--- a/src/batch.rs+++ b/src/batch.rs@@ -288,9 +288,14 @@ impl BatchRunner {}fn exec_apply(&self, args: &[String]) -> Value {- let mode = args.first().map(|s| s.as_str()).unwrap_or("safe");+ let plan_id = Self::flag_value(args, "--plan-id");+ let mode = args+ .iter()+ .find(|a| !a.starts_with("--") && Some(a.as_str()) != plan_id.as_deref())+ .map(|s| s.as_str())+ .unwrap_or("safe");let planner = crate::plan::Planner::new(self.db.clone(), self.graph.clone());- let result = planner.apply(mode)+ let result = planner.apply_plan(plan_id.as_deref(), mode).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 65270734..c8decb9d 100644--- a/src/inputs.rs+++ b/src/inputs.rs@@ -301,6 +301,8 @@ pub struct OntoPlanInput {pub struct OntoApplyInput {/// Apply mode: "safe" (default), "force" (ignores monitor), "migrate" (adds bridges)pub mode: Option<String>,+ /// Plan to apply, as returned by `onto_plan`. Defaults to the most recent plan.+ pub plan_id: Option<String>,}#[derive(Deserialize, JsonSchema)]diff --git a/src/lineage.rs b/src/lineage.rsindex 55360f88..65a8ca9f 100644--- a/src/lineage.rs+++ b/src/lineage.rs@@ -84,7 +84,7 @@ impl LineageLog {}}-fn rand_id() -> u64 {+pub(crate) fn rand_id() -> u64 {use std::sync::atomic::{AtomicU64, Ordering};use std::time::SystemTime;static COUNTER: AtomicU64 = AtomicU64::new(0);diff --git a/src/main.rs b/src/main.rsindex 7e45e883..eae79a08 100644--- a/src/main.rs+++ b/src/main.rs@@ -422,6 +422,9 @@ enum Commands {Apply {#[arg(default_value = "safe")]mode: String,+ /// Plan to apply, as printed by `plan`. Defaults to the most recent plan.+ #[arg(long)]+ plan_id: Option<String>,},/// Lock IRIs to prevent removalLock {@@ -1917,11 +1920,11 @@ async fn async_main() -> anyhow::Result<()> {.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));output_result(&result, cli.pretty);}- Commands::Apply { mode } => {+ Commands::Apply { mode, plan_id } => {let (db, graph) = setup(&cli.data_dir)?;let planner = open_ontologies::plan::Planner::new(db, graph);let result = planner- .apply(&mode)+ .apply_plan(plan_id.as_deref(), &mode).unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e));output_result(&result, cli.pretty);}diff --git a/src/plan.rs b/src/plan.rsindex 7ec19e3e..423f48d0 100644--- a/src/plan.rs+++ b/src/plan.rs@@ -1,18 +1,38 @@use crate::graph::GraphStore;use crate::monitor::Monitor;use crate::state::StateDb;-use std::cell::RefCell;+use rusqlite::OptionalExtension;use std::collections::HashSet;use std::sync::Arc;+/// Minimum name/label similarity before `migrate` will assert that one term+/// replaces another.+///+/// `owl:equivalentClass` is a hard logical assertion, so a wrong bridge is+/// worse than a missing one: downstream reasoners believe it. Measured over+/// the cases in `tests/plan_migrate_test.rs` and `tests/plan_test.rs`, true+/// renames score 0.62–0.98 and unrelated pairs 0.42–0.58, so the usable window+/// is narrow — which is the honest summary of what string similarity can do+/// here. Everything it declines is reported as `unbridged_removals` rather+/// than dropped, and every bridge it does make carries its score.+const MIGRATE_MIN_SIMILARITY: f64 = 0.6;++/// Largest number of triples put in a single DELETE DATA / INSERT DATA.+const DELTA_BATCH: usize = 500;++/// How many plans to keep. A long-lived server plans far more often than it+/// applies, and every plan stores a full copy of the proposed Turtle, so the+/// table is trimmed on write rather than left to grow without bound.+const PLAN_RETENTION: i64 = 100;+/// Terraform-style plan/apply/migrate for ontology changes.pub struct Planner {db: StateDb,graph: Arc<GraphStore>,- last_plan: RefCell<Option<PlanState>>,}struct PlanState {+ plan_id: String,new_turtle: String,added_classes: Vec<String>,removed_classes: Vec<String>,@@ -20,13 +40,43 @@ struct PlanState {removed_properties: Vec<String>,}+type Triple = (String, String, String);++/// The triple-level difference between the store and a proposed graph.+///+/// `plan()` used to diff only `?c a owl:Class` and `?p a owl:*Property`, so+/// instance data was invisible to it — while `apply()` cleared the whole store+/// and reloaded, deleting that same invisible data. Diffing at the triple level+/// is what lets the plan state what the apply is about to do (#91).+struct TripleDelta {+ insertions: Vec<Triple>,+ deletions: Vec<Triple>,+ /// Blank nodes are present somewhere in the two graphs, so `insertions` and+ /// `deletions` are empty and unusable: bnode labels are store-local, which+ /// makes a set difference over them meaningless, and neither `DELETE DATA`+ /// nor `INSERT DATA` may carry them at all. The caller reloads instead.+ reload: bool,+ current_total: usize,+ proposed_total: usize,+}++impl TripleDelta {+ fn counts(&self) -> (usize, usize) {+ if self.reload {+ (self.proposed_total, self.current_total)+ } else {+ (self.insertions.len(), self.deletions.len())+ }+ }++ fn strategy(&self) -> &'static str {+ if self.reload { "reload" } else { "delta" }+ }+}+impl Planner {pub fn new(db: StateDb, graph: Arc<GraphStore>) -> Self {- Self {- db,- graph,- last_plan: RefCell::new(None),- }+ Self { db, graph }}/// Compute a diff plan between current store and proposed new Turtle.@@ -41,17 +91,32 @@ impl Planner {let new_classes = self.extract_classes_from_store(&temp_store);let new_properties = self.extract_properties_from_store(&temp_store);+ let current_individuals = self.extract_individuals_from_store(&self.graph);+ let new_individuals = self.extract_individuals_from_store(&temp_store);+let added_classes: Vec<String> = new_classes.difference(¤t_classes).cloned().collect();let removed_classes: Vec<String> = current_classes.difference(&new_classes).cloned().collect();let added_properties: Vec<String> = new_properties.difference(¤t_properties).cloned().collect();let removed_properties: Vec<String> = current_properties.difference(&new_properties).cloned().collect();+ let added_individuals: Vec<String> = new_individuals.difference(¤t_individuals).cloned().collect();+ let removed_individuals: Vec<String> = current_individuals.difference(&new_individuals).cloned().collect();- // Blast radius: count triples referencing removed IRIs+ // Blast radius: count triples referencing removed IRIs. Individuals are+ // counted too — an apply deletes them just as surely as it deletes a+ // class, and the plan that stayed silent about them was the whole+ // complaint.let mut triples_affected: u64 = 0;- for iri in removed_classes.iter().chain(removed_properties.iter()) {+ for iri in removed_classes+ .iter()+ .chain(removed_properties.iter())+ .chain(removed_individuals.iter())+ {triples_affected += self.count_references(iri);}+ let delta = self.triple_delta(new_turtle)?;+ let (insertions, deletions) = delta.counts();+// Check locked IRIslet locked_violations: Vec<serde_json::Value> = removed_classes.iter()@@ -68,29 +133,42 @@ impl Planner {}).collect();- // Risk scoring- let risk_score = if !removed_classes.is_empty() && triples_affected > 0 {+ // Risk scoring. Any removal counts, including instance data: dropping+ // 194 individuals is not a low-risk change just because the TBox is+ // untouched.+ 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"- } else if !removed_classes.is_empty() || !removed_properties.is_empty() {+ } else if removes_anything {"medium"} else {"low"};- // Cache the plan state- *self.last_plan.borrow_mut() = Some(PlanState {- new_turtle: new_turtle.to_string(),- added_classes: added_classes.clone(),- removed_classes: removed_classes.clone(),- added_properties: added_properties.clone(),- removed_properties: removed_properties.clone(),- });+ // Persist the plan. It has to outlive this `Planner` — see `store_plan`.+ let plan_id = self.store_plan(+ new_turtle,+ &added_classes,+ &removed_classes,+ &added_properties,+ &removed_properties,+ )?;let result = serde_json::json!({+ "plan_id": plan_id,"added_classes": added_classes,"removed_classes": removed_classes,"added_properties": added_properties,"removed_properties": removed_properties,+ "added_individuals": added_individuals,+ "removed_individuals": removed_individuals,+ "triple_delta": {+ "insertions": insertions,+ "deletions": deletions,+ "strategy": delta.strategy(),+ },"blast_radius": {"triples_affected": triples_affected,},@@ -101,9 +179,19 @@ impl Planner {Ok(result.to_string())}- /// Apply the last planned changes.+ /// Apply the most recent plan./// Modes: "safe" (clear + reload), "force" (same but ignores monitor), "migrate" (adds bridges)pub fn apply(&self, mode: &str) -> anyhow::Result<String> {+ self.apply_plan(None, mode)+ }++ /// Apply a specific plan by id, or the most recent one when `plan_id` is+ /// `None`.+ ///+ /// An unknown id is an error rather than a fall-back to the latest plan:+ /// quietly applying something the caller did not name would apply changes+ /// they never reviewed, which is the opposite of what plan/apply is for.+ pub fn apply_plan(&self, plan_id: Option<&str>, mode: &str) -> anyhow::Result<String> {// Check monitor block (unless force mode)if mode != "force" {let monitor = Monitor::new(self.db.clone(), self.graph.clone());@@ -116,75 +204,306 @@ impl Planner {}}- let plan = self.last_plan.borrow();- let plan = match plan.as_ref() {- Some(p) => p,- None => anyhow::bail!("No plan found. Run plan() first."),- };+ let plan = self.load_plan(plan_id)?;if mode == "migrate" {- return self.apply_migrate(plan);+ return self.apply_migrate(&plan);}- // Safe/force mode: clear store, load new turtle- self.graph.clear()?;- let count = self.graph.load_turtle(&plan.new_turtle, None)?;+ // Safe/force mode: bring the store to the proposed state by writing+ // only what differs. The old implementation cleared the entire store+ // and reloaded `new_turtle` wholesale, which rewrote every triple on+ // every apply and made incremental ABox changes impossible to govern.+ let delta = self.triple_delta(&plan.new_turtle)?;+ let (inserted, deleted) = delta.counts();+ if delta.reload {+ self.graph.clear()?;+ self.graph.load_turtle(&plan.new_turtle, None)?;+ } else {+ self.write_delta(&delta)?;+ }+ self.mark_applied(&plan.plan_id, mode);Ok(serde_json::json!({"ok": true,+ "plan_id": plan.plan_id,"mode": mode,- "triples_loaded": count,+ "strategy": delta.strategy(),+ "triples_inserted": inserted,+ "triples_deleted": deleted,+ "triples_loaded": self.graph.triple_count(),"added_classes": plan.added_classes.len(),"removed_classes": plan.removed_classes.len(),}).to_string())}- fn apply_migrate(&self, plan: &PlanState) -> anyhow::Result<String> {- let mut migration_triples = 0u64;+ /// Triples that differ between the live store and `new_turtle`.+ fn triple_delta(&self, new_turtle: &str) -> anyhow::Result<TripleDelta> {+ let proposed_store = GraphStore::new();+ proposed_store.load_turtle(new_turtle, None)?;- // Generate equivalentClass/equivalentProperty bridges for renames- // Heuristic: if a class/property was removed and one was added, they might be renames- for removed in &plan.removed_classes {- if let Some(added) = plan.added_classes.first() {- // Generate equivalentClass bridge- let update = format!(- "INSERT DATA {{ <{}> <http://www.w3.org/2002/07/owl#equivalentClass> <{}> . \- <{}> <http://www.w3.org/2002/07/owl#deprecated> \"true\"^^<http://www.w3.org/2001/XMLSchema#boolean> . \- <{}> <http://www.w3.org/2000/01/rdf-schema#comment> \"Deprecated: migrated to {}\" . }}",- removed, added, removed, removed, added- );- if let Ok(n) = self.graph.sparql_update(&update) {- migration_triples += n as u64;- }+ let current: HashSet<Triple> = self.graph.all_triples()?.into_iter().collect();+ let proposed: HashSet<Triple> = proposed_store.all_triples()?.into_iter().collect();+ let current_total = current.len();+ let proposed_total = proposed.len();++ let is_bnode = |t: &Triple| t.0.starts_with("_:") || t.2.starts_with("_:");+ if current.iter().any(is_bnode) || proposed.iter().any(is_bnode) {+ return Ok(TripleDelta {+ insertions: Vec::new(),+ deletions: Vec::new(),+ reload: true,+ current_total,+ proposed_total,+ });+ }++ Ok(TripleDelta {+ insertions: proposed.difference(¤t).cloned().collect(),+ deletions: current.difference(&proposed).cloned().collect(),+ reload: false,+ current_total,+ proposed_total,+ })+ }++ fn write_delta(&self, delta: &TripleDelta) -> anyhow::Result<()> {+ // Deletions first: a triple that moves from one graph shape to another+ // must not be removed after it has been re-inserted.+ for (verb, triples) in [("DELETE", &delta.deletions), ("INSERT", &delta.insertions)] {+ for batch in triples.chunks(DELTA_BATCH) {+ let body: String = batch+ .iter()+ .map(|(s, p, o)| format!("{s} {p} {o} .\n"))+ .collect();+ self.graph.sparql_update(&format!("{verb} DATA {{ {body} }}"))?;}}+ Ok(())+ }- for removed in &plan.removed_properties {- if let Some(added) = plan.added_properties.first() {- let update = format!(- "INSERT DATA {{ <{}> <http://www.w3.org/2002/07/owl#equivalentProperty> <{}> . \- <{}> <http://www.w3.org/2002/07/owl#deprecated> \"true\"^^<http://www.w3.org/2001/XMLSchema#boolean> . \- <{}> <http://www.w3.org/2000/01/rdf-schema#comment> \"Deprecated: migrated to {}\" . }}",- removed, added, removed, removed, added- );- if let Ok(n) = self.graph.sparql_update(&update) {- migration_triples += n as u64;- }+ /// Persist a plan so a *different* `Planner` can apply it.+ ///+ /// The plan used to live in a `RefCell` on this struct, which meant it+ /// never survived the call that produced it: the `plan`/`apply` CLI+ /// subcommands, `batch`'s `exec_plan`/`exec_apply`, and the `onto_plan` /+ /// `onto_apply` MCP handlers each construct a fresh `Planner`, so `apply`+ /// always reported "No plan found" (#91). The state db is the one thing+ /// every caller shares.+ fn store_plan(+ &self,+ new_turtle: &str,+ added_classes: &[String],+ removed_classes: &[String],+ added_properties: &[String],+ removed_properties: &[String],+ ) -> anyhow::Result<String> {+ let plan_id = format!("plan-{:016x}", crate::lineage::rand_id());+ let conn = self.db.conn();+ conn.execute(+ "INSERT INTO plans \+ (plan_id, new_turtle, added_classes, removed_classes, added_properties, removed_properties) \+ VALUES (?1, ?2, ?3, ?4, ?5, ?6)",+ rusqlite::params![+ plan_id,+ new_turtle,+ serde_json::to_string(added_classes)?,+ serde_json::to_string(removed_classes)?,+ serde_json::to_string(added_properties)?,+ serde_json::to_string(removed_properties)?,+ ],+ )?;+ conn.execute(+ "DELETE FROM plans WHERE seq <= (SELECT MAX(seq) FROM plans) - ?1",+ rusqlite::params![PLAN_RETENTION],+ )?;+ Ok(plan_id)+ }++ fn load_plan(&self, plan_id: Option<&str>) -> anyhow::Result<PlanState> {+ const COLS: &str = "plan_id, new_turtle, added_classes, removed_classes, \+ added_properties, removed_properties";+ let conn = self.db.conn();+ let found = match plan_id {+ Some(id) => conn+ .query_row(+ &format!("SELECT {COLS} FROM plans WHERE plan_id = ?1"),+ rusqlite::params![id],+ Self::row_to_plan,+ )+ .optional()?,+ None => conn+ .query_row(+ &format!("SELECT {COLS} FROM plans ORDER BY seq DESC LIMIT 1"),+ [],+ Self::row_to_plan,+ )+ .optional()?,+ };+ match (found, plan_id) {+ (Some(plan), _) => Ok(plan),+ (None, Some(id)) => anyhow::bail!(+ "No plan found with id '{id}'. Run plan() first, or omit the id to apply the most recent plan."+ ),+ (None, None) => anyhow::bail!("No plan found. Run plan() first."),+ }+ }++ fn row_to_plan(row: &rusqlite::Row<'_>) -> rusqlite::Result<PlanState> {+ fn iris(raw: String) -> Vec<String> {+ serde_json::from_str(&raw).unwrap_or_default()+ }+ Ok(PlanState {+ plan_id: row.get(0)?,+ new_turtle: row.get(1)?,+ added_classes: iris(row.get(2)?),+ removed_classes: iris(row.get(3)?),+ added_properties: iris(row.get(4)?),+ removed_properties: iris(row.get(5)?),+ })+ }++ /// Record that a plan was applied. Advisory audit trail: re-applying is+ /// still allowed, since `apply` is a full clear-and-reload and therefore+ /// idempotent against the same store.+ fn mark_applied(&self, plan_id: &str, mode: &str) {+ let conn = self.db.conn();+ let _ = conn.execute(+ "UPDATE plans SET applied_at = datetime('now'), applied_mode = ?2 WHERE plan_id = ?1",+ rusqlite::params![plan_id, mode],+ );+ }++ /// Add `owl:equivalentClass` / `owl:equivalentProperty` bridges for terms+ /// that appear to have been renamed, then bring the store to the proposed+ /// state.+ ///+ /// This used to pair *every* removed term with `added_classes.first()` /+ /// `added_properties.first()`, so a plan that added two classes and removed+ /// one asserted equivalence between whichever addition happened to sort+ /// first and the removal — a fabricated logical axiom (#91). Candidates now+ /// come from `DriftDetector`, the calibrated rename detector the rest of the+ /// crate already uses, and are assigned one-to-one so no addition can be+ /// declared the replacement for two different removals.+ fn apply_migrate(&self, plan: &PlanState) -> anyhow::Result<String> {+ // Detect renames against the store as it stands, before the delta+ // removes the very terms being matched.+ let pairs = self.rename_candidates(plan)?;++ // Then bring the store to the proposed state. This has to happen before+ // the bridges are written: they are deprecation stubs for terms the+ // proposed Turtle no longer contains, so a delta computed afterwards+ // would delete them again.+ let delta = self.triple_delta(&plan.new_turtle)?;+ let (inserted, deleted) = delta.counts();+ if delta.reload {+ self.graph.clear()?;+ self.graph.load_turtle(&plan.new_turtle, None)?;+ } else {+ self.write_delta(&delta)?;+ }++ let mut migration_triples = 0u64;+ let mut bridges = Vec::new();+ for (removed, added, similarity, predicate) in &pairs {+ let update = format!(+ "INSERT DATA {{ <{removed}> <{predicate}> <{added}> . \+ <{removed}> <http://www.w3.org/2002/07/owl#deprecated> \"true\"^^<http://www.w3.org/2001/XMLSchema#boolean> . \+ <{removed}> <http://www.w3.org/2000/01/rdf-schema#comment> \"Deprecated: migrated to {added}\" . }}"+ );+ if let Ok(n) = self.graph.sparql_update(&update) {+ migration_triples += n as u64;}+ bridges.push(serde_json::json!({+ "from": removed,+ "to": added,+ "similarity": similarity,+ "predicate": predicate,+ }));}- // Also load the new turtle- let count = self.graph.load_turtle(&plan.new_turtle, None)?;+ // Every removal the matcher declined, named. A migrate that quietly+ // bridges some terms and says nothing about the rest is how the old+ // heuristic hid its mistakes.+ let bridged: HashSet<&String> = pairs.iter().map(|(r, _, _, _)| r).collect();+ let unbridged: Vec<&String> = plan+ .removed_classes+ .iter()+ .chain(plan.removed_properties.iter())+ .filter(|r| !bridged.contains(*r))+ .collect();++ self.mark_applied(&plan.plan_id, "migrate");Ok(serde_json::json!({"ok": true,+ "plan_id": plan.plan_id,"mode": "migrate",- "triples_loaded": count,+ "strategy": delta.strategy(),+ "triples_inserted": inserted,+ "triples_deleted": deleted,+ "triples_loaded": self.graph.triple_count(),"migration_triples": migration_triples,- "bridges_created": plan.removed_classes.len() + plan.removed_properties.len(),+ "bridges_created": bridges.len(),+ "bridges": bridges,+ "unbridged_removals": unbridged,}).to_string())}+ /// Rename pairs for `migrate`, as `(removed, added, similarity, predicate)`.+ ///+ /// Candidates below [`MIGRATE_MIN_SIMILARITY`] are dropped, the rest are+ /// taken in descending order of the detector's confidence, and both sides+ /// of an accepted pair are consumed so neither can appear again. A class is+ /// only ever bridged to a class and a property to a property.+ fn rename_candidates(+ &self,+ plan: &PlanState,+ ) -> anyhow::Result<Vec<(String, String, f64, &'static str)>> {+ let current_turtle = self.graph.serialize("turtle")?;+ let detector = crate::drift::DriftDetector::new(self.db.clone());+ let drift: serde_json::Value =+ serde_json::from_str(&detector.detect(¤t_turtle, &plan.new_turtle)?)?;++ let classes: HashSet<&String> = plan.removed_classes.iter().collect();+ let properties: HashSet<&String> = plan.removed_properties.iter().collect();+ let added_classes: HashSet<&String> = plan.added_classes.iter().collect();+ let added_properties: HashSet<&String> = plan.added_properties.iter().collect();++ // `likely_renames` arrives sorted by confidence, descending.+ let mut taken_from: HashSet<String> = HashSet::new();+ let mut taken_to: HashSet<String> = HashSet::new();+ let mut pairs = Vec::new();+ for candidate in drift["likely_renames"].as_array().into_iter().flatten() {+ let (Some(from), Some(to)) = (+ candidate["from"].as_str().map(str::to_string),+ candidate["to"].as_str().map(str::to_string),+ ) else {+ continue;+ };+ let similarity = candidate["signals"]["label_similarity"]+ .as_f64()+ .unwrap_or(0.0);+ if similarity < MIGRATE_MIN_SIMILARITY {+ continue;+ }+ if taken_from.contains(&from) || taken_to.contains(&to) {+ continue;+ }+ let predicate = if classes.contains(&from) && added_classes.contains(&to) {+ "http://www.w3.org/2002/07/owl#equivalentClass"+ } else if properties.contains(&from) && added_properties.contains(&to) {+ "http://www.w3.org/2002/07/owl#equivalentProperty"+ } else {+ continue;+ };+ taken_from.insert(from.clone());+ taken_to.insert(to.clone());+ pairs.push((from, to, similarity, predicate));+ }+ Ok(pairs)+ }+/// Lock an IRI to prevent removal.pub fn lock_iri(&self, iri: &str, reason: &str) {let conn = self.db.conn();@@ -222,6 +541,21 @@ impl Planner {self.extract_iris(store, query, "c")}+ /// Individuals: anything typed by a declared class, plus explicit+ /// `owl:NamedIndividual`s. Blank nodes are excluded — they are structural+ /// (restrictions, lists), not instance data, and have no stable identity to+ /// diff against.+ fn extract_individuals_from_store(&self, store: &GraphStore) -> HashSet<String> {+ let query = "SELECT DISTINCT ?i WHERE { \+ { ?i a <http://www.w3.org/2002/07/owl#NamedIndividual> } \+ UNION \+ { ?i a ?c . ?c a <http://www.w3.org/2002/07/owl#Class> } \+ }";+ let mut set = self.extract_iris(store, query, "i");+ set.retain(|i| !i.starts_with("_:"));+ set+ }+fn extract_properties_from_store(&self, store: &GraphStore) -> HashSet<String> {let query = "SELECT DISTINCT ?p WHERE { \{ ?p a <http://www.w3.org/2002/07/owl#ObjectProperty> } \diff --git a/src/server.rs b/src/server.rsindex 1f14caa8..67050d2f 100644--- a/src/server.rs+++ b/src/server.rs@@ -1533,7 +1533,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.")]- async fn onto_plan(&self, Parameters(input): Parameters<OntoPlanInput>) -> String {+ pub async fn onto_plan(&self, Parameters(input): Parameters<OntoPlanInput>) -> String {let planner = crate::plan::Planner::new(self.db.clone(), self.graph.clone());match planner.plan(&input.new_turtle) {Ok(result) => {@@ -1544,11 +1544,11 @@ impl OpenOntologiesServer {}}- #[tool(name = "onto_apply", description = "Apply the last plan. Modes: 'safe' (clear+reload, checks monitor), 'force' (ignores monitor), 'migrate' (adds owl:equivalentClass/Property bridges for renames).")]- async fn onto_apply(&self, Parameters(input): Parameters<OntoApplyInput>) -> String {+ #[tool(name = "onto_apply", description = "Apply a plan produced by onto_plan, defaulting to the most recent one. Pass plan_id to target a specific plan. Modes: 'safe' (clear+reload, checks monitor), 'force' (ignores monitor), 'migrate' (adds owl:equivalentClass/Property bridges for renames).")]+ pub async fn onto_apply(&self, Parameters(input): Parameters<OntoApplyInput>) -> String {let mode = input.mode.as_deref().unwrap_or("safe");let planner = crate::plan::Planner::new(self.db.clone(), self.graph.clone());- match planner.apply(mode) {+ match planner.apply_plan(input.plan_id.as_deref(), mode) {Ok(result) => {self.lineage().record(&self.session_id, "A", "apply", mode);let monitor_result = self.monitor().run_watchers();diff --git a/src/state.rs b/src/state.rsindex 037a1ac7..246b2b7b 100644--- a/src/state.rs+++ b/src/state.rs@@ -131,6 +131,19 @@ CREATE TABLE IF NOT EXISTS ontology_cache (compiled_at TEXT NOT NULL DEFAULT (datetime('now')),last_access_at TEXT NOT NULL DEFAULT (datetime('now')));++CREATE TABLE IF NOT EXISTS plans (+ seq INTEGER PRIMARY KEY AUTOINCREMENT,+ plan_id TEXT NOT NULL UNIQUE,+ new_turtle TEXT NOT NULL,+ added_classes TEXT NOT NULL,+ removed_classes TEXT NOT NULL,+ added_properties TEXT NOT NULL,+ removed_properties TEXT NOT NULL,+ created_at TEXT NOT NULL DEFAULT (datetime('now')),+ applied_at TEXT,+ applied_mode TEXT+);";/// A column an upgrade adds to an existing table.diff --git a/tests/cli_test.rs b/tests/cli_test.rsindex f6383a3d..f7a89754 100644--- a/tests/cli_test.rs+++ b/tests/cli_test.rs@@ -292,3 +292,109 @@ fn test_cli_lint_suppression_end_to_end() {let v: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap();assert!(v["suppressed_count"].as_u64().unwrap() > 0, "suppressed_count should be > 0 after 3 dismissals");}++// ── #91: plan → apply across the real CLI surface ────────────────────────────+//+// The reporter's repro, run through the shipped binary rather than through a+// held `Planner`. `batch` is a single process; the two-process test covers the+// `plan` and `apply` subcommands, which build a `Planner` each.++fn write_plan_fixtures(dir: &tempfile::TempDir) -> (String, String) {+ let base = dir.path().join("base.ttl");+ let proposed = dir.path().join("proposed.ttl");+ std::fs::write(&base, r#"+ @prefix ex: <https://example.org/> .+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+ ex:Persona a owl:Class ; rdfs:label "Persona" .+ "#).unwrap();+ std::fs::write(&proposed, r#"+ @prefix ex: <https://example.org/> .+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+ ex:Persona a owl:Class ; rdfs:label "Persona" .+ ex:Organizacion a owl:Class ; rdfs:label "Organizacion" .+ "#).unwrap();+ (+ base.to_str().unwrap().to_string(),+ proposed.to_str().unwrap().to_string(),+ )+}++#[test]+fn test_cli_batch_plan_then_apply() {+ let dir = tempfile::tempdir().unwrap();+ let (base, proposed) = write_plan_fixtures(&dir);+ let batch = dir.path().join("batch.txt");+ std::fs::write(+ &batch,+ format!("load {base}\nplan {proposed}\napply safe\nstats\n"),+ )+ .unwrap();++ let out = oo_isolated(&dir)+ .args(["batch", batch.to_str().unwrap()])+ .output()+ .unwrap();+ let stdout = String::from_utf8_lossy(&out.stdout);++ let lines: Vec<serde_json::Value> = stdout+ .lines()+ .filter(|l| !l.trim().is_empty())+ .map(|l| serde_json::from_str(l).unwrap())+ .collect();++ let apply = lines.iter().find(|l| l["command"] == "apply").unwrap();+ assert!(+ apply["result"]["error"].is_null(),+ "apply failed inside a single batch process: {apply}"+ );+ assert_eq!(apply["result"]["ok"], true);++ // The applied class must actually be in the store afterwards.+ let stats = lines.iter().find(|l| l["command"] == "stats").unwrap();+ assert_eq!(+ stats["result"]["classes"], 2,+ "apply reported success but the store did not change: {stats}"+ );+}++#[test]+fn test_cli_plan_then_apply_separate_processes() {+ let dir = tempfile::tempdir().unwrap();+ let (_base, proposed) = write_plan_fixtures(&dir);++ let plan_out = oo_isolated(&dir)+ .args(["plan", &proposed])+ .output()+ .unwrap();+ assert!(plan_out.status.success());+ let plan: serde_json::Value =+ serde_json::from_str(String::from_utf8_lossy(&plan_out.stdout).trim()).unwrap();+ let plan_id = plan["plan_id"].as_str().expect("plan must emit a plan_id");++ // Fresh process, same data-dir: the plan is in the state db, not in memory.+ let apply_out = oo_isolated(&dir)+ .args(["apply", "--plan-id", plan_id])+ .output()+ .unwrap();+ let apply: serde_json::Value =+ serde_json::from_str(String::from_utf8_lossy(&apply_out.stdout).trim()).unwrap();+ assert!(+ apply["error"].is_null(),+ "apply could not find a plan from a previous process: {apply}"+ );+ assert_eq!(apply["ok"], true);+ assert_eq!(apply["plan_id"].as_str().unwrap(), plan_id);+}++#[test]+fn test_cli_apply_without_plan_reports_no_plan() {+ let dir = tempfile::tempdir().unwrap();+ let out = oo_isolated(&dir).args(["apply", "safe"]).output().unwrap();+ let stdout = String::from_utf8_lossy(&out.stdout);+ assert!(+ stdout.contains("No plan found"),+ "expected a no-plan error, got: {stdout}"+ );+}diff --git a/tests/plan_delta_test.rs b/tests/plan_delta_test.rsnew file mode 100644index 00000000..57bbe993--- /dev/null+++ b/tests/plan_delta_test.rs@@ -0,0 +1,200 @@+//! `plan` must see the ABox, and `apply` must write a delta rather than+//! clearing the store.+//!+//! The secondary findings on #91. `plan()` only ever queried `?c a owl:Class`+//! and `?p a owl:{Object,Datatype}Property`, so instance data was invisible to+//! it — while `apply()` did `graph.clear()` + `load_turtle(new_turtle)`, which+//! deleted that same invisible instance data wholesale. A plan that cannot+//! mention what an apply destroys is not a plan.++use open_ontologies::graph::GraphStore;+use open_ontologies::plan::Planner;+use open_ontologies::state::StateDb;+use std::sync::Arc;++fn setup() -> (tempfile::TempDir, StateDb, Arc<GraphStore>) {+ let tmp = tempfile::tempdir().unwrap();+ let db = StateDb::open(&tmp.path().join("state.db")).unwrap();+ (tmp, db, Arc::new(GraphStore::new()))+}++fn json(s: &str) -> serde_json::Value {+ serde_json::from_str(s).unwrap()+}++fn strs(v: &serde_json::Value) -> Vec<String> {+ v.as_array()+ .unwrap()+ .iter()+ .map(|x| x.as_str().unwrap().to_string())+ .collect()+}++const WITH_TWO_INDIVIDUALS: &str = r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://example.org/> .+ ex:Persona a owl:Class .+ ex:ana a ex:Persona .+ ex:beto a ex:Persona .+"#;++#[test]+fn plan_reports_added_individuals() {+ let (_t, db, graph) = setup();+ graph+ .load_turtle(+ r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://example.org/> .+ ex:Persona a owl:Class .+ ex:ana a ex:Persona .+ "#,+ None,+ )+ .unwrap();++ let plan = json(&Planner::new(db, graph).plan(WITH_TWO_INDIVIDUALS).unwrap());+ let added = strs(&plan["added_individuals"]);+ assert_eq!(added, vec!["http://example.org/beto".to_string()]);+ assert!(strs(&plan["removed_individuals"]).is_empty());+}++#[test]+fn plan_reports_individuals_an_apply_would_destroy() {+ let (_t, db, graph) = setup();+ graph.load_turtle(WITH_TWO_INDIVIDUALS, None).unwrap();++ // Proposed Turtle carries the TBox but drops the instance data — exactly+ // the case where the old plan output said "no changes" and apply then+ // deleted both individuals.+ let tbox_only = r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://example.org/> .+ ex:Persona a owl:Class .+ "#;++ let plan = json(&Planner::new(db, graph).plan(tbox_only).unwrap());+ let mut removed = strs(&plan["removed_individuals"]);+ removed.sort();+ assert_eq!(+ removed,+ vec![+ "http://example.org/ana".to_string(),+ "http://example.org/beto".to_string()+ ]+ );+ assert_ne!(+ plan["risk_score"].as_str().unwrap(),+ "low",+ "dropping instance data is not a low-risk change: {plan}"+ );+}++#[test]+fn plan_reports_the_triple_level_delta() {+ let (_t, db, graph) = setup();+ graph+ .load_turtle(+ r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://example.org/> .+ ex:Persona a owl:Class .+ ex:ana a ex:Persona .+ "#,+ None,+ )+ .unwrap();++ let plan = json(&Planner::new(db, graph).plan(WITH_TWO_INDIVIDUALS).unwrap());+ assert_eq!(plan["triple_delta"]["insertions"], 1);+ assert_eq!(plan["triple_delta"]["deletions"], 0);+}++#[test]+fn apply_writes_a_delta_instead_of_clearing_the_store() {+ let (_t, db, graph) = setup();+ graph+ .load_turtle(+ r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://example.org/> .+ ex:Persona a owl:Class .+ ex:ana a ex:Persona .+ "#,+ None,+ )+ .unwrap();++ Planner::new(db.clone(), graph.clone())+ .plan(WITH_TWO_INDIVIDUALS)+ .unwrap();+ let applied = json(+ &Planner::new(db.clone(), graph.clone())+ .apply("safe")+ .unwrap(),+ );++ assert_eq!(applied["strategy"], "delta");+ assert_eq!(applied["triples_inserted"], 1);+ assert_eq!(applied["triples_deleted"], 0);++ // And the store really is the proposed state.+ let ask = "ASK { <http://example.org/beto> a <http://example.org/Persona> }";+ assert!(graph.sparql_select(ask).unwrap().contains("true"));+ assert_eq!(graph.triple_count(), 3);+}++#[test]+fn apply_deletes_individuals_absent_from_the_proposed_turtle() {+ let (_t, db, graph) = setup();+ graph.load_turtle(WITH_TWO_INDIVIDUALS, None).unwrap();++ let tbox_only = r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://example.org/> .+ ex:Persona a owl:Class .+ "#;+ Planner::new(db.clone(), graph.clone()).plan(tbox_only).unwrap();+ let applied = json(&Planner::new(db.clone(), graph.clone()).apply("safe").unwrap());++ assert_eq!(applied["triples_deleted"], 2);+ assert_eq!(graph.triple_count(), 1);+}++#[test]+fn apply_falls_back_to_reload_when_blank_nodes_are_involved() {+ let (_t, db, graph) = setup();+ graph+ .load_turtle(+ r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://example.org/> .+ ex:Persona a owl:Class .+ "#,+ None,+ )+ .unwrap();++ // An anonymous restriction: blank-node labels are store-local, so a+ // triple-set difference over them is meaningless and DELETE DATA /+ // INSERT DATA cannot carry them at all.+ let with_restriction = r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+ @prefix ex: <http://example.org/> .+ ex:Persona a owl:Class .+ ex:Padre a owl:Class ; rdfs:subClassOf [+ a owl:Restriction ;+ owl:onProperty ex:tieneHijo ;+ owl:minCardinality 1+ ] .+ "#;++ Planner::new(db.clone(), graph.clone()).plan(with_restriction).unwrap();+ let applied = json(&Planner::new(db.clone(), graph.clone()).apply("safe").unwrap());++ assert_eq!(applied["strategy"], "reload");+ assert_eq!(applied["ok"], true);+ let ask = "ASK { <http://example.org/Padre> a <http://www.w3.org/2002/07/owl#Class> }";+ assert!(graph.sparql_select(ask).unwrap().contains("true"));+}diff --git a/tests/plan_mcp_test.rs b/tests/plan_mcp_test.rsnew file mode 100644index 00000000..e0cfbd41--- /dev/null+++ b/tests/plan_mcp_test.rs@@ -0,0 +1,111 @@+//! The MCP `onto_plan` / `onto_apply` handlers must share plan state.+//!+//! Part of the #91 regression set. `onto_plan` and `onto_apply` are independent+//! `#[tool]` handlers and each builds its own `Planner`, so nothing about the+//! long-lived server struct saved them: the plan has to be in the state db.+//!+//! This drives the handlers themselves rather than a `Planner`, because the+//! handler pair *is* the surface an MCP client hits.++use open_ontologies::graph::GraphStore;+use open_ontologies::inputs::{OntoApplyInput, OntoPlanInput};+use open_ontologies::server::OpenOntologiesServer;+use open_ontologies::state::StateDb;+use rmcp::handler::server::wrapper::Parameters;+use std::sync::Arc;++const BASE: &str = r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <https://example.org/> .+ ex:Persona a owl:Class .+"#;++const PROPOSED: &str = r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <https://example.org/> .+ ex:Persona a owl:Class .+ ex:Organizacion a owl:Class .+"#;++fn server() -> (tempfile::TempDir, OpenOntologiesServer, Arc<GraphStore>) {+ 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.clone());+ (tmp, server, graph)+}++#[tokio::test]+async fn onto_apply_sees_the_plan_onto_plan_computed() {+ let (_tmp, server, _graph) = server();++ let plan: serde_json::Value = serde_json::from_str(+ &server+ .onto_plan(Parameters(OntoPlanInput {+ new_turtle: PROPOSED.to_string(),+ }))+ .await,+ )+ .unwrap();+ assert_eq!(plan["added_classes"].as_array().unwrap().len(), 1);++ let applied: serde_json::Value = serde_json::from_str(+ &server+ .onto_apply(Parameters(OntoApplyInput {+ mode: Some("safe".to_string()),+ plan_id: None,+ }))+ .await,+ )+ .unwrap();+ assert!(+ applied["error"].is_null(),+ "onto_apply could not see onto_plan's plan: {applied}"+ );+ assert_eq!(applied["ok"], true);+}++#[tokio::test]+async fn onto_apply_accepts_an_explicit_plan_id() {+ let (_tmp, server, _graph) = server();++ let plan: serde_json::Value = serde_json::from_str(+ &server+ .onto_plan(Parameters(OntoPlanInput {+ new_turtle: PROPOSED.to_string(),+ }))+ .await,+ )+ .unwrap();+ let plan_id = plan["plan_id"].as_str().unwrap().to_string();++ let applied: serde_json::Value = serde_json::from_str(+ &server+ .onto_apply(Parameters(OntoApplyInput {+ mode: Some("safe".to_string()),+ plan_id: Some(plan_id.clone()),+ }))+ .await,+ )+ .unwrap();+ assert_eq!(applied["plan_id"].as_str().unwrap(), plan_id);+}++#[tokio::test]+async fn onto_apply_without_a_plan_reports_the_error() {+ let (_tmp, server, _graph) = server();+ let applied: serde_json::Value = serde_json::from_str(+ &server+ .onto_apply(Parameters(OntoApplyInput {+ mode: Some("safe".to_string()),+ plan_id: None,+ }))+ .await,+ )+ .unwrap();+ assert!(+ applied["error"].as_str().unwrap_or_default().contains("No plan found"),+ "expected a no-plan error: {applied}"+ );+}diff --git a/tests/plan_migrate_test.rs b/tests/plan_migrate_test.rsnew file mode 100644index 00000000..0c6a756e--- /dev/null+++ b/tests/plan_migrate_test.rs@@ -0,0 +1,169 @@+//! `migrate` must pair each removal with a plausible replacement.+//!+//! The third finding on #91: `apply_migrate` paired *every* removed class with+//! `plan.added_classes.first()` and every removed property with+//! `added_properties.first()`. With more than one addition in a plan that+//! fabricates `owl:equivalentClass` bridges between terms that have nothing to+//! do with each other — and an ontology bridge asserting a falsehood is worse+//! than no bridge, because downstream reasoners believe it.++use open_ontologies::graph::GraphStore;+use open_ontologies::plan::Planner;+use open_ontologies::state::StateDb;+use std::sync::Arc;++fn setup() -> (tempfile::TempDir, StateDb, Arc<GraphStore>) {+ let tmp = tempfile::tempdir().unwrap();+ let db = StateDb::open(&tmp.path().join("state.db")).unwrap();+ (tmp, db, Arc::new(GraphStore::new()))+}++fn asks(graph: &GraphStore, subject: &str, pred: &str, object: &str) -> bool {+ let q = format!("ASK {{ <{subject}> <{pred}> <{object}> }}");+ graph.sparql_select(&q).unwrap().contains("true")+}++const EQ_CLASS: &str = "http://www.w3.org/2002/07/owl#equivalentClass";++#[test]+fn migrate_does_not_bridge_a_removal_to_an_unrelated_addition() {+ let (_t, db, graph) = setup();+ graph+ .load_turtle(+ r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://example.org/> .+ ex:Automobile a owl:Class .+ "#,+ None,+ )+ .unwrap();++ // Two additions. `Motorcar` is the rename; `Wavelength` is unrelated and+ // happens to sort first, which is all the old heuristic looked at.+ let proposed = r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://example.org/> .+ ex:Automobil a owl:Class .+ ex:Wavelength a owl:Class .+ "#;++ Planner::new(db.clone(), graph.clone()).plan(proposed).unwrap();+ Planner::new(db.clone(), graph.clone()).apply("migrate").unwrap();++ assert!(+ !asks(&graph, "http://example.org/Automobile", EQ_CLASS, "http://example.org/Wavelength"),+ "migrate asserted Automobile ≡ Wavelength"+ );+ assert!(+ asks(&graph, "http://example.org/Automobile", EQ_CLASS, "http://example.org/Automobil"),+ "migrate missed the actual rename"+ );+}++#[test]+fn migrate_pairs_each_removal_with_its_own_best_match() {+ let (_t, db, graph) = setup();+ graph+ .load_turtle(+ r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://example.org/> .+ ex:Automobile a owl:Class .+ ex:Bicycle a owl:Class .+ "#,+ None,+ )+ .unwrap();++ let proposed = r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://example.org/> .+ ex:Automobil a owl:Class .+ ex:Bicicle a owl:Class .+ "#;++ Planner::new(db.clone(), graph.clone()).plan(proposed).unwrap();+ let applied: serde_json::Value = serde_json::from_str(+ &Planner::new(db.clone(), graph.clone()).apply("migrate").unwrap(),+ )+ .unwrap();++ assert!(asks(&graph, "http://example.org/Automobile", EQ_CLASS, "http://example.org/Automobil"));+ assert!(asks(&graph, "http://example.org/Bicycle", EQ_CLASS, "http://example.org/Bicicle"));+ // No cross-pairing.+ assert!(!asks(&graph, "http://example.org/Automobile", EQ_CLASS, "http://example.org/Bicicle"));+ assert!(!asks(&graph, "http://example.org/Bicycle", EQ_CLASS, "http://example.org/Automobil"));+ assert_eq!(applied["bridges_created"], 2);+}++#[test]+fn migrate_reports_removals_it_could_not_bridge() {+ let (_t, db, graph) = setup();+ graph+ .load_turtle(+ r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://example.org/> .+ ex:Automobile a owl:Class .+ "#,+ None,+ )+ .unwrap();++ // Nothing resembling a rename is on offer.+ let proposed = r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://example.org/> .+ ex:Wavelength a owl:Class .+ "#;++ Planner::new(db.clone(), graph.clone()).plan(proposed).unwrap();+ let applied: serde_json::Value = serde_json::from_str(+ &Planner::new(db.clone(), graph.clone()).apply("migrate").unwrap(),+ )+ .unwrap();++ assert_eq!(applied["bridges_created"], 0);+ let unbridged: Vec<String> = applied["unbridged_removals"]+ .as_array()+ .unwrap()+ .iter()+ .map(|v| v.as_str().unwrap().to_string())+ .collect();+ assert_eq!(unbridged, vec!["http://example.org/Automobile".to_string()]);+}++#[test]+fn migrate_never_reuses_one_addition_for_two_removals() {+ let (_t, db, graph) = setup();+ graph+ .load_turtle(+ r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://example.org/> .+ ex:Automobile a owl:Class .+ ex:Automobiles a owl:Class .+ "#,+ None,+ )+ .unwrap();++ // One plausible target for two similar removals.+ let proposed = r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://example.org/> .+ ex:Automobil a owl:Class .+ "#;++ Planner::new(db.clone(), graph.clone()).plan(proposed).unwrap();+ let applied: serde_json::Value = serde_json::from_str(+ &Planner::new(db.clone(), graph.clone()).apply("migrate").unwrap(),+ )+ .unwrap();++ assert_eq!(+ applied["bridges_created"], 1,+ "one addition cannot be the replacement for two different removals: {applied}"+ );+}diff --git a/tests/plan_persistence_test.rs b/tests/plan_persistence_test.rsnew file mode 100644index 00000000..dacc9531--- /dev/null+++ b/tests/plan_persistence_test.rs@@ -0,0 +1,170 @@+//! Plans must outlive the `Planner` that computed them.+//!+//! Regression coverage for #91. Every real call site — the `plan`/`apply` CLI+//! subcommands, `batch`'s `exec_plan`/`exec_apply`, and the `onto_plan` /+//! `onto_apply` MCP handlers — constructs a *fresh* `Planner` per invocation.+//! While the plan lived in a `RefCell` on the instance, `apply` could never see+//! it, and `apply` was dead in every shipped interface.+//!+//! The pre-existing suites (`plan_test.rs`, `terraform_loop_test.rs`) all held+//! one `Planner` across both calls, so they exercised a lifetime shape no+//! caller has. These tests deliberately do not: each one crosses the same+//! boundary a real caller crosses.++use open_ontologies::graph::GraphStore;+use open_ontologies::plan::Planner;+use open_ontologies::state::StateDb;+use std::sync::Arc;++fn setup() -> (tempfile::TempDir, StateDb, Arc<GraphStore>) {+ let tmp = tempfile::tempdir().unwrap();+ let db = StateDb::open(&tmp.path().join("state.db")).unwrap();+ (tmp, db, Arc::new(GraphStore::new()))+}++const BASE: &str = r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+ @prefix ex: <https://example.org/> .+ ex:Persona a owl:Class ; rdfs:label "Persona" .+"#;++const PROPOSED: &str = r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+ @prefix ex: <https://example.org/> .+ ex:Persona a owl:Class ; rdfs:label "Persona" .+ ex:Organizacion a owl:Class ; rdfs:label "Organizacion" .+"#;++fn json(s: &str) -> serde_json::Value {+ serde_json::from_str(s).unwrap()+}++#[test]+fn a_plan_survives_into_a_separately_constructed_planner() {+ let (_tmp, db, graph) = setup();+ graph.load_turtle(BASE, None).unwrap();++ // Two Planners, exactly as batch's exec_plan/exec_apply and the MCP+ // handlers build them: same db, same graph, different instances.+ let plan = json(&Planner::new(db.clone(), graph.clone()).plan(PROPOSED).unwrap());+ assert_eq!(plan["added_classes"].as_array().unwrap().len(), 1);++ let applied = Planner::new(db.clone(), graph.clone())+ .apply("safe")+ .expect("apply must see the plan a different Planner computed");++ let applied = json(&applied);+ assert_eq!(applied["ok"], true);+ assert_eq!(applied["added_classes"], 1);+}++#[test]+fn plan_returns_an_id_that_apply_can_target() {+ let (_tmp, db, graph) = setup();+ graph.load_turtle(BASE, None).unwrap();++ let plan = json(&Planner::new(db.clone(), graph.clone()).plan(PROPOSED).unwrap());+ let plan_id = plan["plan_id"].as_str().expect("plan() must return a plan_id").to_string();++ let applied = json(+ &Planner::new(db.clone(), graph.clone())+ .apply_plan(Some(&plan_id), "safe")+ .unwrap(),+ );+ assert_eq!(applied["ok"], true);+ assert_eq!(applied["plan_id"].as_str().unwrap(), plan_id);+}++#[test]+fn an_older_plan_is_still_reachable_by_id_after_a_newer_one() {+ let (_tmp, db, graph) = setup();+ graph.load_turtle(BASE, None).unwrap();++ let first = json(&Planner::new(db.clone(), graph.clone()).plan(PROPOSED).unwrap());+ let first_id = first["plan_id"].as_str().unwrap().to_string();++ // A second, different plan supersedes it as "latest".+ let second_turtle = format!("{PROPOSED}\n@prefix ex2: <https://example.org/x/> .\nex2:Tercera a <http://www.w3.org/2002/07/owl#Class> .");+ let second = json(&Planner::new(db.clone(), graph.clone()).plan(&second_turtle).unwrap());+ assert_ne!(second["plan_id"].as_str().unwrap(), first_id);++ // Targeting the older id applies the older plan, not the newer one.+ let applied = json(+ &Planner::new(db.clone(), graph.clone())+ .apply_plan(Some(&first_id), "safe")+ .unwrap(),+ );+ assert_eq!(applied["plan_id"].as_str().unwrap(), first_id);+ assert_eq!(applied["added_classes"], 1);+}++#[test]+fn the_most_recent_plan_is_the_one_applied_when_no_id_is_given() {+ let (_tmp, db, graph) = setup();+ graph.load_turtle(BASE, None).unwrap();++ Planner::new(db.clone(), graph.clone()).plan(PROPOSED).unwrap();+ let second_turtle = format!("{PROPOSED}\nex:Cuarta a <http://www.w3.org/2002/07/owl#Class> .");+ let second = json(&Planner::new(db.clone(), graph.clone()).plan(&second_turtle).unwrap());+ let second_id = second["plan_id"].as_str().unwrap().to_string();++ let applied = json(&Planner::new(db.clone(), graph.clone()).apply("safe").unwrap());+ assert_eq!(applied["plan_id"].as_str().unwrap(), second_id);+ assert_eq!(applied["added_classes"], 2);+}++#[test]+fn apply_with_no_plan_at_all_still_fails() {+ let (_tmp, db, graph) = setup();+ let err = Planner::new(db, graph).apply("safe").unwrap_err();+ assert!(+ err.to_string().contains("No plan found"),+ "unexpected error: {err}"+ );+}++#[test]+fn apply_with_an_unknown_plan_id_fails_rather_than_falling_back() {+ let (_tmp, db, graph) = setup();+ graph.load_turtle(BASE, None).unwrap();+ Planner::new(db.clone(), graph.clone()).plan(PROPOSED).unwrap();++ // A stored plan exists, but not this one. Silently applying the latest+ // instead would apply changes the caller never asked for.+ let err = Planner::new(db.clone(), graph.clone())+ .apply_plan(Some("does-not-exist"), "safe")+ .unwrap_err();+ assert!(err.to_string().contains("does-not-exist"), "unexpected error: {err}");+}++#[test]+fn a_plan_survives_reopening_the_state_database() {+ let tmp = tempfile::tempdir().unwrap();+ let db_path = tmp.path().join("state.db");+ let graph = Arc::new(GraphStore::new());+ graph.load_turtle(BASE, None).unwrap();++ let plan_id = {+ let db = StateDb::open(&db_path).unwrap();+ let plan = json(&Planner::new(db, graph.clone()).plan(PROPOSED).unwrap());+ plan["plan_id"].as_str().unwrap().to_string()+ };++ // A separate process is a separate StateDb over the same file.+ let db = StateDb::open(&db_path).unwrap();+ let applied = json(&Planner::new(db, graph.clone()).apply_plan(Some(&plan_id), "safe").unwrap());+ assert_eq!(applied["ok"], true);+}++#[test]+fn migrate_mode_also_reads_the_persisted_plan() {+ let (_tmp, db, graph) = setup();+ graph.load_turtle(BASE, None).unwrap();++ Planner::new(db.clone(), graph.clone()).plan(PROPOSED).unwrap();+ let applied = json(&Planner::new(db.clone(), graph.clone()).apply("migrate").unwrap());+ assert_eq!(applied["ok"], true);+ assert_eq!(applied["mode"], "migrate");+}