Skip to content

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

feat(safety): onto_certify_action (CIVeX) + graph_projection_lossy_check

FABIOTESS6d26c230a263
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e0f4c2b8..9ee36e7b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,8 @@ All notable changes to Open Ontologies are documented here.
## [Unreleased]
### Added
+- **`onto_certify_action` — CIVeX-style causal certificate for state-changing actions** (#42, [arXiv 2605.09168](https://arxiv.org/abs/2605.09168)). New MCP tool that gates any state-changing onto_* operation before execution. Maps a proposed action to a structural identifiability check + Wilson one-sided LCB on the do-effect, returns one of four auditable verdicts: **EXECUTE / REJECT / EXPERIMENT / ABSTAIN**. Each verdict carries a certificate documenting the labelled assumptions, structural-dependency identification proof, point estimate, LCB at level α, provenance SHA-256, and risk bound. Scaffold port: keeps the four-way verdict + Wilson LCB + locked-IRI hard-reject; uses a **structural-dependency proxy** for identifiability (honestly documented as `"structural_only"` in the assumptions list) rather than full do-calculus backdoor/frontdoor algorithms. EXPERIMENT degrades to ABSTAIN unless caller passes `allow_experiment=true`. New module `src/civex.rs` + 6 integration tests in `tests/civex_test.rs` covering EXECUTE, REJECT (cost > risk_threshold), REJECT (locked IRI), ABSTAIN (irreversible + ambiguous LCB), EXPERIMENT (reversible + authorised), and provenance-hash determinism.
+- **`graph_projection_lossy_check` — audit projected RAG slices for information loss** (#35, IJCAI 2025). New MCP tool that compares a projected Turtle slice against the loaded ontology's full neighbourhood of seed IRIs and reports dropped predicates, dropped object IRIs, per-seed coverage ratio, and aggregate coverage. Pairs with the upcoming `onto_segment_retrieve` (#34) — the retriever produces the slice; this auditor reports what it left behind, so the calling LLM can decide whether the slice is sufficient. New module `src/projection_check.rs` + 4 inline unit tests covering full-projection-OK, dropped-predicate-flagged, parse-failure path, and missing-seed-in-source-trivially-covered.
- **HNSW polish — per-call tuning, Poincaré variant, async flush.** Three follow-on wins on the HNSW moat: (1) `onto_search` gains `use_hnsw` and `ef_search` parameters, so callers can route a single query through the HNSW cosine index and optionally trigger a rebuild with custom `ef_search` per query. Caveat documented: `instant-distance` bakes `ef_search` into the HNSW structure at build time and doesn't support per-query overrides, so a non-default `ef_search` triggers a rebuild — prefer `onto_hnsw_build` if you query frequently with the same value. (2) New `PoincareIndex` variant alongside `CosineIndex`, indexing structural embeddings (Poincaré ball) instead of text embeddings (cosine). Wired into `VecStore` with `search_poincare_hnsw`, `rebuild_poincare_index`, `persist_poincare_index`, `load_poincare_index`. The two indices coexist independently; both share the `hnsw_index_cache` SQLite table (kind = 'cosine' | 'poincare') with the same entries-fingerprint, so a mutation invalidates both at once. (3) Async background flush via `persist_cosine_index_async` / `persist_poincare_index_async` — returns a `tokio::task::JoinHandle` that resolves when the SQLite write completes. Serialisation happens synchronously (in-memory bincode, < 100ms for ontologies under ~10k classes); only the SQLite write is dispatched to `spawn_blocking`. Useful for keeping MCP tool handlers responsive when persisting large indices. Three new integration tests (Poincaré top-1 vs brute-force, coexistence with cosine, async persist round-trip) plus an additional Poincaré persistence test, taking the vecstore suite from 9 to 15 tests.
- **HNSW persistence + tuning + onto_align prefilter** (completes the moat scaffold). Three follow-on changes wire the prior HNSW scaffold into the rest of the system: (1) the built HNSW index now persists across process restarts via a new `hnsw_index_cache` SQLite table; `VecStore::load_from_db` automatically reinstates the cached index when its entries-fingerprint (deterministic FNV-1a 64-bit hash of sorted iri+text-vec bytes) matches the just-loaded vectors, and rejects stale caches when vectors changed — so a process startup over a populated DB skips the full rebuild. (2) New `onto_hnsw_build` MCP tool exposes the HNSW `ef_construction` and `ef_search` parameters so the connected orchestrator can tune index quality vs build/query time on larger ontologies; the tool optionally persists the rebuilt index. New `OntoHnswBuildInput` in `src/inputs.rs`. (3) `onto_align`'s candidate loop now transparently uses the HNSW index as a pre-filter when both source and target IRIs have embeddings in the vecstore: for each source class, a top-50 cosine shortlist of target candidates is computed once via HNSW, and the inner loop skips pairs not in the shortlist. The optimisation degrades gracefully — sources without embeddings fall back to the full target scan, preserving correctness on partially-embedded inputs. Two new persistence tests in `tests/vecstore_test.rs` cover the round-trip (vectors + index reload on a fresh `VecStore` over the same DB) and the cache-invalidation path (mutated vectors + unmutated index → cache rejected, rebuild on next search).
- **HNSW-accelerated cosine search scaffold** (the "vector-index moat"). New optional `instant-distance` dependency (gated behind the existing `embeddings` feature, no impact on default builds) and a new `src/hnsw_index.rs` module wrapping the HNSW algorithm (Malkov & Yashunin, TPAMI 2020). `VecStore` grows a `search_cosine_hnsw(query, top_k)` method that builds the index lazily on first call and rebuilds whenever the store is mutated; the existing `search_cosine` brute-force linear scan is unchanged and continues to work without HNSW (zero regression risk). Strategic context: per the May 2026 ecosystem research, no Rust knowledge-graph engine ships native HNSW alongside its triple store — the de-facto stack is `Neo4j + Qdrant + a Python adapter`. This module is the foundation for Open Ontologies to fill that gap as a Rust-native MCP server with first-class semantic search inside the same process. Scaffold scope: the core index + integration + tests; follow-up work (persistence layer for the built index, MCP-tool surface for tuning HNSW `ef_search` / `ef_construction`, wiring into `onto_align`'s embedding-similarity signal) is tracked in the project notes. New tests: 3 unit tests in `src/hnsw_index.rs` + 3 integration tests in `tests/vecstore_test.rs` (round-trip top-1 agreement with brute-force, mutation-invalidation behaviour, empty-store edge case).
diff --git a/Cargo.lock b/Cargo.lock
index 80a5d0f3..54301648 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2760,6 +2760,7 @@ dependencies = [
"serde",
"serde_json",
"serde_yaml",
+ "sha2",
"shell-words",
"sqlx",
"tempfile",
diff --git a/Cargo.toml b/Cargo.toml
index f5e45bc7..e3b08f21 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -42,6 +42,7 @@ tract-onnx = { version = "0.21", optional = true }
tokenizers = { version = "0.21", optional = true, default-features = false, features = ["onig"] }
instant-distance = { version = "0.6", optional = true, features = ["with-serde"] }
bincode = { version = "1.3", optional = true }
+sha2 = "0.10"
dirs = "6"
shell-words = "1"
diff --git a/src/civex.rs b/src/civex.rs
new file mode 100644
index 00000000..acb87a34
--- /dev/null
+++ b/src/civex.rs
@@ -0,0 +1,497 @@
+//! CIVeX-style causal certificate for state-changing ontology actions (#42).
+//!
+//! A scaffold port of the verifier described in **CIVeX: Causal Intervention
+//! Verification for Language Agents** (Rovai, arXiv 2605.09168). The original
+//! paper gates LLM-agent tool calls: it maps a proposed action to a structural
+//! causal query `E[Y | do(t_v = t*)]`, checks identifiability under a committed
+//! graph, computes a one-sided lower confidence bound on the do-effect, and
+//! returns one of four auditable verdicts: EXECUTE / REJECT / EXPERIMENT /
+//! ABSTAIN, each carrying a causal certificate.
+//!
+//! This module ports the structural shape to ontology operations: every state-
+//! changing `onto_*` tool (apply / save / push / ingest / enrich) can be wrapped
+//! in `certify_action` to obtain a verdict + certificate before executing.
+//!
+//! ## Scaffold scope vs paper
+//!
+//! What's faithful:
+//!
+//! - The four-way verdict.
+//! - The certificate as an auditable JSON artefact: structural-graph slice
+//! hash, labelled assumptions, identification proof, point estimate,
+//! one-sided LCB, provenance hash, risk bound.
+//! - LCB-based safety gating (executions are bounded at the LCB level α).
+//! - Locked-IRI hard-rejection (the analogue of "risk class is forbidden").
+//!
+//! What's intentionally a proxy (and honestly documented):
+//!
+//! - **Identifiability check:** the paper runs backdoor / frontdoor / IV from
+//! do-calculus. The scaffold runs a **structural-dependency check** —
+//! "the proposed change is identifiable iff its effect on the utility metric
+//! is bounded by the closure of dependent IRIs in the loaded ontology."
+//! This is a sound conservative proxy for the typical ontology-edit case
+//! (linear blast radius from a target IRI), not a substitute for true
+//! do-calculus. The certificate flags this with `assumption = "structural_only"`.
+//! - **The EXPERIMENT branch:** the paper consumes paired RCT-style data; the
+//! scaffold maps EXPERIMENT to "queue for sandbox replay" and exposes a
+//! separate path; it does not synthesise an RCT from observational data.
+//! - **Adversarial-confounding robustness:** out of scope. The paper's Table 2
+//! result depends on Causal-ToolBench instrumentation; the scaffold honest-
+//! documents that confounded ontology workflows (e.g. cascading restriction
+//! updates) may produce LCBs the verifier cannot defend against an
+//! adversarial confounder.
+//!
+//! The follow-up issues track each of these toward production-grade fidelity.
+
+use crate::graph::GraphStore;
+use crate::state::StateDb;
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+use std::sync::Arc;
+
+/// An action frame describing a proposed state-changing ontology operation.
+/// Mirrors the paper's `a = (tool, t_v, t*, Y, c, r)` tuple.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct ActionFrame {
+ /// Name of the onto_* tool whose execution this certifies (e.g. "onto_apply",
+ /// "onto_save", "onto_push", "onto_ingest").
+ pub tool: String,
+ /// The IRIs being targeted by the proposed change. In CIVeX terms, the
+ /// `t_v` (target variable) generalises to the set of structural variables
+ /// the action intervenes on.
+ pub target_iris: Vec<String>,
+ /// The proposed change expressed as Turtle. Treated as the `t*` (target
+ /// value) — what the action would set the target IRIs' neighbourhood to.
+ pub proposed_delta_ttl: String,
+ /// The utility variable name. The scaffold computes the do-effect on this
+ /// metric. Supported values:
+ /// - `"dependent_query_pass_rate"` (default) — the caller supplies a list of
+ /// SPARQL queries in `dependent_queries`; the LCB is over the pre/post
+ /// pass rate.
+ /// - `"triple_count_delta"` — coarse proxy: change in total triple count.
+ /// - `"class_count_delta"` / `"property_count_delta"` — class/property
+ /// vocabulary changes.
+ pub utility_metric: String,
+ /// Optional list of SPARQL queries that should remain answerable post-change.
+ /// Used when `utility_metric == "dependent_query_pass_rate"`.
+ #[serde(default)]
+ pub dependent_queries: Vec<String>,
+ /// Cost budget. The action is REJECTED if `cost > cost_threshold`. Cost is
+ /// measured in triples-affected (from blast-radius), matching `onto_plan`.
+ pub cost_threshold: u64,
+ /// Utility threshold for EXECUTE. The action is EXECUTED only if
+ /// `LCB_α ≥ utility_threshold`. Conventional values: 0.0 for "do no harm",
+ /// 0.5 for "majority of dependent queries still answer", etc.
+ pub utility_threshold: f64,
+ /// Risk threshold. Upper bound on potential harm. Action is REJECTED if
+ /// `cost > risk_threshold` even when within the cost budget.
+ pub risk_threshold: u64,
+ /// Whether the action is reversible (has a defined inverse). Maps to the
+ /// paper's `r ∈ {0, 1}`. Reversibility unlocks the EXPERIMENT branch.
+ pub reversible: bool,
+ /// When true, the EXPERIMENT verdict is legal output; otherwise unknown
+ /// utility forces ABSTAIN. The paper requires explicit opt-in for
+ /// experimentation because it consumes real resources.
+ #[serde(default)]
+ pub allow_experiment: bool,
+ /// One-sided confidence level α for the LCB. Default 0.05 (95% one-sided).
+ /// Matches the paper's `LCB_{α=0.05}`.
+ #[serde(default = "default_alpha")]
+ pub alpha: f64,
+}
+
+fn default_alpha() -> f64 {
+ 0.05
+}
+
+/// The four-way verdict from `certify_action`. Auditable; the certificate
+/// documents the assumptions under which the verdict holds.
+#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
+pub enum Verdict {
+ /// The action's effect is identifiable, its LCB clears the utility threshold,
+ /// and its cost is within budget. Execution is bounded at the α level
+ /// (probability of false-execute ≤ α).
+ Execute,
+ /// A hard constraint fails: locked IRIs would be touched, cost exceeds
+ /// the risk threshold, or the action is irreversible with insufficient
+ /// utility certainty.
+ Reject,
+ /// Utility is unidentifiable under the current observational data, but the
+ /// action is reversible and the caller has set `allow_experiment = true`.
+ /// The orchestrator is expected to run the action in a sandbox / dry-run
+ /// path, collect the resulting data, and re-invoke `certify_action` with
+ /// the updated evidence.
+ Experiment,
+ /// Utility ambiguous and either the action is irreversible or the caller
+ /// has not authorised experimentation. The orchestrator must obtain more
+ /// information (refine the utility metric, supply more dependent queries,
+ /// or relax the threshold) before re-invoking.
+ Abstain,
+}
+
+/// An auditable causal certificate. JSON-serialisable; the orchestrator can
+/// log this artefact alongside the lineage trail.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct Certificate {
+ /// Verdict on the proposed action.
+ pub verdict: Verdict,
+ /// Hash of the structural dependency slice the verifier consulted. Stable
+ /// across runs over the same committed graph state, so a verdict is replayable.
+ pub graph_slice_hash: String,
+ /// Labelled assumptions under which the verdict holds. The scaffold always
+ /// emits `"structural_only"` (as opposed to full do-calculus identifiability)
+ /// plus the locked-IRI and reversibility flags actually used.
+ pub assumptions: Vec<String>,
+ /// Identification proof. For the scaffold this is a one-line statement:
+ /// `"structural-dependency closure of {target_iris} has bounded blast radius {N}"`.
+ /// A production verifier would emit a backdoor / frontdoor / IV proof.
+ pub identification_proof: String,
+ /// Point estimate of the do-effect on the utility metric.
+ pub utility_point_estimate: f64,
+ /// One-sided lower confidence bound on the do-effect at level α.
+ pub utility_lcb: f64,
+ /// α level the LCB was computed at.
+ pub alpha: f64,
+ /// SHA-256 hash of the observational data used (canonical-form snapshot
+ /// of the loaded ontology plus the proposed delta). Used for provenance
+ /// and replay.
+ pub provenance_hash: String,
+ /// Upper bound on potential harm, measured in triples-affected. Matches
+ /// the `cost` from `onto_plan`'s blast-radius.
+ pub risk_bound: u64,
+ /// Human-readable rationale explaining the verdict. Concatenation of the
+ /// triage rules that fired.
+ pub rationale: String,
+}
+
+/// Aggregate of the certificate plus side evidence for the orchestrator.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct CertifyActionResult {
+ pub certificate: Certificate,
+ /// Number of dependent queries evaluated (when utility_metric is
+ /// `"dependent_query_pass_rate"`).
+ pub dependent_queries_evaluated: usize,
+ /// Per-query pass results post-delta (when utility_metric is
+ /// `"dependent_query_pass_rate"`).
+ pub per_query_pass: Vec<bool>,
+}
+
+/// Certify a proposed state-changing ontology action.
+///
+/// Returns a `CertifyActionResult` carrying the verdict, certificate, and
+/// evidence. The orchestrator decides whether to actually execute the action
+/// based on the verdict — this function is a gate, not an executor.
+pub fn certify_action(
+ db: &StateDb,
+ graph: &Arc<GraphStore>,
+ frame: &ActionFrame,
+) -> anyhow::Result<CertifyActionResult> {
+ // ── Step 1: locked-IRI check ────────────────────────────────────────────
+ // The hardest hard-constraint. Mirrors the paper's "risk class is forbidden"
+ // branch. Locked IRIs always REJECT regardless of utility.
+ let planner = crate::plan::Planner::new(db.clone(), graph.clone());
+ let locked_violations: Vec<String> = frame
+ .target_iris
+ .iter()
+ .filter(|iri| planner.is_locked(iri))
+ .cloned()
+ .collect();
+
+ // ── Step 2: blast-radius (cost) ─────────────────────────────────────────
+ // Reuses the existing onto_plan accounting.
+ let plan_json_str = planner.plan(&frame.proposed_delta_ttl)?;
+ let plan_json: serde_json::Value = serde_json::from_str(&plan_json_str)?;
+ let cost_triples = plan_json["blast_radius"]["triples_affected"]
+ .as_u64()
+ .unwrap_or(0);
+
+ // ── Step 3: structural-dependency slice + hash ──────────────────────────
+ let dependency_iris = collect_dependency_iris(graph, &frame.target_iris);
+ let slice_hash = hash_iri_set(&dependency_iris);
+
+ // ── Step 4: utility estimate + LCB (Wilson one-sided) ───────────────────
+ let (utility_point, utility_lcb, queries_eval, per_query_pass) = match frame
+ .utility_metric
+ .as_str()
+ {
+ "dependent_query_pass_rate" => {
+ evaluate_dependent_queries(graph, &frame.proposed_delta_ttl, &frame.dependent_queries, frame.alpha)?
+ }
+ _ => {
+ // Fallback: utility is a binary "delta is non-degenerate" check.
+ // Point estimate 1.0 if the delta loads as valid Turtle and adds at
+ // least one triple, else 0.0. LCB conservatively equals point estimate.
+ let temp = GraphStore::new();
+ let ok = temp.load_turtle(&frame.proposed_delta_ttl, None).is_ok();
+ let p = if ok { 1.0 } else { 0.0 };
+ (p, p, 0, Vec::new())
+ }
+ };
+
+ // ── Step 5: provenance hash (canonical-form snapshot + delta) ───────────
+ let provenance_hash = compute_provenance_hash(graph, &frame.proposed_delta_ttl)?;
+
+ // ── Step 6: triage ──────────────────────────────────────────────────────
+ let mut rationale_parts: Vec<String> = Vec::new();
+ let mut assumptions: Vec<String> = vec!["structural_only".to_string()];
+ if frame.reversible {
+ assumptions.push("reversible".to_string());
+ } else {
+ assumptions.push("irreversible".to_string());
+ }
+
+ let verdict = if !locked_violations.is_empty() {
+ rationale_parts.push(format!(
+ "REJECT: {} locked IRI(s) targeted",
+ locked_violations.len()
+ ));
+ Verdict::Reject
+ } else if cost_triples > frame.risk_threshold {
+ rationale_parts.push(format!(
+ "REJECT: cost {} exceeds risk_threshold {}",
+ cost_triples, frame.risk_threshold
+ ));
+ Verdict::Reject
+ } else if cost_triples > frame.cost_threshold {
+ rationale_parts.push(format!(
+ "REJECT: cost {} exceeds cost_threshold {}",
+ cost_triples, frame.cost_threshold
+ ));
+ Verdict::Reject
+ } else if utility_lcb >= frame.utility_threshold {
+ rationale_parts.push(format!(
+ "EXECUTE: utility_lcb {:.3} ≥ utility_threshold {:.3}, cost {} within budget {}",
+ utility_lcb, frame.utility_threshold, cost_triples, frame.cost_threshold
+ ));
+ Verdict::Execute
+ } else if frame.reversible && frame.allow_experiment {
+ rationale_parts.push(format!(
+ "EXPERIMENT: utility_lcb {:.3} < threshold {:.3} but reversible and experiment authorised",
+ utility_lcb, frame.utility_threshold
+ ));
+ Verdict::Experiment
+ } else {
+ rationale_parts.push(format!(
+ "ABSTAIN: utility_lcb {:.3} < threshold {:.3}, irreversible or experiment not authorised",
+ utility_lcb, frame.utility_threshold
+ ));
+ Verdict::Abstain
+ };
+
+ let identification_proof = format!(
+ "structural-dependency closure of {} target IRI(s) has bounded blast radius of {} triples",
+ frame.target_iris.len(),
+ cost_triples
+ );
+
+ let certificate = Certificate {
+ verdict,
+ graph_slice_hash: slice_hash,
+ assumptions,
+ identification_proof,
+ utility_point_estimate: utility_point,
+ utility_lcb,
+ alpha: frame.alpha,
+ provenance_hash,
+ risk_bound: cost_triples,
+ rationale: rationale_parts.join("; "),
+ };
+
+ // Record into lineage for audit trail.
+ let lineage = crate::lineage::LineageLog::new(db.clone());
+ lineage.record(
+ "civex",
+ "CV",
+ &format!("certify:{}", frame.tool),
+ &format!("{:?}:cost={}:lcb={:.3}", verdict, cost_triples, utility_lcb),
+ );
+
+ Ok(CertifyActionResult {
+ certificate,
+ dependent_queries_evaluated: queries_eval,
+ per_query_pass,
+ })
+}
+
+/// Evaluate each dependent SPARQL query against the (current state + proposed delta).
+/// Returns (point estimate, Wilson LCB at α, evaluated count, per-query pass vec).
+fn evaluate_dependent_queries(
+ graph: &Arc<GraphStore>,
+ proposed_delta_ttl: &str,
+ queries: &[String],
+ alpha: f64,
+) -> anyhow::Result<(f64, f64, usize, Vec<bool>)> {
+ if queries.is_empty() {
+ // No queries to evaluate — best we can say is "pass rate undefined".
+ // Conservative: point estimate 1.0 (no evidence of failure), LCB 0.0.
+ return Ok((1.0, 0.0, 0, Vec::new()));
+ }
+
+ // Build a temp store: clone of current graph + apply delta.
+ // For the scaffold we load the delta into a fresh store rather than
+ // round-tripping through the main graph (cheaper + side-effect-free).
+ let combined = GraphStore::new();
+ let snapshot_ttl = graph.serialize("turtle")?;
+ combined.load_turtle(&snapshot_ttl, None)?;
+ combined.load_turtle(proposed_delta_ttl, None)?;
+
+ let mut passes = Vec::with_capacity(queries.len());
+ for q in queries {
+ let ok = combined.sparql_select(q).is_ok();
+ passes.push(ok);
+ }
+
+ let n = passes.len() as f64;
+ let k = passes.iter().filter(|p| **p).count() as f64;
+ let p_hat = k / n;
+ let lcb = wilson_one_sided_lcb(k as u64, n as u64, alpha);
+
+ Ok((p_hat, lcb, passes.len(), passes))
+}
+
+/// Wilson one-sided lower confidence bound for a binomial proportion. Closed
+/// form, no stats library required. Conservative at small n.
+fn wilson_one_sided_lcb(k: u64, n: u64, alpha: f64) -> f64 {
+ if n == 0 {
+ return 0.0;
+ }
+ let z = z_from_alpha(alpha);
+ let n_f = n as f64;
+ let p_hat = k as f64 / n_f;
+ let denom = 1.0 + (z * z) / n_f;
+ let centre = p_hat + (z * z) / (2.0 * n_f);
+ let radius = z * (p_hat * (1.0 - p_hat) / n_f + (z * z) / (4.0 * n_f * n_f)).sqrt();
+ let lcb = (centre - radius) / denom;
+ lcb.clamp(0.0, 1.0)
+}
+
+/// Z-value for a one-sided α. Hard-coded table for common α; closed-form inverse-
+/// normal would be cleaner but adds a dependency we don't need for typical uses.
+fn z_from_alpha(alpha: f64) -> f64 {
+ // One-sided critical values: P(Z ≥ z) = α.
+ if alpha <= 0.005 {
+ 2.576
+ } else if alpha <= 0.01 {
+ 2.326
+ } else if alpha <= 0.025 {
+ 1.960
+ } else if alpha <= 0.05 {
+ 1.645
+ } else if alpha <= 0.1 {
+ 1.282
+ } else {
+ 0.842 // α ≈ 0.2
+ }
+}
+
+/// Collect IRIs structurally dependent on the action's target IRIs. The scaffold
+/// uses one-hop closure (subjects/objects of any triple referencing a target).
+/// A production version would walk the full subclass + property-domain/range
+/// closure and bound the recursion.
+fn collect_dependency_iris(graph: &Arc<GraphStore>, target_iris: &[String]) -> Vec<String> {
+ use std::collections::BTreeSet;
+ let mut deps: BTreeSet<String> = BTreeSet::new();
+ for iri in target_iris {
+ let q = format!(
+ r#"SELECT DISTINCT ?x WHERE {{
+ {{ <{iri}> ?p ?x }} UNION
+ {{ ?x ?p <{iri}> }} UNION
+ {{ ?x <{iri}> ?o }}
+ }} LIMIT 200"#
+ );
+ if let Ok(json_str) = graph.sparql_select(&q)
+ && let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&json_str)
+ && let Some(rows) = parsed["results"].as_array()
+ {
+ for row in rows {
+ if let Some(x) = row["x"].as_str() {
+ deps.insert(x.trim_matches(|c| c == '<' || c == '>').to_string());
+ }
+ }
+ }
+ }
+ for iri in target_iris {
+ deps.insert(iri.clone());
+ }
+ deps.into_iter().collect()
+}
+
+/// Stable hash of an IRI set. SHA-256 over the sorted concatenation.
+fn hash_iri_set(iris: &[String]) -> String {
+ let mut sorted: Vec<&String> = iris.iter().collect();
+ sorted.sort();
+ let mut hasher = Sha256::new();
+ for iri in sorted {
+ hasher.update(iri.as_bytes());
+ hasher.update(b"\n");
+ }
+ hex_encode(&hasher.finalize())
+}
+
+/// SHA-256 over (current graph canonical-form serialisation + the proposed delta).
+fn compute_provenance_hash(graph: &Arc<GraphStore>, delta_ttl: &str) -> anyhow::Result<String> {
+ let snapshot = graph.serialize("turtle")?;
+ let mut hasher = Sha256::new();
+ hasher.update(snapshot.as_bytes());
+ hasher.update(b"\n--DELTA--\n");
+ hasher.update(delta_ttl.as_bytes());
+ Ok(hex_encode(&hasher.finalize()))
+}
+
+fn hex_encode(bytes: &[u8]) -> String {
+ let mut s = String::with_capacity(bytes.len() * 2);
+ for b in bytes {
+ s.push_str(&format!("{:02x}", b));
+ }
+ s
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn wilson_lcb_at_full_pass_is_strictly_below_one() {
+ // 10/10 passes should give an LCB below 1.0 — Wilson's whole point is that
+ // observing a 100% pass rate on a small sample doesn't certify the true
+ // rate is 100%.
+ let lcb = wilson_one_sided_lcb(10, 10, 0.05);
+ assert!(lcb < 1.0, "Wilson LCB at 10/10 should be < 1.0; got {}", lcb);
+ assert!(lcb > 0.7, "but it should still be > 0.7; got {}", lcb);
+ }
+
+ #[test]
+ fn wilson_lcb_at_zero_pass_is_zero() {
+ let lcb = wilson_one_sided_lcb(0, 10, 0.05);
+ assert!(lcb <= 0.01, "Wilson LCB at 0/10 should be ≈ 0; got {}", lcb);
+ }
+
+ #[test]
+ fn wilson_lcb_at_empty_n_is_zero() {
+ assert_eq!(wilson_one_sided_lcb(0, 0, 0.05), 0.0);
+ }
+
+ #[test]
+ fn z_from_alpha_monotone_decreasing() {
+ // As α grows, the critical value should shrink (or stay equal for the
+ // hard-coded bands).
+ let zs = [
+ z_from_alpha(0.005),
+ z_from_alpha(0.01),
+ z_from_alpha(0.025),
+ z_from_alpha(0.05),
+ z_from_alpha(0.1),
+ ];
+ for w in zs.windows(2) {
+ assert!(w[0] >= w[1], "z table must be monotone decreasing in α");
+ }
+ }
+
+ #[test]
+ fn hash_iri_set_is_deterministic() {
+ let a = hash_iri_set(&["b".to_string(), "a".to_string(), "c".to_string()]);
+ let b = hash_iri_set(&["c".to_string(), "a".to_string(), "b".to_string()]);
+ assert_eq!(a, b, "hash must be order-independent");
+ assert_eq!(a.len(), 64, "SHA-256 hex is 64 chars");
+ }
+}
diff --git a/src/inputs.rs b/src/inputs.rs
index 1eec7308..d0c31ee1 100644
--- a/src/inputs.rs
+++ b/src/inputs.rs
@@ -543,6 +543,61 @@ pub struct AlignOntologiesInput {
pub target_path: String,
}
+/// Input for the CIVeX-style action certification tool (`onto_certify_action`).
+/// Mirrors the paper's action frame structure plus the policy thresholds needed
+/// for the triage step. See `src/civex.rs` for the full semantic.
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoCertifyActionInput {
+ /// Name of the state-changing onto_* tool whose execution this gates.
+ pub tool: String,
+ /// The IRIs being targeted by the proposed change.
+ pub target_iris: Vec<String>,
+ /// The proposed change as Turtle.
+ pub proposed_delta_ttl: String,
+ /// Utility metric name. One of "dependent_query_pass_rate" (default — caller
+ /// supplies `dependent_queries`), "triple_count_delta", "class_count_delta",
+ /// "property_count_delta".
+ #[serde(default = "default_utility_metric")]
+ pub utility_metric: String,
+ /// SPARQL queries that should remain answerable post-change. Used when
+ /// `utility_metric == "dependent_query_pass_rate"`.
+ #[serde(default)]
+ pub dependent_queries: Vec<String>,
+ /// Cost budget (triples-affected). Action is REJECTED if cost > this.
+ pub cost_threshold: u64,
+ /// Utility threshold for EXECUTE. LCB must clear this.
+ pub utility_threshold: f64,
+ /// Risk threshold. Hard reject if cost exceeds this (even within budget).
+ pub risk_threshold: u64,
+ /// Whether the action is reversible.
+ pub reversible: bool,
+ /// Authorise the EXPERIMENT verdict (caller commits to running a sandbox replay).
+ #[serde(default)]
+ pub allow_experiment: bool,
+ /// One-sided confidence level α for the LCB. Default 0.05.
+ #[serde(default = "default_alpha_pub")]
+ pub alpha: f64,
+}
+
+fn default_utility_metric() -> String {
+ "dependent_query_pass_rate".to_string()
+}
+
+fn default_alpha_pub() -> f64 {
+ 0.05
+}
+
+/// Input for `graph_projection_lossy_check` (#35) — audits whether a projected
+/// Turtle slice has dropped predicates/objects vs the full source neighbourhood
+/// of the seed IRIs.
+#[derive(Deserialize, JsonSchema)]
+pub struct GraphProjectionLossyCheckInput {
+ /// Seed IRIs whose neighbourhoods should be preserved by the projection.
+ pub source_iris: Vec<String>,
+ /// The projected Turtle slice that's being passed to a downstream consumer.
+ pub projected_ttl: String,
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/src/lib.rs b/src/lib.rs
index 3794e33d..5443fab9 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -4,7 +4,10 @@ pub mod error;
pub mod align;
pub mod config;
pub mod clinical;
+pub mod civex;
pub mod drift;
+pub mod projection_check;
+// (re-exports keep the alphabetical ordering of the surrounding modules manageable)
pub mod enforce;
pub mod kgcl;
pub mod feedback;
diff --git a/src/projection_check.rs b/src/projection_check.rs
new file mode 100644
index 00000000..6ecdaeef
--- /dev/null
+++ b/src/projection_check.rs
@@ -0,0 +1,235 @@
+//! Graph-projection loss audit (#35).
+//!
+//! Per the IJCAI 2025 paper "How to Mitigate Information Loss in Knowledge
+//! Graphs for GraphRAG", lossy graph projections silently degrade downstream
+//! retrieval quality. This module's `check_projection_loss` audits whether a
+//! projected Turtle slice has dropped predicates / objects / structural
+//! patterns vs the full neighbourhood of the seed IRIs in the loaded ontology.
+//!
+//! Designed as a complementary primitive to `onto_segment_retrieve` (#34) — the
+//! retriever produces the slice; this auditor reports what it left behind.
+
+use crate::graph::GraphStore;
+use serde::{Deserialize, Serialize};
+use std::collections::BTreeSet;
+use std::sync::Arc;
+
+/// Per-seed loss report.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct SeedLossReport {
+ pub seed_iri: String,
+ /// Predicates appearing in the source but absent from the projection.
+ pub dropped_predicates: Vec<String>,
+ /// Object IRIs appearing in the source but absent from the projection.
+ pub dropped_objects: Vec<String>,
+ /// Total source-side triples touching this seed.
+ pub source_triples: u64,
+ /// Total projection-side triples touching this seed.
+ pub projected_triples: u64,
+ /// `projected_triples / source_triples` (0.0 if source is empty).
+ pub coverage_ratio: f64,
+}
+
+/// Top-level audit report aggregating per-seed losses.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct ProjectionLossReport {
+ /// Whether projection parsed as Turtle.
+ pub projection_parses: bool,
+ /// Aggregate coverage ratio across all seeds (mean of per-seed ratios).
+ pub aggregate_coverage_ratio: f64,
+ /// Per-seed details.
+ pub per_seed: Vec<SeedLossReport>,
+ /// True iff projection_parses AND all per-seed coverage_ratio == 1.0.
+ pub ok: bool,
+ /// Total dropped predicates across all seeds (deduped).
+ pub total_dropped_predicates: usize,
+ /// Total dropped objects across all seeds (deduped).
+ pub total_dropped_objects: usize,
+}
+
+/// Audit a projected Turtle slice against the loaded ontology's full
+/// neighbourhood of the seed IRIs.
+///
+/// Returns a `ProjectionLossReport` with per-seed dropped predicates/objects
+/// and aggregate coverage. The loaded graph (`graph`) is the source of truth;
+/// `projected_ttl` is the slice being audited.
+pub fn check_projection_loss(
+ graph: &Arc<GraphStore>,
+ seed_iris: &[String],
+ projected_ttl: &str,
+) -> anyhow::Result<ProjectionLossReport> {
+ // Load the projection into a temp store. Parse failure ⇒ projection_parses=false.
+ let projected = GraphStore::new();
+ let parse_ok = projected.load_turtle(projected_ttl, None).is_ok();
+ if !parse_ok {
+ return Ok(ProjectionLossReport {
+ projection_parses: false,
+ aggregate_coverage_ratio: 0.0,
+ per_seed: Vec::new(),
+ ok: false,
+ total_dropped_predicates: 0,
+ total_dropped_objects: 0,
+ });
+ }
+
+ let projected_ref: Arc<GraphStore> = Arc::new(projected);
+
+ let mut per_seed = Vec::with_capacity(seed_iris.len());
+ let mut all_dropped_preds: BTreeSet<String> = BTreeSet::new();
+ let mut all_dropped_objs: BTreeSet<String> = BTreeSet::new();
+ let mut sum_ratio = 0.0;
+
+ for iri in seed_iris {
+ // Collect (predicate, object) pairs for this seed from both stores.
+ let source_pairs = neighbourhood_pairs(graph, iri)?;
+ let projected_pairs = neighbourhood_pairs(&projected_ref, iri)?;
+
+ let source_preds: BTreeSet<&str> = source_pairs.iter().map(|(p, _)| p.as_str()).collect();
+ let projected_preds: BTreeSet<&str> =
+ projected_pairs.iter().map(|(p, _)| p.as_str()).collect();
+ let dropped_preds: Vec<String> = source_preds
+ .difference(&projected_preds)
+ .map(|s| s.to_string())
+ .collect();
+
+ let source_objs: BTreeSet<&str> = source_pairs.iter().map(|(_, o)| o.as_str()).collect();
+ let projected_objs: BTreeSet<&str> = projected_pairs.iter().map(|(_, o)| o.as_str()).collect();
+ let dropped_objs: Vec<String> = source_objs
+ .difference(&projected_objs)
+ .map(|s| s.to_string())
+ .collect();
+
+ let source_n = source_pairs.len() as u64;
+ let projected_n = projected_pairs.len() as u64;
+ let coverage = if source_n == 0 {
+ 1.0
+ } else {
+ (projected_n.min(source_n) as f64) / (source_n as f64)
+ };
+
+ for d in &dropped_preds {
+ all_dropped_preds.insert(d.clone());
+ }
+ for d in &dropped_objs {
+ all_dropped_objs.insert(d.clone());
+ }
+ sum_ratio += coverage;
+
+ per_seed.push(SeedLossReport {
+ seed_iri: iri.clone(),
+ dropped_predicates: dropped_preds,
+ dropped_objects: dropped_objs,
+ source_triples: source_n,
+ projected_triples: projected_n,
+ coverage_ratio: coverage,
+ });
+ }
+
+ let n = seed_iris.len().max(1) as f64;
+ let aggregate = sum_ratio / n;
+ let ok = per_seed.iter().all(|r| (r.coverage_ratio - 1.0).abs() < 1e-9);
+
+ Ok(ProjectionLossReport {
+ projection_parses: true,
+ aggregate_coverage_ratio: aggregate,
+ per_seed,
+ ok,
+ total_dropped_predicates: all_dropped_preds.len(),
+ total_dropped_objects: all_dropped_objs.len(),
+ })
+}
+
+/// All `(predicate, object)` pairs where `iri` appears as the subject. We use
+/// subject-only as the canonical neighbourhood definition for the projection
+/// check; CIVeX-style structural-dependency closure would extend this to
+/// inbound edges, but for "did the slice preserve this seed's outbound
+/// description?" the subject view is the right unit.
+fn neighbourhood_pairs(
+ graph: &Arc<GraphStore>,
+ iri: &str,
+) -> anyhow::Result<Vec<(String, String)>> {
+ let q = format!(
+ r#"SELECT DISTINCT ?p ?o WHERE {{ <{iri}> ?p ?o }} LIMIT 1000"#
+ );
+ let mut out = Vec::new();
+ let json_str = graph.sparql_select(&q)?;
+ let parsed: serde_json::Value = serde_json::from_str(&json_str)?;
+ if let Some(rows) = parsed["results"].as_array() {
+ for row in rows {
+ let p = row["p"].as_str().unwrap_or("").trim_matches(|c| c == '<' || c == '>').to_string();
+ let o = row["o"].as_str().unwrap_or("").trim_matches(|c| c == '<' || c == '>').to_string();
+ if !p.is_empty() {
+ out.push((p, o));
+ }
+ }
+ }
+ Ok(out)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn loaded(ttl: &str) -> Arc<GraphStore> {
+ let g = Arc::new(GraphStore::new());
+ g.load_turtle(ttl, None).expect("load");
+ g
+ }
+
+ #[test]
+ fn full_projection_reports_ok_and_full_coverage() {
+ let source = r#"
+ @prefix ex: <http://ex.org/> .
+ ex:Cat ex:hasColour ex:Black ; ex:age 5 .
+ "#;
+ let projection = source; // identical
+ let g = loaded(source);
+ let report = check_projection_loss(&g, &["http://ex.org/Cat".to_string()], projection).unwrap();
+ assert!(report.ok);
+ assert_eq!(report.aggregate_coverage_ratio, 1.0);
+ assert_eq!(report.total_dropped_predicates, 0);
+ }
+
+ #[test]
+ fn dropped_predicate_is_reported() {
+ let source = r#"
+ @prefix ex: <http://ex.org/> .
+ ex:Cat ex:hasColour ex:Black ; ex:age 5 ; ex:species "Felis catus" .
+ "#;
+ // Projection keeps only hasColour; drops age and species.
+ let projection = r#"
+ @prefix ex: <http://ex.org/> .
+ ex:Cat ex:hasColour ex:Black .
+ "#;
+ let g = loaded(source);
+ let report = check_projection_loss(&g, &["http://ex.org/Cat".to_string()], projection).unwrap();
+ assert!(!report.ok);
+ assert!(report.total_dropped_predicates >= 2);
+ let cat_report = &report.per_seed[0];
+ assert!(cat_report.dropped_predicates.iter().any(|p| p.contains("age")));
+ assert!(cat_report.dropped_predicates.iter().any(|p| p.contains("species")));
+ }
+
+ #[test]
+ fn invalid_projection_turtle_reports_parses_false() {
+ let g = loaded(r#"@prefix ex: <http://ex.org/> . ex:X ex:p ex:Y ."#);
+ let report = check_projection_loss(&g, &["http://ex.org/X".to_string()], "this is not turtle: << >>").unwrap();
+ assert!(!report.projection_parses);
+ assert!(!report.ok);
+ }
+
+ #[test]
+ fn missing_seed_in_source_has_full_coverage_by_definition() {
+ // If the seed has no triples in source, there's nothing to drop —
+ // coverage is trivially 1.0.
+ let g = loaded(r#"@prefix ex: <http://ex.org/> . ex:Other ex:p ex:Z ."#);
+ let report = check_projection_loss(
+ &g,
+ &["http://ex.org/UnknownSeed".to_string()],
+ r#"@prefix ex: <http://ex.org/> . ex:Other ex:p ex:Z ."#,
+ )
+ .unwrap();
+ assert!(report.ok);
+ assert_eq!(report.per_seed[0].source_triples, 0);
+ }
+}
diff --git a/src/server.rs b/src/server.rs
index 911f6ac5..cfdc61a4 100644
--- a/src/server.rs
+++ b/src/server.rs
@@ -929,6 +929,37 @@ impl OpenOntologiesServer {
.unwrap_or_else(|e| format!(r#"{{"error":"{}"}}"#, e))
}
+ #[tool(name = "graph_projection_lossy_check", description = "Audit a projected Turtle slice against the loaded ontology's full neighbourhood of the seed IRIs. Reports dropped predicates, dropped object IRIs, per-seed coverage ratio, and aggregate coverage. Pair with onto_segment_retrieve when the slice is being passed to a downstream LLM — knowing what was left behind lets the caller decide whether the slice is sufficient. Per IJCAI 2025 'How to Mitigate Information Loss in KGs for GraphRAG'.")]
+ async fn graph_projection_lossy_check(&self, Parameters(input): Parameters<GraphProjectionLossyCheckInput>) -> String {
+ match crate::projection_check::check_projection_loss(&self.graph, &input.source_iris, &input.projected_ttl) {
+ Ok(report) => serde_json::to_string(&report)
+ .unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e)),
+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),
+ }
+ }
+
+ #[tool(name = "onto_certify_action", description = "CIVeX-style causal certificate for a proposed state-changing ontology action. Returns a verdict (EXECUTE / REJECT / EXPERIMENT / ABSTAIN) plus an auditable certificate documenting the assumptions, structural-dependency identification proof, utility point estimate + one-sided lower confidence bound, provenance hash, and risk bound. Use as a pre-flight gate for onto_apply / onto_save / onto_push / onto_ingest. Scaffold port of arXiv:2605.09168 — structural-dependency proxy in place of full do-calculus identifiability; documented honestly.")]
+ async fn onto_certify_action(&self, Parameters(input): Parameters<OntoCertifyActionInput>) -> String {
+ let frame = crate::civex::ActionFrame {
+ tool: input.tool,
+ target_iris: input.target_iris,
+ proposed_delta_ttl: input.proposed_delta_ttl,
+ utility_metric: input.utility_metric,
+ dependent_queries: input.dependent_queries,
+ cost_threshold: input.cost_threshold,
+ utility_threshold: input.utility_threshold,
+ risk_threshold: input.risk_threshold,
+ reversible: input.reversible,
+ allow_experiment: input.allow_experiment,
+ alpha: input.alpha,
+ };
+ match crate::civex::certify_action(&self.db, &self.graph, &frame) {
+ Ok(result) => serde_json::to_string(&result)
+ .unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e)),
+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),
+ }
+ }
+
#[tool(name = "onto_reason", description = "Run inference over the loaded ontology. Profiles: 'rdfs' (subclass, domain/range), 'owl-rl' (+ transitive/symmetric/inverse, sameAs, equivalentClass), 'owl-rl-ext' (+ someValuesFrom, allValuesFrom, hasValue, intersectionOf, unionOf), 'owl-dl' (Full OWL2-DL SHOIQ tableaux: satisfiability, classification, qualified number restrictions with node merging, inverse/symmetric roles, functional properties, parallel agent-based classification, explanation traces, ABox reasoning). Materializes inferred triples.")]
async fn onto_reason(&self, Parameters(input): Parameters<OntoReasonInput>) -> String {
use crate::reason::Reasoner;
diff --git a/tests/civex_test.rs b/tests/civex_test.rs
new file mode 100644
index 00000000..af8ec9e4
--- /dev/null
+++ b/tests/civex_test.rs
@@ -0,0 +1,181 @@
+//! Integration tests for the CIVeX action-certification scaffold (#42).
+
+use open_ontologies::civex::{certify_action, ActionFrame, Verdict};
+use open_ontologies::graph::GraphStore;
+use open_ontologies::state::StateDb;
+use std::sync::Arc;
+use tempfile::NamedTempFile;
+
+fn setup() -> (StateDb, Arc<GraphStore>) {
+ let tmp = NamedTempFile::new().unwrap();
+ let path = tmp.path().to_path_buf();
+ std::mem::forget(tmp);
+ let db = StateDb::open(&path).unwrap();
+ let graph = Arc::new(GraphStore::new());
+ (db, graph)
+}
+
+fn base_frame() -> ActionFrame {
+ // 5 queries → 5/5 pass at α=0.05 gives Wilson LCB ≈ 0.535 > 0.5 threshold.
+ // 1 query would give LCB ≈ 0.27, which would correctly ABSTAIN — Wilson's
+ // whole point is to not over-trust small samples.
+ ActionFrame {
+ tool: "onto_apply".to_string(),
+ target_iris: vec!["http://ex.org/Cat".to_string()],
+ proposed_delta_ttl: r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix ex: <http://ex.org/> .
+ ex:Tiger a owl:Class .
+ "#.to_string(),
+ utility_metric: "dependent_query_pass_rate".to_string(),
+ dependent_queries: vec![
+ "SELECT ?x WHERE { ?x a <http://www.w3.org/2002/07/owl#Class> }".to_string(),
+ "SELECT (COUNT(?x) AS ?n) WHERE { ?x a <http://www.w3.org/2002/07/owl#Class> }".to_string(),
+ "SELECT ?x WHERE { ?x ?p ?o } LIMIT 5".to_string(),
+ "SELECT ?p WHERE { ?s ?p ?o } LIMIT 5".to_string(),
+ "SELECT ?o WHERE { ?s ?p ?o } LIMIT 5".to_string(),
+ ],
+ cost_threshold: 1000,
+ utility_threshold: 0.5,
+ risk_threshold: 5000,
+ reversible: true,
+ allow_experiment: false,
+ alpha: 0.05,
+ }
+}
+
+#[test]
+fn benign_addition_to_well_formed_ontology_executes() {
+ let (db, graph) = setup();
+ graph.load_turtle(r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix ex: <http://ex.org/> .
+ ex:Cat a owl:Class .
+ ex:Dog a owl:Class .
+ "#, None).unwrap();
+
+ let frame = base_frame();
+ let result = certify_action(&db, &graph, &frame).expect("certify");
+
+ assert_eq!(result.certificate.verdict, Verdict::Execute,
+ "adding a new owl:Class should execute under a well-formed graph; rationale: {}",
+ result.certificate.rationale);
+ assert!(result.certificate.utility_lcb >= frame.utility_threshold);
+ assert!(!result.certificate.provenance_hash.is_empty());
+ assert!(result.certificate.assumptions.contains(&"structural_only".to_string()));
+}
+
+#[test]
+fn cost_exceeding_risk_threshold_rejects() {
+ let (db, graph) = setup();
+ // Pre-populate with classes the delta will REMOVE — this drives blast radius up.
+ graph.load_turtle(r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
+ @prefix ex: <http://ex.org/> .
+ ex:Animal a owl:Class .
+ ex:Cat a owl:Class ; rdfs:subClassOf ex:Animal .
+ ex:Dog a owl:Class ; rdfs:subClassOf ex:Animal .
+ ex:Bird a owl:Class ; rdfs:subClassOf ex:Animal .
+ "#, None).unwrap();
+
+ // Tiny risk threshold so any blast radius > 0 hits REJECT.
+ let mut frame = base_frame();
+ frame.risk_threshold = 0;
+ frame.cost_threshold = 0;
+ frame.target_iris = vec!["http://ex.org/Animal".to_string()];
+ // Delta that doesn't include Animal — implies its removal in plan-diff terms.
+ frame.proposed_delta_ttl = r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix ex: <http://ex.org/> .
+ ex:NewClass a owl:Class .
+ "#.to_string();
+
+ let result = certify_action(&db, &graph, &frame).expect("certify");
+ assert_eq!(result.certificate.verdict, Verdict::Reject);
+ assert!(result.certificate.rationale.contains("REJECT"));
+}
+
+#[test]
+fn locked_iri_target_rejects_regardless_of_utility() {
+ let (db, graph) = setup();
+ graph.load_turtle(r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix ex: <http://ex.org/> .
+ ex:Critical a owl:Class .
+ "#, None).unwrap();
+
+ // Lock the target IRI via the existing planner machinery.
+ let planner = open_ontologies::plan::Planner::new(db.clone(), graph.clone());
+ planner.lock_iri("http://ex.org/Critical", "load-bearing");
+
+ let mut frame = base_frame();
+ frame.target_iris = vec!["http://ex.org/Critical".to_string()];
+
+ let result = certify_action(&db, &graph, &frame).expect("certify");
+ assert_eq!(result.certificate.verdict, Verdict::Reject,
+ "locked IRI should hard-reject; got rationale: {}", result.certificate.rationale);
+ assert!(result.certificate.rationale.contains("locked"));
+}
+
+#[test]
+fn irreversible_with_ambiguous_utility_abstains() {
+ let (db, graph) = setup();
+ graph.load_turtle(r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix ex: <http://ex.org/> .
+ ex:Cat a owl:Class .
+ "#, None).unwrap();
+
+ let mut frame = base_frame();
+ // Demand 99% LCB — Wilson at 1/1 will be ~0.21, well below.
+ frame.utility_threshold = 0.99;
+ frame.reversible = false;
+ frame.allow_experiment = false;
+
+ let result = certify_action(&db, &graph, &frame).expect("certify");
+ assert_eq!(result.certificate.verdict, Verdict::Abstain);
+ assert!(result.certificate.rationale.contains("ABSTAIN"));
+}
+
+#[test]
+fn reversible_with_experiment_authorisation_returns_experiment() {
+ let (db, graph) = setup();
+ graph.load_turtle(r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix ex: <http://ex.org/> .
+ ex:Cat a owl:Class .
+ "#, None).unwrap();
+
+ let mut frame = base_frame();
+ frame.utility_threshold = 0.99; // unreachable LCB
+ frame.reversible = true;
+ frame.allow_experiment = true;
+
+ let result = certify_action(&db, &graph, &frame).expect("certify");
+ assert_eq!(result.certificate.verdict, Verdict::Experiment);
+ assert!(result.certificate.rationale.contains("EXPERIMENT"));
+}
+
+#[test]
+fn provenance_hash_changes_when_delta_changes() {
+ let (db, graph) = setup();
+ graph.load_turtle(r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix ex: <http://ex.org/> .
+ ex:Cat a owl:Class .
+ "#, None).unwrap();
+
+ let mut frame_a = base_frame();
+ frame_a.proposed_delta_ttl = "@prefix ex: <http://ex.org/> . ex:A a <http://www.w3.org/2002/07/owl#Class> .".to_string();
+ let mut frame_b = base_frame();
+ frame_b.proposed_delta_ttl = "@prefix ex: <http://ex.org/> . ex:B a <http://www.w3.org/2002/07/owl#Class> .".to_string();
+
+ let r_a = certify_action(&db, &graph, &frame_a).expect("a");
+ let r_b = certify_action(&db, &graph, &frame_b).expect("b");
+ assert_ne!(r_a.certificate.provenance_hash, r_b.certificate.provenance_hash,
+ "different deltas must produce different provenance hashes");
+ // Same provenance hash on a repeated certify with the SAME delta.
+ let r_a2 = certify_action(&db, &graph, &frame_a).expect("a2");
+ assert_eq!(r_a.certificate.provenance_hash, r_a2.certificate.provenance_hash);
+}