diff --git a/rust/contracts/application-boundary.md b/rust/contracts/application-boundary.md index 0116cdc8..6d873566 100644 --- a/rust/contracts/application-boundary.md +++ b/rust/contracts/application-boundary.md @@ -367,10 +367,24 @@ owns the resulting session; stopping preparation or accepting late replies canno start a session after invalidation. Cross-plugin preparation is not covered by this native increment. +## Local branch deletion + +Ordinary deletion preserves unmerged branches and reports `git_branch_not_merged` +with the exact branch tip for review. A force-delete entry opens a separate warning +and requires a second explicit destructive confirmation; cancelling or dismissing +that confirmation never sends a forced write. The force request binds the reviewed +full object ID with `expectedTarget`, rejects changes as `git_branch_changed`, and +still refuses the current branch or a branch checked out in any worktree. A batch +confirmation contains only the unmerged failures, never already deleted branches +or remote failures. The shape is pinned by +[`branch-delete-v1.json`](../fixtures/git/branch-delete-v1.json). + ## Error Codes Use stable categories rather than platform error strings: +- `git_branch_not_merged` +- `git_branch_changed` - `invalid_request` - `workspace_not_found` - `permission_denied` diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 5ef6a8f8..615cf13d 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -923,8 +923,9 @@ shows, top to bottom; the empty path is the workspace root. `selection` is `{ selected?, marked?, anchor? }`: the selected row, the paths marked for a batch (returned in path order) and the path a Shift click extends from. `action.kind` is `choose { path }` (a plain click: select the row, drop the marks and the anchor), -`toggle { path }` (Cmd or Ctrl: mark or unmark the row, select it and make it the -anchor), `extend { path }` (Shift: mark every row from the anchor, else from the +`toggle { path }` (Cmd or Ctrl: when there are neither marks nor an anchor, first +include the non-root selected row if it is visible; then toggle the clicked row, +select it and make it the anchor), `extend { path }` (Shift: mark every row from the anchor, else from the selected row, else the clicked row alone, to the clicked row, keep the other marks and select it) or `clear` (a batch is over: drop the marks and the anchor, keep the selected row). The root is never marked: `toggle` and `extend` on it change nothing, @@ -1826,8 +1827,19 @@ and `message`; the tagger identity and timestamp are intentionally not preserved. Deletion supplies the observed unpeeled object ID to `update-ref`, so a concurrent force-update fails atomically instead of deleting new state and returning a stale recovery target. `deleteBranch` applies the same expected-OID -guard after checking the branch is fully merged and not checked out, then -on success, carries a structured `branchDeletion` record — +guard after checking the branch is fully merged and not checked out. An unmerged +branch returns `operationError.code: git_branch_not_merged`; its `details` is a +JSON string `{ "name": string, "expectedTarget": string }` containing the exact +branch tip. Hosts must offer a separate explicit destructive confirmation before +retrying `deleteBranch` with `force: true` and that `expectedTarget`. Force only +bypasses merge validation: the current branch and any branch checked out in a +worktree remain protected. `expectedTarget` must be a full 40- or 64-digit hex +object ID and is mandatory with force (`invalid_request` otherwise). A changed +target returns `git_branch_changed`; hosts must discard the old confirmation and +ask the user to restart deletion. Even after validation, the atomic expected-OID +guard prevents deleting a concurrent update. Omitted `force` retains ordinary safe +deletion. The compatibility fixture is `rust/fixtures/git/branch-delete-v1.json`. +On success, deletion carries a structured `branchDeletion` record — `{ "name": string, "deletedTarget": string }` — so hosts can offer to recreate the branch at its previous commit; a missing branch fails with `The branch '' does not exist`. If the ref deletion succeeds but branch diff --git a/rust/crates/core/src/tests/git.rs b/rust/crates/core/src/tests/git.rs index 37e5bbd8..c947f7f6 100644 --- a/rust/crates/core/src/tests/git.rs +++ b/rust/crates/core/src/tests/git.rs @@ -2804,7 +2804,7 @@ fn git_write_records_the_deleted_branch_target() { assert_eq!(unmerged["ok"], true, "{unmerged:?}"); assert_eq!( unmerged["data"]["operationError"]["code"], - "invalid_request" + "git_branch_not_merged" ); assert_eq!( unmerged["data"]["operationError"]["message"], diff --git a/rust/crates/core/src/tests/git_branch_delete.rs b/rust/crates/core/src/tests/git_branch_delete.rs new file mode 100644 index 00000000..b26e5abe --- /dev/null +++ b/rust/crates/core/src/tests/git_branch_delete.rs @@ -0,0 +1,156 @@ +use super::support::temporary_root; +use crate::execute_json; +use serde_json::{json, Value}; +use std::{fs, path::PathBuf}; + +// Every request has a Core deadline; the owner removes the repository and linked worktrees +// together on success and assertion failure, without touching any developer repository. +struct Repository(PathBuf); + +impl Repository { + fn new() -> Self { + let repo = Self(temporary_root("branch-force-delete")); + fs::create_dir_all(&repo.0).unwrap(); + repo.git(&["init", "-q", "-b", "main"]); + repo.git(&["config", "user.name", "Lithe Fixture"]); + repo.git(&["config", "user.email", "fixture@example.invalid"]); + repo.git(&["config", "commit.gpgSign", "false"]); + repo.git(&["config", "core.hooksPath", "disabled-fixture-hooks"]); + repo.git(&["commit", "--allow-empty", "-qm", "base"]); + repo + } + + fn request(&self, command: &str, mut payload: Value) -> Value { + payload["root"] = json!(self.0); + let response: Value = serde_json::from_str(&execute_json( + &json!({ + "id": "branch-delete", "command": command, "timeoutMilliseconds": 5000, + "payload": payload + }) + .to_string(), + )) + .unwrap(); + assert_eq!(response["ok"], true, "{response}"); + response["data"].clone() + } + + fn git(&self, arguments: &[&str]) -> String { + let data = self.request("git.command", json!({"arguments": arguments})); + assert_eq!(data["exitCode"], 0, "{data}"); + assert!(data["operationError"].is_null(), "{data}"); + data["stdout"].as_str().unwrap().trim().to_string() + } + + fn delete(&self, branch: &str, force: bool, expected: Option<&str>) -> Value { + self.request("git.write", json!({ + "operation": "deleteBranch", + "gitReference": {"fullName": format!("refs/heads/{branch}"), "shortName": branch, "kind": "local"}, + "force": force, "expectedTarget": expected + })) + } + + fn unmerged(&self) -> String { + self.git(&["switch", "-qc", "backup/before-strip-trailers"]); + self.git(&["commit", "--allow-empty", "-qm", "unique work"]); + let target = self.git(&["rev-parse", "HEAD"]); + self.git(&["switch", "-q", "main"]); + target + } +} + +impl Drop for Repository { + fn drop(&mut self) { + if let Err(error) = fs::remove_dir_all(&self.0) { + eprintln!("Could not remove branch deletion fixture: {error}"); + } + } +} + +#[test] +fn branch_force_delete_requires_reviewed_target_and_preserves_recovery() { + let repo = Repository::new(); + let target = repo.unmerged(); + let fixture: Value = serde_json::from_str(include_str!( + "../../../../fixtures/git/branch-delete-v1.json" + )) + .unwrap(); + let refused = repo.delete("backup/before-strip-trailers", false, None); + assert_eq!( + refused["operationError"]["code"], fixture["unmergedCode"], + "{refused}" + ); + let review: Value = + serde_json::from_str(refused["operationError"]["details"].as_str().unwrap()).unwrap(); + assert_eq!(review["name"], "backup/before-strip-trailers"); + assert_eq!(review["expectedTarget"], target); + assert_eq!( + repo.git(&["rev-parse", "refs/heads/backup/before-strip-trailers"]), + target + ); + + let unreviewed = repo.delete("backup/before-strip-trailers", true, None); + assert_eq!( + unreviewed["operationError"]["code"], "invalid_request", + "{unreviewed}" + ); + let invalid = repo.delete("backup/before-strip-trailers", true, Some("HEAD")); + assert_eq!( + invalid["operationError"]["code"], "invalid_request", + "{invalid}" + ); + let deleted = repo.delete("backup/before-strip-trailers", true, Some(&target)); + assert!(deleted["operationError"].is_null(), "{deleted}"); + assert_eq!( + deleted["branchDeletion"], + json!({"name":"backup/before-strip-trailers", "deletedTarget":target}) + ); + assert!(repo + .git(&["branch", "--list", "backup/before-strip-trailers"]) + .is_empty()); + repo.git(&["branch", "backup/before-strip-trailers", &target]); + assert_eq!( + repo.git(&["rev-parse", "refs/heads/backup/before-strip-trailers"]), + target + ); +} + +#[test] +fn branch_force_delete_rejects_changed_targets_and_checked_out_branches() { + let repo = Repository::new(); + let target = repo.unmerged(); + let changed = repo.delete( + "backup/before-strip-trailers", + true, + Some(&repo.git(&["rev-parse", "main"])), + ); + assert_eq!( + changed["operationError"]["code"], "git_branch_changed", + "{changed}" + ); + assert_eq!( + repo.git(&["rev-parse", "refs/heads/backup/before-strip-trailers"]), + target + ); + let current = repo.delete("main", true, Some(&repo.git(&["rev-parse", "main"]))); + assert_eq!( + current["operationError"]["code"], "invalid_request", + "{current}" + ); + let checkout = repo.0.join("linked-checkout"); + repo.git(&[ + "worktree", + "add", + "-q", + checkout.to_str().unwrap(), + "backup/before-strip-trailers", + ]); + let occupied = repo.delete("backup/before-strip-trailers", true, Some(&target)); + assert_eq!( + occupied["operationError"]["code"], "invalid_request", + "{occupied}" + ); + assert_eq!( + repo.git(&["rev-parse", "refs/heads/backup/before-strip-trailers"]), + target + ); +} diff --git a/rust/crates/core/src/tests/mod.rs b/rust/crates/core/src/tests/mod.rs index 02dff963..279e5976 100644 --- a/rust/crates/core/src/tests/mod.rs +++ b/rust/crates/core/src/tests/mod.rs @@ -15,6 +15,7 @@ mod execution_commands; mod file_name_order; mod file_operations; mod git; +mod git_branch_delete; mod git_change_targets; mod git_changed_file_groups; mod git_diff_blocks; diff --git a/rust/crates/git/src/branches.rs b/rust/crates/git/src/branches.rs index 08905aa0..c402047d 100644 --- a/rust/crates/git/src/branches.rs +++ b/rust/crates/git/src/branches.rs @@ -174,9 +174,24 @@ pub(crate) fn delete_tag(root: &str, value: Option<&str>) -> Result Result { +/// host can offer a restore. Forced deletion requires a reviewed exact target and +/// skips only merge validation; checked-out branches remain protected. +pub(crate) fn delete_branch( + root: &str, + branch: &str, + force: bool, + expected_target: Option<&str>, +) -> Result { + if force && expected_target.is_none() + || expected_target.is_some_and(|value| { + !matches!(value.len(), 40 | 64) || !value.bytes().all(|byte| byte.is_ascii_hexdigit()) + }) + { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Forced branch deletion requires a reviewed full object ID in expectedTarget", + )); + } let reference = format!("refs/heads/{branch}"); let target = resolve_ref_object(root, &reference)?.ok_or_else(|| { CoreError::new( @@ -184,7 +199,13 @@ pub(crate) fn delete_branch(root: &str, branch: &str) -> Result Result<(), CoreError> { let worktrees = execute_git( root, @@ -280,6 +303,10 @@ fn ensure_branch_is_safely_deletable( )); } + if force { + return Ok(()); + } + let upstream = execute_git( root, &[ @@ -316,9 +343,10 @@ fn ensure_branch_is_safely_deletable( match merged.exit_code { 0 => Ok(()), 1 => Err(CoreError::new( - ErrorCode::InvalidRequest, + ErrorCode::GitBranchNotMerged, format!("The branch '{branch}' is not fully merged"), - )), + ) + .with_details(serde_json::json!({"name": branch, "expectedTarget": target}).to_string())), _ => Err(CoreError::new( ErrorCode::ProcessFailed, format!("Could not verify whether branch '{branch}' is merged"), diff --git a/rust/crates/git/src/requests.rs b/rust/crates/git/src/requests.rs index 212c08ad..d86d21c2 100644 --- a/rust/crates/git/src/requests.rs +++ b/rust/crates/git/src/requests.rs @@ -312,6 +312,10 @@ pub struct GitWriteRequest { /// Omission preserves interactive Pull compatibility. #[serde(default)] pub expected_branch: Option, + /// Exact full object ID reviewed for `deleteBranch`; mandatory with `force`. + /// Core refuses a changed target instead of deleting commits the user did not review. + #[serde(default)] + pub expected_target: Option, #[serde(default)] pub(crate) include_untracked: bool, #[serde(default)] @@ -338,6 +342,7 @@ pub struct GitWriteRequest { /// Exact child commits to record; requires expected_commit_state. #[serde(default)] pub gitlink_updates: Vec, + /// Explicitly discard checkout/worktree changes, or bypass only the branch merge check. #[serde(default)] pub(crate) force: bool, /// Tag scope for push: `none`, `all`, or `reachable`. diff --git a/rust/crates/git/src/write.rs b/rust/crates/git/src/write.rs index e1f8e774..1d8ea2ab 100644 --- a/rust/crates/git/src/write.rs +++ b/rust/crates/git/src/write.rs @@ -289,7 +289,12 @@ fn write_with_trace(request: GitWriteRequest) -> Result { let reference = write_request_reference(&root, &request)?; diff --git a/rust/crates/protocol/src/error.rs b/rust/crates/protocol/src/error.rs index c98ce5f8..6f751e6f 100644 --- a/rust/crates/protocol/src/error.rs +++ b/rust/crates/protocol/src/error.rs @@ -25,6 +25,11 @@ pub enum ErrorCode { ProcessFailed, /// A reviewed pull-request checkout would overwrite or conflict with a local ref. GitBranchExists, + /// Ordinary branch deletion found commits not merged into the upstream or HEAD. + /// Details carries the exact target to review before an explicit forced retry. + GitBranchNotMerged, + /// The branch no longer points at the commit reviewed for deletion. + GitBranchChanged, /// The reviewed checkout or its GitHub origin no longer matches the current repository. GitCheckoutChanged, /// The Git remote refused the credentials, or none were available. Only diff --git a/rust/crates/row-selection/src/lib.rs b/rust/crates/row-selection/src/lib.rs index ff799f59..8f34b056 100644 --- a/rust/crates/row-selection/src/lib.rs +++ b/rust/crates/row-selection/src/lib.rs @@ -3,8 +3,9 @@ //! //! A selection has three parts: the selected row, which the keyboard moves and a plain click //! sets; the rows a Cmd or Ctrl click or a Shift click marked for a batch; and the anchor, the -//! row a Shift click extends from. A Cmd or Ctrl click marks or unmarks one row and makes it -//! the anchor. A Shift click marks every row from the anchor, or from the selected row when +//! row a Shift click extends from. The first Cmd or Ctrl click preserves the visible selected +//! row before toggling the clicked row and making it the anchor. Later clicks toggle one row. +//! A Shift click marks every row from the anchor, or from the selected row when //! there is no anchor, to the clicked one, and leaves the marks it does not cover. A plain //! click selects its row and drops the marks and the anchor. The empty path is the workspace //! root, which is never marked: a batch on the whole workspace is never what a click meant. @@ -160,6 +161,13 @@ fn apply(rows: &[String], selection: &mut Selection, action: Action) -> Option<& if path.is_empty() { return None; } + if selection.marked.is_empty() && selection.anchor.is_none() { + if let Some(selected) = selection.selected.as_ref() { + if !selected.is_empty() && row(selected).is_some() { + selection.marked.insert(selected.clone()); + } + } + } if !selection.marked.remove(&path) { selection.marked.insert(path.clone()); } diff --git a/rust/fixtures/git/branch-delete-v1.json b/rust/fixtures/git/branch-delete-v1.json new file mode 100644 index 00000000..776a1ff2 --- /dev/null +++ b/rust/fixtures/git/branch-delete-v1.json @@ -0,0 +1,8 @@ +{ + "protocolVersion": 1, + "operation": "deleteBranch", + "unmergedCode": "git_branch_not_merged", + "changedCode": "git_branch_changed", + "review": {"name": "backup/before-strip-trailers", "expectedTarget": "0123456789abcdef0123456789abcdef01234567"}, + "forceRequiresExpectedTarget": true +} diff --git a/rust/fixtures/workspace/row-selection-v1.json b/rust/fixtures/workspace/row-selection-v1.json index 9784ff3e..cf871c6b 100644 --- a/rust/fixtures/workspace/row-selection-v1.json +++ b/rust/fixtures/workspace/row-selection-v1.json @@ -1,5 +1,5 @@ { - "description": "workspace.rowSelection.reduce: one click on rows that show workspace paths, such as the project tree and the changes of a change list. A plain click (choose) selects and drops the marks and the anchor; Cmd or Ctrl (toggle) marks or unmarks and sets the anchor; Shift (extend) marks from the anchor, else the selected row, to the clicked row and keeps other marks; clear ends a batch. The empty path is the workspace root and is never marked. targets is what a batch acts on: the marks without those inside a marked folder. Hosts keep focus, painting and the batch itself.", + "description": "workspace.rowSelection.reduce: one click on rows that show workspace paths, such as the project tree and the changes of a change list. A plain click (choose) selects and drops the marks and the anchor; Cmd or Ctrl (toggle) preserves the visible selected row when starting a batch, marks or unmarks the clicked row and sets the anchor; Shift (extend) marks from the anchor, else the selected row, to the clicked row and keeps other marks; clear ends a batch. The empty path is the workspace root and is never marked. targets is what a batch acts on: the marks without those inside a marked folder. Hosts keep focus, painting and the batch itself.", "cases": [ { "name": "a plain click selects its row and drops the marks and the anchor", @@ -83,15 +83,42 @@ "selection": { "selected": "b", "marked": [ + "a", "b" ], "anchor": "b" }, "targets": [ + "a", "b" ] } }, + { + "name": "the first Cmd or Ctrl click on the selected row unselects it", + "request": { + "rows": [ + "", + "a", + "b" + ], + "selection": { + "selected": "a" + }, + "action": { + "kind": "toggle", + "path": "a" + } + }, + "response": { + "selection": { + "selected": "a", + "marked": [], + "anchor": "a" + }, + "targets": [] + } + }, { "name": "a Cmd or Ctrl click on a marked row unmarks it", "request": {