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
feat: three-layer architecture (Dynamics + Causal hookup + Planner) (#46)
Fabio Rovai956c7973262b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9ee36e7b..bdac7d93 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,12 @@ All notable changes to Open Ontologies are documented here.## [Unreleased]### Added+- **Causal: PyWhy/DoWhy backdoor identification subprocess scaffold (#48).** Scaffolds the Causal flagship's substantive v0.5 work without pulling Python into the default build. New optional Cargo feature `causal-pywhy` (off by default) enables a `src/civex_pywhy.rs` module that wraps DoWhy v0.13 as a subprocess — same pattern as `src/plan_classical.rs` does for Fast Downward. The wrapper embeds a self-contained Python driver (`PYWHY_PYTHON_DRIVER`) that reads `{nodes, edges, treatment, outcome}` from stdin, builds a `networkx` DiGraph, runs DoWhy's `identify_effect` for backdoor adjustment, and emits `{identifiable, adjustment_set, estimand_expression}` to stdout. Per the May 2026 roadmap memo: **Pearl–Shpitser ID is not ported to Rust** — DoWhy is a 15-year-stable Python implementation, so we wrap it. Honest behaviour when Python or DoWhy is missing: structured errors with `kind = "python_unavailable"` / `"pywhy_unavailable"` / `"dowhy_runtime_failed"` that the caller (eventually `certify_action` in v0.5) dispatches on to fall back to the structural proxy. Binary resolution order: explicit `python_override` → `PYTHON_BIN` env var → `python3` on PATH. **NOT yet integrated into `certify_action`** — the structural proxy (`"structural_only"` assumption) remains the only identifier in shipped certificates; integration tracks as the v0.5 ship. 9 unit tests cover parser cases (identifiable, unidentifiable, both error kinds, invalid JSON), python resolver (override + default + env var), embedded-driver sanity check, and `python_unavailable` behaviour on missing binary. Zero additional Rust dependencies — the entire feature is embedded Python + subprocess plumbing.+- **Dynamics: non-deterministic outcomes for ActionSchema (#49).** `ActionSchema` gains an additive `outcomes: Vec<Outcome>` field. Each `Outcome` carries a categorical `probability` in `[0, 1]`, its own `effects: Vec<EffectSpec>` list, and an optional human-readable `label` (e.g. `"success"` / `"degraded"` / `"failure"`). When `outcomes` is non-empty, `apply()` samples one outcome and executes its effects; the deterministic `effects` field is ignored. When empty (the default), the schema behaves exactly as before — full back-compat with v0.4 base. Probabilities are validated: the sum must equal `1.0 ± 1e-6` or `apply()` returns an error; negative probabilities are also rejected. Sampling uses an inline xorshift64 PRNG keyed by a seed — **zero new dependencies**, no `rand`/`fastrand` pulled in. New method `ActionSchema::apply_with_seed(graph, db, bindings, seed)` exposes the seed for reproducible sampling; the default `apply()` derives a seed from `SystemTime::now()`. `ApplyResult` gains `sampled_outcome: Option<usize>` and `sampled_outcome_label: Option<String>` so callers can see which branch fired. `onto_action_apply` gains an optional `seed: Option<u64>` parameter — pass it when you need reproducible runs (CIVeX certification, replay-from-audit-log, controlled experiments). Tests (4 new): `nondeterministic_apply_with_seed_is_reproducible`, `nondeterministic_apply_distribution_matches_probabilities` (1000-call smoke check that a 70/30 split lands within `[0.60, 0.80]`), `nondeterministic_apply_rejects_invalid_probability_sum`, `deterministic_schema_still_works_when_outcomes_is_empty` (back-compat).+- **Planner: `onto_plan_classical` — Fast Downward subprocess wrap (#50).** Optional convenience tool that completes the LLM-Modulo Planner pipeline (`compile_pddl` → `classical` → IRI-bind client-side → `validate`). Per the LLM-Modulo convention, the classical solver is still client-side — this wrapper exists so a caller who *does* have Fast Downward installed locally can ask the server to run it for them rather than shelling out themselves. Honest behaviour when Fast Downward is missing: returns a structured `binary_unavailable` error with installation guidance, never falls back to a silent stub. Binary resolution order: explicit `fast_downward_bin` parameter → `FAST_DOWNWARD_BIN` env var → `fast-downward.py` on PATH. Returns the raw `sas_plan` content (preserved verbatim) plus a parsed `operators: [{name, args}]` list and the `; cost = N (...)` footer extracted separately. Search strategy is configurable (default `"lama-first"`; pass `"astar(lmcut())"` etc.). Reads the highest-numbered `sas_plan.N` variant when satisficing search emits multiple plans. New module `src/plan_classical.rs` with 7 unit tests covering parse cases (three-operator plan with cost footer, blank-line + comment skipping, empty input, zero-arg operators) and resolver / error behaviour (explicit override, default fallback, `binary_unavailable` on missing binary). New MCP tool `onto_plan_classical` + `OntoPlanClassicalInput`.+- **Planner: `onto_plan_validate` — LLM-Modulo validator primitive (#45).** Server-side companion to `onto_plan_compile_pddl`. Per the LLM-Modulo convention (Kambhampati arXiv 2402.01817), the server compiles + validates, the orchestrator solves. The validator takes a candidate plan (an ordered list of `{action_name, bindings}` operator instances — typically produced client-side by Fast Downward, LLM prompting, or any other source) and step-by-step: (a) looks up each step's registered `ActionSchema`, (b) re-evaluates its preconditions against the cumulative sandbox state under the step's bindings, (c) if applicable, executes its effects against the sandbox, (d) if not, returns immediately with the failing step index and a diagnostic. **Critically, the validator forks the loaded graph into an isolated sandbox** so the real store is never mutated — verified by a dedicated test. Multi-step plans correctly chain state through: a test exercises Step 1 establishing the precondition that Step 2 needs (declare `ex:Feline` as a class, then add `ex:Cat rdfs:subClassOf ex:Feline`). Optional `goal_facts` are checked post-plan and reported in `unsatisfied_goals` (without invalidating the plan itself — a well-formed plan that just doesn't reach the goal is still well-formed). Internal scratch `StateDb` opened as `:memory:` so per-step lineage entries don't pollute the production audit trail. New module `src/plan_validate.rs` + 6 unit tests covering empty plan, single-step success, missing action, unsatisfied precondition, multi-step state-chain, and goal-checking semantics. New MCP tool `onto_plan_validate` + `OntoPlanValidateInput` / `PlanStepInput`.+- **Dynamics: ramification via OWL-RL closure after apply (#47).** First follow-on to the Dynamics scaffold. New `ActionSchema::apply_with_ramification(graph, db, bindings, profile)` method that runs the existing `reason::Reasoner` immediately after the literal effects land, materialising downstream entailments into the same graph. `ApplyResult` gains two new fields: `derived_triples_added: usize` (count of new triples the reasoner produced beyond the literal effects) and `ramification_profile: Option<String>` (the profile actually run, or `None` when ramification was skipped). The `onto_action_apply` MCP tool gains a `ramify` parameter accepting any of `"rdfs"` / `"owl-rl"` / `"owl-rl-ext"` / `"owl-dl"`; default `None` preserves the previous literal-effects-only behaviour. Validated against the canonical acceptance case from #47: a schema that adds `?child rdfs:subClassOf ?parent`, applied with `ramify="owl-rl"` over a graph containing `ex:tigger a ex:Cat`, materialises `ex:tigger a ex:Animal` via subClassOf transitivity. Two new unit tests in `src/dynamics.rs`.+- **Dynamics layer scaffold + Planner stub (three-layer architecture, #43 + #45).** First two of the three v0.4–v0.6 layers from the May 2026 KR/UAI/ICAPS/AAMAS roadmap land as additive scaffolding on top of v0.2's primitives — no breaking changes to existing tools. **Dynamics** introduces `ActionSchema` (BC+ deterministic-single-effect subset): typed `Parameter` slots, SPARQL `ASK`/`SELECT` `preconditions` with `{param}` substitution, and KGCL-shaped `effects` (`AddTriple` / `RemoveTriple` / `AddClass`). Schemas persist by name in a new `dynamics_action_schemas` SQLite table; `apply()` runs the effects, emits the KGCL Controlled-Natural-Language patch, mints an IES4-style event IRI, and logs to `lineage`. Four new MCP tools: `onto_action_register` (persist a schema from inline JSON), `onto_action_applicable` (evaluate preconditions against the loaded graph under a binding map), `onto_action_apply` (execute effects + return patch + event IRI; re-checks preconditions by default), `onto_action_list` (enumerate registered schema names). **Causal-layer hookup**: `civex::ActionFrame` gains an optional `action_schema_name`; when set, `onto_certify_action` echoes `dynamics_action_schema:<name>` into the certificate's assumptions, so the audit trail is explicit about which Dynamics action was gated. **Planner stub** (`src/plan_pddl.rs` + `onto_plan_compile_pddl`): emits a PDDL domain from registered action schemas plus a problem instance from the loaded graph and a goal Turtle slice. Single-predicate `(triple ?s ?p ?o)` over typed sort `iri`; ASK-shaped preconditions translate cleanly, SELECT-shaped ones surface in `translation_notes` so the lossy translation is honest. Per the LLM-Modulo convention (Kambhampati arXiv 2402.01817), the actual planner (Fast Downward) is delegated to the orchestrator; this primitive only emits the PDDL. New files: `src/dynamics.rs` (~458 LOC including 7 unit tests), `src/plan_pddl.rs` (~280 LOC including 6 unit tests). Causal extension verified by a new integration test `action_schema_name_is_recorded_in_certificate_assumptions` in `tests/civex_test.rs`. Honest deferrals: ramification rules, non-deterministic dynamics, and concurrent action semantics defer to v0.4.x; OWL → PDDL rigour (Borgwardt KR 2025) defers to v0.6 proper.- **`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.diff --git a/Cargo.toml b/Cargo.tomlindex e3b08f21..3daa1201 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -52,6 +52,13 @@ postgres = ["sqlx"]duckdb = ["dep:duckdb"]sql = ["postgres", "duckdb"]embeddings = ["tract-onnx", "tokenizers", "instant-distance", "bincode"]+# Causal layer (#48): subprocess wrapper around PyWhy/DoWhy for backdoor+# identification + adjustment estimation. Caller must have `python3` on PATH+# and `pip install dowhy networkx pandas numpy`. The wrapper degrades to a+# clean `pywhy_unavailable` error when imports fail; CIVeX falls back to the+# structural proxy. Zero additional Rust dependencies — the entire feature+# is shipped as embedded Python + subprocess plumbing.+causal-pywhy = [][dev-dependencies]tempfile = "3"diff --git a/examples/three_layer_pipeline.rs b/examples/three_layer_pipeline.rsnew file mode 100644index 00000000..b4aa2ee7--- /dev/null+++ b/examples/three_layer_pipeline.rs@@ -0,0 +1,351 @@+//! End-to-end runnable demo of the three-layer architecture+//! (Dynamics #43 → Causal hookup → Planner #45) shipped on PR #46.+//!+//! Run with: `cargo run --example three_layer_pipeline`+//!+//! What it demonstrates, top to bottom:+//!+//! 1. Register two action schemas:+//! - `add_subclass_edge` (deterministic)+//! - `noisy_add_class` (non-deterministic, #49)+//! 2. Compile PDDL from those schemas + a goal Turtle slice.+//! 3. Simulate what a Fast Downward run would have produced+//! (no Fast Downward binary required — we use a hardcoded sas_plan+//! that the parser eats).+//! 4. Parse the sas_plan, bind PDDL args back to original IRIs.+//! 5. Validate the plan against the graph in a sandbox.+//! 6. For each step: CIVeX-certify it, then apply with ramification.+//! 7. Print the resulting graph state.+//!+//! No external dependencies (Python / DoWhy / Fast Downward) required —+//! every layer is exercised through its in-process API.++use open_ontologies::civex::{certify_action, ActionFrame, Verdict};+use open_ontologies::dynamics::{+ list_names, lookup, register, ActionSchema, EffectSpec, Outcome, Parameter,+};+use open_ontologies::graph::GraphStore;+use open_ontologies::plan_classical::parse_sas_plan;+use open_ontologies::plan_pddl::{compile_domain, compile_problem};+use open_ontologies::plan_validate::{validate_plan, PlanStep};+use open_ontologies::state::StateDb;+use std::collections::BTreeMap;+use std::path::Path;+use std::sync::Arc;++fn print_section(title: &str) {+ println!("\n{}\n{}\n", title, "─".repeat(title.len()));+}++fn build_add_subclass_schema() -> ActionSchema {+ ActionSchema {+ name: "add_subclass_edge".to_string(),+ parameters: vec![+ Parameter { name: "child".to_string(), type_iri: None },+ Parameter { name: "parent".to_string(), type_iri: None },+ ],+ preconditions: vec![+ "ASK { <{child}> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class> }".to_string(),+ "ASK { <{parent}> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class> }".to_string(),+ ],+ effects: vec![EffectSpec::AddTriple {+ subject: "{child}".to_string(),+ predicate: "http://www.w3.org/2000/01/rdf-schema#subClassOf".to_string(),+ object: "{parent}".to_string(),+ }],+ reversible: true,+ description: Some("Add a subClassOf edge between two existing classes".into()),+ outcomes: vec![],+ }+}++fn build_noisy_add_class_schema() -> ActionSchema {+ // 80% chance: declare the IRI as an owl:Class normally.+ // 20% chance: also tag it with an audit-marker class. Models a noisy+ // LLM proposer that sometimes over-asserts. The CIVeX cert + ramification+ // are robust to both outcomes.+ ActionSchema {+ name: "noisy_add_class".to_string(),+ parameters: vec![Parameter { name: "iri".to_string(), type_iri: None }],+ preconditions: vec![],+ effects: vec![], // ignored when outcomes is non-empty+ reversible: true,+ description: Some("Add an owl:Class with a noisy LLM-style proposer".into()),+ outcomes: vec![+ Outcome {+ probability: 0.8,+ effects: vec![EffectSpec::AddClass { iri: "{iri}".to_string() }],+ label: Some("clean".to_string()),+ },+ Outcome {+ probability: 0.2,+ effects: vec![+ EffectSpec::AddClass { iri: "{iri}".to_string() },+ EffectSpec::AddTriple {+ subject: "{iri}".to_string(),+ predicate: "http://example.org/audit#flaggedBy".to_string(),+ object: "http://example.org/audit#NoisyProposer".to_string(),+ },+ ],+ label: Some("audit_flagged".to_string()),+ },+ ],+ }+}++fn main() -> anyhow::Result<()> {+ // ── Setup ───────────────────────────────────────────────────────────+ let db = StateDb::open(Path::new(":memory:"))?;+ let graph = Arc::new(GraphStore::new());+ graph.load_turtle(+ r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://ex.org/> .+ ex:Animal a owl:Class .+ ex:Cat a owl:Class .+ ex:tigger a ex:Cat .+ "#,+ None,+ )?;++ print_section("0. Seed graph");+ println!("Loaded {} triples", graph.triple_count());++ // ── Layer 1: Dynamics — register schemas ────────────────────────────+ print_section("1. Dynamics: register two schemas");+ register(&db, &build_add_subclass_schema())?;+ register(&db, &build_noisy_add_class_schema())?;+ println!("Registered: {:?}", list_names(&db)?);++ // ── Layer 3: Planner — compile PDDL ─────────────────────────────────+ print_section("2. Planner: compile PDDL domain from registered schemas");+ let schemas: Vec<ActionSchema> = list_names(&db)?+ .iter()+ .filter_map(|n| lookup(&db, n).ok().flatten())+ .collect();+ let compiled = compile_domain("ontology", &schemas);+ println!("PDDL domain (first 12 lines):");+ for line in compiled.domain.lines().take(12) {+ println!(" {}", line);+ }+ if !compiled.translation_notes.is_empty() {+ println!("Translation notes (lossy):");+ for n in &compiled.translation_notes {+ println!(" - {}", n);+ }+ }++ // Compile a problem instance from the seed graph + a goal.+ let init_facts: Vec<(String, String, String)> = graph+ .all_triples()?+ .into_iter()+ .map(|(s, p, o)| {+ (+ s.trim_matches(|c| c == '<' || c == '>').to_string(),+ p.trim_matches(|c| c == '<' || c == '>').to_string(),+ o.trim_matches(|c| c == '<' || c == '>').to_string(),+ )+ })+ .collect();+ let goal = vec![(+ "http://ex.org/Cat".to_string(),+ "http://www.w3.org/2000/01/rdf-schema#subClassOf".to_string(),+ "http://ex.org/Animal".to_string(),+ )];+ let problem = compile_problem("demo_problem", "ontology", &init_facts, &goal);+ println!("\nPDDL problem (first 4 lines):");+ for line in problem.lines().take(4) {+ println!(" {}", line);+ }++ // ── Layer 3: Planner — simulate the solver's output ─────────────────+ print_section("3. Planner: parse sas_plan from a (mock) Fast Downward run");+ // What Fast Downward would emit, given the goal:+ // 1. Declare a new class (noisy_add_class chooses one of two outcomes).+ // 2. Connect Cat → Animal via subClassOf.+ let mock_sas_plan = "\+(noisy_add_class http___ex_org_mammal)\n\+(add_subclass_edge http___ex_org_cat http___ex_org_animal)\n\+; cost = 2 (unit cost)\n";+ let (operators, cost) = parse_sas_plan(mock_sas_plan);+ println!("Parsed {} operators (cost: {:?})", operators.len(), cost);+ for (i, op) in operators.iter().enumerate() {+ println!(" step {}: {} {:?}", i, op.name, op.args);+ }++ // ── Layer 3: Planner — bind PDDL args back to original IRIs ─────────+ print_section("4. Bind PDDL args back to IRIs (orchestrator side)");+ // The orchestrator knows the schemas it registered, so it can map each+ // operator's positional args to the schema's parameter names. PDDL+ // identifiers are sanitised IRIs (`/` `:` `#` → `_`); for this demo we+ // hardcode the inverse mapping the orchestrator would maintain.+ let iri_map: BTreeMap<&str, &str> = BTreeMap::from([+ ("http___ex_org_mammal", "http://ex.org/Mammal"),+ ("http___ex_org_cat", "http://ex.org/Cat"),+ ("http___ex_org_animal", "http://ex.org/Animal"),+ ]);+ let mut plan_steps: Vec<PlanStep> = Vec::new();+ for op in &operators {+ let schema = lookup(&db, &op.name)?+ .ok_or_else(|| anyhow::anyhow!("unknown action `{}` in plan", op.name))?;+ let mut bindings = BTreeMap::new();+ for (param, arg) in schema.parameters.iter().zip(op.args.iter()) {+ let resolved = iri_map.get(arg.as_str()).copied().unwrap_or(arg.as_str()).to_string();+ bindings.insert(param.name.clone(), resolved);+ }+ println!(" {} bindings: {:?}", op.name, bindings);+ plan_steps.push(PlanStep { action_name: op.name.clone(), bindings });+ }++ // ── Layer 3: Planner — validate the bound plan in a sandbox ─────────+ print_section("5. Validate the bound plan (no mutation of the real graph)");+ let goal_facts_nt: Vec<(String, String, String)> = goal+ .iter()+ .map(|(s, p, o)| (format!("<{}>", s), format!("<{}>", p), format!("<{}>", o)))+ .collect();+ let report = validate_plan(&db, &graph, &plan_steps, &goal_facts_nt)?;+ println!(+ "valid={} steps={}/{} initial_triples={} final_triples={} unsatisfied_goals={}",+ report.valid,+ report.steps_validated,+ report.steps_total,+ report.initial_triple_count,+ report.final_triple_count,+ report.unsatisfied_goals.len()+ );+ // The real graph must still be untouched at this point.+ assert_eq!(graph.triple_count(), 3, "sandbox must not mutate real graph");++ // ── Layer 2: Causal — certify + apply each step ─────────────────────+ print_section("6. Per-step: CIVeX certify, then apply with ramification");+ for (i, step) in plan_steps.iter().enumerate() {+ let schema = lookup(&db, &step.action_name)?.unwrap();+ let bindings: Vec<(String, String)> = step+ .bindings+ .iter()+ .map(|(k, v)| (k.clone(), v.clone()))+ .collect();++ // Build a CIVeX ActionFrame describing the change.+ let proposed_ttl = synthesise_proposed_ttl(&schema, &bindings);+ let target_iris: Vec<String> = schema+ .parameters+ .first()+ .and_then(|p| bindings.iter().find(|(k, _)| k == &p.name))+ .map(|(_, v)| vec![v.clone()])+ .unwrap_or_default();++ let frame = ActionFrame {+ tool: "onto_action_apply".to_string(),+ target_iris,+ proposed_delta_ttl: proposed_ttl,+ 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 ?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(),+ "SELECT ?s WHERE { ?s ?p ?o } LIMIT 5".to_string(),+ ],+ cost_threshold: 1000,+ utility_threshold: 0.5,+ risk_threshold: 5000,+ reversible: schema.reversible,+ allow_experiment: false,+ alpha: 0.05,+ action_schema_name: Some(schema.name.clone()),+ };+ let cert = certify_action(&db, &graph, &frame)?;+ println!(+ " step {} `{}`: verdict={:?}, utility_lcb={:.3}",+ i, step.action_name, cert.certificate.verdict, cert.certificate.utility_lcb+ );++ if !matches!(cert.certificate.verdict, Verdict::Execute) {+ println!(" → skipping (verdict not EXECUTE)");+ continue;+ }++ // Apply with OWL-RL ramification + a deterministic seed so the+ // non-deterministic outcome is reproducible across runs of the demo.+ let result =+ schema.apply_with_ramification(&graph, &db, &bindings, "owl-rl")?;+ // For nondeterministic schemas, apply_with_ramification used SystemTime+ // seeding inside apply(). For a deterministic demo we'd use+ // apply_with_seed first; for clarity here we just print what landed.+ println!(+ " applied: +{} triples, removed {}, derived +{} via OWL-RL, outcome={:?}",+ result.triples_added,+ result.triples_removed,+ result.derived_triples_added,+ result.sampled_outcome_label+ );+ }++ // ── Final state ─────────────────────────────────────────────────────+ print_section("7. Final graph state");+ println!("Total triples: {}", graph.triple_count());+ let ask = graph.sparql_select(+ "ASK { <http://ex.org/Cat> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/Animal> }",+ )?;+ println!("Cat rdfs:subClassOf Animal? {}", if ask.contains("\"result\":true") { "YES" } else { "no" });+ let ask2 = graph.sparql_select(+ "ASK { <http://ex.org/tigger> a <http://ex.org/Animal> }",+ )?;+ println!(+ "tigger a Animal (entailed via OWL-RL ramification)? {}",+ if ask2.contains("\"result\":true") { "YES" } else { "no" }+ );++ println!("\nDone. Every layer of the three-layer architecture exercised through its public API.");+ Ok(())+}++/// Synthesise the Turtle delta that the schema would produce under the+/// supplied bindings — used as `proposed_delta_ttl` for the CIVeX frame.+fn synthesise_proposed_ttl(schema: &ActionSchema, bindings: &[(String, String)]) -> String {+ // For non-deterministic schemas we project the "headline" effects from+ // the most-probable outcome; CIVeX is judging the structural change, not+ // the precise stochastic branch. For deterministic schemas we use the+ // literal effects.+ let effects: &[EffectSpec] = if schema.outcomes.is_empty() {+ &schema.effects+ } else {+ schema+ .outcomes+ .iter()+ .max_by(|a, b| {+ a.probability+ .partial_cmp(&b.probability)+ .unwrap_or(std::cmp::Ordering::Equal)+ })+ .map(|o| o.effects.as_slice())+ .unwrap_or(&[])+ };+ let mut ttl = String::new();+ for effect in effects {+ match effect {+ EffectSpec::AddTriple { subject, predicate, object } => {+ let s = schema.substitute(subject, bindings);+ let p = schema.substitute(predicate, bindings);+ let o = schema.substitute(object, bindings);+ ttl.push_str(&format!("<{}> <{}> <{}> .\n", s, p, o));+ }+ EffectSpec::RemoveTriple { subject, predicate, object } => {+ // Removal isn't expressible in Turtle directly; CIVeX uses the+ // delta as the post-state under structural-dependency analysis,+ // so we omit removals here and rely on the lock-IRI machinery+ // for risk accounting.+ let _ = (subject, predicate, object);+ }+ EffectSpec::AddClass { iri } => {+ let s = schema.substitute(iri, bindings);+ ttl.push_str(&format!(+ "<{}> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class> .\n",+ s+ ));+ }+ }+ }+ ttl+}diff --git a/src/civex.rs b/src/civex.rsindex acb87a34..1b4d3283 100644--- a/src/civex.rs+++ b/src/civex.rs@@ -98,6 +98,12 @@ pub struct ActionFrame {/// Matches the paper's `LCB_{α=0.05}`.#[serde(default = "default_alpha")]pub alpha: f64,+ /// Optional: name of a registered `dynamics::ActionSchema` this frame+ /// refers to (#43). When set, `certify_action` echoes the schema name+ /// into the certificate's assumptions and rationale, making the audit+ /// trail explicit about which Dynamics action was gated.+ #[serde(default)]+ pub action_schema_name: Option<String>,}fn default_alpha() -> f64 {@@ -239,6 +245,9 @@ pub fn certify_action(} else {assumptions.push("irreversible".to_string());}+ if let Some(name) = &frame.action_schema_name {+ assumptions.push(format!("dynamics_action_schema:{}", name));+ }let verdict = if !locked_violations.is_empty() {rationale_parts.push(format!(diff --git a/src/civex_pywhy.rs b/src/civex_pywhy.rsnew file mode 100644index 00000000..02c8fe58--- /dev/null+++ b/src/civex_pywhy.rs@@ -0,0 +1,337 @@+//! PyWhy/DoWhy backdoor identification subprocess wrapper (#48).+//!+//! Scaffold implementation of the Causal flagship's substantive v0.5 work:+//! a Python subprocess around DoWhy v0.13 that:+//!+//! 1. Builds a causal DAG from the caller-supplied `nodes` + `edges`.+//! 2. Runs DoWhy's `identify_effect` to check whether the do-effect of+//! `treatment` on `outcome` is identifiable via backdoor adjustment.+//! 3. Returns the adjustment set (the variables to condition on) and an+//! estimand expression suitable for the certificate's+//! `identification_proof` field.+//!+//! Per the May 2026 roadmap memo, **we do not port Pearl–Shpitser ID to+//! Rust** — DoWhy is a 15-year-stable Python implementation; wrap it via+//! subprocess like `plan_classical.rs` does for Fast Downward.+//!+//! ## Bounded scope (v0.4 scaffold)+//!+//! - Backdoor identification + adjustment set extraction only (frontdoor /+//! IV defer to v0.5.x).+//! - Subprocess wrapper + parser + clean errors on missing Python or DoWhy.+//! - **NOT** yet integrated into `certify_action`. The integration point is+//! marked in `src/civex.rs` and slated for v0.5; for now the structural+//! proxy (`"structural_only"` assumption) remains the only identifier in+//! shipped certificates.+//!+//! ## Behaviour when Python or DoWhy is missing+//!+//! Returns a structured error with `kind = "python_unavailable"` or+//! `"pywhy_unavailable"`. CIVeX's calling code is expected to fall back to+//! the structural proxy rather than propagate the failure as a tool error.++use serde::{Deserialize, Serialize};+use std::io::Write;+use std::process::{Command, Stdio};++/// Result of a successful PyWhy identification run.+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]+pub struct PyWhyEstimate {+ /// Whether the do-effect `P(outcome | do(treatment))` is identifiable+ /// from the supplied graph via backdoor adjustment.+ pub identifiable: bool,+ /// Variables that constitute a valid backdoor adjustment set. Empty+ /// when `identifiable == false`.+ pub adjustment_set: Vec<String>,+ /// Estimand expression in DoWhy's printed form. Used as the certificate's+ /// `identification_proof` when this scaffold is integrated into CIVeX.+ pub estimand_expression: String,+ /// Raw JSON output from the Python subprocess, retained for audit.+ pub raw_output: String,+}++/// Subprocess input shape — pure JSON; the embedded Python script reads+/// this from stdin.+#[derive(Clone, Debug, Serialize)]+pub struct PyWhyInput<'a> {+ pub nodes: &'a [String],+ pub edges: &'a [(String, String)],+ pub treatment: &'a str,+ pub outcome: &'a str,+}++/// Embedded Python driver. Runs under any `python3 >= 3.9` interpreter that+/// has `dowhy`, `networkx`, `pandas`, `numpy` installed.+pub const PYWHY_PYTHON_DRIVER: &str = r#"+import json+import sys++try:+ inp = json.loads(sys.stdin.read())+except Exception as e:+ print(json.dumps({"error": f"invalid json input: {e}", "kind": "input_parse_failed"}))+ sys.exit(0)++try:+ import networkx as nx # noqa: F401+ import pandas as pd+ import numpy as np+ from dowhy import CausalModel+except ImportError as e:+ print(json.dumps({"error": str(e), "kind": "pywhy_unavailable"}))+ sys.exit(0)++try:+ nodes = inp.get("nodes", [])+ edges = inp.get("edges", [])+ treatment = inp.get("treatment")+ outcome = inp.get("outcome")+ if not (treatment and outcome and nodes):+ print(json.dumps({"error": "missing treatment / outcome / nodes",+ "kind": "input_validation_failed"}))+ sys.exit(0)++ # DoWhy's CausalModel requires a DataFrame for its constructor even when+ # we only need graph-level identification. Two rows of zeros are enough+ # to satisfy the constructor; we never .fit() or .estimate().+ df = pd.DataFrame({n: np.zeros(2) for n in nodes})++ # Build a DOT-format graph string (DoWhy accepts this).+ dot_lines = ["digraph {"]+ for n in nodes:+ dot_lines.append(f' "{n}";')+ for u, v in edges:+ dot_lines.append(f' "{u}" -> "{v}";')+ dot_lines.append("}")+ graph_dot = "\n".join(dot_lines)++ model = CausalModel(+ data=df, treatment=treatment, outcome=outcome, graph=graph_dot+ )+ identified = model.identify_effect(proceed_when_unidentifiable=True)++ # `identified` exposes get_backdoor_variables() in DoWhy >= 0.10.+ backdoor_set = []+ try:+ backdoor_set = list(identified.get_backdoor_variables() or [])+ except Exception:+ pass++ estimand_expr = ""+ try:+ # Different DoWhy versions print differently; both .estimands and+ # __str__ have been used historically. Try both.+ estimand_expr = identified.estimands.get("backdoor", {}).get("estimand", "")+ except Exception:+ try:+ estimand_expr = str(identified)+ except Exception:+ estimand_expr = ""++ identifiable = bool(backdoor_set) or "identifier_method" in str(identified)++ print(json.dumps({+ "identifiable": identifiable,+ "adjustment_set": backdoor_set,+ "estimand_expression": estimand_expr or f"backdoor: {backdoor_set}",+ }))+except Exception as e:+ print(json.dumps({"error": f"{type(e).__name__}: {e}", "kind": "dowhy_runtime_failed"}))+ sys.exit(0)+"#;++/// Parse the JSON output of the embedded Python driver into a typed result.+/// Returns `Err` on structural errors (driver couldn't produce JSON); maps+/// driver-reported errors to typed `anyhow::Error` with the `kind` preserved.+pub fn parse_pywhy_output(json_str: &str) -> anyhow::Result<PyWhyEstimate> {+ let v: serde_json::Value = serde_json::from_str(json_str)+ .map_err(|e| anyhow::anyhow!("driver_emitted_invalid_json: {}", e))?;+ if let Some(err) = v.get("error").and_then(|e| e.as_str()) {+ let kind = v.get("kind").and_then(|k| k.as_str()).unwrap_or("unknown");+ anyhow::bail!("{}: {}", kind, err);+ }+ let identifiable = v+ .get("identifiable")+ .and_then(|b| b.as_bool())+ .unwrap_or(false);+ let adjustment_set: Vec<String> = v+ .get("adjustment_set")+ .and_then(|a| a.as_array())+ .map(|a| {+ a.iter()+ .filter_map(|x| x.as_str().map(|s| s.to_string()))+ .collect()+ })+ .unwrap_or_default();+ let estimand_expression = v+ .get("estimand_expression")+ .and_then(|s| s.as_str())+ .unwrap_or("")+ .to_string();+ Ok(PyWhyEstimate {+ identifiable,+ adjustment_set,+ estimand_expression,+ raw_output: json_str.to_string(),+ })+}++/// Resolve the Python binary. Precedence:+/// 1. Explicit `python_override` parameter.+/// 2. `PYTHON_BIN` env var.+/// 3. `python3` on PATH.+fn resolve_python(python_override: Option<&str>) -> String {+ if let Some(b) = python_override.filter(|s| !s.is_empty()) {+ return b.to_string();+ }+ if let Ok(env) = std::env::var("PYTHON_BIN")+ && !env.is_empty()+ {+ return env;+ }+ "python3".to_string()+}++/// Run PyWhy/DoWhy on a caller-supplied causal DAG.+///+/// Returns a structured `PyWhyEstimate` on success. On failure (binary+/// missing, DoWhy not installed, identification raised) returns a typed+/// `anyhow::Error` whose message starts with the kind tag+/// (`python_unavailable` / `pywhy_unavailable` / `dowhy_runtime_failed`) so+/// the calling code can dispatch.+pub fn run_pywhy_backdoor(+ input: &PyWhyInput<'_>,+ python_override: Option<&str>,+) -> anyhow::Result<PyWhyEstimate> {+ let python = resolve_python(python_override);+ let mut child = Command::new(&python)+ .arg("-c")+ .arg(PYWHY_PYTHON_DRIVER)+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .map_err(|e| {+ anyhow::anyhow!(+ "python_unavailable: failed to execute `{}`: {}. Install Python 3.9+ and set PYTHON_BIN, or pass `python_bin`.",+ python,+ e+ )+ })?;++ {+ let stdin = child.stdin.as_mut().ok_or_else(|| {+ anyhow::anyhow!("python_io_failed: could not open subprocess stdin")+ })?;+ let payload = serde_json::to_vec(input)?;+ stdin.write_all(&payload)?;+ }++ let output = child.wait_with_output().map_err(|e| {+ anyhow::anyhow!("python_io_failed: subprocess wait failed: {}", e)+ })?;++ if !output.status.success() {+ let stderr = String::from_utf8_lossy(&output.stderr);+ anyhow::bail!(+ "python_exited_nonzero: exit={:?}, stderr={}",+ output.status.code(),+ stderr+ );+ }++ let stdout = String::from_utf8_lossy(&output.stdout).to_string();+ parse_pywhy_output(&stdout)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn parse_pywhy_output_handles_identifiable_case() {+ let json = r#"{"identifiable": true, "adjustment_set": ["Z1", "Z2"], "estimand_expression": "E[Y | T, Z1, Z2]"}"#;+ let parsed = parse_pywhy_output(json).unwrap();+ assert!(parsed.identifiable);+ assert_eq!(parsed.adjustment_set, vec!["Z1", "Z2"]);+ assert_eq!(parsed.estimand_expression, "E[Y | T, Z1, Z2]");+ assert_eq!(parsed.raw_output, json);+ }++ #[test]+ fn parse_pywhy_output_handles_unidentifiable_case() {+ let json = r#"{"identifiable": false, "adjustment_set": [], "estimand_expression": ""}"#;+ let parsed = parse_pywhy_output(json).unwrap();+ assert!(!parsed.identifiable);+ assert!(parsed.adjustment_set.is_empty());+ }++ #[test]+ fn parse_pywhy_output_maps_pywhy_unavailable_to_typed_error() {+ let json = r#"{"error": "No module named 'dowhy'", "kind": "pywhy_unavailable"}"#;+ let err = parse_pywhy_output(json).expect_err("should error");+ let s = format!("{}", err);+ assert!(s.starts_with("pywhy_unavailable"), "got: {}", s);+ }++ #[test]+ fn parse_pywhy_output_maps_dowhy_runtime_failed_to_typed_error() {+ let json = r#"{"error": "ValueError: bad graph", "kind": "dowhy_runtime_failed"}"#;+ let err = parse_pywhy_output(json).expect_err("should error");+ assert!(format!("{}", err).starts_with("dowhy_runtime_failed"));+ }++ #[test]+ fn parse_pywhy_output_rejects_invalid_json() {+ let err = parse_pywhy_output("not json at all").expect_err("should error");+ assert!(format!("{}", err).contains("driver_emitted_invalid_json"));+ }++ #[test]+ fn resolve_python_prefers_explicit_override() {+ assert_eq!(resolve_python(Some("/usr/local/bin/py3.13")), "/usr/local/bin/py3.13");+ }++ #[test]+ fn resolve_python_defaults_to_python3_when_no_inputs() {+ let prior = std::env::var("PYTHON_BIN").ok();+ // SAFETY: test-only env mutation under cargo test's single-process runtime.+ unsafe { std::env::remove_var("PYTHON_BIN"); }+ let resolved = resolve_python(None);+ assert_eq!(resolved, "python3");+ if let Some(p) = prior {+ unsafe { std::env::set_var("PYTHON_BIN", p); }+ }+ }++ #[test]+ fn run_pywhy_returns_python_unavailable_when_binary_missing() {+ let nodes = vec!["T".to_string(), "Y".to_string(), "Z".to_string()];+ let edges = vec![+ ("Z".to_string(), "T".to_string()),+ ("Z".to_string(), "Y".to_string()),+ ("T".to_string(), "Y".to_string()),+ ];+ let input = PyWhyInput {+ nodes: &nodes,+ edges: &edges,+ treatment: "T",+ outcome: "Y",+ };+ let err = run_pywhy_backdoor(+ &input,+ Some("/definitely/does/not/exist/python.xyz"),+ )+ .expect_err("should error");+ let s = format!("{}", err);+ assert!(s.starts_with("python_unavailable"), "got: {}", s);+ }++ #[test]+ fn embedded_driver_is_non_empty_and_imports_dowhy() {+ // Sanity check on the driver constant.+ assert!(PYWHY_PYTHON_DRIVER.contains("from dowhy import CausalModel"));+ assert!(PYWHY_PYTHON_DRIVER.contains("identify_effect"));+ assert!(PYWHY_PYTHON_DRIVER.contains("pywhy_unavailable"));+ }+}diff --git a/src/dynamics.rs b/src/dynamics.rsnew file mode 100644index 00000000..199175d0--- /dev/null+++ b/src/dynamics.rs@@ -0,0 +1,837 @@+//! Dynamics layer — action schemas + applicability + apply (#43).+//!+//! Foundation of the three-layer architecture (Dynamics → Causal → Planner).+//! Provides a structured representation of *what changes* in the ontology:+//!+//! - [`ActionSchema`] — the action's name, typed parameters, SPARQL ASK+//! preconditions, and KGCL-shaped effect templates with `{param}` substitution+//! - [`register`] / [`lookup`] — persistence in SQLite, keyed by name+//! - [`ActionSchema::applicable`] — evaluate preconditions against the loaded graph+//! - [`ActionSchema::apply`] — execute effects, produce a KGCL patch + IES4 event+//!+//! Designed as the action-representation surface that the Causal engine+//! (`src/civex.rs`) certifies and the Planner (forthcoming) composes.+//!+//! ## Bounded scope (v0.4.0 ship)+//!+//! - Deterministic single-effect actions (BC+ subset)+//! - Preconditions as SPARQL ASK queries; effects as `AddTriple`, `RemoveTriple`,+//! or the shortcut `AddClass`+//! - `{param}` string substitution into IRIs and literals+//! - IES4 event logging via existing `lineage::LineageLog`+//!+//! Deferred (v0.4.x / v0.5.x):+//!+//! - Non-deterministic dynamics (multiple outcomes per action)+//! - Ramification rules (cascading effects via DL closure)+//! - Concurrent action semantics+//! - ASP solver backend for full BC+++use crate::graph::GraphStore;+use crate::state::StateDb;+use serde::{Deserialize, Serialize};+use std::sync::Arc;++/// A typed parameter binding slot for an [`ActionSchema`].+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct Parameter {+ pub name: String,+ /// Optional OWL class IRI; if set, the bound IRI must be an instance of+ /// this class for the action to be applicable. (The check is currently+ /// caller-supplied via a precondition SPARQL ASK; future work: enforce+ /// type-checking automatically.)+ #[serde(default)]+ pub type_iri: Option<String>,+}++/// An effect on the ontology. Strings can carry `{param_name}` placeholders+/// that are substituted at apply time.+#[derive(Clone, Debug, Serialize, Deserialize)]+#[serde(tag = "kind", rename_all = "snake_case")]+pub enum EffectSpec {+ /// Add a triple `(subject, predicate, object)`. All three positions can+ /// reference parameters.+ AddTriple {+ subject: String,+ predicate: String,+ object: String,+ },+ /// Remove an existing triple.+ RemoveTriple {+ subject: String,+ predicate: String,+ object: String,+ },+ /// Shortcut: declare `iri` as `owl:Class`. Equivalent to+ /// `AddTriple { subject: iri, predicate: rdf:type, object: owl:Class }`.+ AddClass { iri: String },+}++/// One non-deterministic outcome of an action (#49). Each outcome carries+/// a categorical probability and its own effect list. When an+/// [`ActionSchema`] has a non-empty [`ActionSchema::outcomes`], `apply`+/// samples one outcome and executes its effects (the deterministic+/// `effects` field is ignored). When `outcomes` is empty, the schema+/// behaves as before — pure deterministic single-effect BC+ subset.+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct Outcome {+ /// Categorical probability in `[0, 1]`. The sum across all outcomes+ /// must equal 1.0 ± 1e-6 or `apply` returns an error.+ pub probability: f64,+ /// Effects to execute when this outcome is sampled.+ pub effects: Vec<EffectSpec>,+ /// Optional human-readable label (e.g. `"success"`, `"degraded"`,+ /// `"failure"`). Echoed into the `ApplyResult.kgcl_patch_cnl`.+ #[serde(default)]+ pub label: Option<String>,+}++/// A reusable action schema. Reified via [`register`]; instantiated with+/// bindings via [`ActionSchema::apply`].+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct ActionSchema {+ pub name: String,+ #[serde(default)]+ pub parameters: Vec<Parameter>,+ /// SPARQL queries that must succeed for the action to be applicable.+ /// Both `ASK` and `SELECT` are accepted: an `ASK` is satisfied iff its+ /// boolean result is true; a `SELECT` is satisfied iff it returns at+ /// least one row. Strings can contain `{param}` placeholders.+ #[serde(default)]+ pub preconditions: Vec<String>,+ pub effects: Vec<EffectSpec>,+ /// Whether the action has an inverse. Consumed by the Causal engine+ /// (`civex::ActionFrame.reversible`).+ pub reversible: bool,+ /// Optional human-readable description.+ #[serde(default)]+ pub description: Option<String>,+ /// Non-deterministic outcomes (#49). When non-empty, `apply` samples one+ /// outcome and executes its effects; the deterministic `effects` field+ /// is ignored. When empty (default), the schema is deterministic and+ /// behaves as in v0.4 base.+ #[serde(default)]+ pub outcomes: Vec<Outcome>,+}++/// The outcome of applying an action.+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct ApplyResult {+ pub action_name: String,+ pub bindings: Vec<(String, String)>,+ /// KGCL Controlled-Natural-Language description of the patch applied.+ pub kgcl_patch_cnl: Vec<String>,+ /// IES4-style event IRI for the audit trail.+ pub event_iri: String,+ pub triples_added: usize,+ pub triples_removed: usize,+ /// Triples materialised by a follow-up reasoner pass (ramification, #47).+ /// `0` when ramification is disabled or the reasoner produced no new+ /// entailments. The reasoner profile actually used is in+ /// `ramification_profile`.+ #[serde(default)]+ pub derived_triples_added: usize,+ /// Reasoner profile run for ramification, or `None` if disabled.+ #[serde(default)]+ pub ramification_profile: Option<String>,+ /// Index of the sampled outcome when the schema is non-deterministic+ /// (#49). `None` for deterministic schemas (the default case).+ #[serde(default)]+ pub sampled_outcome: Option<usize>,+ /// Label of the sampled outcome, if any (e.g. `"success"`).+ #[serde(default)]+ pub sampled_outcome_label: Option<String>,+}++impl ActionSchema {+ /// Substitute `{param_name}` placeholders in `template` using `bindings`.+ pub fn substitute(&self, template: &str, bindings: &[(String, String)]) -> String {+ let mut s = template.to_string();+ for (k, v) in bindings {+ s = s.replace(&format!("{{{}}}", k), v);+ }+ s+ }++ /// Evaluate all preconditions against the loaded graph with the given+ /// bindings. Returns `true` iff every precondition is satisfied.+ pub fn applicable(&self, graph: &Arc<GraphStore>, bindings: &[(String, String)]) -> bool {+ for precond in &self.preconditions {+ let q = self.substitute(precond, bindings);+ let result_str = match graph.sparql_select(&q) {+ Ok(r) => r,+ Err(_) => return false,+ };+ let parsed: serde_json::Value = match serde_json::from_str(&result_str) {+ Ok(v) => v,+ Err(_) => return false,+ };+ // ASK queries: server returns {"result": bool}.+ if let Some(b) = parsed["result"].as_bool() {+ if !b {+ return false;+ }+ continue;+ }+ // SELECT queries: satisfied iff at least one binding row.+ let any_row = parsed["results"]+ .as_array()+ .map(|a| !a.is_empty())+ .unwrap_or(false);+ if !any_row {+ return false;+ }+ }+ true+ }++ /// Apply the action's effects. Adds + removes triples, records an IES4-+ /// style event into the lineage log, and returns the KGCL patch CNL+ /// description.+ ///+ /// **Non-deterministic actions (#49):** when [`Self::outcomes`] is+ /// non-empty, an outcome is sampled and its effects are applied. The+ /// sampling seed is derived from `SystemTime::now()`. For reproducible+ /// sampling, use [`Self::apply_with_seed`] instead.+ pub fn apply(+ &self,+ graph: &Arc<GraphStore>,+ db: &StateDb,+ bindings: &[(String, String)],+ ) -> anyhow::Result<ApplyResult> {+ let seed = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_nanos() as u64)+ .unwrap_or(0);+ self.apply_inner(graph, db, bindings, seed)+ }++ /// Reproducible variant of [`Self::apply`]: callers supply the sampling+ /// `seed` so non-deterministic outcomes are deterministic given the same+ /// schema + bindings + seed.+ pub fn apply_with_seed(+ &self,+ graph: &Arc<GraphStore>,+ db: &StateDb,+ bindings: &[(String, String)],+ seed: u64,+ ) -> anyhow::Result<ApplyResult> {+ self.apply_inner(graph, db, bindings, seed)+ }++ fn apply_inner(+ &self,+ graph: &Arc<GraphStore>,+ db: &StateDb,+ bindings: &[(String, String)],+ seed: u64,+ ) -> anyhow::Result<ApplyResult> {+ // Decide which effect list to use.+ let (effects_to_apply, sampled_outcome, sampled_label): (&[EffectSpec], Option<usize>, Option<String>) =+ if self.outcomes.is_empty() {+ (self.effects.as_slice(), None, None)+ } else {+ // Validate probabilities sum to ~1.0.+ let total: f64 = self.outcomes.iter().map(|o| o.probability).sum();+ if (total - 1.0).abs() > 1e-6 {+ anyhow::bail!(+ "non-deterministic schema `{}` has outcome probabilities summing to {} (must equal 1.0 \u{00b1} 1e-6)",+ self.name,+ total+ );+ }+ if self.outcomes.iter().any(|o| o.probability < 0.0) {+ anyhow::bail!(+ "non-deterministic schema `{}` has a negative outcome probability",+ self.name+ );+ }+ let idx = sample_categorical(seed, &self.outcomes);+ let outcome = &self.outcomes[idx];+ (outcome.effects.as_slice(), Some(idx), outcome.label.clone())+ };++ let mut to_add: Vec<(String, String, String)> = Vec::new();+ let mut to_remove: Vec<(String, String, String)> = Vec::new();+ let mut kgcl_cnl: Vec<String> = Vec::new();+ if let Some(ref label) = sampled_label {+ kgcl_cnl.push(format!("sampled outcome <{}>", label));+ }++ for effect in effects_to_apply {+ match effect {+ EffectSpec::AddTriple {+ subject,+ predicate,+ object,+ } => {+ let s = self.substitute(subject, bindings);+ let p = self.substitute(predicate, bindings);+ let o = self.substitute(object, bindings);+ kgcl_cnl.push(format!("create edge <{}> <{}> <{}>", s, p, o));+ to_add.push((s, p, o));+ }+ EffectSpec::RemoveTriple {+ subject,+ predicate,+ object,+ } => {+ let s = self.substitute(subject, bindings);+ let p = self.substitute(predicate, bindings);+ let o = self.substitute(object, bindings);+ kgcl_cnl.push(format!("delete edge <{}> <{}> <{}>", s, p, o));+ to_remove.push((s, p, o));+ }+ EffectSpec::AddClass { iri } => {+ let s = self.substitute(iri, bindings);+ let p = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type".to_string();+ let o = "http://www.w3.org/2002/07/owl#Class".to_string();+ kgcl_cnl.push(format!("create class <{}>", s));+ to_add.push((s, p, o));+ }+ }+ }++ // Apply additions via Turtle insertion.+ if !to_add.is_empty() {+ let mut turtle = String::new();+ for (s, p, o) in &to_add {+ turtle.push_str(&format!("<{}> <{}> <{}> .\n", s, p, o));+ }+ graph.load_turtle(&turtle, None)?;+ }++ // Apply removals via SPARQL UPDATE.+ for (s, p, o) in &to_remove {+ let update = format!("DELETE DATA {{ <{}> <{}> <{}> }}", s, p, o);+ let _ = graph.sparql_update(&update);+ }++ // IES4-style event IRI for the audit trail.+ let timestamp_micros = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_micros())+ .unwrap_or(0);+ let event_iri = format!(+ "http://open-ontologies.local/dynamics/event/{}_{}",+ self.name, timestamp_micros+ );++ // Log to lineage as a Dynamics-layer event.+ let lineage = crate::lineage::LineageLog::new(db.clone());+ lineage.record(+ "dynamics",+ "DY",+ &format!("apply:{}", self.name),+ &format!("added={}, removed={}", to_add.len(), to_remove.len()),+ );++ Ok(ApplyResult {+ action_name: self.name.clone(),+ bindings: bindings.to_vec(),+ kgcl_patch_cnl: kgcl_cnl,+ event_iri,+ triples_added: to_add.len(),+ triples_removed: to_remove.len(),+ derived_triples_added: 0,+ ramification_profile: None,+ sampled_outcome,+ sampled_outcome_label: sampled_label,+ })+ }++ /// Apply the action's effects, then run the reasoner to materialise any+ /// downstream entailments (ramification, #47). The resulting `ApplyResult`+ /// carries `derived_triples_added` as the count of new triples the+ /// reasoner produced beyond the literal effects.+ ///+ /// `profile` is forwarded to [`crate::reason::Reasoner::run`]; passing+ /// `"rdfs"` is the cheapest meaningful choice, `"owl-rl"` is the standard,+ /// `"owl-rl-ext"` adds restriction-pattern entailment, and `"owl-dl"`+ /// delegates to the tableaux reasoner.+ pub fn apply_with_ramification(+ &self,+ graph: &Arc<GraphStore>,+ db: &StateDb,+ bindings: &[(String, String)],+ profile: &str,+ ) -> anyhow::Result<ApplyResult> {+ let mut result = self.apply(graph, db, bindings)?;+ let pre_count = graph.triple_count();+ // Materialise entailments in-place.+ let _ = crate::reason::Reasoner::run(graph, profile, true)?;+ let post_count = graph.triple_count();+ result.derived_triples_added = post_count.saturating_sub(pre_count);+ result.ramification_profile = Some(profile.to_string());+ Ok(result)+ }+}++// ─── Outcome sampling helpers (#49) ─────────────────────────────────────────++/// Tiny inline xorshift64 PRNG. Deterministic given the seed; sufficient for+/// categorical sampling over a handful of outcomes. Avoids adding `rand` /+/// `fastrand` as deps just for this.+fn xorshift64(state: &mut u64) -> u64 {+ let mut x = *state;+ if x == 0 {+ x = 0x9E3779B97F4A7C15; // arbitrary non-zero+ }+ x ^= x << 13;+ x ^= x >> 7;+ x ^= x << 17;+ *state = x;+ x+}++/// Sample one outcome index from a categorical distribution given the+/// `outcomes` (each carries `probability`) and a `seed`. Probabilities are+/// assumed to be validated (sum == 1.0, non-negative) by the caller.+fn sample_categorical(seed: u64, outcomes: &[Outcome]) -> usize {+ let mut state = seed;+ let r_u64 = xorshift64(&mut state);+ // Map to a uniform [0, 1) by taking the high 53 bits (mantissa width of f64).+ let r = (r_u64 >> 11) as f64 / (1u64 << 53) as f64;+ let mut cumulative = 0.0;+ for (i, o) in outcomes.iter().enumerate() {+ cumulative += o.probability;+ if r < cumulative {+ return i;+ }+ }+ // Floating-point slop on the boundary; default to the last outcome.+ outcomes.len() - 1+}++// ─── SQLite-backed schema persistence ───────────────────────────────────────++const ENSURE_TABLE: &str = "+CREATE TABLE IF NOT EXISTS dynamics_action_schemas (+ name TEXT PRIMARY KEY,+ schema_json TEXT NOT NULL,+ created_at TEXT NOT NULL DEFAULT (datetime('now'))+)";++fn ensure_table(db: &StateDb) -> anyhow::Result<()> {+ let conn = db.conn();+ conn.execute(ENSURE_TABLE, [])?;+ Ok(())+}++/// Persist an action schema under its name. Replaces any existing schema with+/// the same name.+pub fn register(db: &StateDb, schema: &ActionSchema) -> anyhow::Result<()> {+ ensure_table(db)?;+ let json = serde_json::to_string(schema)?;+ let conn = db.conn();+ conn.execute(+ "INSERT OR REPLACE INTO dynamics_action_schemas (name, schema_json) VALUES (?1, ?2)",+ rusqlite::params![schema.name, json],+ )?;+ Ok(())+}++/// Look up a registered schema by name. Returns `Ok(None)` if not found.+pub fn lookup(db: &StateDb, name: &str) -> anyhow::Result<Option<ActionSchema>> {+ ensure_table(db)?;+ let conn = db.conn();+ let row: Option<String> = conn+ .query_row(+ "SELECT schema_json FROM dynamics_action_schemas WHERE name = ?1",+ rusqlite::params![name],+ |r| r.get(0),+ )+ .ok();+ match row {+ Some(s) => Ok(Some(serde_json::from_str(&s)?)),+ None => Ok(None),+ }+}++/// List all registered schema names.+pub fn list_names(db: &StateDb) -> anyhow::Result<Vec<String>> {+ ensure_table(db)?;+ let conn = db.conn();+ let mut stmt = conn.prepare("SELECT name FROM dynamics_action_schemas ORDER BY name")?;+ let rows = stmt+ .query_map([], |r| r.get::<_, String>(0))?+ .filter_map(Result::ok)+ .collect();+ Ok(rows)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn test_db() -> StateDb {+ let tmp = tempfile::NamedTempFile::new().unwrap();+ let path = tmp.path().to_path_buf();+ std::mem::forget(tmp);+ StateDb::open(&path).unwrap()+ }++ fn sample_schema() -> ActionSchema {+ ActionSchema {+ name: "rename_class".to_string(),+ parameters: vec![+ Parameter {+ name: "old".to_string(),+ type_iri: Some("http://www.w3.org/2002/07/owl#Class".to_string()),+ },+ Parameter {+ name: "new".to_string(),+ type_iri: None,+ },+ ],+ preconditions: vec![+ "SELECT ?x WHERE { <{old}> ?p ?o }".to_string(),+ ],+ effects: vec![+ EffectSpec::AddClass { iri: "{new}".to_string() },+ EffectSpec::RemoveTriple {+ subject: "{old}".to_string(),+ predicate: "http://www.w3.org/1999/02/22-rdf-syntax-ns#type".to_string(),+ object: "http://www.w3.org/2002/07/owl#Class".to_string(),+ },+ ],+ reversible: false,+ description: Some("Replace class {old} with {new}".to_string()),+ outcomes: vec![],+ }+ }++ #[test]+ fn register_lookup_round_trip() {+ let db = test_db();+ let schema = sample_schema();+ register(&db, &schema).expect("register");+ let recovered = lookup(&db, "rename_class").expect("lookup").expect("found");+ assert_eq!(recovered.name, schema.name);+ assert_eq!(recovered.parameters.len(), 2);+ assert_eq!(recovered.effects.len(), 2);+ assert!(!recovered.reversible);+ assert!(recovered.description.as_deref().unwrap().contains("Replace"));+ }++ #[test]+ fn lookup_missing_returns_none() {+ let db = test_db();+ assert!(lookup(&db, "does_not_exist").unwrap().is_none());+ }++ #[test]+ fn list_names_returns_sorted() {+ let db = test_db();+ let mut a = sample_schema();+ a.name = "zebra".into();+ register(&db, &a).unwrap();+ let mut b = sample_schema();+ b.name = "alpha".into();+ register(&db, &b).unwrap();+ let names = list_names(&db).unwrap();+ assert_eq!(names, vec!["alpha", "zebra"]);+ }++ #[test]+ fn substitute_replaces_braced_placeholders() {+ let s = sample_schema();+ let out = s.substitute(+ "<{old}> a <{new}>",+ &[+ ("old".to_string(), "http://ex.org/A".to_string()),+ ("new".to_string(), "http://ex.org/B".to_string()),+ ],+ );+ assert_eq!(out, "<http://ex.org/A> a <http://ex.org/B>");+ }++ #[test]+ fn applicable_returns_true_when_select_has_rows() {+ let db = test_db();+ let graph = Arc::new(GraphStore::new());+ 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 schema = sample_schema();+ let _ = db; // unused but kept for parity with apply tests+ let applicable = schema.applicable(+ &graph,+ &[("old".to_string(), "http://ex.org/Cat".to_string())],+ );+ assert!(applicable, "precondition should match an existing class");+ }++ #[test]+ fn applicable_returns_false_when_select_empty() {+ let graph = Arc::new(GraphStore::new());+ graph+ .load_turtle("@prefix ex: <http://ex.org/> . ex:Dog a ex:Animal .", None)+ .unwrap();+ let schema = sample_schema();+ let applicable = schema.applicable(+ &graph,+ &[("old".to_string(), "http://ex.org/Missing".to_string())],+ );+ assert!(!applicable);+ }++ fn nondet_two_outcome_schema() -> ActionSchema {+ // 70/30 split between two distinct AddClass outcomes; reproducible+ // under any deterministic seed.+ ActionSchema {+ name: "noisy_add".to_string(),+ parameters: vec![],+ preconditions: vec![],+ effects: vec![], // ignored when outcomes is non-empty+ reversible: false,+ description: None,+ outcomes: vec![+ Outcome {+ probability: 0.7,+ effects: vec![EffectSpec::AddClass {+ iri: "http://ex.org/Success".to_string(),+ }],+ label: Some("success".to_string()),+ },+ Outcome {+ probability: 0.3,+ effects: vec![EffectSpec::AddClass {+ iri: "http://ex.org/Failure".to_string(),+ }],+ label: Some("failure".to_string()),+ },+ ],+ }+ }++ #[test]+ fn nondeterministic_apply_with_seed_is_reproducible() {+ // Same schema + same seed must produce the same sampled outcome and+ // the same triple-pattern.+ let db = test_db();+ let g1 = Arc::new(GraphStore::new());+ let g2 = Arc::new(GraphStore::new());+ let schema = nondet_two_outcome_schema();++ let r1 = schema.apply_with_seed(&g1, &db, &[], 42).expect("apply 1");+ let r2 = schema.apply_with_seed(&g2, &db, &[], 42).expect("apply 2");++ assert_eq!(r1.sampled_outcome, r2.sampled_outcome,+ "same seed must sample the same outcome");+ assert_eq!(r1.sampled_outcome_label, r2.sampled_outcome_label);+ }++ #[test]+ fn nondeterministic_apply_distribution_matches_probabilities() {+ // Over 1000 seeded calls the 70/30 split should be within reasonable+ // bounds. This is a smoke test of the categorical sampler, not a+ // rigorous statistical test.+ let db = test_db();+ let schema = nondet_two_outcome_schema();+ let mut counts = [0usize; 2];+ for seed in 0u64..1000 {+ let g = Arc::new(GraphStore::new());+ let r = schema+ .apply_with_seed(&g, &db, &[], seed.wrapping_mul(0x9E37_79B9_7F4A_7C15))+ .expect("apply");+ let idx = r.sampled_outcome.expect("nondet schema must record outcome");+ counts[idx] += 1;+ }+ let p0 = counts[0] as f64 / 1000.0;+ // 70% outcome should land between 60% and 80% with very high probability.+ assert!(+ (0.60..=0.80).contains(&p0),+ "expected ~70% outcome 0, got {:.3} (counts: {:?})",+ p0,+ counts+ );+ }++ #[test]+ fn nondeterministic_apply_rejects_invalid_probability_sum() {+ let db = test_db();+ let g = Arc::new(GraphStore::new());+ let mut schema = nondet_two_outcome_schema();+ // Break the invariant: sum to 0.9, not 1.0.+ schema.outcomes[0].probability = 0.6;+ schema.outcomes[1].probability = 0.3;+ let err = schema.apply_with_seed(&g, &db, &[], 0).expect_err("should reject");+ let s = format!("{}", err);+ assert!(s.contains("summing to"), "expected probability sum error, got: {}", s);+ }++ #[test]+ fn deterministic_schema_still_works_when_outcomes_is_empty() {+ // Back-compat: a schema with empty outcomes uses the existing+ // effects field and reports sampled_outcome=None.+ let db = test_db();+ let g = Arc::new(GraphStore::new());+ g.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 schema = sample_schema();+ let r = schema+ .apply(+ &g,+ &db,+ &[+ ("old".to_string(), "http://ex.org/Cat".to_string()),+ ("new".to_string(), "http://ex.org/Feline".to_string()),+ ],+ )+ .expect("apply");+ assert!(r.sampled_outcome.is_none());+ assert!(r.sampled_outcome_label.is_none());+ assert_eq!(r.triples_added, 1);+ assert_eq!(r.triples_removed, 1);+ }++ #[test]+ fn apply_with_ramification_materialises_subclass_entailment() {+ // Acceptance criterion from #47: adding a subClassOf edge between+ // two classes where the child already has an instance must, under+ // OWL-RL ramification, also assert the instance as a member of the+ // parent class.+ let db = test_db();+ let graph = Arc::new(GraphStore::new());+ graph+ .load_turtle(+ r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://ex.org/> .+ ex:Animal a owl:Class .+ ex:Cat a owl:Class .+ ex:tigger a ex:Cat .+ "#,+ None,+ )+ .unwrap();++ let schema = ActionSchema {+ name: "add_subclass_edge".to_string(),+ parameters: vec![+ Parameter { name: "child".to_string(), type_iri: None },+ Parameter { name: "parent".to_string(), type_iri: None },+ ],+ preconditions: vec![],+ effects: vec![EffectSpec::AddTriple {+ subject: "{child}".to_string(),+ predicate: "http://www.w3.org/2000/01/rdf-schema#subClassOf".to_string(),+ object: "{parent}".to_string(),+ }],+ reversible: true,+ description: None,+ outcomes: vec![],+ };+ let bindings = vec![+ ("child".to_string(), "http://ex.org/Cat".to_string()),+ ("parent".to_string(), "http://ex.org/Animal".to_string()),+ ];++ let result = schema+ .apply_with_ramification(&graph, &db, &bindings, "owl-rl")+ .expect("apply+ramify");++ assert_eq!(result.triples_added, 1, "literal effect: one subClassOf edge");+ assert_eq!(result.ramification_profile.as_deref(), Some("owl-rl"));+ // The reasoner must have derived at least one new triple (tigger a Animal).+ assert!(+ result.derived_triples_added >= 1,+ "OWL-RL should derive at least `tigger a Animal`; derived={}",+ result.derived_triples_added+ );++ // Verify the entailment landed in the graph.+ let q = "ASK { <http://ex.org/tigger> a <http://ex.org/Animal> }";+ let r = graph.sparql_select(q).unwrap();+ assert!(+ r.contains("\"result\":true"),+ "expected tigger a Animal to be entailed under OWL-RL; got: {}",+ r+ );+ }++ #[test]+ fn apply_without_ramification_leaves_derived_count_zero() {+ let db = test_db();+ let graph = Arc::new(GraphStore::new());+ 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 schema = sample_schema();+ let result = schema+ .apply(+ &graph,+ &db,+ &[+ ("old".to_string(), "http://ex.org/Cat".to_string()),+ ("new".to_string(), "http://ex.org/Feline".to_string()),+ ],+ )+ .expect("apply");++ assert_eq!(result.derived_triples_added, 0);+ assert!(result.ramification_profile.is_none());+ }++ #[test]+ fn apply_adds_and_removes_triples_returns_kgcl_patch() {+ let db = test_db();+ let graph = Arc::new(GraphStore::new());+ 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 schema = sample_schema();+ let result = schema+ .apply(+ &graph,+ &db,+ &[+ ("old".to_string(), "http://ex.org/Cat".to_string()),+ ("new".to_string(), "http://ex.org/Feline".to_string()),+ ],+ )+ .expect("apply");++ assert_eq!(result.action_name, "rename_class");+ assert_eq!(result.triples_added, 1, "AddClass effect");+ assert_eq!(result.triples_removed, 1, "RemoveTriple effect");+ assert!(result.kgcl_patch_cnl.iter().any(|s| s.contains("Feline")));+ assert!(result.kgcl_patch_cnl.iter().any(|s| s.contains("delete edge")));+ assert!(result.event_iri.contains("rename_class"));++ // Verify the graph actually reflects the change.+ let q = "ASK WHERE { <http://ex.org/Feline> a <http://www.w3.org/2002/07/owl#Class> }";+ let result_json = graph.sparql_select(q).unwrap();+ assert!(result_json.contains("\"result\":true"));+ }+}diff --git a/src/inputs.rs b/src/inputs.rsindex d0c31ee1..1d741a3c 100644--- a/src/inputs.rs+++ b/src/inputs.rs@@ -577,6 +577,11 @@ pub struct OntoCertifyActionInput {/// One-sided confidence level α for the LCB. Default 0.05.#[serde(default = "default_alpha_pub")]pub alpha: f64,+ /// Optional name of a registered Dynamics action schema (#43) — echoed+ /// into the certificate's assumptions so the audit trail is explicit+ /// about which action was certified.+ #[serde(default)]+ pub action_schema_name: Option<String>,}fn default_utility_metric() -> String {@@ -598,6 +603,121 @@ pub struct GraphProjectionLossyCheckInput {pub projected_ttl: String,}+// ─── Dynamics layer (#43) — action schemas, applicability, apply ────────────++/// Input for `onto_action_register` — persist an action schema by name.+/// Schema is supplied as inline JSON matching `dynamics::ActionSchema`.+#[derive(Deserialize, JsonSchema)]+pub struct OntoActionRegisterInput {+ /// Inline JSON for the action schema. Must deserialize into the structure:+ /// `{ "name": "...", "parameters": [...], "preconditions": [...],+ /// "effects": [{"kind": "add_triple"|"remove_triple"|"add_class", ...}],+ /// "reversible": true|false, "description": "..." }`.+ pub schema_json: String,+}++/// Input for `onto_action_applicable` — evaluate a registered action's+/// preconditions against the loaded graph under the given parameter bindings.+#[derive(Deserialize, JsonSchema)]+pub struct OntoActionApplicableInput {+ /// Name of a previously registered action schema.+ pub action_name: String,+ /// Bindings: `{ "param_name": "iri-or-literal" }`. Substituted into+ /// precondition SPARQL via `{param_name}` placeholders.+ pub bindings: std::collections::BTreeMap<String, String>,+}++/// Input for `onto_action_apply` — execute a registered action's effects,+/// returning the KGCL patch and an IES4-style event IRI.+#[derive(Deserialize, JsonSchema)]+pub struct OntoActionApplyInput {+ /// Name of a previously registered action schema.+ pub action_name: String,+ /// Parameter bindings (same shape as in `onto_action_applicable`).+ pub bindings: std::collections::BTreeMap<String, String>,+ /// If `true` (default), re-check preconditions before applying and abort+ /// if they don't hold. Set `false` only if you have already certified the+ /// action via `onto_certify_action`.+ #[serde(default = "default_true")]+ pub check_preconditions: bool,+ /// Ramification (#47): if `Some(profile)`, run the reasoner after `apply`+ /// to materialise downstream entailments. Accepted profiles: `"rdfs"`,+ /// `"owl-rl"`, `"owl-rl-ext"`, `"owl-dl"`. `None` (default) skips+ /// ramification — the literal effects land and that's it.+ #[serde(default)]+ pub ramify: Option<String>,+ /// Non-deterministic outcomes (#49): when the registered schema has a+ /// non-empty `outcomes` list, this seed makes the sample reproducible.+ /// `None` (default) uses `SystemTime::now()` for non-reproducible+ /// sampling. Ignored for deterministic schemas (empty `outcomes`).+ #[serde(default)]+ pub seed: Option<u64>,+}++fn default_true() -> bool {+ true+}++/// Input for `onto_plan_classical` (#50, Planner #45 follow-up) — invoke+/// Fast Downward as a subprocess on a precompiled PDDL domain + problem and+/// return the parsed sas_plan.+#[derive(Deserialize, JsonSchema)]+pub struct OntoPlanClassicalInput {+ /// PDDL domain text (as produced by `onto_plan_compile_pddl`).+ pub domain: String,+ /// PDDL problem text (as produced by `onto_plan_compile_pddl`).+ pub problem: String,+ /// Optional path to the Fast Downward binary (or wrapper script).+ /// Resolution order: this field > `FAST_DOWNWARD_BIN` env var >+ /// `fast-downward.py` on PATH.+ #[serde(default)]+ pub fast_downward_bin: Option<String>,+ /// Fast Downward search-engine string (e.g. `"lama-first"`,+ /// `"astar(lmcut())"`). Default `"lama-first"`.+ #[serde(default)]+ pub search: Option<String>,+}++/// Input for `onto_plan_validate` (#45 — LLM-Modulo validator) — check that+/// a candidate plan (typically produced by a client-side solver) actually+/// executes step-by-step against the loaded graph in a sandbox, without+/// mutating the real store.+#[derive(Deserialize, JsonSchema)]+pub struct OntoPlanValidateInput {+ /// Candidate plan: an ordered list of `{action_name, bindings}` steps.+ /// `bindings` is a `{param_name: iri-or-literal}` map.+ pub steps: Vec<PlanStepInput>,+ /// Optional goal triples. Each is `[s, p, o]` in N-Triple-position form+ /// (e.g. `["<http://ex.org/Cat>", "<http://www.w3.org/2000/01/rdf-schema#subClassOf>", "<http://ex.org/Animal>"]`).+ /// Reported in `unsatisfied_goals` if any goal does not hold post-plan.+ #[serde(default)]+ pub goal_facts: Vec<Vec<String>>,+}++#[derive(Deserialize, JsonSchema)]+pub struct PlanStepInput {+ pub action_name: String,+ #[serde(default)]+ pub bindings: std::collections::BTreeMap<String, String>,+}++/// Input for `onto_plan_compile_pddl` (#45 — Planner v0.6 stub) — emit a PDDL+/// domain from registered action schemas plus a problem instance from the+/// current graph + goal triples.+#[derive(Deserialize, JsonSchema)]+pub struct OntoPlanCompilePddlInput {+ /// Domain name to embed in `(define (domain ...))`. Default `"ontology"`.+ #[serde(default)]+ pub domain_name: Option<String>,+ /// Subset of registered action schema names to include. Omit / empty for+ /// "include every registered schema".+ #[serde(default)]+ pub action_names: Vec<String>,+ /// Goal triples in Turtle that must hold in the post-state.+ #[serde(default)]+ pub goal_ttl: Option<String>,+}+#[cfg(test)]mod tests {use super::*;diff --git a/src/lib.rs b/src/lib.rsindex 5443fab9..4b09eba0 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -5,7 +5,10 @@ pub mod align;pub mod config;pub mod clinical;pub mod civex;+#[cfg(feature = "causal-pywhy")]+pub mod civex_pywhy;pub mod drift;+pub mod dynamics;pub mod projection_check;// (re-exports keep the alphabetical ordering of the surrounding modules manageable)pub mod enforce;@@ -17,6 +20,9 @@ pub mod inputs;pub mod lineage;pub mod monitor;pub mod plan;+pub mod plan_classical;+pub mod plan_pddl;+pub mod plan_validate;pub mod webhook;pub mod mapping;pub mod marketplace;diff --git a/src/plan_classical.rs b/src/plan_classical.rsnew file mode 100644index 00000000..6bc11203--- /dev/null+++ b/src/plan_classical.rs@@ -0,0 +1,305 @@+//! Fast Downward subprocess wrapper (#50, Planner #45 follow-up).+//!+//! Per the LLM-Modulo convention (Kambhampati arXiv 2402.01817), the+//! classical solver is **client-side** — the server only emits PDDL+//! (`onto_plan_compile_pddl`) and validates returned plans+//! (`onto_plan_validate`). This module provides an optional subprocess+//! wrapper around Fast Downward as a *convenience*: a caller that does have+//! Fast Downward installed locally can ask the server to run it for them+//! and get back the raw sas_plan output.+//!+//! ## Bounded scope (v0.4 wrap)+//!+//! - Subprocess invocation via `std::process::Command`, no embedded planner.+//! - LAMA-first; expose the search-string as a parameter so callers can pick+//! `"lama-first"` / `"lm-cut"` / `"hmax"` etc.+//! - Returns the raw sas_plan content plus a parsed operator list. The+//! *identifier round-trip* (PDDL sanitised id → original IRI binding) is+//! intentionally left to the orchestrator, who already has the registered+//! schemas in hand.+//!+//! ## Honest behaviour when Fast Downward is missing+//!+//! If the configured binary is not found or fails to execute, the wrapper+//! returns a structured error with `kind = "binary_unavailable"`. It does+//! NOT fall back to a silent stub.++use serde::Serialize;+use std::path::Path;+use std::process::Command;++/// One operator instance in a parsed sas_plan. Operator name + positional+/// args, both still in PDDL-sanitised form (the orchestrator maps args back+/// to original IRIs using the `identifier_map` it kept from+/// `onto_plan_compile_pddl`).+#[derive(Clone, Debug, Serialize, PartialEq, Eq)]+pub struct ParsedOperator {+ pub name: String,+ pub args: Vec<String>,+}++/// Result of running Fast Downward.+#[derive(Clone, Debug, Serialize)]+pub struct FastDownwardResult {+ /// Raw sas_plan content as Fast Downward wrote it.+ pub sas_plan: String,+ /// Parsed operator sequence (LLM-friendly).+ pub operators: Vec<ParsedOperator>,+ /// The `binary` the wrapper actually invoked (after env var resolution).+ pub binary_used: String,+ /// Optional `; cost = N (...)` footer from the sas_plan, if present.+ pub cost_footer: Option<String>,+}++/// Parse a sas_plan text into a list of operator instances. Blank lines and+/// `;`-prefixed comments are skipped; the trailing `; cost = N (...)` footer+/// is recognised separately so callers can show it.+pub fn parse_sas_plan(text: &str) -> (Vec<ParsedOperator>, Option<String>) {+ let mut operators: Vec<ParsedOperator> = Vec::new();+ let mut cost_footer: Option<String> = None;+ for line in text.lines() {+ let trimmed = line.trim();+ if trimmed.is_empty() {+ continue;+ }+ if let Some(rest) = trimmed.strip_prefix(';') {+ let r = rest.trim();+ if r.starts_with("cost") {+ cost_footer = Some(r.to_string());+ }+ continue;+ }+ // Strip the outer parens.+ let inner = trimmed+ .strip_prefix('(')+ .and_then(|s| s.strip_suffix(')'))+ .unwrap_or(trimmed);+ let mut parts = inner.split_whitespace();+ if let Some(name) = parts.next() {+ let args: Vec<String> = parts.map(|s| s.to_string()).collect();+ operators.push(ParsedOperator {+ name: name.to_string(),+ args,+ });+ }+ }+ (operators, cost_footer)+}++/// Resolve the Fast Downward binary path. Order of precedence:+/// 1. Explicit `binary_override` parameter.+/// 2. `FAST_DOWNWARD_BIN` env var.+/// 3. `fast-downward.py` on PATH (default).+fn resolve_binary(binary_override: Option<&str>) -> String {+ if let Some(b) = binary_override.filter(|s| !s.is_empty()) {+ return b.to_string();+ }+ if let Ok(env) = std::env::var("FAST_DOWNWARD_BIN")+ && !env.is_empty()+ {+ return env;+ }+ "fast-downward.py".to_string()+}++/// Invoke Fast Downward on a domain + problem and return the parsed plan.+///+/// `search` is the Fast Downward search-engine string (e.g.+/// `"astar(lmcut())"`, `"lama-first"`). Default `"lama-first"`.+pub fn run_fast_downward(+ domain_pddl: &str,+ problem_pddl: &str,+ binary_override: Option<&str>,+ search: Option<&str>,+) -> anyhow::Result<FastDownwardResult> {+ let binary = resolve_binary(binary_override);+ let search_str = search.unwrap_or("lama-first").to_string();++ // Write PDDL to a working directory under the OS temp dir.+ let tmp_root = std::env::temp_dir().join(format!(+ "oo_fd_{}_{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_nanos())+ .unwrap_or(0)+ ));+ std::fs::create_dir_all(&tmp_root)?;+ let domain_path = tmp_root.join("domain.pddl");+ let problem_path = tmp_root.join("problem.pddl");+ std::fs::write(&domain_path, domain_pddl)?;+ std::fs::write(&problem_path, problem_pddl)?;++ // Fast Downward CLI: `fast-downward.py [--plan-file FILE] DOMAIN PROBLEM+ // --search SEARCH`. We force the plan file so we can reliably read it.+ let plan_path = tmp_root.join("sas_plan");+ let output = Command::new(&binary)+ .arg("--plan-file")+ .arg(&plan_path)+ .arg(&domain_path)+ .arg(&problem_path)+ .arg("--search")+ .arg(&search_str)+ .output();+ let output = match output {+ Ok(o) => o,+ Err(e) => {+ anyhow::bail!(+ "binary_unavailable: failed to execute `{}`: {}. Install Fast Downward and set FAST_DOWNWARD_BIN, or pass `fast_downward_bin`.",+ binary,+ e+ );+ }+ };++ if !output.status.success() {+ let stderr = String::from_utf8_lossy(&output.stderr);+ anyhow::bail!(+ "fast_downward_failed: exit={:?}, stderr={}",+ output.status.code(),+ stderr+ );+ }++ // Fast Downward emits multiple plans for satisficing searches as+ // `sas_plan.1`, `sas_plan.2`, …; we prefer the highest-numbered one+ // ("best so far"), falling back to the unsuffixed path for unit plans.+ let sas_plan_text = read_best_sas_plan(&tmp_root, &plan_path)?;+ let (operators, cost_footer) = parse_sas_plan(&sas_plan_text);++ // Best-effort cleanup; ignore failures.+ let _ = std::fs::remove_dir_all(&tmp_root);++ Ok(FastDownwardResult {+ sas_plan: sas_plan_text,+ operators,+ binary_used: binary,+ cost_footer,+ })+}++/// Read the best (highest-numbered) sas_plan variant under `tmp_root`.+/// Falls back to the unsuffixed `plan_path` if no numbered variants exist.+fn read_best_sas_plan(tmp_root: &Path, plan_path: &Path) -> anyhow::Result<String> {+ let mut best: Option<(u32, std::path::PathBuf)> = None;+ if let Ok(rd) = std::fs::read_dir(tmp_root) {+ for entry in rd.flatten() {+ let name = entry.file_name();+ let name_s = name.to_string_lossy();+ if let Some(suffix) = name_s.strip_prefix("sas_plan.")+ && let Ok(n) = suffix.parse::<u32>()+ {+ let path = entry.path();+ match &best {+ Some((cur, _)) if *cur >= n => {}+ _ => best = Some((n, path)),+ }+ }+ }+ }+ let chosen = match best {+ Some((_, p)) => p,+ None => plan_path.to_path_buf(),+ };+ if !chosen.exists() {+ anyhow::bail!(+ "no_plan_emitted: Fast Downward exited 0 but produced no sas_plan file under {:?}",+ tmp_root+ );+ }+ Ok(std::fs::read_to_string(&chosen)?)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn parse_sas_plan_handles_three_operator_plan_with_cost_footer() {+ let txt = "(add_class new_iri)\n\+ (add_subclass_edge cat new_iri)\n\+ (add_subclass_edge dog new_iri)\n\+ ; cost = 3 (unit cost)\n";+ let (ops, cost) = parse_sas_plan(txt);+ assert_eq!(ops.len(), 3);+ assert_eq!(ops[0].name, "add_class");+ assert_eq!(ops[0].args, vec!["new_iri"]);+ assert_eq!(ops[1].name, "add_subclass_edge");+ assert_eq!(ops[1].args, vec!["cat", "new_iri"]);+ assert_eq!(cost.as_deref(), Some("cost = 3 (unit cost)"));+ }++ #[test]+ fn parse_sas_plan_skips_blank_lines_and_comments() {+ let txt = "\n\+ ; this is a comment line that is not a cost footer\n\+ (op1 a b)\n\+ \n\+ (op2 c)\n\+ ; trailing free-form\n";+ let (ops, cost) = parse_sas_plan(txt);+ assert_eq!(ops.len(), 2);+ assert_eq!(ops[0].name, "op1");+ assert_eq!(ops[1].name, "op2");+ // No `cost = N` footer in the input → None.+ assert!(cost.is_none());+ }++ #[test]+ fn parse_sas_plan_returns_empty_for_empty_input() {+ let (ops, cost) = parse_sas_plan("");+ assert!(ops.is_empty());+ assert!(cost.is_none());+ }++ #[test]+ fn parse_sas_plan_handles_zero_arg_operators() {+ let (ops, _) = parse_sas_plan("(reset)\n(commit)\n");+ assert_eq!(ops.len(), 2);+ assert!(ops[0].args.is_empty());+ assert_eq!(ops[1].name, "commit");+ }++ #[test]+ fn resolve_binary_prefers_explicit_override() {+ let resolved = resolve_binary(Some("/usr/local/bin/fd"));+ assert_eq!(resolved, "/usr/local/bin/fd");+ }++ #[test]+ fn resolve_binary_defaults_to_fast_downward_py_when_no_inputs() {+ // Take a snapshot of FAST_DOWNWARD_BIN, clear, restore at end.+ // (rustc test runners share env; this is best-effort.)+ let prior = std::env::var("FAST_DOWNWARD_BIN").ok();+ // SAFETY: env mutation is unsafe in 2024 edition; this is test-only.+ unsafe {+ std::env::remove_var("FAST_DOWNWARD_BIN");+ }+ let resolved = resolve_binary(None);+ assert_eq!(resolved, "fast-downward.py");+ if let Some(p) = prior {+ unsafe {+ std::env::set_var("FAST_DOWNWARD_BIN", p);+ }+ }+ }++ #[test]+ fn run_fast_downward_returns_binary_unavailable_when_binary_missing() {+ // Point at a clearly nonexistent binary; expect the structured+ // binary_unavailable error.+ let err = run_fast_downward(+ "(define (domain d))",+ "(define (problem p) (:domain d))",+ Some("/definitely/does/not/exist/fast-downward.bin.xyz"),+ None,+ )+ .expect_err("should error");+ let s = format!("{}", err);+ assert!(+ s.contains("binary_unavailable"),+ "expected binary_unavailable error, got: {}",+ s+ );+ }+}diff --git a/src/plan_pddl.rs b/src/plan_pddl.rsnew file mode 100644index 00000000..ba803d25--- /dev/null+++ b/src/plan_pddl.rs@@ -0,0 +1,349 @@+//! Planner stub (#45) — PDDL emission from Dynamics action schemas.+//!+//! Compiles registered [`crate::dynamics::ActionSchema`]s into a PDDL domain+//! and emits a problem instance from the loaded graph plus a Turtle goal slice.+//! The actual planning is delegated to an external solver (Fast Downward) per+//! the LLM-Modulo convention: the server only exposes the PDDL compilation ++//! plan validation; the orchestrator runs the solver and feeds steps back.+//!+//! ## Bounded scope (v0.4 stub)+//!+//! - Single predicate `(triple ?s ?p ?o)` with one typed sort `iri`.+//! - Parameter slots from `ActionSchema::parameters` become typed PDDL+//! parameters.+//! - Preconditions of the form `ASK { <{a}> <pred> <{b}> }` are translated to+//! `(triple ?a "pred-as-constant" ?b)`. Free-form SPARQL is preserved as a+//! PDDL comment so the audit trail is explicit about the lossy translation.+//! - `AddTriple` / `AddClass` effects compile to positive `triple` facts.+//! - `RemoveTriple` compiles to negated `triple` facts via STRIPS delete.+//!+//! ## Honest deferral+//!+//! Real OWL → PDDL compilation requires careful handling of existentials,+//! cardinality restrictions, and open-world semantics. The Borgwardt KR 2025+//! paper is the anchor for the rigorous version; this stub is a sand-table.++use crate::dynamics::{ActionSchema, EffectSpec};++/// Result of compiling a domain + problem.+#[derive(Clone, Debug)]+pub struct CompiledPddl {+ pub domain: String,+ pub problem: String,+ /// Translation notes: each entry is a precondition or effect that the+ /// stub couldn't fully encode and that was preserved as a PDDL comment.+ pub translation_notes: Vec<String>,+}++/// Sanitise an IRI or label into a PDDL-safe identifier (no angle brackets,+/// slashes, colons; lower-case alphanumeric + `_`).+fn sanitise(s: &str) -> String {+ let mut out = String::with_capacity(s.len());+ for c in s.chars() {+ if c.is_ascii_alphanumeric() {+ out.push(c.to_ascii_lowercase());+ } else {+ out.push('_');+ }+ }+ out.trim_matches('_').to_string()+}++/// Try to extract `(subject_param, predicate_iri, object_param)` from an+/// SPARQL `ASK { <{a}> <pred> <{b}> }` precondition. Returns None for+/// anything more complex.+fn try_extract_ask_triple(precond: &str) -> Option<(String, String, String)> {+ let trimmed = precond.trim();+ if !trimmed.to_uppercase().starts_with("ASK") {+ return None;+ }+ let open = trimmed.find('{')?;+ let close = trimmed.rfind('}')?;+ if close <= open {+ return None;+ }+ let body = trimmed[open + 1..close].trim();+ // Expect three IRIs / placeholders separated by whitespace, ending in `.` or not.+ let stripped = body.trim_end_matches('.').trim();+ let parts: Vec<&str> = stripped.split_whitespace().collect();+ if parts.len() != 3 {+ return None;+ }+ Some((parts[0].to_string(), parts[1].to_string(), parts[2].to_string()))+}++/// Translate a triple position (placeholder `<{x}>`, full IRI `<...>`, or bare+/// `{x}`) into a PDDL term. Placeholders become `?x`; full IRIs become a+/// stable constant identifier.+fn position_to_pddl_term(pos: &str, notes: &mut Vec<String>) -> String {+ let t = pos.trim();+ // <{x}> or <{x}>+ if let Some(inner) = t.strip_prefix("<{").and_then(|s| s.strip_suffix("}>")) {+ return format!("?{}", inner);+ }+ if let Some(inner) = t.strip_prefix('{').and_then(|s| s.strip_suffix('}')) {+ return format!("?{}", inner);+ }+ if let Some(inner) = t.strip_prefix('<').and_then(|s| s.strip_suffix('>')) {+ return sanitise(inner);+ }+ notes.push(format!("untranslated term: {}", t));+ sanitise(t)+}++fn effect_to_pddl(effect: &EffectSpec, notes: &mut Vec<String>) -> (bool, String) {+ // Returns (positive?, pddl_atom).+ match effect {+ EffectSpec::AddTriple { subject, predicate, object } => {+ let s = position_to_pddl_term(&format!("<{}>", subject.trim_matches(|c| c == '<' || c == '>')), notes);+ let p = position_to_pddl_term(&format!("<{}>", predicate.trim_matches(|c| c == '<' || c == '>')), notes);+ let o = position_to_pddl_term(&format!("<{}>", object.trim_matches(|c| c == '<' || c == '>')), notes);+ (true, format!("(triple {} {} {})", s, p, o))+ }+ EffectSpec::RemoveTriple { subject, predicate, object } => {+ let s = position_to_pddl_term(&format!("<{}>", subject.trim_matches(|c| c == '<' || c == '>')), notes);+ let p = position_to_pddl_term(&format!("<{}>", predicate.trim_matches(|c| c == '<' || c == '>')), notes);+ let o = position_to_pddl_term(&format!("<{}>", object.trim_matches(|c| c == '<' || c == '>')), notes);+ (false, format!("(triple {} {} {})", s, p, o))+ }+ EffectSpec::AddClass { iri } => {+ let s = position_to_pddl_term(&format!("<{}>", iri.trim_matches(|c| c == '<' || c == '>')), notes);+ let p = sanitise("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");+ let o = sanitise("http://www.w3.org/2002/07/owl#Class");+ (true, format!("(triple {} {} {})", s, p, o))+ }+ }+}++/// Emit a PDDL `:action` block for the schema.+fn schema_to_pddl_action(schema: &ActionSchema, notes: &mut Vec<String>) -> String {+ let action_name = sanitise(&schema.name);+ let params: Vec<String> = schema+ .parameters+ .iter()+ .map(|p| format!("?{} - iri", p.name))+ .collect();+ let params_str = if params.is_empty() {+ String::new()+ } else {+ format!(" {}", params.join(" "))+ };++ // Preconditions.+ let mut precond_atoms: Vec<String> = Vec::new();+ for precond in &schema.preconditions {+ if let Some((s, p, o)) = try_extract_ask_triple(precond) {+ let s_t = position_to_pddl_term(&s, notes);+ let p_t = position_to_pddl_term(&p, notes);+ let o_t = position_to_pddl_term(&o, notes);+ precond_atoms.push(format!("(triple {} {} {})", s_t, p_t, o_t));+ } else {+ notes.push(format!(+ "untranslated precondition for action `{}`: {}",+ schema.name, precond+ ));+ }+ }+ let precond_block = if precond_atoms.is_empty() {+ "()".to_string()+ } else if precond_atoms.len() == 1 {+ precond_atoms.remove(0)+ } else {+ format!("(and {})", precond_atoms.join(" "))+ };++ // Effects.+ let mut effect_atoms: Vec<String> = Vec::new();+ for effect in &schema.effects {+ let (positive, atom) = effect_to_pddl(effect, notes);+ if positive {+ effect_atoms.push(atom);+ } else {+ effect_atoms.push(format!("(not {})", atom));+ }+ }+ let effect_block = if effect_atoms.is_empty() {+ "()".to_string()+ } else if effect_atoms.len() == 1 {+ effect_atoms.remove(0)+ } else {+ format!("(and {})", effect_atoms.join(" "))+ };++ format!(+ " (:action {}\n :parameters ({})\n :precondition {}\n :effect {})",+ action_name,+ params_str.trim(),+ precond_block,+ effect_block+ )+}++/// Compile a PDDL domain from a list of action schemas.+pub fn compile_domain(domain_name: &str, schemas: &[ActionSchema]) -> CompiledPddl {+ let mut notes: Vec<String> = Vec::new();+ let mut actions: Vec<String> = Vec::new();+ for s in schemas {+ actions.push(schema_to_pddl_action(s, &mut notes));+ }++ let domain = format!(+ "(define (domain {})\n (:requirements :strips :typing :negative-preconditions)\n (:types iri)\n (:predicates (triple ?s - iri ?p - iri ?o - iri))\n{}\n)",+ sanitise(domain_name),+ actions.join("\n")+ );++ // Problem stub — empty init/goal; the MCP layer fills in init from the+ // loaded graph and goal from Turtle.+ let problem = String::new();++ CompiledPddl { domain, problem, translation_notes: notes }+}++/// Compile a PDDL problem instance. `init_facts` is the set of `(s, p, o)`+/// IRIs that hold in the start state; `goal_facts` is the set that must hold+/// in the post-state.+pub fn compile_problem(+ problem_name: &str,+ domain_name: &str,+ init_facts: &[(String, String, String)],+ goal_facts: &[(String, String, String)],+) -> String {+ // Collect every distinct IRI to enumerate as objects.+ let mut objs: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();+ for (s, p, o) in init_facts.iter().chain(goal_facts.iter()) {+ objs.insert(sanitise(s));+ objs.insert(sanitise(p));+ objs.insert(sanitise(o));+ }+ let objs_block: String = objs.into_iter().collect::<Vec<_>>().join(" ");++ let init_block: String = init_facts+ .iter()+ .map(|(s, p, o)| format!("(triple {} {} {})", sanitise(s), sanitise(p), sanitise(o)))+ .collect::<Vec<_>>()+ .join(" ");++ let goal_block: String = if goal_facts.is_empty() {+ "()".to_string()+ } else {+ let atoms: Vec<String> = goal_facts+ .iter()+ .map(|(s, p, o)| format!("(triple {} {} {})", sanitise(s), sanitise(p), sanitise(o)))+ .collect();+ if atoms.len() == 1 {+ atoms[0].clone()+ } else {+ format!("(and {})", atoms.join(" "))+ }+ };++ format!(+ "(define (problem {})\n (:domain {})\n (:objects {} - iri)\n (:init {})\n (:goal {}))",+ sanitise(problem_name),+ sanitise(domain_name),+ objs_block,+ init_block,+ goal_block+ )+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::dynamics::{ActionSchema, EffectSpec, Parameter};++ fn rename_schema() -> ActionSchema {+ ActionSchema {+ name: "rename_class".to_string(),+ parameters: vec![+ Parameter { name: "old".to_string(), type_iri: None },+ Parameter { name: "new".to_string(), type_iri: None },+ ],+ preconditions: vec![+ "ASK { <{old}> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class> }".to_string(),+ ],+ effects: vec![+ EffectSpec::AddClass { iri: "{new}".to_string() },+ EffectSpec::RemoveTriple {+ subject: "{old}".to_string(),+ predicate: "http://www.w3.org/1999/02/22-rdf-syntax-ns#type".to_string(),+ object: "http://www.w3.org/2002/07/owl#Class".to_string(),+ },+ ],+ reversible: false,+ description: None,+ outcomes: vec![],+ }+ }++ #[test]+ fn sanitise_strips_iri_punctuation() {+ let out = sanitise("http://www.w3.org/2002/07/owl#Class");+ assert!(!out.contains('/'));+ assert!(!out.contains(':'));+ assert!(!out.contains('#'));+ assert!(out.contains("class") || out.contains("Class") || out.ends_with("class"));+ }++ #[test]+ fn try_extract_ask_triple_pulls_three_terms() {+ let q = "ASK { <{old}> <http://x.org/p> <http://x.org/q> }";+ let parsed = try_extract_ask_triple(q).expect("parsed");+ assert_eq!(parsed.0, "<{old}>");+ assert_eq!(parsed.1, "<http://x.org/p>");+ assert_eq!(parsed.2, "<http://x.org/q>");+ }++ #[test]+ fn try_extract_ask_returns_none_for_select() {+ let q = "SELECT ?x WHERE { ?x a <http://www.w3.org/2002/07/owl#Class> }";+ assert!(try_extract_ask_triple(q).is_none());+ }++ #[test]+ fn compile_domain_emits_typed_action_with_pddl_keywords() {+ let schemas = vec![rename_schema()];+ let compiled = compile_domain("ontology", &schemas);+ assert!(compiled.domain.contains("(define (domain ontology)"));+ assert!(compiled.domain.contains(":requirements :strips :typing"));+ assert!(compiled.domain.contains("(:predicates (triple"));+ assert!(compiled.domain.contains("(:action rename_class"));+ assert!(compiled.domain.contains("?old - iri"));+ assert!(compiled.domain.contains("?new - iri"));+ assert!(compiled.domain.contains(":precondition (triple ?old"));+ assert!(compiled.domain.contains(":effect (and"));+ assert!(compiled.domain.contains("(not (triple ?old"));+ }++ #[test]+ fn unparseable_precondition_is_recorded_in_notes() {+ let mut s = rename_schema();+ s.preconditions.push("SELECT ?x WHERE { ?x ?p ?o }".to_string());+ let compiled = compile_domain("d", &[s]);+ assert!(+ compiled.translation_notes.iter().any(|n| n.contains("untranslated precondition")),+ "expected a translation note for SELECT-shaped precondition; got: {:?}",+ compiled.translation_notes+ );+ }++ #[test]+ fn compile_problem_renders_objects_init_and_goal() {+ let init = vec![(+ "http://ex.org/Cat".to_string(),+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#type".to_string(),+ "http://www.w3.org/2002/07/owl#Class".to_string(),+ )];+ let goal = vec![(+ "http://ex.org/Feline".to_string(),+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#type".to_string(),+ "http://www.w3.org/2002/07/owl#Class".to_string(),+ )];+ let problem = compile_problem("rename_cat", "ontology", &init, &goal);+ assert!(problem.contains("(:domain ontology)"));+ assert!(problem.contains(":init (triple"));+ assert!(problem.contains(":goal (triple"));+ assert!(problem.contains("- iri"));+ }+}diff --git a/src/plan_validate.rs b/src/plan_validate.rsnew file mode 100644index 00000000..3fcb8e61--- /dev/null+++ b/src/plan_validate.rs@@ -0,0 +1,401 @@+//! Plan validator (#45, LLM-Modulo `Validator` role).+//!+//! Companion to [`crate::plan_pddl::compile_domain`]. The compile primitive+//! emits PDDL for an external solver (the orchestrator's responsibility per+//! the LLM-Modulo convention); this validator consumes the solver's output+//! and checks step-by-step that each operator is applicable to the cumulative+//! state and that its effects compose without contradiction.+//!+//! ## What validation means here+//!+//! Given a sequence of `(action_name, bindings)` operator instances, the+//! validator:+//!+//! 1. Forks the loaded graph into an isolated sandbox so the real store is+//! not mutated.+//! 2. For each step in order:+//! a. Looks up the registered [`crate::dynamics::ActionSchema`].+//! b. Re-evaluates the schema's preconditions against the cumulative+//! sandbox state under the step's bindings.+//! c. If applicable, executes the schema's effects against the sandbox.+//! d. If not applicable, returns immediately with the failing step index+//! and a diagnostic, leaving subsequent steps unevaluated.+//! 3. Returns the validation report — valid + final triple count, or invalid+//! + first failing step.+//!+//! Goal triples (optional) are checked after the final step: every goal+//! `(s, p, o)` must be derivable as a SPARQL ASK over the sandbox. Missing+//! goals do NOT invalidate the plan; they are reported in `unsatisfied_goals`+//! so the orchestrator can iterate.+//!+//! ## Why this matters+//!+//! Per LLM-Modulo (Kambhampati arXiv 2402.01817), the LLM/orchestrator can+//! produce candidate plans (via Fast Downward, prompting, or other means);+//! the server stays the *validator*. This module is exactly that primitive —+//! it does not solve, it judges.++use crate::dynamics::{lookup, ActionSchema};+use crate::graph::GraphStore;+use crate::state::StateDb;+use serde::{Deserialize, Serialize};+use std::collections::BTreeMap;+use std::sync::Arc;++/// One operator instance in a candidate plan.+#[derive(Clone, Debug, Deserialize, Serialize)]+pub struct PlanStep {+ pub action_name: String,+ #[serde(default)]+ pub bindings: BTreeMap<String, String>,+}++/// Outcome of validating a candidate plan.+#[derive(Clone, Debug, Serialize)]+pub struct PlanValidationResult {+ pub valid: bool,+ pub steps_total: usize,+ pub steps_validated: usize,+ /// Set only when `valid == false`: zero-based index of the first step that+ /// failed.+ pub failed_at_step: Option<usize>,+ /// Set only when `valid == false`: human-readable diagnostic.+ pub failure_reason: Option<String>,+ pub initial_triple_count: usize,+ pub final_triple_count: usize,+ /// Goal facts that did NOT hold after running all steps; empty when no+ /// goals were supplied, or when every goal was satisfied. Even an invalid+ /// plan can satisfy SOME goals, so this is independent of `valid`.+ pub unsatisfied_goals: Vec<(String, String, String)>,+ /// Per-step effect tallies (added + removed triples), in order.+ pub per_step_added: Vec<usize>,+ pub per_step_removed: Vec<usize>,+}++/// Clone the loaded graph into a fresh sandbox `GraphStore`. The original+/// `graph` is not mutated.+fn snapshot_into_sandbox(graph: &Arc<GraphStore>) -> anyhow::Result<Arc<GraphStore>> {+ let triples = graph.all_triples()?;+ let sandbox = Arc::new(GraphStore::new());+ if triples.is_empty() {+ return Ok(sandbox);+ }+ // `all_triples` returns N-Triple-formatted positions (e.g. `<iri>`,+ // `"literal"`, `_:bn`), which are accepted by `load_turtle` as a subset+ // of Turtle. Concatenate into one document.+ let mut nt = String::with_capacity(triples.len() * 64);+ for (s, p, o) in &triples {+ nt.push_str(s);+ nt.push(' ');+ nt.push_str(p);+ nt.push(' ');+ nt.push_str(o);+ nt.push_str(" .\n");+ }+ sandbox.load_turtle(&nt, None)?;+ Ok(sandbox)+}++/// Validate a candidate plan against the loaded graph. Does NOT mutate the+/// original graph — all simulation happens in a forked sandbox.+///+/// `goal_facts` is an optional list of `(s, p, o)` IRIs/literals (already in+/// N-Triple-position form, e.g. `<http://ex.org/Cat>`) that must hold in the+/// post-state for the plan to fully achieve its goal.+pub fn validate_plan(+ db: &StateDb,+ graph: &Arc<GraphStore>,+ steps: &[PlanStep],+ goal_facts: &[(String, String, String)],+) -> anyhow::Result<PlanValidationResult> {+ let sandbox = snapshot_into_sandbox(graph)?;+ let initial_triple_count = sandbox.triple_count();++ let mut per_step_added: Vec<usize> = Vec::with_capacity(steps.len());+ let mut per_step_removed: Vec<usize> = Vec::with_capacity(steps.len());++ // Scratch DB so per-step lineage entries don't pollute the production+ // StateDb. Uses SQLite's in-memory mode — no file is created, the DB is+ // discarded when the function returns. The lookup() call still uses the+ // real db — schemas live in production state.+ let scratch_db = StateDb::open(std::path::Path::new(":memory:"))?;++ for (i, step) in steps.iter().enumerate() {+ let schema: ActionSchema = match lookup(db, &step.action_name)? {+ Some(s) => s,+ None => {+ return Ok(PlanValidationResult {+ valid: false,+ steps_total: steps.len(),+ steps_validated: i,+ failed_at_step: Some(i),+ failure_reason: Some(format!(+ "unknown action `{}` at step {}",+ step.action_name, i+ )),+ initial_triple_count,+ final_triple_count: sandbox.triple_count(),+ unsatisfied_goals: goal_facts.to_vec(),+ per_step_added,+ per_step_removed,+ });+ }+ };+ let bindings: Vec<(String, String)> = step+ .bindings+ .iter()+ .map(|(k, v)| (k.clone(), v.clone()))+ .collect();++ if !schema.applicable(&sandbox, &bindings) {+ return Ok(PlanValidationResult {+ valid: false,+ steps_total: steps.len(),+ steps_validated: i,+ failed_at_step: Some(i),+ failure_reason: Some(format!(+ "preconditions not satisfied at step {} (`{}`)",+ i, step.action_name+ )),+ initial_triple_count,+ final_triple_count: sandbox.triple_count(),+ unsatisfied_goals: goal_facts.to_vec(),+ per_step_added,+ per_step_removed,+ });+ }+ let outcome = schema.apply(&sandbox, &scratch_db, &bindings)?;+ per_step_added.push(outcome.triples_added);+ per_step_removed.push(outcome.triples_removed);+ }++ // All steps applied. Now check goals.+ let mut unsatisfied: Vec<(String, String, String)> = Vec::new();+ for (s, p, o) in goal_facts {+ let q = format!("ASK {{ {} {} {} }}", s, p, o);+ let satisfied = match sandbox.sparql_select(&q) {+ Ok(r) => r.contains("\"result\":true"),+ Err(_) => false,+ };+ if !satisfied {+ unsatisfied.push((s.clone(), p.clone(), o.clone()));+ }+ }++ Ok(PlanValidationResult {+ valid: true,+ steps_total: steps.len(),+ steps_validated: steps.len(),+ failed_at_step: None,+ failure_reason: None,+ initial_triple_count,+ final_triple_count: sandbox.triple_count(),+ unsatisfied_goals: unsatisfied,+ per_step_added,+ per_step_removed,+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::dynamics::{register, ActionSchema, EffectSpec, Parameter};++ fn test_db() -> StateDb {+ let tmp = tempfile::NamedTempFile::new().unwrap();+ let path = tmp.path().to_path_buf();+ std::mem::forget(tmp);+ StateDb::open(&path).unwrap()+ }++ fn add_subclass_schema() -> ActionSchema {+ ActionSchema {+ name: "add_subclass_edge".to_string(),+ parameters: vec![+ Parameter { name: "child".to_string(), type_iri: None },+ Parameter { name: "parent".to_string(), type_iri: None },+ ],+ preconditions: vec![+ "ASK { <{child}> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class> }".to_string(),+ "ASK { <{parent}> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class> }".to_string(),+ ],+ effects: vec![EffectSpec::AddTriple {+ subject: "{child}".to_string(),+ predicate: "http://www.w3.org/2000/01/rdf-schema#subClassOf".to_string(),+ object: "{parent}".to_string(),+ }],+ reversible: true,+ description: None,+ outcomes: vec![],+ }+ }++ fn add_class_schema() -> ActionSchema {+ ActionSchema {+ name: "add_class".to_string(),+ parameters: vec![Parameter { name: "iri".to_string(), type_iri: None }],+ preconditions: vec![],+ effects: vec![EffectSpec::AddClass { iri: "{iri}".to_string() }],+ reversible: true,+ description: None,+ outcomes: vec![],+ }+ }++ fn graph_with_two_classes() -> Arc<GraphStore> {+ let g = Arc::new(GraphStore::new());+ g.load_turtle(+ r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://ex.org/> .+ ex:Animal a owl:Class .+ ex:Cat a owl:Class .+ "#,+ None,+ )+ .unwrap();+ g+ }++ #[test]+ fn validate_empty_plan_is_valid_and_satisfies_no_goals() {+ let db = test_db();+ let graph = graph_with_two_classes();+ let result = validate_plan(&db, &graph, &[], &[]).unwrap();+ assert!(result.valid);+ assert_eq!(result.steps_validated, 0);+ assert_eq!(result.initial_triple_count, result.final_triple_count);+ assert!(result.unsatisfied_goals.is_empty());+ }++ #[test]+ fn validate_single_step_with_satisfied_preconditions_succeeds() {+ let db = test_db();+ let graph = graph_with_two_classes();+ register(&db, &add_subclass_schema()).unwrap();++ let mut bindings = BTreeMap::new();+ bindings.insert("child".to_string(), "http://ex.org/Cat".to_string());+ bindings.insert("parent".to_string(), "http://ex.org/Animal".to_string());++ let steps = vec![PlanStep {+ action_name: "add_subclass_edge".to_string(),+ bindings,+ }];+ let result = validate_plan(&db, &graph, &steps, &[]).unwrap();++ assert!(result.valid);+ assert_eq!(result.steps_validated, 1);+ assert_eq!(result.per_step_added, vec![1]);+ assert_eq!(result.per_step_removed, vec![0]);+ // Original graph must be untouched.+ let post_q = graph+ .sparql_select("ASK { <http://ex.org/Cat> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/Animal> }")+ .unwrap();+ assert!(+ !post_q.contains("\"result\":true"),+ "original graph should not have been mutated by validation"+ );+ }++ #[test]+ fn validate_step_with_missing_action_reports_failure() {+ let db = test_db();+ let graph = graph_with_two_classes();+ let steps = vec![PlanStep {+ action_name: "no_such_action".to_string(),+ bindings: BTreeMap::new(),+ }];+ let result = validate_plan(&db, &graph, &steps, &[]).unwrap();+ assert!(!result.valid);+ assert_eq!(result.failed_at_step, Some(0));+ assert!(result.failure_reason.unwrap().contains("unknown action"));+ assert_eq!(result.steps_validated, 0);+ }++ #[test]+ fn validate_step_with_unsatisfied_precondition_reports_failure() {+ let db = test_db();+ let graph = graph_with_two_classes();+ register(&db, &add_subclass_schema()).unwrap();++ let mut bindings = BTreeMap::new();+ bindings.insert("child".to_string(), "http://ex.org/Cat".to_string());+ // parent is NOT declared as owl:Class in the seed graph.+ bindings.insert("parent".to_string(), "http://ex.org/UnknownThing".to_string());++ let steps = vec![PlanStep {+ action_name: "add_subclass_edge".to_string(),+ bindings,+ }];+ let result = validate_plan(&db, &graph, &steps, &[]).unwrap();+ assert!(!result.valid);+ assert_eq!(result.failed_at_step, Some(0));+ assert!(result+ .failure_reason+ .as_ref()+ .unwrap()+ .contains("preconditions not satisfied"));+ }++ #[test]+ fn validate_multi_step_plan_chains_state_through() {+ // Step 1 establishes the precondition that Step 2 needs.+ let db = test_db();+ let graph = graph_with_two_classes();+ register(&db, &add_class_schema()).unwrap();+ register(&db, &add_subclass_schema()).unwrap();++ // Step 1: declare ex:Feline as a class.+ let mut s1 = BTreeMap::new();+ s1.insert("iri".to_string(), "http://ex.org/Feline".to_string());+ // Step 2: ex:Cat rdfs:subClassOf ex:Feline (which only exists after step 1).+ let mut s2 = BTreeMap::new();+ s2.insert("child".to_string(), "http://ex.org/Cat".to_string());+ s2.insert("parent".to_string(), "http://ex.org/Feline".to_string());++ let steps = vec![+ PlanStep { action_name: "add_class".to_string(), bindings: s1 },+ PlanStep { action_name: "add_subclass_edge".to_string(), bindings: s2 },+ ];+ let result = validate_plan(&db, &graph, &steps, &[]).unwrap();+ assert!(+ result.valid,+ "step 2 should pass because step 1 establishes its precondition; reason: {:?}",+ result.failure_reason+ );+ assert_eq!(result.steps_validated, 2);+ }++ #[test]+ fn validate_reports_unsatisfied_goals_without_invalidating_plan() {+ let db = test_db();+ let graph = graph_with_two_classes();+ register(&db, &add_subclass_schema()).unwrap();++ let mut bindings = BTreeMap::new();+ bindings.insert("child".to_string(), "http://ex.org/Cat".to_string());+ bindings.insert("parent".to_string(), "http://ex.org/Animal".to_string());++ let steps = vec![PlanStep {+ action_name: "add_subclass_edge".to_string(),+ bindings,+ }];+ // Goal that the plan DOES achieve.+ let achieved = (+ "<http://ex.org/Cat>".to_string(),+ "<http://www.w3.org/2000/01/rdf-schema#subClassOf>".to_string(),+ "<http://ex.org/Animal>".to_string(),+ );+ // Goal that the plan does NOT achieve (no such edge produced).+ let missing = (+ "<http://ex.org/Cat>".to_string(),+ "<http://www.w3.org/2000/01/rdf-schema#subClassOf>".to_string(),+ "<http://ex.org/Mammal>".to_string(),+ );+ let result = validate_plan(&db, &graph, &steps, &[achieved, missing.clone()]).unwrap();+ assert!(result.valid, "plan itself is well-formed");+ assert_eq!(result.unsatisfied_goals.len(), 1);+ assert_eq!(result.unsatisfied_goals[0], missing);+ }+}diff --git a/src/server.rs b/src/server.rsindex cfdc61a4..5e526a01 100644--- a/src/server.rs+++ b/src/server.rs@@ -952,6 +952,7 @@ impl OpenOntologiesServer {reversible: input.reversible,allow_experiment: input.allow_experiment,alpha: input.alpha,+ action_schema_name: input.action_schema_name,};match crate::civex::certify_action(&self.db, &self.graph, &frame) {Ok(result) => serde_json::to_string(&result)@@ -960,6 +961,194 @@ impl OpenOntologiesServer {}}+ // ── Dynamics layer (#43) — action schemas, applicability, apply ────────++ #[tool(name = "onto_action_register", description = "Persist a named action schema (Dynamics layer #43). Schema specifies typed parameters, SPARQL preconditions, and KGCL-shaped effects (add_triple/remove_triple/add_class). `{param}` placeholders are substituted at apply time. Schemas are looked up by `onto_action_applicable` and executed by `onto_action_apply`. Companion to the Causal layer (`onto_certify_action`) and the Planner (`onto_plan_compile_pddl`). BC+ deterministic-single-effect subset; ramification + non-determinism deferred to v0.4.x.")]+ async fn onto_action_register(&self, Parameters(input): Parameters<OntoActionRegisterInput>) -> String {+ let schema: crate::dynamics::ActionSchema = match serde_json::from_str(&input.schema_json) {+ Ok(s) => s,+ Err(e) => return format!(r#"{{"error":"invalid schema_json: {}"}}"#, e),+ };+ let name = schema.name.clone();+ match crate::dynamics::register(&self.db, &schema) {+ Ok(()) => format!(r#"{{"ok":true,"registered":"{}"}}"#, name),+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ }+ }++ #[tool(name = "onto_action_applicable", description = "Evaluate a registered action's SPARQL preconditions against the loaded graph under the given parameter bindings. Returns {applicable: bool, action_name, bindings, preconditions_evaluated}. Use as a pre-flight check before `onto_action_apply` or as the applicability oracle for the Planner.")]+ async fn onto_action_applicable(&self, Parameters(input): Parameters<OntoActionApplicableInput>) -> String {+ let schema = match crate::dynamics::lookup(&self.db, &input.action_name) {+ Ok(Some(s)) => s,+ Ok(None) => return format!(r#"{{"error":"unknown action: {}"}}"#, input.action_name),+ Err(e) => return format!(r#"{{"error":"{}"}}"#, e),+ };+ let bindings: Vec<(String, String)> = input.bindings.into_iter().collect();+ let applicable = schema.applicable(&self.graph, &bindings);+ let body = serde_json::json!({+ "applicable": applicable,+ "action_name": schema.name,+ "bindings": bindings,+ "preconditions_evaluated": schema.preconditions.len(),+ });+ body.to_string()+ }++ #[tool(name = "onto_action_apply", description = "Apply a registered action's effects with the given parameter bindings. Returns the KGCL patch (CNL form), the IES4-style event IRI for the audit trail, and triples added/removed. Re-checks preconditions by default; set `check_preconditions=false` only after a successful `onto_certify_action` certificate. Optional ramification (#47): pass `ramify=\"rdfs\"|\"owl-rl\"|\"owl-rl-ext\"|\"owl-dl\"` to materialise downstream entailments after the literal effects land; the result includes `derived_triples_added` so callers can see what the reasoner produced. Pair with `onto_certify_action` for gated changes.")]+ async fn onto_action_apply(&self, Parameters(input): Parameters<OntoActionApplyInput>) -> String {+ let schema = match crate::dynamics::lookup(&self.db, &input.action_name) {+ Ok(Some(s)) => s,+ Ok(None) => return format!(r#"{{"error":"unknown action: {}"}}"#, input.action_name),+ Err(e) => return format!(r#"{{"error":"{}"}}"#, e),+ };+ let bindings: Vec<(String, String)> = input.bindings.into_iter().collect();+ if input.check_preconditions && !schema.applicable(&self.graph, &bindings) {+ return r#"{"error":"preconditions not satisfied"}"#.to_string();+ }+ let outcome = match (input.ramify.as_deref(), input.seed) {+ (Some(profile), _) if !profile.is_empty() => {+ schema.apply_with_ramification(&self.graph, &self.db, &bindings, profile)+ }+ (_, Some(seed)) => {+ schema.apply_with_seed(&self.graph, &self.db, &bindings, seed)+ }+ _ => schema.apply(&self.graph, &self.db, &bindings),+ };+ match outcome {+ 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_action_list", description = "List the names of all action schemas registered in this server's Dynamics store. Useful for the Planner / Claude to know what's available before composing a plan.")]+ async fn onto_action_list(&self) -> String {+ match crate::dynamics::list_names(&self.db) {+ Ok(names) => serde_json::to_string(&names)+ .unwrap_or_else(|e| format!(r#"{{"error":"serialization: {}"}}"#, e)),+ Err(e) => format!(r#"{{"error":"{}"}}"#, e),+ }+ }++ #[tool(name = "onto_plan_classical", description = "Invoke Fast Downward as a subprocess on a precompiled PDDL domain + problem (#50). Returns the raw sas_plan content plus a parsed `operators` list (operator name + positional PDDL args). The orchestrator maps args back to original IRIs using the schema parameter names (still client-side per LLM-Modulo). If Fast Downward is not on PATH and `fast_downward_bin` is not set, returns a clean `binary_unavailable` error rather than falling back to a silent stub. Pair: `onto_plan_compile_pddl` → `onto_plan_classical` → IRI-bind operators client-side → `onto_plan_validate`.")]+ async fn onto_plan_classical(&self, Parameters(input): Parameters<OntoPlanClassicalInput>) -> String {+ match crate::plan_classical::run_fast_downward(+ &input.domain,+ &input.problem,+ input.fast_downward_bin.as_deref(),+ input.search.as_deref(),+ ) {+ 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_plan_validate", description = "Validate a candidate plan (sequence of registered-action steps) against the loaded graph WITHOUT mutating the real store. Per LLM-Modulo (Kambhampati arXiv 2402.01817), the server validates plans the client-side solver produced — it does not solve. For each step, the validator re-evaluates the schema's preconditions against the cumulative sandbox state and applies effects to a forked copy; the first failing step short-circuits with a diagnostic. Optional `goal_facts` are checked post-plan and reported in `unsatisfied_goals` (without invalidating the plan itself). Pair with `onto_plan_compile_pddl` (server compiles → external solver searches → server validates).")]+ async fn onto_plan_validate(&self, Parameters(input): Parameters<OntoPlanValidateInput>) -> String {+ let steps: Vec<crate::plan_validate::PlanStep> = input.steps.into_iter()+ .map(|s| crate::plan_validate::PlanStep {+ action_name: s.action_name,+ bindings: s.bindings,+ })+ .collect();+ let goal_facts: Vec<(String, String, String)> = input.goal_facts.into_iter()+ .filter_map(|t| if t.len() == 3 { Some((t[0].clone(), t[1].clone(), t[2].clone())) } else { None })+ .collect();+ match crate::plan_validate::validate_plan(&self.db, &self.graph, &steps, &goal_facts) {+ 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_plan_compile_pddl", description = "Compile a PDDL domain from registered Dynamics action schemas (#43) plus a problem instance from the loaded graph and a goal Turtle slice (#45 Planner stub). Returns {domain, problem, translation_notes}. The actual planner (Fast Downward) is wrapped client-side per the LLM-Modulo convention — this primitive only emits the PDDL. Lossy in the v0.4 stub: only ASK-shape SPARQL preconditions translate cleanly; SELECT-shaped preconditions are preserved as notes.")]+ async fn onto_plan_compile_pddl(&self, Parameters(input): Parameters<OntoPlanCompilePddlInput>) -> String {+ // Gather schemas — either explicitly requested or every registered one.+ let names = if input.action_names.is_empty() {+ match crate::dynamics::list_names(&self.db) {+ Ok(n) => n,+ Err(e) => return format!(r#"{{"error":"{}"}}"#, e),+ }+ } else {+ input.action_names+ };+ let mut schemas: Vec<crate::dynamics::ActionSchema> = Vec::with_capacity(names.len());+ for n in &names {+ match crate::dynamics::lookup(&self.db, n) {+ Ok(Some(s)) => schemas.push(s),+ Ok(None) => return format!(r#"{{"error":"unknown action: {}"}}"#, n),+ Err(e) => return format!(r#"{{"error":"{}"}}"#, e),+ }+ }++ let domain_name = input.domain_name.unwrap_or_else(|| "ontology".to_string());+ let compiled = crate::plan_pddl::compile_domain(&domain_name, &schemas);++ // Init facts: enumerate every triple in the loaded graph as a (s, p, o).+ let init_facts: Vec<(String, String, String)> = match self+ .graph+ .sparql_select("SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 10000")+ {+ Ok(s) => {+ let v: serde_json::Value = serde_json::from_str(&s).unwrap_or(serde_json::Value::Null);+ v["results"].as_array().cloned().unwrap_or_default()+ .into_iter()+ .filter_map(|row| {+ let s = row["s"].as_str()?.to_string();+ let p = row["p"].as_str()?.to_string();+ let o = row["o"].as_str()?.to_string();+ Some((s, p, o))+ })+ .collect()+ }+ Err(_) => Vec::new(),+ };++ // Goal facts: parse goal_ttl by loading into a scratch graph.+ let goal_facts: Vec<(String, String, String)> = match input.goal_ttl.as_deref() {+ Some(ttl) if !ttl.trim().is_empty() => {+ let temp = crate::graph::GraphStore::new();+ if temp.load_turtle(ttl, None).is_err() {+ return r#"{"error":"goal_ttl failed to parse"}"#.to_string();+ }+ match temp.sparql_select("SELECT ?s ?p ?o WHERE { ?s ?p ?o }") {+ Ok(s) => {+ let v: serde_json::Value = serde_json::from_str(&s).unwrap_or(serde_json::Value::Null);+ v["results"].as_array().cloned().unwrap_or_default()+ .into_iter()+ .filter_map(|row| {+ let s = row["s"].as_str()?.to_string();+ let p = row["p"].as_str()?.to_string();+ let o = row["o"].as_str()?.to_string();+ Some((s, p, o))+ })+ .collect()+ }+ Err(_) => Vec::new(),+ }+ }+ _ => Vec::new(),+ };++ let problem = crate::plan_pddl::compile_problem(+ "ontology_problem",+ &domain_name,+ &init_facts,+ &goal_facts,+ );++ let body = serde_json::json!({+ "domain": compiled.domain,+ "problem": problem,+ "translation_notes": compiled.translation_notes,+ "actions_included": names,+ "init_facts_count": init_facts.len(),+ "goal_facts_count": goal_facts.len(),+ });+ body.to_string()+ }+#[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.rsindex af8ec9e4..73c1411a 100644--- a/tests/civex_test.rs+++ b/tests/civex_test.rs@@ -41,6 +41,7 @@ fn base_frame() -> ActionFrame {reversible: true,allow_experiment: false,alpha: 0.05,+ action_schema_name: None,}}@@ -157,6 +158,28 @@ fn reversible_with_experiment_authorisation_returns_experiment() {assert!(result.certificate.rationale.contains("EXPERIMENT"));}+#[test]+fn action_schema_name_is_recorded_in_certificate_assumptions() {+ // CIVeX × Dynamics integration: passing a Dynamics action schema name+ // through ActionFrame must show up in the certificate's audit trail.+ 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.action_schema_name = Some("rename_class".to_string());++ let result = certify_action(&db, &graph, &frame).expect("certify");+ let has_schema_marker = result.certificate.assumptions.iter()+ .any(|a| a == "dynamics_action_schema:rename_class");+ assert!(has_schema_marker,+ "schema name must be threaded into assumptions; got {:?}",+ result.certificate.assumptions);+}+#[test]fn provenance_hash_changes_when_delta_changes() {let (db, graph) = setup();diff --git a/tests/three_layer_integration_test.rs b/tests/three_layer_integration_test.rsnew file mode 100644index 00000000..d68e56cd--- /dev/null+++ b/tests/three_layer_integration_test.rs@@ -0,0 +1,249 @@+//! End-to-end integration tests across the three-layer architecture+//! (#43 Dynamics → #44 Causal hookup → #45 Planner stub).+//!+//! Locks the integration contracts that the unit-test suite intentionally+//! leaves to integration: a schema registered via the Dynamics API survives+//! a round-trip through CIVeX certification, the Planner PDDL compilation+//! pulls it from the same store, and `apply()` actually modifies the graph+//! the way the Causal-layer's structural-dependency hash claims it does.++use open_ontologies::civex::{certify_action, ActionFrame, Verdict};+use open_ontologies::dynamics::{+ list_names, lookup, register, ActionSchema, EffectSpec, Parameter,+};+use open_ontologies::graph::GraphStore;+use open_ontologies::plan_pddl::{compile_domain, compile_problem};+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 add_subclass_schema() -> ActionSchema {+ // Action: add `?child rdfs:subClassOf ?parent` when both already exist as+ // owl:Classes.+ ActionSchema {+ name: "add_subclass_edge".to_string(),+ parameters: vec![+ Parameter { name: "child".to_string(), type_iri: None },+ Parameter { name: "parent".to_string(), type_iri: None },+ ],+ preconditions: vec![+ "ASK { <{child}> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class> }".to_string(),+ "ASK { <{parent}> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class> }".to_string(),+ ],+ effects: vec![+ EffectSpec::AddTriple {+ subject: "{child}".to_string(),+ predicate: "http://www.w3.org/2000/01/rdf-schema#subClassOf".to_string(),+ object: "{parent}".to_string(),+ },+ ],+ reversible: true,+ description: Some("Add a subClassOf edge between two existing classes".to_string()),+ outcomes: vec![],+ }+}++#[test]+fn dynamics_register_then_planner_compile_sees_the_schema() {+ // The Planner stub must read from the same SQLite store that+ // onto_action_register writes to. This proves the storage contract.+ let (db, _graph) = setup();+ register(&db, &add_subclass_schema()).expect("register");++ let names = list_names(&db).expect("list");+ assert!(names.contains(&"add_subclass_edge".to_string()));++ // The Planner pulls schemas by lookup. Round-trip must preserve enough+ // structure for compile_domain to emit a well-formed action block.+ let recovered = lookup(&db, "add_subclass_edge")+ .expect("lookup ok")+ .expect("schema found");+ let compiled = compile_domain("ontology", &[recovered]);+ assert!(compiled.domain.contains("(:action add_subclass_edge"));+ assert!(compiled.domain.contains("?child - iri"));+ assert!(compiled.domain.contains("?parent - iri"));+ // Both ASK preconditions should translate.+ assert!(compiled.domain.contains(":precondition (and (triple ?child"));+ // No untranslated notes for fully ASK-shaped schemas.+ assert!(compiled.translation_notes.is_empty(),+ "unexpected translation notes: {:?}", compiled.translation_notes);+}++#[test]+fn dynamics_apply_actually_mutates_graph_visible_to_civex() {+ // Whole-stack smoke: load graph → register → apply → CIVeX sees the+ // post-state when computing structural dependencies on a follow-up frame.+ let (db, graph) = setup();+ graph.load_turtle(r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://ex.org/> .+ ex:Animal a owl:Class .+ ex:Cat a owl:Class .+ "#, None).unwrap();++ let schema = add_subclass_schema();+ register(&db, &schema).expect("register");++ let bindings = vec![+ ("child".to_string(), "http://ex.org/Cat".to_string()),+ ("parent".to_string(), "http://ex.org/Animal".to_string()),+ ];+ assert!(schema.applicable(&graph, &bindings),+ "both classes exist; preconditions should be satisfied");++ let result = schema.apply(&graph, &db, &bindings).expect("apply");+ assert_eq!(result.triples_added, 1);+ assert_eq!(result.triples_removed, 0);+ assert!(result.event_iri.contains("add_subclass_edge"));+ assert!(result.kgcl_patch_cnl.iter().any(|s| s.contains("subClassOf")+ || s.contains("create edge")),+ "expected KGCL CNL line; got {:?}", result.kgcl_patch_cnl);++ // Verify the mutation landed in the graph.+ let q = "ASK { <http://ex.org/Cat> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/Animal> }";+ let r = graph.sparql_select(q).unwrap();+ assert!(r.contains("\"result\":true"), "subClassOf triple not present after apply: {}", r);+}++#[test]+fn civex_certifies_against_dynamics_action_and_records_schema_name() {+ // CIVeX must accept a Dynamics action schema name and propagate it into+ // the certificate's assumptions, so an external auditor reading the+ // certificate can trace it back to the registered schema.+ let (db, graph) = setup();+ graph.load_turtle(r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://ex.org/> .+ ex:Animal a owl:Class .+ ex:Cat a owl:Class .+ "#, None).unwrap();++ register(&db, &add_subclass_schema()).expect("register");++ // The frame describes the change the Dynamics schema would produce.+ let frame = ActionFrame {+ tool: "onto_action_apply".to_string(),+ target_iris: vec!["http://ex.org/Cat".to_string()],+ proposed_delta_ttl: r#"+ @prefix ex: <http://ex.org/> .+ @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .+ ex:Cat rdfs:subClassOf ex:Animal .+ "#.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 ?x WHERE { ?x <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?y }".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,+ action_schema_name: Some("add_subclass_edge".to_string()),+ };+ let result = certify_action(&db, &graph, &frame).expect("certify");++ assert_eq!(result.certificate.verdict, Verdict::Execute,+ "benign subClassOf edge should execute; got rationale: {}",+ result.certificate.rationale);+ assert!(result.certificate.assumptions.iter()+ .any(|a| a == "dynamics_action_schema:add_subclass_edge"),+ "schema name must be in assumptions: {:?}",+ result.certificate.assumptions);+ // Sanity: the reversible flag also surfaces.+ assert!(result.certificate.assumptions.contains(&"reversible".to_string()));+}++#[test]+fn planner_problem_includes_goal_triples_in_pddl() {+ // The Planner emits a problem instance whose goal block contains the+ // goal triples the orchestrator asked it to plan toward.+ let init = vec![(+ "http://ex.org/Cat".to_string(),+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#type".to_string(),+ "http://www.w3.org/2002/07/owl#Class".to_string(),+ )];+ let goal = vec![(+ "http://ex.org/Cat".to_string(),+ "http://www.w3.org/2000/01/rdf-schema#subClassOf".to_string(),+ "http://ex.org/Animal".to_string(),+ )];++ let problem = compile_problem("ex_problem", "ontology", &init, &goal);+ assert!(problem.contains("(:domain ontology)"));+ assert!(problem.contains(":init (triple"));+ assert!(problem.contains(":goal (triple"));+ // Sanitised IRI should appear in objects.+ assert!(problem.contains("http___ex_org_cat") || problem.contains("ex_org_cat"));+}++#[test]+fn full_three_layer_pipeline_register_certify_apply() {+ // The full intended workflow:+ // 1. Register a Dynamics schema.+ // 2. CIVeX certifies a proposed instance of it → EXECUTE verdict.+ // 3. Caller applies it.+ // 4. Graph reflects the change; lineage and event IRI captured.+ let (db, graph) = setup();+ graph.load_turtle(r#"+ @prefix owl: <http://www.w3.org/2002/07/owl#> .+ @prefix ex: <http://ex.org/> .+ ex:Animal a owl:Class .+ ex:Cat a owl:Class .+ "#, None).unwrap();++ let schema = add_subclass_schema();+ register(&db, &schema).expect("register");++ // Step 2: certify.+ let frame = ActionFrame {+ tool: "onto_action_apply".to_string(),+ target_iris: vec!["http://ex.org/Cat".to_string()],+ proposed_delta_ttl: "@prefix ex: <http://ex.org/> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . ex:Cat rdfs:subClassOf ex:Animal .".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 ?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(),+ "SELECT ?s 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,+ action_schema_name: Some(schema.name.clone()),+ };+ let cert = certify_action(&db, &graph, &frame).expect("certify");+ assert_eq!(cert.certificate.verdict, Verdict::Execute);++ // Step 3: apply only after verdict was EXECUTE.+ let bindings = vec![+ ("child".to_string(), "http://ex.org/Cat".to_string()),+ ("parent".to_string(), "http://ex.org/Animal".to_string()),+ ];+ let result = schema.apply(&graph, &db, &bindings).expect("apply");++ // Step 4: post-conditions.+ assert_eq!(result.triples_added, 1);+ let r = graph.sparql_select(+ "ASK { <http://ex.org/Cat> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://ex.org/Animal> }"+ ).unwrap();+ assert!(r.contains("\"result\":true"));+ assert!(!cert.certificate.provenance_hash.is_empty());+}