From 1426c817db87e3cfc8d6d39bba70f99d8b3551fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 22 Nov 2026 00:14:48 -0500 Subject: [PATCH 1/9] fix(engine): measure layers in shared steps, and say plugin commands are never steps (#2645) What a shared step changed is compared before and after it; that now includes each map's layers, in every build, instead of a debug-only check. A step that failed inside its savepoint was undone whole and no longer counts as an edit; shared_step runs the savepoint itself, so the two can't disagree. Other failed steps that mutate still count: nothing undoes what they did part way, and measuring it would copy each layer per call. A plugin's command can't be a step of another command (scripts and tasks run registered commands only, and a plugin can't run another's), so invoke refuses one with a shared transaction instead of opening a nested transaction with an undo step of its own. --- crates/engine/src/cmd/plugins.rs | 14 +++++++ crates/engine/src/lib.rs | 58 +++++++++++++++------------- crates/engine/src/policy/dispatch.rs | 9 ++++- crates/engine/src/tests.rs | 34 ++++++++++++++++ 4 files changed, 86 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/cmd/plugins.rs b/crates/engine/src/cmd/plugins.rs index db55513eba..b36cf6741f 100644 --- a/crates/engine/src/cmd/plugins.rs +++ b/crates/engine/src/cmd/plugins.rs @@ -1380,6 +1380,20 @@ mod tests { rustgis_plugins::unload("eng-bridge"); } + /// A host call that fails inside a savepoint is undone whole, so it isn't an edit (#2645). + #[test] + fn a_failed_savepoint_call_is_not_an_edit() { + let pkg = rustgis_plugins::Package::from_zip(&rustgis_plugins::testing::package("eng-savepoint", &["edit"])).unwrap(); + rustgis_plugins::load(pkg, "test").unwrap(); + let plugin = rustgis_plugins::get("eng-savepoint").unwrap(); + let mut s = Session::new(crate::Project::default()); + let fetches = fetch::Calls::for_plugin("eng-savepoint"); + let mut bridge = Bridge { s: &mut s, plugin, fetches }; + assert!(bridge.call("edit.applyShapeConversion", &json!({})).is_err()); + assert!(!bridge.s.shared_steps.edited, "a call its savepoint undid changed nothing"); + rustgis_plugins::unload("eng-savepoint"); + } + /// A plugin can't choose a download's number: the app gives it, so one plugin can't land or /// share another command's wait (#1202). #[test] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 97914fbe0e..b56be7e642 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -760,18 +760,20 @@ pub(crate) struct StepTally { pub(crate) edited: bool, } -/// What a command that doesn't mutate can move of what undo restores: the history state -/// (`edit.undo`), the project replaced (`project.new`), its file (`project.saveAs`), and the -/// unsaved mark a write that changed layers leaves (Publish to Source). Measured before and after -/// a shared step ([`Session::shared_step`]), not inferred from what the command may reach. The -/// project's contents change only by commands that mutate, except its history log, where an -/// export records itself as a log entry, not an edit, as when it runs by itself. +/// What a step can move of what undo restores without saying so: the history state +/// (`edit.undo`), the project replaced (`project.new`), its file (`project.saveAs`), the unsaved +/// mark a write that changed layers leaves (Publish to Source), and each map's layers. Measured +/// before and after a shared step ([`Session::shared_step`]), not inferred from what the command +/// may reach. The project's other contents change only by commands that mutate, +/// except its history log, where an export records itself as a log entry, not an edit, as when +/// it runs by itself. #[derive(PartialEq, Eq)] struct Restored { state: u64, opened: u64, files: ProjectFiles, unsaved_marks: u64, + layers: Vec, } pub struct Session { @@ -2238,34 +2240,36 @@ impl Session { } /// Runs `run`, the command `spec`, as a step of the command running now, in its transaction - /// (a script's line, a task's step, a plugin's call): it takes no undo step of its own, and - /// what it did goes into [`Session::shared_steps`]. Whether it left a request or changed - /// nothing ([`Session::request_only`]) is its own, never the enclosing command's. It edited - /// when it mutated and didn't say it changed nothing, or when [`Restored`] moved: a failed - /// step that kept a record (a failure note, a source file written) moved the history state. - pub(crate) fn shared_step(&mut self, spec: &CommandSpec, run: impl FnOnce(&mut Session) -> CmdResult) -> CmdResult { + /// (a script's line, a task's step, a plugin's call), or in a [`Session::savepoint`] of it: + /// it takes no undo step of its own, and what it did goes into [`Session::shared_steps`]. + /// Whether it left a request or changed nothing ([`Session::request_only`]) is its own, never + /// the enclosing command's. It edited when it mutates and didn't say it changed nothing, or + /// when [`Restored`] moved. A failed step that mutates counts too unless a savepoint undid it: + /// telling what it changed would cost a copy of each layer it touched. + pub(crate) fn shared_step(&mut self, spec: &CommandSpec, savepoint: bool, run: impl FnOnce(&mut Session) -> CmdResult) -> CmdResult { let outer = std::mem::take(&mut self.request_only); - let before = self.restored(); - #[cfg(debug_assertions)] - let layers = (!spec.mutates).then(|| self.project.maps.iter().map(Map::layer_mark).collect::>()); - let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(self))); + // Once the account holds an edit, nothing a step does changes it: no need to measure. + let before = (!self.shared_steps.edited).then(|| self.restored()); + let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match savepoint { + true => self.savepoint(spec.label, run), + false => run(self), + })); let unchanged = std::mem::replace(&mut self.request_only, outer); - let moved = self.restored() != before; - // A command that doesn't mutate leaves the layers alone, or the measure above misses it. - #[cfg(debug_assertions)] - debug_assert!( - moved || res.is_err() || layers.is_none_or(|layers| self.project.maps.iter().map(Map::layer_mark).eq(layers)), - "{} doesn't mutate but changed the layers", - spec.id - ); - // A failed step counts too: in a shared transaction nothing undoes what it did part way. + let moved = before.is_some_and(|before| self.restored() != before); + let kept = !savepoint || matches!(res, Ok(Ok(_))); self.shared_steps.requested |= unchanged; - self.shared_steps.edited |= moved || (spec.mutates && !unchanged); + self.shared_steps.edited |= moved || (spec.mutates && kept && !unchanged); res.unwrap_or_else(|panic| std::panic::resume_unwind(panic)) } fn restored(&self) -> Restored { - Restored { state: self.state, opened: self.opened, files: self.project_files(), unsaved_marks: self.unsaved_marks } + Restored { + state: self.state, + opened: self.opened, + files: self.project_files(), + unsaved_marks: self.unsaved_marks, + layers: self.project.maps.iter().map(Map::layer_mark).collect(), + } } fn project_files(&self) -> ProjectFiles { diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index 27f722a602..190b551bab 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -917,6 +917,12 @@ impl Session { let node = op.node.clone(); match &op.op { CommandOp::Plugin { pin, .. } => { + // A plugin's command is a transaction of its own, never a step of another + // command: scripts and tasks run registered commands only, and a plugin can't run + // another's. + if !matches!(txn, Txn::Own) { + return Err("a plugin's command runs only by itself, not as a step of another command".into()); + } let pin = pin.clone(); // Plugin host calls are checked against the pinned manifest, not an invented // finite list of calls made by code that has yet to run. @@ -977,8 +983,7 @@ impl Session { let first_layer = crate::cmd::project::first_layer_watch(self, &spec); let result = match txn { Txn::Own => self.guarded(spec.label, spec.mutates, run), - Txn::Shared if spec.id == "edit.applyShapeConversion" => self.shared_step(&spec, |s| s.savepoint(spec.label, run)), - Txn::Shared => self.shared_step(&spec, run), + Txn::Shared => self.shared_step(&spec, spec.id == "edit.applyShapeConversion", run), }; if let (Ok(_), Some(before)) = (&result, first_layer) { crate::cmd::project::take_first_layer_system(self, &before); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ed8cd2a544..a7e5477f88 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -373,6 +373,40 @@ fn script_step_follows_what_its_lines_change_not_what_they_reach() { assert_eq!(s.path.as_deref(), Some(first.as_path())); } +/// A plugin's command can't run as a step of another command (#2645): it would be a transaction +/// of its own inside the caller's. +#[test] +fn invoke_refuses_a_plugin_command_as_a_step() { + let mut s = world(); + plugin("step-plugin", &["edit"]); + let err = s.run("script.run", &json!({"script": "plugin:step-plugin/h {}"})).unwrap_err(); + assert!(err.contains("unknown command"), "{err}"); + let op = s.authorize("plugin:step-plugin/h", &json!({})).unwrap(); + let err = s.invoke(op, crate::policy::Txn::Shared).unwrap_err(); + assert!(err.contains("runs only by itself"), "{err}"); +} + +/// A command that doesn't mutate but adds a layer still makes a script's line an edit (#2645): +/// the layers are measured in every build, not only checked in debug ones. +#[test] +fn script_step_measures_the_layers_a_step_changes() { + let mut s = world(); + s.registry.commands.push( + crate::CommandSpec::new("test.quietLayer", "Quiet layer", "Test", |s, _| { + let ds = s.map().layers[0].dataset.clone(); + crate::cmd::layer::add_dataset(s, ds); + Ok(Value::Null) + }) + .view(), + ); + s.mark_saved(); + let (depth, count) = (s.undo_depth(), s.map().layers.len()); + s.run("script.run", &json!({"script": "test.quietLayer {}"})).unwrap(); + assert_eq!((s.undo_depth(), s.dirty(), s.map().layers.len()), (depth + 1, true, count + 1)); + s.run("edit.undo", &Value::Null).unwrap(); + assert_eq!(s.map().layers.len(), count); +} + /// A task's steps are counted as a script's lines: an undo step only when one edited (#2621). #[test] fn task_takes_an_undo_step_only_when_a_step_edits() { From 07c5e39d4ee8136ad25cf4d1be6eacd380441b27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 22 Nov 2026 00:37:36 -0500 Subject: [PATCH 2/9] test(engine): a failed step is undone by its savepoint and only then isn't an edit (#2645) --- crates/engine/src/cmd/plugins.rs | 14 -------------- crates/engine/src/lib.rs | 10 +++++----- crates/engine/src/tests.rs | 19 +++++++++++++++++++ 3 files changed, 24 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/plugins.rs b/crates/engine/src/cmd/plugins.rs index b36cf6741f..db55513eba 100644 --- a/crates/engine/src/cmd/plugins.rs +++ b/crates/engine/src/cmd/plugins.rs @@ -1380,20 +1380,6 @@ mod tests { rustgis_plugins::unload("eng-bridge"); } - /// A host call that fails inside a savepoint is undone whole, so it isn't an edit (#2645). - #[test] - fn a_failed_savepoint_call_is_not_an_edit() { - let pkg = rustgis_plugins::Package::from_zip(&rustgis_plugins::testing::package("eng-savepoint", &["edit"])).unwrap(); - rustgis_plugins::load(pkg, "test").unwrap(); - let plugin = rustgis_plugins::get("eng-savepoint").unwrap(); - let mut s = Session::new(crate::Project::default()); - let fetches = fetch::Calls::for_plugin("eng-savepoint"); - let mut bridge = Bridge { s: &mut s, plugin, fetches }; - assert!(bridge.call("edit.applyShapeConversion", &json!({})).is_err()); - assert!(!bridge.s.shared_steps.edited, "a call its savepoint undid changed nothing"); - rustgis_plugins::unload("eng-savepoint"); - } - /// A plugin can't choose a download's number: the app gives it, so one plugin can't land or /// share another command's wait (#1202). #[test] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index b56be7e642..284d423674 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -762,11 +762,11 @@ pub(crate) struct StepTally { /// What a step can move of what undo restores without saying so: the history state /// (`edit.undo`), the project replaced (`project.new`), its file (`project.saveAs`), the unsaved -/// mark a write that changed layers leaves (Publish to Source), and each map's layers. Measured -/// before and after a shared step ([`Session::shared_step`]), not inferred from what the command -/// may reach. The project's other contents change only by commands that mutate, -/// except its history log, where an export records itself as a log entry, not an edit, as when -/// it runs by itself. +/// mark a write that changed layers leaves (Publish to Source), and which layers each map has, +/// in what order. Measured before and after a shared step ([`Session::shared_step`]), not +/// inferred from what the command may reach. The project's other contents (a layer's name, look +/// or features) change only by commands that mutate, except its history log, where an export +/// records itself as a log entry, not an edit, as when it runs by itself. #[derive(PartialEq, Eq)] struct Restored { state: u64, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a7e5477f88..0fe4c2aa49 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -386,6 +386,25 @@ fn invoke_refuses_a_plugin_command_as_a_step() { assert!(err.contains("runs only by itself"), "{err}"); } +/// A step that changed the project and then failed is undone whole by its savepoint, so it isn't +/// an edit; without one, nothing undoes it part way, so it counts (#2645). +#[test] +fn a_failed_step_counts_unless_its_savepoint_undid_it() { + let mut s = world(); + let spec = *s.registry.get("map.rename").unwrap(); + let name = s.map().name.clone(); + let half_done = |s: &mut Session| -> crate::CmdResult { + s.map_mut().name = "Half done".into(); + Err("failed part way".into()) + }; + for savepoint in [true, false] { + s.shared_steps = crate::StepTally::default(); + assert!(s.shared_step(&spec, savepoint, half_done).is_err()); + assert_eq!((s.map().name == name, s.shared_steps.edited), (savepoint, !savepoint), "savepoint: {savepoint}"); + s.map_mut().name = name.clone(); + } +} + /// A command that doesn't mutate but adds a layer still makes a script's line an edit (#2645): /// the layers are measured in every build, not only checked in debug ones. #[test] From a5f668f33ac384ee42121bf6cfc685574548d2ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 22 Nov 2026 01:24:18 -0500 Subject: [PATCH 3/9] fix(engine): a command says it runs as a savepoint, and the tests check every declaration (#2645) CommandSpec::savepoint replaces the command id written into the dispatcher: shared_step reads it from the spec. In the tests, invoke fails a command declared as not mutating that changes the layers without moving the rest of what undo restores, by itself or as a step, so a wrong declaration fails the suite instead of only a debug assertion on script steps. --- crates/engine/src/cmd/edit.rs | 2 +- crates/engine/src/lib.rs | 15 ++++++++++-- crates/engine/src/policy/dispatch.rs | 14 +++++++++++- crates/engine/src/tests.rs | 34 +++++++++++++++++++--------- 4 files changed, 50 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 3ad48f37c6..6082219acf 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -18,7 +18,7 @@ pub fn commands() -> Vec { .roles(&[crate::ParamRole {key:"frame",role:crate::Role::Opaque}]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).view() .when(crate::cmd::design::need_editable).params(r#"{"layer"?:name|id,"row":number,"featureId"?:number,"kind":"circle|rotatedBox","request"?:number (preview correlation only),"image"?:GeoTIFF layer name|id,"frame"?:construction grid as edit.addBox.box.frame (otherwise Web Mercator)}"#), C::new("edit.applyShapeConversion", "Apply Shape Conversion", "Edit › Features", crate::shape_conversion::apply).inputs(crate::shape_conversion::apply_inputs) - .roles(&[crate::ParamRole {key:"preview",role:crate::Role::Opaque}]).effects(crate::policy::Effects::NONE) + .roles(&[crate::ParamRole {key:"preview",role:crate::Role::Opaque}]).effects(crate::policy::Effects::NONE).savepoint() .when(crate::shape_conversion::need_editing).params(r#"{"preview":result of edit.previewShapeConversion,"confirm":true}"#), C::new("edit.calculateGeometry", "Calculate Geometry", "Attribute Table", crate::geometry_calc::run).roles(&[]).effects(crate::policy::Effects::NONE) .when(super::design::need_editable) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 284d423674..29fc38c5c6 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -109,6 +109,9 @@ pub struct CommandSpec { /// Pure executor-owned resolution for commands whose inputs exceed the common layer selector. pub(crate) transition: Option, &Value) -> Result, String>>, pub(crate) inputs: Option, &Value) -> Result>, + /// As a step of another command, it runs in a [`Session::savepoint`]: undone whole when it + /// fails, since a plugin may handle the error and go on. + pub(crate) savepoint: bool, } fn always(_: &Session) -> Option<&'static str> { @@ -147,8 +150,14 @@ impl CommandSpec { roles: None, inputs: None, transition: None, + savepoint: false, } } + /// See [`CommandSpec::savepoint`]. + pub(crate) const fn savepoint(mut self) -> Self { + self.savepoint = true; + self + } /// Declares the effects reviewed for this command; omitted declarations fail closed. pub const fn effects(mut self, effects: policy::Effects) -> Self { self.effects = effects; @@ -2240,13 +2249,15 @@ impl Session { } /// Runs `run`, the command `spec`, as a step of the command running now, in its transaction - /// (a script's line, a task's step, a plugin's call), or in a [`Session::savepoint`] of it: + /// (a script's line, a task's step, a plugin's call), or in a [`Session::savepoint`] of it + /// when the command asks ([`CommandSpec::savepoint`]): /// it takes no undo step of its own, and what it did goes into [`Session::shared_steps`]. /// Whether it left a request or changed nothing ([`Session::request_only`]) is its own, never /// the enclosing command's. It edited when it mutates and didn't say it changed nothing, or /// when [`Restored`] moved. A failed step that mutates counts too unless a savepoint undid it: /// telling what it changed would cost a copy of each layer it touched. - pub(crate) fn shared_step(&mut self, spec: &CommandSpec, savepoint: bool, run: impl FnOnce(&mut Session) -> CmdResult) -> CmdResult { + pub(crate) fn shared_step(&mut self, spec: &CommandSpec, run: impl FnOnce(&mut Session) -> CmdResult) -> CmdResult { + let savepoint = spec.savepoint; let outer = std::mem::take(&mut self.request_only); // Once the account holds an edit, nothing a step does changes it: no need to measure. let before = (!self.shared_steps.edited).then(|| self.restored()); diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index 190b551bab..d26faaa4c3 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -981,13 +981,25 @@ impl Session { // start in it, and inside the transaction that made it, so Undo and a failure take // it back and the project is unsaved ([`crate::cmd::project::first_layer_watch`]). let first_layer = crate::cmd::project::first_layer_watch(self, &spec); + // A command that doesn't mutate leaves the layers alone unless it moved what undo + // restores (an undo, a project opened): checked on every command the tests run, + // by itself or as a step, so a command declared wrong fails them. + #[cfg(test)] + let declared = (!spec.mutates).then(|| self.restored()); let result = match txn { Txn::Own => self.guarded(spec.label, spec.mutates, run), - Txn::Shared => self.shared_step(&spec, spec.id == "edit.applyShapeConversion", run), + Txn::Shared => self.shared_step(&spec, run), }; if let (Ok(_), Some(before)) = (&result, first_layer) { crate::cmd::project::take_first_layer_system(self, &before); } + #[cfg(test)] + if let Some(before) = declared { + let after = self.restored(); + let rest = |r: crate::Restored| crate::Restored { layers: Vec::new(), ..r }; + let layers = after.layers == before.layers; + assert!(result.is_err() || layers || rest(after) != rest(before), "{} doesn't mutate but changed the layers", spec.id); + } self.url_completion_landed(spec.id, ¶ms, &result); if result.is_ok() && (spec.mutates || spec.effects.contains(crate::policy::Effect::History)) && spec.id != "data.similar" { // Edits and history moves can replace selections without select::set. History diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 0fe4c2aa49..e5d632cee3 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -391,7 +391,7 @@ fn invoke_refuses_a_plugin_command_as_a_step() { #[test] fn a_failed_step_counts_unless_its_savepoint_undid_it() { let mut s = world(); - let spec = *s.registry.get("map.rename").unwrap(); + let rename = *s.registry.get("map.rename").unwrap(); let name = s.map().name.clone(); let half_done = |s: &mut Session| -> crate::CmdResult { s.map_mut().name = "Half done".into(); @@ -399,16 +399,33 @@ fn a_failed_step_counts_unless_its_savepoint_undid_it() { }; for savepoint in [true, false] { s.shared_steps = crate::StepTally::default(); - assert!(s.shared_step(&spec, savepoint, half_done).is_err()); + let spec = crate::CommandSpec { savepoint, ..rename }; + assert!(s.shared_step(&spec, half_done).is_err()); assert_eq!((s.map().name == name, s.shared_steps.edited), (savepoint, !savepoint), "savepoint: {savepoint}"); s.map_mut().name = name.clone(); } } -/// A command that doesn't mutate but adds a layer still makes a script's line an edit (#2645): -/// the layers are measured in every build, not only checked in debug ones. +/// A step that doesn't mutate but changes the layers is still an edit (#2645): they are measured +/// in every build, not inferred from the command's declaration. #[test] -fn script_step_measures_the_layers_a_step_changes() { +fn shared_step_measures_the_layers_a_step_changes() { + let mut s = world(); + let spec = *s.registry.commands.iter().find(|c| !c.mutates).unwrap(); + let (count, ds) = (s.map().layers.len(), s.map().layers[0].dataset.clone()); + let quiet_layer = |s: &mut Session| -> crate::CmdResult { + crate::cmd::layer::add_dataset(s, ds); + Ok(Value::Null) + }; + s.shared_step(&spec, quiet_layer).unwrap(); + assert_eq!((s.shared_steps.edited, s.map().layers.len()), (true, count + 1)); +} + +/// A command declared as not mutating that changes the layers fails the tests (#2645), by itself +/// or as a script's line, so its declaration stays honest. +#[test] +#[should_panic(expected = "test.quietLayer doesn't mutate but changed the layers")] +fn a_command_that_changes_layers_must_say_it_mutates() { let mut s = world(); s.registry.commands.push( crate::CommandSpec::new("test.quietLayer", "Quiet layer", "Test", |s, _| { @@ -418,12 +435,7 @@ fn script_step_measures_the_layers_a_step_changes() { }) .view(), ); - s.mark_saved(); - let (depth, count) = (s.undo_depth(), s.map().layers.len()); - s.run("script.run", &json!({"script": "test.quietLayer {}"})).unwrap(); - assert_eq!((s.undo_depth(), s.dirty(), s.map().layers.len()), (depth + 1, true, count + 1)); - s.run("edit.undo", &Value::Null).unwrap(); - assert_eq!(s.map().layers.len(), count); + let _ = s.run("test.quietLayer", &Value::Null); } /// A task's steps are counted as a script's lines: an undo step only when one edited (#2621). From 237395d00f6c04c00e41d0132ba510df5997e621 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 22 Nov 2026 02:11:58 -0500 Subject: [PATCH 4/9] fix(engine): marking the project unsaved doesn't excuse a layer change in the declaration check (#2645) The test-time check in invoke now lets a command declared as not mutating change the layers only when it moved the history state or the project, not when it only marked the project unsaved. CommandSpec's flag is renamed atomic, so it no longer shares its name with Session::savepoint. --- crates/engine/src/cmd/edit.rs | 2 +- crates/engine/src/lib.rs | 44 +++++++++++++++------------- crates/engine/src/policy/dispatch.rs | 9 +++--- crates/engine/src/tests.rs | 8 +++-- 4 files changed, 34 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 6082219acf..875e55fc0f 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -18,7 +18,7 @@ pub fn commands() -> Vec { .roles(&[crate::ParamRole {key:"frame",role:crate::Role::Opaque}]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).view() .when(crate::cmd::design::need_editable).params(r#"{"layer"?:name|id,"row":number,"featureId"?:number,"kind":"circle|rotatedBox","request"?:number (preview correlation only),"image"?:GeoTIFF layer name|id,"frame"?:construction grid as edit.addBox.box.frame (otherwise Web Mercator)}"#), C::new("edit.applyShapeConversion", "Apply Shape Conversion", "Edit › Features", crate::shape_conversion::apply).inputs(crate::shape_conversion::apply_inputs) - .roles(&[crate::ParamRole {key:"preview",role:crate::Role::Opaque}]).effects(crate::policy::Effects::NONE).savepoint() + .roles(&[crate::ParamRole {key:"preview",role:crate::Role::Opaque}]).effects(crate::policy::Effects::NONE).atomic() .when(crate::shape_conversion::need_editing).params(r#"{"preview":result of edit.previewShapeConversion,"confirm":true}"#), C::new("edit.calculateGeometry", "Calculate Geometry", "Attribute Table", crate::geometry_calc::run).roles(&[]).effects(crate::policy::Effects::NONE) .when(super::design::need_editable) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 29fc38c5c6..403d58285b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -109,9 +109,9 @@ pub struct CommandSpec { /// Pure executor-owned resolution for commands whose inputs exceed the common layer selector. pub(crate) transition: Option, &Value) -> Result, String>>, pub(crate) inputs: Option, &Value) -> Result>, - /// As a step of another command, it runs in a [`Session::savepoint`]: undone whole when it - /// fails, since a plugin may handle the error and go on. - pub(crate) savepoint: bool, + /// As a step of another command, it is atomic: it runs in a [`Session::savepoint`], undone + /// whole when it fails, since a plugin may handle the error and go on. + pub(crate) atomic: bool, } fn always(_: &Session) -> Option<&'static str> { @@ -150,12 +150,12 @@ impl CommandSpec { roles: None, inputs: None, transition: None, - savepoint: false, + atomic: false, } } - /// See [`CommandSpec::savepoint`]. - pub(crate) const fn savepoint(mut self) -> Self { - self.savepoint = true; + /// See [`CommandSpec::atomic`]. + pub(crate) const fn atomic(mut self) -> Self { + self.atomic = true; self } /// Declares the effects reviewed for this command; omitted declarations fail closed. @@ -772,10 +772,11 @@ pub(crate) struct StepTally { /// What a step can move of what undo restores without saying so: the history state /// (`edit.undo`), the project replaced (`project.new`), its file (`project.saveAs`), the unsaved /// mark a write that changed layers leaves (Publish to Source), and which layers each map has, -/// in what order. Measured before and after a shared step ([`Session::shared_step`]), not -/// inferred from what the command may reach. The project's other contents (a layer's name, look -/// or features) change only by commands that mutate, except its history log, where an export -/// records itself as a log entry, not an edit, as when it runs by itself. +/// in what order, with the id its next layer takes. Measured before and after a shared step +/// ([`Session::shared_step`]), not inferred from what the command may reach. The project's other +/// contents (a layer's name, look or features) change only by commands that mutate, except its +/// history log, where an export records itself as a log entry, not an edit, as when it runs by +/// itself. #[derive(PartialEq, Eq)] struct Restored { state: u64, @@ -2248,26 +2249,27 @@ impl Session { self.guarded_inner(label, true, false, f) } - /// Runs `run`, the command `spec`, as a step of the command running now, in its transaction - /// (a script's line, a task's step, a plugin's call), or in a [`Session::savepoint`] of it - /// when the command asks ([`CommandSpec::savepoint`]): - /// it takes no undo step of its own, and what it did goes into [`Session::shared_steps`]. + /// Runs `run`, the command `spec`, as a step of the command running now (a script's line, a + /// task's step, a plugin's call), in its transaction or, for an [atomic](CommandSpec::atomic) + /// command, in a [`Session::savepoint`] of it. It takes no undo step of its own, and what it + /// did goes into [`Session::shared_steps`]. /// Whether it left a request or changed nothing ([`Session::request_only`]) is its own, never /// the enclosing command's. It edited when it mutates and didn't say it changed nothing, or /// when [`Restored`] moved. A failed step that mutates counts too unless a savepoint undid it: /// telling what it changed would cost a copy of each layer it touched. pub(crate) fn shared_step(&mut self, spec: &CommandSpec, run: impl FnOnce(&mut Session) -> CmdResult) -> CmdResult { - let savepoint = spec.savepoint; let outer = std::mem::take(&mut self.request_only); // Once the account holds an edit, nothing a step does changes it: no need to measure. let before = (!self.shared_steps.edited).then(|| self.restored()); - let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match savepoint { - true => self.savepoint(spec.label, run), - false => run(self), - })); + let res = + std::panic::catch_unwind(std::panic::AssertUnwindSafe( + || { + if spec.atomic { self.savepoint(spec.label, run) } else { run(self) } + }, + )); let unchanged = std::mem::replace(&mut self.request_only, outer); let moved = before.is_some_and(|before| self.restored() != before); - let kept = !savepoint || matches!(res, Ok(Ok(_))); + let kept = !spec.atomic || matches!(res, Ok(Ok(_))); self.shared_steps.requested |= unchanged; self.shared_steps.edited |= moved || (spec.mutates && kept && !unchanged); res.unwrap_or_else(|panic| std::panic::resume_unwind(panic)) diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index d26faaa4c3..aafee85480 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -981,9 +981,10 @@ impl Session { // start in it, and inside the transaction that made it, so Undo and a failure take // it back and the project is unsaved ([`crate::cmd::project::first_layer_watch`]). let first_layer = crate::cmd::project::first_layer_watch(self, &spec); - // A command that doesn't mutate leaves the layers alone unless it moved what undo - // restores (an undo, a project opened): checked on every command the tests run, - // by itself or as a step, so a command declared wrong fails them. + // A command that doesn't mutate leaves the layers alone unless it moved the history + // state or the project (an undo, a project opened or saved elsewhere), not just + // marked it unsaved: checked on every command the tests run, by itself or as a + // step, so a command declared wrong fails them. #[cfg(test)] let declared = (!spec.mutates).then(|| self.restored()); let result = match txn { @@ -996,7 +997,7 @@ impl Session { #[cfg(test)] if let Some(before) = declared { let after = self.restored(); - let rest = |r: crate::Restored| crate::Restored { layers: Vec::new(), ..r }; + let rest = |r: crate::Restored| crate::Restored { layers: Vec::new(), unsaved_marks: 0, ..r }; let layers = after.layers == before.layers; assert!(result.is_err() || layers || rest(after) != rest(before), "{} doesn't mutate but changed the layers", spec.id); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e5d632cee3..372d7f039a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -399,7 +399,7 @@ fn a_failed_step_counts_unless_its_savepoint_undid_it() { }; for savepoint in [true, false] { s.shared_steps = crate::StepTally::default(); - let spec = crate::CommandSpec { savepoint, ..rename }; + let spec = crate::CommandSpec { atomic: savepoint, ..rename }; assert!(s.shared_step(&spec, half_done).is_err()); assert_eq!((s.map().name == name, s.shared_steps.edited), (savepoint, !savepoint), "savepoint: {savepoint}"); s.map_mut().name = name.clone(); @@ -411,7 +411,7 @@ fn a_failed_step_counts_unless_its_savepoint_undid_it() { #[test] fn shared_step_measures_the_layers_a_step_changes() { let mut s = world(); - let spec = *s.registry.commands.iter().find(|c| !c.mutates).unwrap(); + let spec = *s.registry.get("map.zoomFull").unwrap(); let (count, ds) = (s.map().layers.len(), s.map().layers[0].dataset.clone()); let quiet_layer = |s: &mut Session| -> crate::CmdResult { crate::cmd::layer::add_dataset(s, ds); @@ -422,7 +422,8 @@ fn shared_step_measures_the_layers_a_step_changes() { } /// A command declared as not mutating that changes the layers fails the tests (#2645), by itself -/// or as a script's line, so its declaration stays honest. +/// or as a script's line, so its declaration stays honest; marking the project unsaved doesn't +/// excuse it. #[test] #[should_panic(expected = "test.quietLayer doesn't mutate but changed the layers")] fn a_command_that_changes_layers_must_say_it_mutates() { @@ -431,6 +432,7 @@ fn a_command_that_changes_layers_must_say_it_mutates() { crate::CommandSpec::new("test.quietLayer", "Quiet layer", "Test", |s, _| { let ds = s.map().layers[0].dataset.clone(); crate::cmd::layer::add_dataset(s, ds); + s.mark_unsaved(); Ok(Value::Null) }) .view(), From d5e19e7e91789ab8af5246030ace6f2cbf0462e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 22 Nov 2026 02:26:48 -0500 Subject: [PATCH 5/9] fix(engine): failing doesn't excuse a layer change in the declaration check (#2645) --- crates/engine/src/policy/dispatch.rs | 7 ++++--- crates/engine/src/tests.rs | 6 +++--- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index aafee85480..1b74f1ece6 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -983,8 +983,9 @@ impl Session { let first_layer = crate::cmd::project::first_layer_watch(self, &spec); // A command that doesn't mutate leaves the layers alone unless it moved the history // state or the project (an undo, a project opened or saved elsewhere), not just - // marked it unsaved: checked on every command the tests run, by itself or as a - // step, so a command declared wrong fails them. + // marked it unsaved, and failing doesn't excuse it: by itself, nothing undoes it. + // Checked on every command the tests run, by itself or as a step, so a command + // declared wrong fails them. #[cfg(test)] let declared = (!spec.mutates).then(|| self.restored()); let result = match txn { @@ -999,7 +1000,7 @@ impl Session { let after = self.restored(); let rest = |r: crate::Restored| crate::Restored { layers: Vec::new(), unsaved_marks: 0, ..r }; let layers = after.layers == before.layers; - assert!(result.is_err() || layers || rest(after) != rest(before), "{} doesn't mutate but changed the layers", spec.id); + assert!(layers || rest(after) != rest(before), "{} doesn't mutate but changed the layers", spec.id); } self.url_completion_landed(spec.id, ¶ms, &result); if result.is_ok() && (spec.mutates || spec.effects.contains(crate::policy::Effect::History)) && spec.id != "data.similar" { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 372d7f039a..67be86020e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -422,8 +422,8 @@ fn shared_step_measures_the_layers_a_step_changes() { } /// A command declared as not mutating that changes the layers fails the tests (#2645), by itself -/// or as a script's line, so its declaration stays honest; marking the project unsaved doesn't -/// excuse it. +/// or as a script's line, so its declaration stays honest; marking the project unsaved or failing +/// afterwards doesn't excuse it. #[test] #[should_panic(expected = "test.quietLayer doesn't mutate but changed the layers")] fn a_command_that_changes_layers_must_say_it_mutates() { @@ -433,7 +433,7 @@ fn a_command_that_changes_layers_must_say_it_mutates() { let ds = s.map().layers[0].dataset.clone(); crate::cmd::layer::add_dataset(s, ds); s.mark_unsaved(); - Ok(Value::Null) + Err("failed after adding it".into()) }) .view(), ); From 015767f1bd8980e948a56042ce3f15a17bdb3880 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 22 Nov 2026 03:18:56 -0500 Subject: [PATCH 6/9] refactor(engine): read the declaration check and shared_step plainly (#2645) --- crates/engine/src/lib.rs | 8 ++------ crates/engine/src/policy/dispatch.rs | 4 ++-- crates/engine/src/tests.rs | 6 +++--- 3 files changed, 7 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 403d58285b..bce5aa9ab5 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -2261,12 +2261,8 @@ impl Session { let outer = std::mem::take(&mut self.request_only); // Once the account holds an edit, nothing a step does changes it: no need to measure. let before = (!self.shared_steps.edited).then(|| self.restored()); - let res = - std::panic::catch_unwind(std::panic::AssertUnwindSafe( - || { - if spec.atomic { self.savepoint(spec.label, run) } else { run(self) } - }, - )); + let step = |s: &mut Session| if spec.atomic { s.savepoint(spec.label, run) } else { run(s) }; + let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| step(self))); let unchanged = std::mem::replace(&mut self.request_only, outer); let moved = before.is_some_and(|before| self.restored() != before); let kept = !spec.atomic || matches!(res, Ok(Ok(_))); diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index 1b74f1ece6..1d459b6b50 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -999,8 +999,8 @@ impl Session { if let Some(before) = declared { let after = self.restored(); let rest = |r: crate::Restored| crate::Restored { layers: Vec::new(), unsaved_marks: 0, ..r }; - let layers = after.layers == before.layers; - assert!(layers || rest(after) != rest(before), "{} doesn't mutate but changed the layers", spec.id); + let same_layers = after.layers == before.layers; + assert!(same_layers || rest(after) != rest(before), "{} doesn't mutate but changed the layers", spec.id); } self.url_completion_landed(spec.id, ¶ms, &result); if result.is_ok() && (spec.mutates || spec.effects.contains(crate::policy::Effect::History)) && spec.id != "data.similar" { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 67be86020e..ce7c1252cc 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -421,9 +421,9 @@ fn shared_step_measures_the_layers_a_step_changes() { assert_eq!((s.shared_steps.edited, s.map().layers.len()), (true, count + 1)); } -/// A command declared as not mutating that changes the layers fails the tests (#2645), by itself -/// or as a script's line, so its declaration stays honest; marking the project unsaved or failing -/// afterwards doesn't excuse it. +/// A command declared as not mutating that adds, removes or reorders layers fails the tests +/// (#2645), by itself or as a script's line; marking the project unsaved or failing afterwards +/// doesn't excuse it. A layer's name, look or features aren't measured. #[test] #[should_panic(expected = "test.quietLayer doesn't mutate but changed the layers")] fn a_command_that_changes_layers_must_say_it_mutates() { From 7f65faac24e4fac219afdcc8a12b9d91cd8c5d48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 22 Nov 2026 07:08:08 -0500 Subject: [PATCH 7/9] docs: say what .view() promises about the layers, and the check that holds it (#2645) --- AGENTS.md | 4 ++++ crates/engine/src/policy/dispatch.rs | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2dce159a12..4adb613863 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -90,6 +90,10 @@ measures. - **Everything is a command**: a `CommandSpec` in `crates/engine/src/cmd/*.rs`. UI-only commands (`ui.*`) live in `crates/ui-egui/src/lib.rs`. The ribbon, shortcuts, command search and CLI dispatch by id. Commands never open dialogs. +- **`.view()` leaves the layers as they are**: a command that adds, removes or reorders layers + mutates, even when it fails part way, or run by itself it leaves no Undo step. The engine tests + fail a registered command declared `.view()` that does (the check in `invoke`, + `policy/dispatch.rs`), but only on the paths they run. - **Command ingress**: root `Session::run` is trusted native User dispatch. Assistant, MCP, plugin, imported-item and continuation adapters carry their named opaque policy scope; scopes inherit or narrow, and `with_scope` rejects nested ingress. Peer project text uses diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index 1d459b6b50..45c59d3bec 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -984,8 +984,8 @@ impl Session { // A command that doesn't mutate leaves the layers alone unless it moved the history // state or the project (an undo, a project opened or saved elsewhere), not just // marked it unsaved, and failing doesn't excuse it: by itself, nothing undoes it. - // Checked on every command the tests run, by itself or as a step, so a command - // declared wrong fails them. + // Checked on every registered command the tests run, by itself or as a step, so + // one declared wrong fails them on the paths they reach (AGENTS.md). #[cfg(test)] let declared = (!spec.mutates).then(|| self.restored()); let result = match txn { From ad4ef5de90d320a0c01b447afab3084c04940045 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 22 Nov 2026 07:32:14 -0500 Subject: [PATCH 8/9] fix(engine): the declaration check excuses a layer change by what a command declares (#2645) A command declared as not mutating may change the layers only when it declares that it moves the history (Undo, Redo) or replaces the project. What it does on the way, a nested edit included, no longer excuses it: a nested edit moved the history state the check used to read. --- AGENTS.md | 5 +++-- crates/engine/src/policy/dispatch.rs | 20 ++++++++++---------- crates/engine/src/tests.rs | 9 +++++++-- 3 files changed, 20 insertions(+), 14 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 4adb613863..682bb515b0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -91,8 +91,9 @@ measures. commands (`ui.*`) live in `crates/ui-egui/src/lib.rs`. The ribbon, shortcuts, command search and CLI dispatch by id. Commands never open dialogs. - **`.view()` leaves the layers as they are**: a command that adds, removes or reorders layers - mutates, even when it fails part way, or run by itself it leaves no Undo step. The engine tests - fail a registered command declared `.view()` that does (the check in `invoke`, + mutates, even when it fails part way. Declared `.view()`, it leaves no Undo step when it runs by + itself. Only Undo, Redo (`Effect::History`) and a project replaced (`Effect::Replaces`) may. + The engine tests fail a registered command declared wrong (the check in `invoke`, `policy/dispatch.rs`), but only on the paths they run. - **Command ingress**: root `Session::run` is trusted native User dispatch. Assistant, MCP, plugin, imported-item and continuation adapters carry their named opaque policy scope; diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index 45c59d3bec..124bfaf2a4 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -981,13 +981,16 @@ impl Session { // start in it, and inside the transaction that made it, so Undo and a failure take // it back and the project is unsaved ([`crate::cmd::project::first_layer_watch`]). let first_layer = crate::cmd::project::first_layer_watch(self, &spec); - // A command that doesn't mutate leaves the layers alone unless it moved the history - // state or the project (an undo, a project opened or saved elsewhere), not just - // marked it unsaved, and failing doesn't excuse it: by itself, nothing undoes it. - // Checked on every registered command the tests run, by itself or as a step, so - // one declared wrong fails them on the paths they reach (AGENTS.md). + // A command that doesn't mutate leaves the layers alone, unless it says it moves the + // history (Undo, Redo) or replaces the project: what it did on the way (a nested + // edit, an unsaved mark, a failure) doesn't excuse it, since by itself nothing + // undoes it. Checked on every registered command the tests run, by itself or as a + // step, so one declared wrong fails them on the paths they reach (AGENTS.md). #[cfg(test)] - let declared = (!spec.mutates).then(|| self.restored()); + let declared = (!spec.mutates + && !spec.effects.contains(crate::policy::Effect::History) + && !spec.effects.contains(crate::policy::Effect::Replaces)) + .then(|| self.restored().layers); let result = match txn { Txn::Own => self.guarded(spec.label, spec.mutates, run), Txn::Shared => self.shared_step(&spec, run), @@ -997,10 +1000,7 @@ impl Session { } #[cfg(test)] if let Some(before) = declared { - let after = self.restored(); - let rest = |r: crate::Restored| crate::Restored { layers: Vec::new(), unsaved_marks: 0, ..r }; - let same_layers = after.layers == before.layers; - assert!(same_layers || rest(after) != rest(before), "{} doesn't mutate but changed the layers", spec.id); + assert!(self.restored().layers == before, "{} doesn't mutate but changed the layers", spec.id); } self.url_completion_landed(spec.id, ¶ms, &result); if result.is_ok() && (spec.mutates || spec.effects.contains(crate::policy::Effect::History)) && spec.id != "data.similar" { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ce7c1252cc..24f3b0c9da 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -422,8 +422,9 @@ fn shared_step_measures_the_layers_a_step_changes() { } /// A command declared as not mutating that adds, removes or reorders layers fails the tests -/// (#2645), by itself or as a script's line; marking the project unsaved or failing afterwards -/// doesn't excuse it. A layer's name, look or features aren't measured. +/// (#2645), by itself or as a script's line; an edit it makes on the way, marking the project +/// unsaved or failing afterwards doesn't excuse it. A layer's name, look or features aren't +/// measured. #[test] #[should_panic(expected = "test.quietLayer doesn't mutate but changed the layers")] fn a_command_that_changes_layers_must_say_it_mutates() { @@ -433,6 +434,10 @@ fn a_command_that_changes_layers_must_say_it_mutates() { let ds = s.map().layers[0].dataset.clone(); crate::cmd::layer::add_dataset(s, ds); s.mark_unsaved(); + s.guarded("Rename", true, |s| { + s.map_mut().name = "Renamed on the way".into(); + Ok(Value::Null) + })?; Err("failed after adding it".into()) }) .view(), From 2ef9f5dede26ff1bb1b49f0008452e6cbb0a0b2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sun, 22 Nov 2026 07:53:05 -0500 Subject: [PATCH 9/9] test(engine): the declaration check runs in the integration tests too (#2645) --- AGENTS.md | 4 ++-- Cargo.lock | 1 + crates/engine/Cargo.toml | 5 +++++ crates/engine/src/policy/dispatch.rs | 9 +++++---- crates/engine/tests/integration/workflows.rs | 17 +++++++++++++++++ 5 files changed, 30 insertions(+), 6 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 682bb515b0..6de03ca0bb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -93,8 +93,8 @@ measures. - **`.view()` leaves the layers as they are**: a command that adds, removes or reorders layers mutates, even when it fails part way. Declared `.view()`, it leaves no Undo step when it runs by itself. Only Undo, Redo (`Effect::History`) and a project replaced (`Effect::Replaces`) may. - The engine tests fail a registered command declared wrong (the check in `invoke`, - `policy/dispatch.rs`), but only on the paths they run. + The engine's unit and integration tests fail a registered command declared wrong (the check in + `invoke`, `policy/dispatch.rs`, feature `declaration-check`), but only on the paths they run. - **Command ingress**: root `Session::run` is trusted native User dispatch. Assistant, MCP, plugin, imported-item and continuation adapters carry their named opaque policy scope; scopes inherit or narrow, and `with_scope` rejects nested ingress. Peer project text uses diff --git a/Cargo.lock b/Cargo.lock index 7f12acf9a4..0cd7a5f822 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5198,6 +5198,7 @@ dependencies = [ "rusqlite", "rustgis-analysis", "rustgis-data", + "rustgis-engine", "rustgis-geolibre", "rustgis-geom", "rustgis-map", diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index dd2f904405..cd957a1299 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -34,10 +34,15 @@ geolibre = ["dep:rustgis-geolibre"] pdf = ["rustgis-data/pdf"] # Existing in-tree Wasm fixtures for adapter tests; no guest or production interface change. testing = ["rustgis-plugins/testing"] +# The check that a command declared as not mutating leaves the layers alone, in the integration +# tests too (they link the library without `cfg(test)`; AGENTS.md). Never in a release. +declaration-check = [] # The JSON Schema of the project file (`cargo xtask schema`). schema = ["dep:schemars", "rustgis-data/schema", "rustgis-geom/schema"] [dev-dependencies] +# The declaration check in the integration tests. +rustgis-engine = { path = ".", features = ["declaration-check"] } # Reading back the PDFs layouts export (#2336). rustgis-data = { workspace = true, features = ["pdf"] } miniz_oxide = { workspace = true } diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index 124bfaf2a4..7f639452bd 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -984,9 +984,10 @@ impl Session { // A command that doesn't mutate leaves the layers alone, unless it says it moves the // history (Undo, Redo) or replaces the project: what it did on the way (a nested // edit, an unsaved mark, a failure) doesn't excuse it, since by itself nothing - // undoes it. Checked on every registered command the tests run, by itself or as a - // step, so one declared wrong fails them on the paths they reach (AGENTS.md). - #[cfg(test)] + // undoes it. Checked on every registered command the unit and integration tests + // run, by itself or as a step, so one declared wrong fails them on the paths they + // reach (AGENTS.md). + #[cfg(any(test, feature = "declaration-check"))] let declared = (!spec.mutates && !spec.effects.contains(crate::policy::Effect::History) && !spec.effects.contains(crate::policy::Effect::Replaces)) @@ -998,7 +999,7 @@ impl Session { if let (Ok(_), Some(before)) = (&result, first_layer) { crate::cmd::project::take_first_layer_system(self, &before); } - #[cfg(test)] + #[cfg(any(test, feature = "declaration-check"))] if let Some(before) = declared { assert!(self.restored().layers == before, "{} doesn't mutate but changed the layers", spec.id); } diff --git a/crates/engine/tests/integration/workflows.rs b/crates/engine/tests/integration/workflows.rs index db7aeb0826..557f0760eb 100644 --- a/crates/engine/tests/integration/workflows.rs +++ b/crates/engine/tests/integration/workflows.rs @@ -9,6 +9,23 @@ use rustgis_engine::{Project, Session}; use serde_json::{Value, json}; use std::path::{Path, PathBuf}; +/// The check that a command declared as not mutating leaves the layers alone runs here too, where +/// commands take their valid paths (#2645; AGENTS.md, feature `declaration-check`). +#[test] +#[should_panic(expected = "test.quietLayer doesn't mutate but changed the layers")] +fn a_command_that_adds_a_layer_must_say_it_mutates() { + let mut s = Session::new(Project::new("Declared")); + s.registry.commands.push( + rustgis_engine::CommandSpec::new("test.quietLayer", "Quiet layer", "Test", |s, _| { + let ds = Dataset::new("Quiet", rustgis_engine::data::GeometryType::Point, vec![]); + rustgis_engine::cmd::layer::add_dataset(s, ds); + Ok(Value::Null) + }) + .view(), + ); + let _ = s.run("test.quietLayer", &Value::Null); +} + /// Declared versions are checked before payloads, and unreadable nodes cannot disappear on import. #[test] fn model_import_refuses_unsupported_files_without_changing_session() {