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
14 changes: 14 additions & 0 deletions rust/contracts/application-boundary.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
20 changes: 16 additions & 4 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 '<name>' does not exist`. If the ref deletion succeeds but branch
Expand Down
2 changes: 1 addition & 1 deletion rust/crates/core/src/tests/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
Expand Down
156 changes: 156 additions & 0 deletions rust/crates/core/src/tests/git_branch_delete.rs
Original file line number Diff line number Diff line change
@@ -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
);
}
1 change: 1 addition & 0 deletions rust/crates/core/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
42 changes: 35 additions & 7 deletions rust/crates/git/src/branches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,17 +174,38 @@ pub(crate) fn delete_tag(root: &str, value: Option<&str>) -> Result<GitCommandRe
}

/// Deletes one local branch and returns a structured deletion record so the
/// host can offer a restore. The commit is resolved before the deletion
/// because `git branch -d` diagnostics are localized prose.
pub(crate) fn delete_branch(root: &str, branch: &str) -> Result<GitCommandResponse, CoreError> {
/// 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<GitCommandResponse, CoreError> {
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(
ErrorCode::InvalidRequest,
format!("The branch '{branch}' does not exist"),
)
})?;
ensure_branch_is_safely_deletable(root, branch, &reference, &target)?;
if expected_target.is_some_and(|expected| expected != target) {
return Err(CoreError::new(
ErrorCode::GitBranchChanged,
format!("The branch '{branch}' changed since deletion was reviewed"),
));
}
ensure_branch_is_safely_deletable(root, branch, &reference, &target, force)?;
let mut result = delete_ref_if_unchanged(root, &reference, &target)?;
if result.exit_code == 0 {
result.branch_deletion = Some(GitBranchDeletionResponse {
Expand Down Expand Up @@ -251,12 +272,14 @@ fn delete_ref_if_unchanged(

/// Preserves `git branch -d` safety before the atomic ref mutation: a branch
/// must not be checked out in any worktree and must be merged into its valid
/// upstream, or into HEAD when it has no usable upstream.
/// upstream, or into HEAD when it has no usable upstream. An explicit forced
/// retry bypasses the merge check only, after checking every worktree.
fn ensure_branch_is_safely_deletable(
root: &str,
branch: &str,
reference: &str,
target: &str,
force: bool,
) -> Result<(), CoreError> {
let worktrees = execute_git(
root,
Expand All @@ -280,6 +303,10 @@ fn ensure_branch_is_safely_deletable(
));
}

if force {
return Ok(());
}

let upstream = execute_git(
root,
&[
Expand Down Expand Up @@ -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"),
Expand Down
5 changes: 5 additions & 0 deletions rust/crates/git/src/requests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,10 @@ pub struct GitWriteRequest {
/// Omission preserves interactive Pull compatibility.
#[serde(default)]
pub expected_branch: Option<String>,
/// 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<String>,
#[serde(default)]
pub(crate) include_untracked: bool,
#[serde(default)]
Expand All @@ -338,6 +342,7 @@ pub struct GitWriteRequest {
/// Exact child commits to record; requires expected_commit_state.
#[serde(default)]
pub gitlink_updates: Vec<GitCommitGitlink>,
/// 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`.
Expand Down
7 changes: 6 additions & 1 deletion rust/crates/git/src/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,12 @@ fn write_with_trace(request: GitWriteRequest) -> Result<GitCommandResponse, Core
"The current branch cannot be deleted",
));
}
return delete_branch(&root, &branch);
return delete_branch(
&root,
&branch,
request.force,
request.expected_target.as_deref(),
);
}
"merge" => {
let reference = write_request_reference(&root, &request)?;
Expand Down
5 changes: 5 additions & 0 deletions rust/crates/protocol/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 10 additions & 2 deletions rust/crates/row-selection/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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());
}
Expand Down
8 changes: 8 additions & 0 deletions rust/fixtures/git/branch-delete-v1.json
Original file line number Diff line number Diff line change
@@ -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
}
Loading
Loading