Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(tools): reject edit moves that resolve to the source
cauliflower2ab74c332cd9
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rsindex 04b36480a..cbdd5036e 100644--- a/crates/host-core/src/rpc/mod.rs+++ b/crates/host-core/src/rpc/mod.rs@@ -8765,6 +8765,75 @@ mod tests {assert_eq!(missing.data.unwrap()["errorCode"], "NOT_FOUND");}+ #[tokio::test]+ async fn edit_self_move_rpc_preserves_file_and_read_provenance() {+ let data_dir = tempfile::tempdir().unwrap();+ let project = data_dir.path().join("project");+ fs::create_dir_all(&project).unwrap();+ let source = project.join("source.txt");+ fs::write(&source, "original\n").unwrap();+ let mut app_state = AppState::open(data_dir.path()).unwrap();+ app_state.handshook = true;+ let session = sessions::create_session(+ &app_state.db,+ Some("Self move".into()),+ Some("agent".into()),+ None,+ None,+ Some(project.to_string_lossy().into_owned()),+ )+ .unwrap();+ sessions::configure_session_with_thinking(+ &app_state.db,+ &session.id,+ "agent",+ None,+ None,+ None,+ Some("auto"),+ )+ .unwrap();+ let state = Arc::new(Mutex::new(app_state));+ let (tx, _rx) = mpsc::unbounded_channel();+ let read = handle_request(+ state.clone(),+ "tools.execute",+ json!({"sessionId": session.id, "toolCallId": "read-source",+ "toolName": "Read", "args": {"path": "source.txt"}, "mode": "agent"}),+ tx.clone(),+ )+ .await+ .unwrap();+ assert_eq!(read["ok"], true, "{read}");+ let tag = &read["content"]["tag"];+ let rejected = handle_request(+ state.clone(),+ "tools.execute",+ json!({"sessionId": session.id, "toolCallId": "self-move",+ "toolName": "Edit", "args": {"path": "source.txt", "tag": tag,+ "ops": "PUT 1.=1:\n+must not land\nMV ./source.txt\n"}, "mode": "agent"}),+ tx.clone(),+ )+ .await+ .unwrap();+ assert_eq!(rejected["ok"], false, "{rejected}");+ assert_eq!(rejected["errorCode"], "EDIT_NO_CHANGE", "{rejected}");+ assert_eq!(fs::read(&source).unwrap(), b"original\n");+ // Failure must not invalidate the Read snapshot or poison later edits.+ let edited = handle_request(+ state,+ "tools.execute",+ json!({"sessionId": session.id, "toolCallId": "valid-edit",+ "toolName": "Edit", "args": {"path": "source.txt", "tag": tag,+ "ops": "PUT 1.=1:\n+changed\n"}, "mode": "agent"}),+ tx,+ )+ .await+ .unwrap();+ assert_eq!(edited["ok"], true, "{edited}");+ assert_eq!(fs::read(&source).unwrap(), b"changed\n");+ }+/// D137: the audit row for a tool call must carry the three segments/// separately, so "the tool was slow" can be told apart from "the user/// took 20s to approve it".diff --git a/crates/host-core/src/tools/mod.rs b/crates/host-core/src/tools/mod.rsindex 6a9acc556..424dc26ae 100644--- a/crates/host-core/src/tools/mod.rs+++ b/crates/host-core/src/tools/mod.rs@@ -1665,6 +1665,14 @@ fn tool_edit(let (code, message) = ignore_rules::denied_error(dest);return Err(hashline::ToolError::new(code, message));}+ // Both paths have passed the same canonical, permission-aware resolver.+ // Writing then unlinking an alias of the source would delete the file.+ if dest_resolved == resolved {+ return Err(hashline::ToolError::new(+ "EDIT_NO_CHANGE",+ "MV destination resolves to the source file; choose a different destination",+ ));+ }if let Some(parent) = dest_resolved.parent() {std::fs::create_dir_all(parent).map_err(|e| {hashline::ToolError::new("TOOL_FAILED", format!("mkdir failed: {e}"))@@ -4874,6 +4882,138 @@ mod tests {.await;assert_eq!(native.content["exitCode"], 7);}+ #[tokio::test]+ async fn edit_move_to_self_preserves_source_bytes() {+ let dir = tempfile::tempdir().unwrap();+ let target = dir.path().join("source.txt");+ let input = b"original\r\n";+ let mut destinations = vec![+ "source.txt".to_string(),+ "./source.txt".to_string(),+ "sub/../source.txt".to_string(),+ target.to_string_lossy().into_owned(),+ ];+ if cfg!(windows) {+ destinations.push("SOURCE.TXT".to_string());+ }+ let mut failures = Vec::new();+ for dest in destinations {+ std::fs::write(&target, input).unwrap();+ let read = execute_tool(+ Some(dir.path()),+ None,+ "Read",+ &json!({"path": "source.txt"}),+ 5_000,+ )+ .await;+ assert!(read.ok, "Read failed: {:?}", read.content);+ // A mixed call must reject the move before even the PUT bytes land.+ let result = execute_tool(+ Some(dir.path()),+ None,+ "Edit",+ &json!({"path": "source.txt", "tag": read.content["tag"],+ "ops": format!("PUT 1.=1:\n+changed\nMV \"{dest}\"\n")}),+ 5_000,+ )+ .await;+ if result.ok || result.error_code.as_deref() != Some("EDIT_NO_CHANGE") {+ failures.push(format!("{dest}: expected EDIT_NO_CHANGE, got {result:?}"));+ }+ if std::fs::read(&target).ok().as_deref() != Some(input.as_slice()) {+ failures.push(format!("{dest}: source bytes changed or file disappeared"));+ }+ }+ assert!(failures.is_empty(), "{}", failures.join("\n"));+ }++ #[tokio::test]+ async fn edit_move_through_directory_link_preserves_source_bytes() {+ let dir = tempfile::tempdir().unwrap();+ let real = dir.path().join("real");+ let alias = dir.path().join("alias");+ std::fs::create_dir(&real).unwrap();+ #[cfg(unix)]+ std::os::unix::fs::symlink(&real, &alias).unwrap();+ #[cfg(windows)]+ {+ // Junctions exercise real filesystem aliases without symlink privilege.+ let output = std::process::Command::new("cmd.exe")+ .args(["/d", "/c", "mklink", "/J"])+ .arg(&alias)+ .arg(&real)+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "junction creation failed: {output:?}"+ );+ }+ let target = real.join("source.txt");+ std::fs::write(&target, b"original\n").unwrap();+ let read = execute_tool(+ Some(dir.path()),+ None,+ "Read",+ &json!({"path": "real/source.txt"}),+ 5_000,+ )+ .await;+ assert!(read.ok, "Read failed: {:?}", read.content);+ let result = execute_tool(+ Some(dir.path()),+ None,+ "Edit",+ &json!({"path": "real/source.txt", "tag": read.content["tag"],+ "ops": "MV alias/source.txt\n"}),+ 5_000,+ )+ .await;+ assert!(+ !result.ok,+ "Move through alias succeeded: {:?}",+ result.content+ );+ assert_eq!(result.error_code.as_deref(), Some("EDIT_NO_CHANGE"));+ assert_eq!(std::fs::read(&target).unwrap(), b"original\n");+ #[cfg(windows)]+ std::fs::remove_dir(&alias).unwrap();+ }++ #[tokio::test]+ async fn edit_move_to_different_path_applies_edits_and_removes_source() {+ let dir = tempfile::tempdir().unwrap();+ let target = dir.path().join("source.txt");+ std::fs::write(&target, b"original\r\n").unwrap();+ let read = execute_tool(+ Some(dir.path()),+ None,+ "Read",+ &json!({"path": "source.txt"}),+ 5_000,+ )+ .await;+ assert!(read.ok, "Read failed: {:?}", read.content);+ let result = execute_tool(+ Some(dir.path()),+ None,+ "Edit",+ &json!({"path": "source.txt", "tag": read.content["tag"],+ "ops": "PUT 1.=1:\n+changed\nMV nested/destination.txt\n"}),+ 5_000,+ )+ .await;+ assert!(result.ok, "Move failed: {:?}", result.content);+ assert!(!target.exists());+ assert_eq!(+ std::fs::read(dir.path().join("nested/destination.txt")).unwrap(),+ b"changed\r\n"+ );+ assert_eq!(result.content["movedFrom"], "source.txt");+ assert_eq!(result.content["tag"].as_str().unwrap().len(), 4);+ }+#[tokio::test]async fn edit_preserves_crlf_line_endings() {let dir = tempfile::tempdir().unwrap();diff --git a/docs/spec/03-runtime/08-error-codes.md b/docs/spec/03-runtime/08-error-codes.mdindex 222ebe340..e0281588f 100644--- a/docs/spec/03-runtime/08-error-codes.md+++ b/docs/spec/03-runtime/08-error-codes.md@@ -206,7 +206,7 @@ loses that. See| `EDIT_REGISTER_EMPTY` | no | paste from an unset register || `EDIT_REGISTER_AMBIGUOUS` | no | anonymous paste with more than one pending anonymous capture || `EDIT_REPAIR_AMBIGUOUS` | no | boundary-repair candidates tied at minimum cost |-| `EDIT_NO_CHANGE` | no | the apply produced text identical to the input |+| `EDIT_NO_CHANGE` | no | the apply produced text identical to the input, or `MV` resolved to the source path; the entire call leaves the source bytes untouched || `EDIT_AMPLIFICATION_LIMIT` | no | lowering exceeded the expansion cap |`EDIT_LINES_UNSEEN` is retriable **without** a further `Read` when its messagediff --git a/docs/spec/03-runtime/18-line-anchored-edit-contract.md b/docs/spec/03-runtime/18-line-anchored-edit-contract.mdindex 028178922..44a2e620d 100644--- a/docs/spec/03-runtime/18-line-anchored-edit-contract.md+++ b/docs/spec/03-runtime/18-line-anchored-edit-contract.md@@ -264,6 +264,15 @@ dest := path | quoted_path| `REM` | none | Delete the file named by `path`. || `MV DEST` | none | Move/rename to `DEST` after applying every other op to the source. |+Before writing the destination or removing the source, `MV` compares the paths+returned by the host's permission-aware canonical resolver. If both resolve to+the same path, the entire call fails with `EDIT_NO_CHANGE` and the source bytes+stay untouched, including when the payload also contains content edits. This+covers relative/absolute aliases, `.` and `..`, symlinks, and case-only spellings+on case-insensitive filesystems. `MV` does not support case-only renaming there;+use a distinct destination instead. Case-sensitive filesystems retain their+normal distinction between different files whose names differ only in case.+### 7.3 Anchoring rules1. All line numbers refer to the **tagged snapshot**. They are never shifted by@@ -541,7 +550,7 @@ Recovery warnings distinguish cause, because the corrective action differs:| `EDIT_REGISTER_EMPTY` | no | paste from an unset register || `EDIT_REGISTER_AMBIGUOUS` | no | anonymous paste with more than one pending anonymous capture || `EDIT_REPAIR_AMBIGUOUS` | no | boundary repair candidates tied at minimum cost |-| `EDIT_NO_CHANGE` | no | apply produced identical text |+| `EDIT_NO_CHANGE` | no | apply produced identical text, or `MV` resolved to the source path || `EDIT_AMPLIFICATION_LIMIT` | no | lowering exceeded the expansion cap |All of these are `Edit`-scoped and additive todiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 89c75b8a4..2976ffd6c 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -11195,12 +11195,19 @@ This test plan spec is accepted when:6. Emit `Edit` on a path that does not exist but whose basename and tag matchexactly one file this session recorded, and inspect the warning.7. Repeat step 6 with two recorded candidates sharing that basename and tag.+ 8. Emit `MV` to the source itself, `./source`, `sub/../source`, and its+ absolute path, plus a directory symlink (Windows junction) pointing back+ to its directory; on Windows also use a case-only alias. Repeat with a+ content-changing `PUT` in the same call, then use the original Read tag+ for a valid content edit.- **Expected**: Step 1 records a source deletion and a destination creation underone tool call; step 3 restores both or neither. Step 4's rollback restores thecaptured bytes, hash-guarded on the full digest rather than the 16-bit tag.Step 5 fails rather than editing against content the rollback replaced. Step 6rebinds to the real file with a warning, and the write-permission gate isevaluated against the rebound path; step 7 declines instead of picking one.+ Step 8 returns `EDIT_NO_CHANGE` without writing or deleting the source, and+ the original Read tag remains usable for the following valid edit.- **Specs linked**: `03-runtime/18-line-anchored-edit-contract.md` §9.2, §13.1,`03-runtime/03-tools-and-permissions.md` §4c, ADR 0043, ADR 0087- **Acceptance**: E (tools & permissions), Quality