Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,11 @@ 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. 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'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
Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions crates/engine/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub fn commands() -> Vec<C> {
.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).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)
Expand Down
67 changes: 40 additions & 27 deletions crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,9 @@ pub struct CommandSpec {
/// Pure executor-owned resolution for commands whose inputs exceed the common layer selector.
pub(crate) transition: Option<fn(&cmd::InputContext<'_>, &Value) -> Result<Option<cmd::Selection>, String>>,
pub(crate) inputs: Option<fn(&cmd::InputContext<'_>, &Value) -> Result<cmd::Inputs, String>>,
/// 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> {
Expand Down Expand Up @@ -147,8 +150,14 @@ impl CommandSpec {
roles: None,
inputs: None,
transition: None,
atomic: false,
}
}
/// 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.
pub const fn effects(mut self, effects: policy::Effects) -> Self {
self.effects = effects;
Expand Down Expand Up @@ -760,18 +769,21 @@ 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 which layers each map has,
/// 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,
opened: u64,
files: ProjectFiles,
unsaved_marks: u64,
layers: Vec<rustgis_map::LayerMark>,
}

pub struct Session {
Expand Down Expand Up @@ -2237,35 +2249,36 @@ 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): 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.
/// 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 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::<Vec<_>>());
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 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 = 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 = !spec.atomic || 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 {
Expand Down
22 changes: 21 additions & 1 deletion crates/engine/src/policy/dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -975,14 +981,28 @@ 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 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 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))
.then(|| self.restored().layers);
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),
};
if let (Ok(_), Some(before)) = (&result, first_layer) {
crate::cmd::project::take_first_layer_system(self, &before);
}
#[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);
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
}
self.url_completion_landed(spec.id, &params, &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
Expand Down
72 changes: 72 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,78 @@ 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}");
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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 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 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();
Err("failed part way".into())
};
for savepoint in [true, false] {
s.shared_steps = crate::StepTally::default();
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();
}
}

/// 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 shared_step_measures_the_layers_a_step_changes() {
let mut s = world();
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);
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 adds, removes or reorders layers fails the tests
/// (#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() {
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);
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(),
);
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).
#[test]
fn task_takes_an_undo_step_only_when_a_step_edits() {
Expand Down
17 changes: 17 additions & 0 deletions crates/engine/tests/integration/workflows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
Loading