Skip to content

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

fix(batch,plan): tokenise Windows paths, and scope plans to their owner

FABIOTESS5d8e5e2cc519
diff --git a/Cargo.lock b/Cargo.lock
index 9f07844c..8d253b6b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2771,7 +2771,6 @@ dependencies = [
"serde_json",
"serde_yaml",
"sha2",
- "shell-words",
"sqlx",
"tempfile",
"thiserror",
@@ -4087,12 +4086,6 @@ dependencies = [
"lazy_static",
]
-[[package]]
-name = "shell-words"
-version = "1.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77"
-
[[package]]
name = "shlex"
version = "1.3.0"
diff --git a/Cargo.toml b/Cargo.toml
index 67902f9a..b5f01df3 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -44,7 +44,6 @@ instant-distance = { version = "0.6", optional = true, features = ["with-serde"]
bincode = { version = "1.3", optional = true }
sha2 = "0.10"
dirs = "6"
-shell-words = "1"
[features]
default = []
diff --git a/docs/lifecycle.md b/docs/lifecycle.md
index 4719c6c6..ff417201 100644
--- a/docs/lifecycle.md
+++ b/docs/lifecycle.md
@@ -52,6 +52,12 @@ Applies the most recent plan by default. Pass a `plan_id` (`--plan-id` on the
CLI, `plan_id` to `onto_apply`) to apply a specific one; an id that does not
match a stored plan is an error rather than a silent fall-back to the latest.
+"Most recent" is scoped to whoever computed the plan: one MCP session, or the
+CLI as a whole. A single state db is shared by every session in HTTP mode, so an
+unscoped default would let one session apply changes another was still
+reviewing. Naming a `plan_id` still reaches across deliberately, and the error
+says so when plans exist but belong to someone else.
+
```bash
oo plan proposed.ttl # prints plan_id
oo apply safe --plan-id plan-0a1b2c3d… # or just: oo apply safe
diff --git a/src/batch.rs b/src/batch.rs
index 4b13e19a..d8fe046c 100644
--- a/src/batch.rs
+++ b/src/batch.rs
@@ -17,6 +17,7 @@ pub struct BatchRunner {
}
/// A parsed batch command with its arguments.
+#[derive(Debug)]
struct BatchCmd {
name: String,
args: Vec<String>,
@@ -501,6 +502,63 @@ fn parse_json(input: &str) -> Result<Vec<BatchCmd>, String> {
Ok(cmds)
}
+/// Split a batch line into a command and its arguments.
+///
+/// Deliberately not `shell_words::split`. POSIX escaping treats `\` as an
+/// escape character everywhere, which silently consumed every separator in a
+/// Windows path: `plan C:\onto\proposed.ttl` arrived as `C:ontoproposed.ttl`,
+/// the file was never found, and the failure surfaced somewhere else entirely
+/// — `apply` reporting "No plan found" because the `plan` before it could not
+/// read its input.
+///
+/// In a batch file a backslash is a path separator far more often than an
+/// escape, so here it is literal outside quotes, and an escape only inside
+/// double quotes and only before `"` or `\`. Single quotes are literal
+/// throughout. Quoting still groups arguments containing spaces.
+fn split_command_line(line: &str) -> Result<Vec<String>, String> {
+ let mut words = Vec::new();
+ let mut word = String::new();
+ let mut started = false;
+ let mut chars = line.chars().peekable();
+
+ while let Some(c) = chars.next() {
+ if c.is_whitespace() {
+ if started {
+ words.push(std::mem::take(&mut word));
+ started = false;
+ }
+ continue;
+ }
+ started = true;
+ match c {
+ '\'' => loop {
+ match chars.next() {
+ Some('\'') => break,
+ Some(c) => word.push(c),
+ None => return Err("unterminated single quote".to_string()),
+ }
+ },
+ '"' => loop {
+ match chars.next() {
+ Some('"') => break,
+ Some('\\') => match chars.peek() {
+ Some('"') | Some('\\') => word.push(chars.next().unwrap()),
+ _ => word.push('\\'),
+ },
+ Some(c) => word.push(c),
+ None => return Err("unterminated double quote".to_string()),
+ }
+ },
+ c => word.push(c),
+ }
+ }
+
+ if started {
+ words.push(word);
+ }
+ Ok(words)
+}
+
fn parse_lines(input: &str) -> Result<Vec<BatchCmd>, String> {
let mut cmds = Vec::new();
for line in input.lines() {
@@ -508,7 +566,7 @@ fn parse_lines(input: &str) -> Result<Vec<BatchCmd>, String> {
if line.is_empty() || line.starts_with('#') {
continue;
}
- let words = shell_words::split(line)
+ let words = split_command_line(line)
.map_err(|e| format!("bad quoting on line '{}': {}", line, e))?;
if words.is_empty() {
continue;
@@ -546,6 +604,49 @@ query "SELECT (COUNT(*) AS ?c) WHERE { ?s ?p ?o }"
assert_eq!(cmds[3].args[0], "SELECT (COUNT(*) AS ?c) WHERE { ?s ?p ?o }");
}
+ #[test]
+ fn a_windows_absolute_path_keeps_its_separators() {
+ // `shell_words::split` applies POSIX escaping, so every backslash in a
+ // Windows path was consumed before the file was ever opened: `oo batch`
+ // could not load, plan against, or apply any absolute path on Windows.
+ let cmds = parse_lines(r"plan C:\Users\runneradmin\Temp\ttl\proposed.ttl").unwrap();
+ assert_eq!(cmds[0].name, "plan");
+ assert_eq!(
+ cmds[0].args,
+ vec![r"C:\Users\runneradmin\Temp\ttl\proposed.ttl"]
+ );
+ }
+
+ #[test]
+ fn a_quoted_argument_keeps_its_spaces() {
+ let cmds = parse_lines(r#"load "my ontology.ttl""#).unwrap();
+ assert_eq!(cmds[0].args, vec!["my ontology.ttl"]);
+ }
+
+ #[test]
+ fn a_quoted_windows_path_with_spaces_survives_both_hazards() {
+ let cmds = parse_lines(r#"load "C:\Program Files\onto\my file.ttl""#).unwrap();
+ assert_eq!(cmds[0].args, vec![r"C:\Program Files\onto\my file.ttl"]);
+ }
+
+ #[test]
+ fn a_backslash_escapes_a_quote_inside_a_quoted_argument() {
+ let cmds = parse_lines(r#"query "he said \"hi\"""#).unwrap();
+ assert_eq!(cmds[0].args, vec![r#"he said "hi""#]);
+ }
+
+ #[test]
+ fn single_quotes_take_their_contents_literally() {
+ let cmds = parse_lines(r#"query 'C:\x\y "quoted"'"#).unwrap();
+ assert_eq!(cmds[0].args, vec![r#"C:\x\y "quoted""#]);
+ }
+
+ #[test]
+ fn an_unterminated_quote_is_an_error() {
+ let err = parse_lines(r#"load "unfinished"#).unwrap_err();
+ assert!(err.contains("quot"), "unexpected error: {err}");
+ }
+
#[test]
fn test_parse_json() {
let input = r#"[
diff --git a/src/plan.rs b/src/plan.rs
index 423f48d0..9488e67e 100644
--- a/src/plan.rs
+++ b/src/plan.rs
@@ -25,10 +25,22 @@ const DELTA_BATCH: usize = 500;
/// table is trimmed on write rather than left to grow without bound.
const PLAN_RETENTION: i64 = 100;
+/// Owner recorded for plans computed outside an MCP session.
+///
+/// `plan` and `apply` are separate processes with nothing shared between them,
+/// so the CLI's owner has to be a stable constant rather than anything
+/// per-process.
+pub const CLI_OWNER: &str = "cli";
+
/// Terraform-style plan/apply/migrate for ontology changes.
pub struct Planner {
db: StateDb,
graph: Arc<GraphStore>,
+ /// Who a plan computed here belongs to, and whose plans an `apply` without
+ /// an explicit id will consider. One state db is shared by every MCP
+ /// session and by the CLI, so "the most recent plan" is only a safe default
+ /// within one of them.
+ owner: String,
}
struct PlanState {
@@ -76,7 +88,16 @@ impl TripleDelta {
impl Planner {
pub fn new(db: StateDb, graph: Arc<GraphStore>) -> Self {
- Self { db, graph }
+ Self::with_owner(db, graph, CLI_OWNER)
+ }
+
+ /// A planner whose plans belong to `owner` — an MCP session id, typically.
+ pub fn with_owner(db: StateDb, graph: Arc<GraphStore>, owner: &str) -> Self {
+ Self {
+ db,
+ graph,
+ owner: owner.to_string(),
+ }
}
/// Compute a diff plan between current store and proposed new Turtle.
@@ -302,10 +323,11 @@ impl Planner {
let conn = self.db.conn();
conn.execute(
"INSERT INTO plans \
- (plan_id, new_turtle, added_classes, removed_classes, added_properties, removed_properties) \
- VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
+ (plan_id, owner, new_turtle, added_classes, removed_classes, added_properties, removed_properties) \
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
rusqlite::params![
plan_id,
+ self.owner,
new_turtle,
serde_json::to_string(added_classes)?,
serde_json::to_string(removed_classes)?,
@@ -334,8 +356,8 @@ impl Planner {
.optional()?,
None => conn
.query_row(
- &format!("SELECT {COLS} FROM plans ORDER BY seq DESC LIMIT 1"),
- [],
+ &format!("SELECT {COLS} FROM plans WHERE owner = ?1 ORDER BY seq DESC LIMIT 1"),
+ rusqlite::params![self.owner],
Self::row_to_plan,
)
.optional()?,
@@ -345,7 +367,25 @@ impl Planner {
(None, Some(id)) => anyhow::bail!(
"No plan found with id '{id}'. Run plan() first, or omit the id to apply the most recent plan."
),
- (None, None) => anyhow::bail!("No plan found. Run plan() first."),
+ (None, None) => {
+ // Say when plans exist but belong to someone else. Reporting a
+ // bare "no plan" would read as "nothing was ever planned",
+ // which is false and sends the reader after the wrong problem.
+ let others: i64 = conn
+ .query_row(
+ "SELECT COUNT(*) FROM plans WHERE owner <> ?1",
+ rusqlite::params![self.owner],
+ |r| r.get(0),
+ )
+ .unwrap_or(0);
+ if others > 0 {
+ anyhow::bail!(
+ "No plan found for this session. Run plan() first. \
+ ({others} plan(s) belong to another session — pass that plan's id to apply one deliberately.)"
+ )
+ }
+ anyhow::bail!("No plan found. Run plan() first.")
+ }
}
}
diff --git a/src/server.rs b/src/server.rs
index 67050d2f..0dc57b1a 100644
--- a/src/server.rs
+++ b/src/server.rs
@@ -1534,7 +1534,11 @@ impl OpenOntologiesServer {
#[tool(name = "onto_plan", description = "Terraform-style plan: diff current store against proposed Turtle. Shows added/removed classes/properties, blast radius, risk score, and locked IRI violations.")]
pub async fn onto_plan(&self, Parameters(input): Parameters<OntoPlanInput>) -> String {
- let planner = crate::plan::Planner::new(self.db.clone(), self.graph.clone());
+ let planner = crate::plan::Planner::with_owner(
+ self.db.clone(),
+ self.graph.clone(),
+ &self.session_id,
+ );
match planner.plan(&input.new_turtle) {
Ok(result) => {
self.lineage().record(&self.session_id, "P", "plan", "computed");
@@ -1547,7 +1551,11 @@ impl OpenOntologiesServer {
#[tool(name = "onto_apply", description = "Apply a plan produced by onto_plan, defaulting to the most recent one. Pass plan_id to target a specific plan. Modes: 'safe' (clear+reload, checks monitor), 'force' (ignores monitor), 'migrate' (adds owl:equivalentClass/Property bridges for renames).")]
pub async fn onto_apply(&self, Parameters(input): Parameters<OntoApplyInput>) -> String {
let mode = input.mode.as_deref().unwrap_or("safe");
- let planner = crate::plan::Planner::new(self.db.clone(), self.graph.clone());
+ let planner = crate::plan::Planner::with_owner(
+ self.db.clone(),
+ self.graph.clone(),
+ &self.session_id,
+ );
match planner.apply_plan(input.plan_id.as_deref(), mode) {
Ok(result) => {
self.lineage().record(&self.session_id, "A", "apply", mode);
diff --git a/src/state.rs b/src/state.rs
index 246b2b7b..f157a437 100644
--- a/src/state.rs
+++ b/src/state.rs
@@ -135,6 +135,7 @@ CREATE TABLE IF NOT EXISTS ontology_cache (
CREATE TABLE IF NOT EXISTS plans (
seq INTEGER PRIMARY KEY AUTOINCREMENT,
plan_id TEXT NOT NULL UNIQUE,
+ owner TEXT NOT NULL DEFAULT 'cli',
new_turtle TEXT NOT NULL,
added_classes TEXT NOT NULL,
removed_classes TEXT NOT NULL,
@@ -245,6 +246,27 @@ fn column_exists(conn: &Connection, table: &str, column: &str) -> Result<bool> {
Ok(false)
}
+/// Add `plans.owner` to a database created before the column existed.
+///
+/// Not a [`MIGRATIONS`] entry, by that list's own rule: it exists for *columns
+/// added to tables that already shipped*, and `plans` has never appeared in a
+/// release — it was added and then given an owner within the same unreleased
+/// window. Taking a schema version for it would cost every in-flight branch a
+/// renumber and every field database a version bump, to repair a table that
+/// only exists on `main`. The `CREATE TABLE IF NOT EXISTS` in [`SCHEMA`]
+/// handles every other case.
+///
+/// Adding the column rather than recreating the table keeps any plan already
+/// computed against `main` usable, under the default owner.
+fn add_plan_owner_column(conn: &Connection) -> Result<()> {
+ if column_exists(conn, "plans", "owner")? {
+ return Ok(());
+ }
+ conn.execute_batch("ALTER TABLE plans ADD COLUMN owner TEXT NOT NULL DEFAULT 'cli'")
+ .map_err(|e| anyhow::anyhow!("failed adding plans.owner: {e}"))?;
+ Ok(())
+}
+
/// Bring the schema up to [`SCHEMA_VERSION`], recording progress in
/// `PRAGMA user_version`.
///
@@ -305,6 +327,7 @@ impl StateDb {
conn.pragma_update(None, "synchronous", "NORMAL")?;
conn.execute_batch(SCHEMA)?;
conn.execute_batch(BUFFER_SCHEMA)?;
+ add_plan_owner_column(&conn)?;
run_migrations(&mut conn)?;
Ok(Self {
conn: Arc::new(Mutex::new(conn)),
diff --git a/tests/cli_test.rs b/tests/cli_test.rs
index c7d71dc5..41034841 100644
--- a/tests/cli_test.rs
+++ b/tests/cli_test.rs
@@ -324,20 +324,19 @@ fn write_plan_fixtures(dir: &tempfile::TempDir) -> (String, String) {
#[test]
fn test_cli_batch_plan_then_apply() {
let dir = tempfile::tempdir().unwrap();
- let _ = write_plan_fixtures(&dir);
+ let (base, proposed) = write_plan_fixtures(&dir);
+ let batch = dir.path().join("batch.txt");
+ // Absolute paths on purpose: batch lines are tokenised by
+ // `split_command_line`, and a Windows path here is what caught
+ // `shell_words::split` eating every separator.
std::fs::write(
- dir.path().join("batch.txt"),
- "load base.ttl\nplan proposed.ttl\napply safe\nstats\n",
+ &batch,
+ format!("load {base}\nplan {proposed}\napply safe\nstats\n"),
)
.unwrap();
- // Relative paths, run from the fixture directory — the reporter's repro
- // verbatim. Batch lines go through `shell_words::split`, which applies
- // POSIX escaping, so an absolute Windows path would have its separators
- // eaten before the file is ever opened.
let out = oo_isolated(&dir)
- .current_dir(dir.path())
- .args(["batch", "batch.txt"])
+ .args(["batch", batch.to_str().unwrap()])
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&out.stdout);
diff --git a/tests/plan_ownership_test.rs b/tests/plan_ownership_test.rs
new file mode 100644
index 00000000..1b5c05dc
--- /dev/null
+++ b/tests/plan_ownership_test.rs
@@ -0,0 +1,151 @@
+//! A plan belongs to whoever computed it.
+//!
+//! Persisting plans (#91) fixed `apply`, but put every caller's plans in one
+//! table. In HTTP mode the MCP server shares a state db across sessions, so
+//! "apply the most recent plan" could hand session A the changes session B was
+//! still reviewing — a governance tool applying an ontology change nobody
+//! approved. Plans are therefore scoped to an owner, and an explicit `plan_id`
+//! remains the way to reach across one deliberately.
+
+use open_ontologies::graph::GraphStore;
+use open_ontologies::plan::Planner;
+use open_ontologies::state::StateDb;
+use std::sync::Arc;
+
+fn setup() -> (tempfile::TempDir, StateDb) {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = StateDb::open(&tmp.path().join("state.db")).unwrap();
+ (tmp, db)
+}
+
+fn graph_with_base() -> Arc<GraphStore> {
+ let g = Arc::new(GraphStore::new());
+ g.load_turtle(
+ r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix ex: <http://example.org/> .
+ ex:Persona a owl:Class .
+ "#,
+ None,
+ )
+ .unwrap();
+ g
+}
+
+const PROPOSED_A: &str = r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix ex: <http://example.org/> .
+ ex:Persona a owl:Class .
+ ex:Organizacion a owl:Class .
+"#;
+
+const PROPOSED_B: &str = r#"
+ @prefix owl: <http://www.w3.org/2002/07/owl#> .
+ @prefix ex: <http://example.org/> .
+ ex:Persona a owl:Class .
+ ex:Vehiculo a owl:Class .
+ ex:Bicicleta a owl:Class .
+"#;
+
+fn json(s: &str) -> serde_json::Value {
+ serde_json::from_str(s).unwrap()
+}
+
+#[test]
+fn one_session_does_not_apply_another_sessions_plan() {
+ let (_t, db) = setup();
+ let graph = graph_with_base();
+
+ // Session B plans last, so "most recent overall" would be B's.
+ let plan_a = json(
+ &Planner::with_owner(db.clone(), graph.clone(), "session-a")
+ .plan(PROPOSED_A)
+ .unwrap(),
+ );
+ Planner::with_owner(db.clone(), graph.clone(), "session-b")
+ .plan(PROPOSED_B)
+ .unwrap();
+
+ let applied = json(
+ &Planner::with_owner(db.clone(), graph.clone(), "session-a")
+ .apply("safe")
+ .unwrap(),
+ );
+ assert_eq!(
+ applied["plan_id"].as_str().unwrap(),
+ plan_a["plan_id"].as_str().unwrap(),
+ "session A applied a plan it did not compute"
+ );
+ assert_eq!(applied["added_classes"], 1);
+}
+
+#[test]
+fn a_session_with_no_plan_of_its_own_is_told_so() {
+ let (_t, db) = setup();
+ let graph = graph_with_base();
+
+ Planner::with_owner(db.clone(), graph.clone(), "session-a")
+ .plan(PROPOSED_A)
+ .unwrap();
+
+ let err = Planner::with_owner(db.clone(), graph.clone(), "session-b")
+ .apply("safe")
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("No plan found"), "unexpected error: {err}");
+ // Silence here would read as "nothing was ever planned", which is false and
+ // would send someone hunting the wrong problem.
+ assert!(
+ err.contains("another session") || err.contains("other owners") || err.contains("1 plan"),
+ "the error should say plans exist under a different owner: {err}"
+ );
+}
+
+#[test]
+fn an_explicit_plan_id_still_crosses_owners() {
+ let (_t, db) = setup();
+ let graph = graph_with_base();
+
+ let plan_a = json(
+ &Planner::with_owner(db.clone(), graph.clone(), "session-a")
+ .plan(PROPOSED_A)
+ .unwrap(),
+ );
+ let id = plan_a["plan_id"].as_str().unwrap();
+
+ // Naming a plan is a deliberate act, and the audit trail records it.
+ let applied = json(
+ &Planner::with_owner(db.clone(), graph.clone(), "session-b")
+ .apply_plan(Some(id), "safe")
+ .unwrap(),
+ );
+ assert_eq!(applied["plan_id"].as_str().unwrap(), id);
+}
+
+#[test]
+fn every_cli_invocation_shares_one_owner() {
+ let (_t, db) = setup();
+ let graph = graph_with_base();
+
+ // `plan` and `apply` are separate processes with no session between them,
+ // so the default owner has to be stable rather than per-process.
+ let plan = json(&Planner::new(db.clone(), graph.clone()).plan(PROPOSED_A).unwrap());
+ let applied = json(&Planner::new(db.clone(), graph.clone()).apply("safe").unwrap());
+ assert_eq!(
+ applied["plan_id"].as_str().unwrap(),
+ plan["plan_id"].as_str().unwrap()
+ );
+}
+
+#[test]
+fn a_server_session_does_not_pick_up_a_cli_plan() {
+ let (_t, db) = setup();
+ let graph = graph_with_base();
+
+ Planner::new(db.clone(), graph.clone()).plan(PROPOSED_A).unwrap();
+ let err = Planner::with_owner(db.clone(), graph.clone(), "session-a")
+ .apply("safe")
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("No plan found"), "unexpected error: {err}");
+}