Procházet zdrojové kódy

Add Git branch/history actions to GitApp

Introduces new git manager capabilities for local/remote branch delete/rename and commit-level history actions (checkout, reset, branch/tag creation, revert, cherry-pick, amend), then wires them through AGI bindings and new GitApp backend endpoints. Updates the GitApp UI with branch and commit context menus, tag labels in history, and credential-aware remote branch operations. Also extends git log/branch metadata (commit tags, remote/short branch fields), adds unmerged-branch signaling, refreshes API docs, and adds comprehensive tests plus a .gitignore append regression fix.
Toby Chui před 4 měsíci
rodič
revize
14c044cb68

+ 73 - 2
src/mod/agi/README.md

@@ -2175,12 +2175,47 @@ console.log(status.branch + ": " + status.changes.length + " changed files");
 
 Commits reachable from HEAD, newest first (default limit 50). Each commit has
 `hash`, `shortHash`, `subject`, `message`, `authorName`, `authorEmail`,
-`timestamp` and `parents`.
+`timestamp`, `parents` and `tags` (names of any tags pointing at it).
 
 ### `git.branches(vpath)` → array
 
 Local and remote-tracking branches: `name`, `fullRef`, `hash`, `isRemote`,
-`isCurrent`.
+`isCurrent`, plus `remote` and `short` — for `origin/feature/login` those are
+`origin` and `feature/login`, which is what the branch-management calls below
+expect. For a local branch `short` equals `name` and `remote` is empty.
+
+### `git.deleteBranch(vpath, branch, force)` → object
+
+Delete a local branch. The checked-out branch is never deleted. A branch holding
+commits unreachable from HEAD is refused with `unmerged: true` unless `force` is
+set, mirroring `git branch -d` versus `-D`.
+
+```javascript
+var result = git.deleteBranch("user:/Desktop/myproject", "old-feature", false);
+if (result.unmerged) {
+    // confirm with the user, then retry with force
+    git.deleteBranch("user:/Desktop/myproject", "old-feature", true);
+}
+```
+
+### `git.renameBranch(vpath, oldName, newName)` → object
+
+Rename a local branch. Its upstream configuration moves with it, and HEAD
+follows when the renamed branch is the checked-out one.
+
+### `git.deleteRemoteBranch(vpath, remote, branch, options)` → object
+
+Delete a branch **on the remote** — a network push with an empty source refspec.
+The local remote-tracking ref is pruned too, so the branch stops appearing in
+`git.branches()`. The matching local branch, if any, is left alone. Options:
+`username`, `token`, `remember`.
+
+### `git.renameRemoteBranch(vpath, remote, oldName, newName, options)` → object
+
+Rename a branch on the remote. Git cannot rename a remote ref, so this pushes
+the new name and then deletes the old one — in that order, so an interrupted
+rename leaves the branch under both names rather than losing it. Options:
+`username`, `token`, `remember`.
 
 ### `git.checkout(vpath, branch, create)` → object
 
@@ -2268,6 +2303,42 @@ if (blob.exists) {
 }
 ```
 
+### History actions
+
+Operations on a single commit, used by the GitApp History tab. Each returns
+`{success, error, message}`, and the ones that create a commit also return its
+`hash`.
+
+- `git.checkoutCommit(vpath, hash)` — check the commit out in detached HEAD
+  state. Refuses when the working tree is dirty.
+- `git.resetToCommit(vpath, hash, mode)` — move the current branch to the
+  commit. `mode` is `"soft"`, `"mixed"` (default) or `"hard"`; a hard reset
+  refuses when there are uncommitted changes.
+- `git.createBranchAt(vpath, branch, hash)` — create a branch at the commit and
+  check it out.
+- `git.createTag(vpath, tag, hash, message)` — tag the commit. A non-empty
+  `message` makes an annotated tag, otherwise a lightweight one.
+- `git.revertCommit(vpath, hash, options)` — create a new commit undoing the
+  commit's changes.
+- `git.cherryPickCommit(vpath, hash, options)` — apply the commit's changes onto
+  the current HEAD, preserving the original author.
+- `git.amendMessage(vpath, message, options)` — rewrite the message of the HEAD
+  commit, keeping its tree, parents and author.
+
+Revert and cherry-pick use a **clean-or-refuse** strategy: because go-git has no
+merge engine, a change is applied only when the files it touches still hold the
+exact content it expects. If any file has diverged the whole operation is
+refused with a readable message rather than producing an incorrect result. This
+covers the common cases (reverting the latest commit, or an older commit whose
+files were untouched since) and safely declines the rest.
+
+```javascript
+var result = git.revertCommit("user:/Desktop/myproject", commitHash, {});
+if (!result.success) {
+    console.log(result.error); // e.g. "cannot apply cleanly — …"
+}
+```
+
 ### `git.fetch(vpath, options)` / `git.pull(vpath, options)` / `git.push(vpath, options)` → object
 
 Options: `remote` (default `origin`), `branch` (default the current branch),

+ 283 - 2
src/mod/agi/agi.git.go

@@ -504,6 +504,205 @@ func (g *Gateway) injectGitLibFunctions(payload *static.AgiLibInjectionPayload)
 		return gitJSONValue(vm, files)
 	})
 
+	// git.deleteBranch(vpath, branch, force) -> {success, error, unmerged}
+	vm.Set("_git_deletebranch", func(call otto.FunctionCall) otto.Value {
+		vpath, _ := call.Argument(0).ToString()
+		branch, _ := call.Argument(1).ToString()
+		force, _ := call.Argument(2).ToBoolean()
+
+		rpath, err := resolveRepo(vpath, true)
+		if err != nil {
+			return gitOperationFailure(vm, err)
+		}
+		if err := manager.DeleteBranch(rpath, branch, force); err != nil {
+			return gitOperationFailure(vm, err)
+		}
+		return gitOperationSuccess(vm, "deleted branch "+branch)
+	})
+
+	// git.renameBranch(vpath, oldName, newName) -> {success, error}
+	vm.Set("_git_renamebranch", func(call otto.FunctionCall) otto.Value {
+		vpath, _ := call.Argument(0).ToString()
+		oldName, _ := call.Argument(1).ToString()
+		newName, _ := call.Argument(2).ToString()
+
+		rpath, err := resolveRepo(vpath, true)
+		if err != nil {
+			return gitOperationFailure(vm, err)
+		}
+		if err := manager.RenameBranch(rpath, oldName, newName); err != nil {
+			return gitOperationFailure(vm, err)
+		}
+		return gitOperationSuccess(vm, "renamed to "+newName)
+	})
+
+	// git.deleteRemoteBranch(vpath, remote, branch, options) -> {success, error, authRequired}
+	vm.Set("_git_deleteremotebranch", func(call otto.FunctionCall) otto.Value {
+		vpath, _ := call.Argument(0).ToString()
+		remote, _ := call.Argument(1).ToString()
+		branch, _ := call.Argument(2).ToString()
+		options := exportOptions(call.Argument(3))
+
+		rpath, err := resolveRepo(vpath, true)
+		if err != nil {
+			return gitOperationFailure(vm, err)
+		}
+
+		request, err := g.remoteBranchRequest(u, rpath, remote, options)
+		if err != nil {
+			return gitOperationFailure(vm, err)
+		}
+
+		if err := manager.DeleteRemoteBranch(rpath, remote, branch, request); err != nil {
+			return gitOperationFailure(vm, err)
+		}
+		g.rememberGitCredentialForRemote(u, rpath, remote, options)
+		return gitOperationSuccess(vm, "deleted "+remoteOrOrigin(remote)+"/"+branch)
+	})
+
+	// git.renameRemoteBranch(vpath, remote, oldName, newName, options) -> {success, error, authRequired}
+	vm.Set("_git_renameremotebranch", func(call otto.FunctionCall) otto.Value {
+		vpath, _ := call.Argument(0).ToString()
+		remote, _ := call.Argument(1).ToString()
+		oldName, _ := call.Argument(2).ToString()
+		newName, _ := call.Argument(3).ToString()
+		options := exportOptions(call.Argument(4))
+
+		rpath, err := resolveRepo(vpath, true)
+		if err != nil {
+			return gitOperationFailure(vm, err)
+		}
+
+		request, err := g.remoteBranchRequest(u, rpath, remote, options)
+		if err != nil {
+			return gitOperationFailure(vm, err)
+		}
+
+		if err := manager.RenameRemoteBranch(rpath, remote, oldName, newName, request); err != nil {
+			return gitOperationFailure(vm, err)
+		}
+		g.rememberGitCredentialForRemote(u, rpath, remote, options)
+		return gitOperationSuccess(vm, "renamed to "+remoteOrOrigin(remote)+"/"+newName)
+	})
+
+	// git.checkoutCommit(vpath, hash) -> {success, error}
+	vm.Set("_git_checkoutcommit", func(call otto.FunctionCall) otto.Value {
+		vpath, _ := call.Argument(0).ToString()
+		hash, _ := call.Argument(1).ToString()
+
+		rpath, err := resolveRepo(vpath, true)
+		if err != nil {
+			return gitOperationFailure(vm, err)
+		}
+		if err := manager.CheckoutCommit(rpath, hash); err != nil {
+			return gitOperationFailure(vm, err)
+		}
+		return gitOperationSuccess(vm, "checked out "+shortHash(hash))
+	})
+
+	// git.resetToCommit(vpath, hash, mode) -> {success, error}
+	vm.Set("_git_resettocommit", func(call otto.FunctionCall) otto.Value {
+		vpath, _ := call.Argument(0).ToString()
+		hash, _ := call.Argument(1).ToString()
+		mode, _ := call.Argument(2).ToString()
+
+		rpath, err := resolveRepo(vpath, true)
+		if err != nil {
+			return gitOperationFailure(vm, err)
+		}
+		if err := manager.ResetToCommit(rpath, hash, mode); err != nil {
+			return gitOperationFailure(vm, err)
+		}
+		return gitOperationSuccess(vm, "reset to "+shortHash(hash))
+	})
+
+	// git.createBranchAt(vpath, branch, hash) -> {success, error}
+	vm.Set("_git_createbranchat", func(call otto.FunctionCall) otto.Value {
+		vpath, _ := call.Argument(0).ToString()
+		branch, _ := call.Argument(1).ToString()
+		hash, _ := call.Argument(2).ToString()
+
+		rpath, err := resolveRepo(vpath, true)
+		if err != nil {
+			return gitOperationFailure(vm, err)
+		}
+		if err := manager.CreateBranchAt(rpath, branch, hash); err != nil {
+			return gitOperationFailure(vm, err)
+		}
+		return gitOperationSuccess(vm, "created branch "+branch)
+	})
+
+	// git.createTag(vpath, tag, hash, message) -> {success, error}
+	vm.Set("_git_createtag", func(call otto.FunctionCall) otto.Value {
+		vpath, _ := call.Argument(0).ToString()
+		tag, _ := call.Argument(1).ToString()
+		hash, _ := call.Argument(2).ToString()
+		message, _ := call.Argument(3).ToString()
+
+		rpath, err := resolveRepo(vpath, true)
+		if err != nil {
+			return gitOperationFailure(vm, err)
+		}
+		if err := manager.CreateTag(rpath, tag, hash, message, u.Username, ""); err != nil {
+			return gitOperationFailure(vm, err)
+		}
+		return gitOperationSuccess(vm, "created tag "+tag)
+	})
+
+	// git.revertCommit(vpath, hash, options) -> {success, error, hash}
+	vm.Set("_git_revertcommit", func(call otto.FunctionCall) otto.Value {
+		vpath, _ := call.Argument(0).ToString()
+		hash, _ := call.Argument(1).ToString()
+		options := exportOptions(call.Argument(2))
+
+		rpath, err := resolveRepo(vpath, true)
+		if err != nil {
+			return gitOperationFailure(vm, err)
+		}
+
+		newHash, err := manager.RevertCommit(rpath, hash, commitRequestFromOptions(u, options))
+		if err != nil {
+			return gitOperationFailure(vm, err)
+		}
+		return gitJSONValue(vm, git.OperationResult{Success: true, Hash: newHash, Message: "reverted " + shortHash(hash)})
+	})
+
+	// git.cherryPickCommit(vpath, hash, options) -> {success, error, hash}
+	vm.Set("_git_cherrypickcommit", func(call otto.FunctionCall) otto.Value {
+		vpath, _ := call.Argument(0).ToString()
+		hash, _ := call.Argument(1).ToString()
+		options := exportOptions(call.Argument(2))
+
+		rpath, err := resolveRepo(vpath, true)
+		if err != nil {
+			return gitOperationFailure(vm, err)
+		}
+
+		newHash, err := manager.CherryPickCommit(rpath, hash, commitRequestFromOptions(u, options))
+		if err != nil {
+			return gitOperationFailure(vm, err)
+		}
+		return gitJSONValue(vm, git.OperationResult{Success: true, Hash: newHash, Message: "cherry-picked " + shortHash(hash)})
+	})
+
+	// git.amendMessage(vpath, message, options) -> {success, error, hash}
+	vm.Set("_git_amendmessage", func(call otto.FunctionCall) otto.Value {
+		vpath, _ := call.Argument(0).ToString()
+		message, _ := call.Argument(1).ToString()
+		options := exportOptions(call.Argument(2))
+
+		rpath, err := resolveRepo(vpath, true)
+		if err != nil {
+			return gitOperationFailure(vm, err)
+		}
+
+		newHash, err := manager.AmendCommitMessage(rpath, message, commitRequestFromOptions(u, options))
+		if err != nil {
+			return gitOperationFailure(vm, err)
+		}
+		return gitJSONValue(vm, git.OperationResult{Success: true, Hash: newHash, Message: "amended commit message"})
+	})
+
 	// git.fetch(vpath, options) -> {success, error, authRequired}
 	vm.Set("_git_fetch", func(call otto.FunctionCall) otto.Value {
 		return g.runGitTransport(vm, u, call, resolveRepo, func(rpath string, request *git.TransportRequest) (string, error) {
@@ -628,6 +827,17 @@ const gitLibJavaScript = `
 		git.diffCommit = function(vpath, hash, file) { return _git_parse(_git_diffcommit(vpath, hash, file)); };
 		git.commitFiles = function(vpath, hash) { return _git_parse(_git_commitfiles(vpath, hash)); };
 		git.fileBlob = function(vpath, file, revision) { return _git_parse(_git_fileblob(vpath, file, revision || "HEAD")); };
+		git.deleteBranch = function(vpath, branch, force) { return _git_parse(_git_deletebranch(vpath, branch, force === true)); };
+		git.renameBranch = function(vpath, oldName, newName) { return _git_parse(_git_renamebranch(vpath, oldName, newName)); };
+		git.deleteRemoteBranch = function(vpath, remote, branch, options) { return _git_parse(_git_deleteremotebranch(vpath, remote || "origin", branch, options || {})); };
+		git.renameRemoteBranch = function(vpath, remote, oldName, newName, options) { return _git_parse(_git_renameremotebranch(vpath, remote || "origin", oldName, newName, options || {})); };
+		git.checkoutCommit = function(vpath, hash) { return _git_parse(_git_checkoutcommit(vpath, hash)); };
+		git.resetToCommit = function(vpath, hash, mode) { return _git_parse(_git_resettocommit(vpath, hash, mode || "mixed")); };
+		git.createBranchAt = function(vpath, branch, hash) { return _git_parse(_git_createbranchat(vpath, branch, hash)); };
+		git.createTag = function(vpath, tag, hash, message) { return _git_parse(_git_createtag(vpath, tag, hash, message || "")); };
+		git.revertCommit = function(vpath, hash, options) { return _git_parse(_git_revertcommit(vpath, hash, options || {})); };
+		git.cherryPickCommit = function(vpath, hash, options) { return _git_parse(_git_cherrypickcommit(vpath, hash, options || {})); };
+		git.amendMessage = function(vpath, message, options) { return _git_parse(_git_amendmessage(vpath, message, options || {})); };
 		git.fetch = function(vpath, options) { return _git_parse(_git_fetch(vpath, options || {})); };
 		git.pull = function(vpath, options) { return _git_parse(_git_pull(vpath, options || {})); };
 		git.push = function(vpath, options) { return _git_parse(_git_push(vpath, options || {})); };
@@ -678,6 +888,75 @@ func (g *Gateway) runGitTransport(vm *otto.Otto, u *user.User, call otto.Functio
 	return gitOperationSuccess(vm, message)
 }
 
+/*
+remoteBranchRequest builds the TransportRequest for a remote branch operation,
+resolving which credential applies from the remote's own URL.
+
+The remote-branch calls take the remote by name rather than by URL, so the URL
+has to be looked up before the stored credential can be found.
+*/
+func (g *Gateway) remoteBranchRequest(u *user.User, rpath string, remote string, options map[string]interface{}) (*git.TransportRequest, error) {
+	remoteURL, err := g.Option.GitManager.RemoteURLForName(rpath, remote)
+	if err != nil {
+		return nil, err
+	}
+
+	username, token := g.resolveGitCredential(u, remoteURL, options)
+	return &git.TransportRequest{
+		Remote:   remote,
+		Username: username,
+		Token:    token,
+	}, nil
+}
+
+// rememberGitCredentialForRemote stores a credential that has just proven itself
+// against a remote addressed by name.
+func (g *Gateway) rememberGitCredentialForRemote(u *user.User, rpath string, remote string, options map[string]interface{}) {
+	if !optionBool(options, "remember") {
+		return
+	}
+	remoteURL, err := g.Option.GitManager.RemoteURLForName(rpath, remote)
+	if err != nil {
+		return
+	}
+	g.rememberGitCredential(u, remoteURL, options)
+}
+
+// remoteOrOrigin mirrors the manager's default so status messages name the same
+// remote the operation actually used.
+func remoteOrOrigin(remote string) string {
+	remote = strings.TrimSpace(remote)
+	if remote == "" {
+		return "origin"
+	}
+	return remote
+}
+
+// commitRequestFromOptions builds a CommitRequest for the history actions,
+// defaulting the author name to the calling user so a commit always has an
+// identity even when the front-end sends none.
+func commitRequestFromOptions(u *user.User, options map[string]interface{}) *git.CommitRequest {
+	name := optionString(options, "name")
+	if name == "" && u != nil {
+		name = u.Username
+	}
+	return &git.CommitRequest{
+		Message: optionString(options, "message"),
+		Name:    name,
+		Email:   optionString(options, "email"),
+	}
+}
+
+// shortHash abbreviates a commit hash for status messages, tolerating a hash
+// that is already short.
+func shortHash(hash string) string {
+	hash = strings.TrimSpace(hash)
+	if len(hash) > 7 {
+		return hash[:7]
+	}
+	return hash
+}
+
 // gitCredentialStore returns the credential store or a readable error when git
 // support was started without a database.
 func (g *Gateway) gitCredentialStore() (*git.CredentialStore, error) {
@@ -861,13 +1140,15 @@ func gitOperationSuccess(vm *otto.Otto, message string) otto.Value {
 	})
 }
 
-// gitOperationFailure builds the standard failure envelope, flagging
-// credential problems so the front-end knows to open its sign-in dialog.
+// gitOperationFailure builds the standard failure envelope, flagging credential
+// problems so the front-end knows to open its sign-in dialog, and an unmerged
+// branch so it can offer to delete anyway.
 func gitOperationFailure(vm *otto.Otto, err error) otto.Value {
 	return gitJSONValue(vm, git.OperationResult{
 		Success:      false,
 		Error:        err.Error(),
 		AuthRequired: errors.Is(err, git.ErrAuthRequired),
+		Unmerged:     errors.Is(err, git.ErrUnmergedBranch),
 	})
 }
 

+ 17 - 2
src/mod/agi/agi.git_test.go

@@ -500,7 +500,10 @@ func TestGitLibJavaScriptWrapper(t *testing.T) {
 		"_git_add", "_git_addall", "_git_unstage", "_git_discard", "_git_commit",
 		"_git_diff", "_git_diffcommit", "_git_commitfiles", "_git_fetch",
 		"_git_pull", "_git_push", "_git_savecredential", "_git_listcredentials",
-		"_git_removecredential", "_git_ignore",
+		"_git_removecredential", "_git_ignore", "_git_fileblob",
+		"_git_checkoutcommit", "_git_resettocommit", "_git_createbranchat",
+		"_git_createtag", "_git_revertcommit", "_git_cherrypickcommit", "_git_amendmessage",
+		"_git_deletebranch", "_git_renamebranch", "_git_deleteremotebranch", "_git_renameremotebranch",
 	}
 	for _, native := range natives {
 		name := native
@@ -539,6 +542,17 @@ func TestGitLibJavaScriptWrapper(t *testing.T) {
 		{name: "diff", expression: `git.diff("user:/repo", "a.txt").message`},
 		{name: "diffCommit", expression: `git.diffCommit("user:/repo", "abc", "a.txt").message`},
 		{name: "commitFiles", expression: `git.commitFiles("user:/repo", "abc").message`},
+		{name: "deleteBranch", expression: `git.deleteBranch("user:/repo", "old", true).message`},
+		{name: "renameBranch", expression: `git.renameBranch("user:/repo", "old", "new").message`},
+		{name: "deleteRemoteBranch", expression: `git.deleteRemoteBranch("user:/repo", "origin", "old").message`},
+		{name: "renameRemoteBranch", expression: `git.renameRemoteBranch("user:/repo", "origin", "old", "new").message`},
+		{name: "checkoutCommit", expression: `git.checkoutCommit("user:/repo", "abc").message`},
+		{name: "resetToCommit", expression: `git.resetToCommit("user:/repo", "abc", "hard").message`},
+		{name: "createBranchAt", expression: `git.createBranchAt("user:/repo", "legacy", "abc").message`},
+		{name: "createTag", expression: `git.createTag("user:/repo", "v1", "abc", "msg").message`},
+		{name: "revertCommit", expression: `git.revertCommit("user:/repo", "abc").message`},
+		{name: "cherryPickCommit", expression: `git.cherryPickCommit("user:/repo", "abc").message`},
+		{name: "amendMessage", expression: `git.amendMessage("user:/repo", "new msg").message`},
 		{name: "fetch", expression: `git.fetch("user:/repo").message`},
 		{name: "pull", expression: `git.pull("user:/repo").message`},
 		{name: "push", expression: `git.push("user:/repo").message`},
@@ -583,7 +597,8 @@ func TestGitLibJavaScriptHandlesMalformedNativeResponse(t *testing.T) {
 		"_git_addremote", "_git_removeremote", "_git_add", "_git_addall", "_git_unstage",
 		"_git_discard", "_git_commit", "_git_ignore", "_git_diff", "_git_diffcommit", "_git_commitfiles",
 		"_git_fetch", "_git_pull", "_git_push", "_git_savecredential", "_git_listcredentials",
-		"_git_removecredential"} {
+		"_git_removecredential", "_git_deletebranch", "_git_renamebranch",
+		"_git_deleteremotebranch", "_git_renameremotebranch"} {
 		vm.Set(name, func(call otto.FunctionCall) otto.Value { return otto.FalseValue() })
 	}
 

+ 326 - 0
src/mod/git/branch_actions.go

@@ -0,0 +1,326 @@
+package git
+
+/*
+	branch_actions.go
+
+	Deleting and renaming branches, both local and on a remote.
+
+	Local operations are pure ref manipulation. Remote ones are network pushes:
+	a delete is a push with an empty source refspec, and a rename is a push of
+	the new name followed by a delete of the old, because git has no notion of
+	renaming a ref on a server. That two-step is done in the safe order — the new
+	name is created first — so a failure never leaves the branch missing.
+*/
+
+import (
+	"errors"
+	"strings"
+
+	gogit "github.com/go-git/go-git/v5"
+	"github.com/go-git/go-git/v5/config"
+	"github.com/go-git/go-git/v5/plumbing"
+)
+
+const (
+	//branchRefPrefix is the ref namespace holding local branches.
+	branchRefPrefix = "refs/heads/"
+
+	//remoteRefPrefix is the ref namespace holding remote-tracking branches.
+	remoteRefPrefix = "refs/remotes/"
+)
+
+// DeleteBranch removes a local branch.
+//
+// The checked-out branch is never deleted. A branch holding commits that are not
+// reachable from HEAD returns ErrUnmergedBranch unless force is set, so the
+// caller can confirm before losing work — the same protection `git branch -d`
+// gives over `-D`.
+func (m *Manager) DeleteBranch(realpath string, branch string, force bool) error {
+	branch = strings.TrimSpace(branch)
+	if err := validateBranchName(branch); err != nil {
+		return err
+	}
+
+	repo, err := m.open(realpath)
+	if err != nil {
+		return err
+	}
+
+	referenceName := plumbing.NewBranchReferenceName(branch)
+	branchRef, err := repo.Reference(referenceName, false)
+	if err != nil {
+		return errors.New("no such local branch: " + branch)
+	}
+
+	if head, herr := repo.Head(); herr == nil && head.Name() == referenceName {
+		return errors.New("cannot delete " + branch + " because it is the current branch — switch to another branch first")
+	}
+
+	if !force {
+		merged, cerr := branchIsMerged(repo, branchRef.Hash())
+		//A failed reachability check is not a reason to block the delete; only a
+		//definite "not merged" answer is.
+		if cerr == nil && !merged {
+			return ErrUnmergedBranch
+		}
+	}
+
+	if err := repo.Storer.RemoveReference(referenceName); err != nil {
+		return err
+	}
+
+	//Drop the tracking configuration so a future branch reusing the name does
+	//not silently inherit this one's upstream.
+	removeBranchConfig(repo, branch)
+	return nil
+}
+
+// RenameBranch renames a local branch, carrying its upstream configuration over
+// and following HEAD when the renamed branch is the checked-out one.
+func (m *Manager) RenameBranch(realpath string, oldName string, newName string) error {
+	oldName = strings.TrimSpace(oldName)
+	newName = strings.TrimSpace(newName)
+
+	if err := validateBranchName(oldName); err != nil {
+		return err
+	}
+	if err := validateBranchName(newName); err != nil {
+		return err
+	}
+	if oldName == newName {
+		return errors.New("the new name is the same as the current one")
+	}
+
+	repo, err := m.open(realpath)
+	if err != nil {
+		return err
+	}
+
+	oldReferenceName := plumbing.NewBranchReferenceName(oldName)
+	newReferenceName := plumbing.NewBranchReferenceName(newName)
+
+	oldRef, err := repo.Reference(oldReferenceName, false)
+	if err != nil {
+		return errors.New("no such local branch: " + oldName)
+	}
+	if _, err := repo.Reference(newReferenceName, false); err == nil {
+		return errors.New("a branch named " + newName + " already exists")
+	}
+
+	//Whether this is the current branch has to be settled before the old ref
+	//disappears, otherwise HEAD can no longer be resolved.
+	isCurrent := false
+	if head, herr := repo.Head(); herr == nil && head.Name() == oldReferenceName {
+		isCurrent = true
+	}
+
+	if err := repo.Storer.SetReference(plumbing.NewHashReference(newReferenceName, oldRef.Hash())); err != nil {
+		return err
+	}
+
+	moveBranchConfig(repo, oldName, newName)
+
+	if isCurrent {
+		if err := repo.Storer.SetReference(plumbing.NewSymbolicReference(plumbing.HEAD, newReferenceName)); err != nil {
+			return err
+		}
+	}
+
+	return repo.Storer.RemoveReference(oldReferenceName)
+}
+
+// DeleteRemoteBranch deletes a branch on the remote and prunes the local
+// remote-tracking ref so it stops showing in the branch list.
+func (m *Manager) DeleteRemoteBranch(realpath string, remote string, branch string, req *TransportRequest) error {
+	branch = strings.TrimSpace(branch)
+	if err := validateBranchName(branch); err != nil {
+		return err
+	}
+	if req == nil {
+		req = &TransportRequest{}
+	}
+	remote = remoteOrName(remote)
+
+	repo, err := m.open(realpath)
+	if err != nil {
+		return err
+	}
+	if _, rerr := repo.Remote(remote); rerr != nil {
+		return ErrNoRemote
+	}
+
+	//An empty source is git's "delete this ref on the remote" refspec
+	err = repo.Push(&gogit.PushOptions{
+		RemoteName: remote,
+		RefSpecs:   []config.RefSpec{config.RefSpec(":" + branchRefPrefix + branch)},
+		Auth:       buildAuth(req.Username, req.Token),
+	})
+	if err != nil && !errors.Is(err, gogit.NoErrAlreadyUpToDate) {
+		return classifyError(err)
+	}
+
+	//Pruning is best effort: the branch is already gone on the server, so a
+	//stale local pointer must not turn a success into a failure.
+	repo.Storer.RemoveReference(plumbing.NewRemoteReferenceName(remote, branch))
+	return nil
+}
+
+/*
+RenameRemoteBranch renames a branch on the remote.
+
+Git cannot rename a remote ref, so this pushes the branch under its new name and
+then deletes the old one. The order matters: if the second push fails the branch
+still exists under both names, which is recoverable, whereas deleting first could
+lose it entirely.
+*/
+func (m *Manager) RenameRemoteBranch(realpath string, remote string, oldName string, newName string, req *TransportRequest) error {
+	oldName = strings.TrimSpace(oldName)
+	newName = strings.TrimSpace(newName)
+
+	if err := validateBranchName(oldName); err != nil {
+		return err
+	}
+	if err := validateBranchName(newName); err != nil {
+		return err
+	}
+	if oldName == newName {
+		return errors.New("the new name is the same as the current one")
+	}
+	if req == nil {
+		req = &TransportRequest{}
+	}
+	remote = remoteOrName(remote)
+
+	repo, err := m.open(realpath)
+	if err != nil {
+		return err
+	}
+	if _, rerr := repo.Remote(remote); rerr != nil {
+		return ErrNoRemote
+	}
+
+	//The remote-tracking ref is the local record of what the remote holds, and
+	//is a valid push source.
+	sourceName := plumbing.NewRemoteReferenceName(remote, oldName)
+	if _, rerr := repo.Reference(sourceName, false); rerr != nil {
+		return errors.New("no such branch on " + remote + ": " + oldName)
+	}
+
+	auth := buildAuth(req.Username, req.Token)
+
+	err = repo.Push(&gogit.PushOptions{
+		RemoteName: remote,
+		RefSpecs:   []config.RefSpec{config.RefSpec(sourceName.String() + ":" + branchRefPrefix + newName)},
+		Auth:       auth,
+	})
+	if err != nil && !errors.Is(err, gogit.NoErrAlreadyUpToDate) {
+		return classifyError(err)
+	}
+
+	//The new name now exists on the server; remove the old one.
+	err = repo.Push(&gogit.PushOptions{
+		RemoteName: remote,
+		RefSpecs:   []config.RefSpec{config.RefSpec(":" + branchRefPrefix + oldName)},
+		Auth:       auth,
+	})
+	if err != nil && !errors.Is(err, gogit.NoErrAlreadyUpToDate) {
+		return errors.New(newName + " was created on " + remote +
+			", but the old branch could not be removed: " + err.Error())
+	}
+
+	//Mirror the change locally so the branch list is correct without a fetch
+	if oldRef, rerr := repo.Reference(sourceName, false); rerr == nil {
+		repo.Storer.SetReference(plumbing.NewHashReference(
+			plumbing.NewRemoteReferenceName(remote, newName), oldRef.Hash()))
+		repo.Storer.RemoveReference(sourceName)
+	}
+
+	return nil
+}
+
+// branchIsMerged reports whether a branch tip is reachable from HEAD, i.e. its
+// commits are already contained in the current branch.
+func branchIsMerged(repo *gogit.Repository, branchHash plumbing.Hash) (bool, error) {
+	head, err := repo.Head()
+	if err != nil {
+		//Nothing checked out to compare against
+		return false, err
+	}
+	if head.Hash() == branchHash {
+		return true, nil
+	}
+
+	//The walk is bounded (see maxAheadBehindWalk), so on a very large history a
+	//long-since-merged branch may be reported as unmerged. That only costs the
+	//user a confirmation prompt, never data.
+	reachable, err := ancestorSet(repo, head.Hash())
+	if err != nil {
+		return false, err
+	}
+
+	_, merged := reachable[branchHash]
+	return merged, nil
+}
+
+// removeBranchConfig deletes a branch's tracking configuration.
+func removeBranchConfig(repo *gogit.Repository, branch string) {
+	cfg, err := repo.Config()
+	if err != nil || cfg.Branches == nil {
+		return
+	}
+	if _, ok := cfg.Branches[branch]; !ok {
+		return
+	}
+
+	delete(cfg.Branches, branch)
+	repo.SetConfig(cfg)
+}
+
+// moveBranchConfig re-keys a branch's tracking configuration under a new name.
+func moveBranchConfig(repo *gogit.Repository, oldName string, newName string) {
+	cfg, err := repo.Config()
+	if err != nil || cfg.Branches == nil {
+		return
+	}
+
+	branchCfg, ok := cfg.Branches[oldName]
+	if !ok {
+		return
+	}
+
+	renamed := *branchCfg
+	renamed.Name = newName
+	cfg.Branches[newName] = &renamed
+	delete(cfg.Branches, oldName)
+
+	if err := cfg.Validate(); err != nil {
+		//A config that will not validate must not be written back
+		return
+	}
+	repo.SetConfig(cfg)
+}
+
+// splitRemoteRef breaks a remote-tracking ref into its remote and branch parts.
+// "refs/remotes/origin/feature/login" yields ("origin", "feature/login").
+func splitRemoteRef(fullRef string) (string, string) {
+	trimmed := strings.TrimPrefix(fullRef, remoteRefPrefix)
+	if trimmed == fullRef {
+		//Not a remote-tracking ref
+		return "", strings.TrimPrefix(fullRef, branchRefPrefix)
+	}
+
+	parts := strings.SplitN(trimmed, "/", 2)
+	if len(parts) != 2 {
+		return "", trimmed
+	}
+	return parts[0], parts[1]
+}
+
+// remoteOrName defaults a remote name to "origin".
+func remoteOrName(remote string) string {
+	remote = strings.TrimSpace(remote)
+	if remote == "" {
+		return defaultRemote
+	}
+	return remote
+}

+ 587 - 0
src/mod/git/branch_actions_test.go

@@ -0,0 +1,587 @@
+package git
+
+import (
+	"errors"
+	"path/filepath"
+	"testing"
+
+	gogit "github.com/go-git/go-git/v5"
+	"github.com/go-git/go-git/v5/plumbing"
+)
+
+// newBareRemote creates an empty bare repository to act as a push target, so the
+// network code paths (delete / rename on a remote) can be exercised without a
+// real server.
+func newBareRemote(t *testing.T) string {
+	t.Helper()
+
+	path := filepath.Join(t.TempDir(), "remote.git")
+	if _, err := gogit.PlainInit(path, true); err != nil {
+		t.Fatalf("cannot create the bare remote: %v", err)
+	}
+	return path
+}
+
+// bareHasBranch reports whether the bare repository holds a given branch.
+func bareHasBranch(t *testing.T, barePath string, branch string) bool {
+	t.Helper()
+
+	repo, err := gogit.PlainOpen(barePath)
+	if err != nil {
+		t.Fatalf("cannot open the bare remote: %v", err)
+	}
+	_, err = repo.Reference(plumbing.NewBranchReferenceName(branch), false)
+	return err == nil
+}
+
+// hasLocalRef reports whether a reference exists in a working repository.
+func hasLocalRef(t *testing.T, manager *Manager, repoPath string, name plumbing.ReferenceName) bool {
+	t.Helper()
+
+	repo, err := manager.open(repoPath)
+	if err != nil {
+		t.Fatalf("open() returned error: %v", err)
+	}
+	_, err = repo.Reference(name, false)
+	return err == nil
+}
+
+/*
+newRepoWithRemote builds a working repository wired to a fresh bare remote, with
+master pushed and a second branch pushed under the given name. It returns the
+working repository path, the bare remote path and the default branch name.
+*/
+func newRepoWithRemote(t *testing.T, manager *Manager, extraBranch string) (string, string, string) {
+	t.Helper()
+
+	bare := newBareRemote(t)
+	repoPath := newTestRepo(t, manager)
+	commitFile(t, manager, repoPath, "a.txt", "one\n", "first")
+
+	if err := manager.AddRemote(repoPath, "origin", bare); err != nil {
+		t.Fatalf("AddRemote() returned error: %v", err)
+	}
+
+	branches, _ := manager.Branches(repoPath)
+	defaultBranch := branches[0].Name
+
+	if _, err := manager.Push(repoPath, &TransportRequest{SetUpstream: true}); err != nil {
+		t.Fatalf("Push() of the default branch returned error: %v", err)
+	}
+
+	if extraBranch != "" {
+		if err := manager.Checkout(repoPath, extraBranch, true); err != nil {
+			t.Fatalf("Checkout(create %s) returned error: %v", extraBranch, err)
+		}
+		commitFile(t, manager, repoPath, "b.txt", "two\n", "on "+extraBranch)
+
+		if _, err := manager.Push(repoPath, &TransportRequest{SetUpstream: true}); err != nil {
+			t.Fatalf("Push() of %s returned error: %v", extraBranch, err)
+		}
+		//Return to the default branch so the extra one can be operated on
+		if err := manager.Checkout(repoPath, defaultBranch, false); err != nil {
+			t.Fatalf("Checkout(%s) returned error: %v", defaultBranch, err)
+		}
+	}
+
+	return repoPath, bare, defaultBranch
+}
+
+/* ── Local branch deletion ────────────────────────────────────────────── */
+
+func TestDeleteBranchRemovesMergedBranch(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	commitFile(t, manager, repoPath, "a.txt", "one\n", "first")
+
+	branches, _ := manager.Branches(repoPath)
+	defaultBranch := branches[0].Name
+
+	//A branch created at HEAD with no extra commits is fully merged
+	if err := manager.Checkout(repoPath, "scratch", true); err != nil {
+		t.Fatalf("Checkout(create) returned error: %v", err)
+	}
+	if err := manager.Checkout(repoPath, defaultBranch, false); err != nil {
+		t.Fatalf("Checkout(back) returned error: %v", err)
+	}
+
+	if err := manager.DeleteBranch(repoPath, "scratch", false); err != nil {
+		t.Fatalf("DeleteBranch() returned error: %v", err)
+	}
+
+	if hasLocalRef(t, manager, repoPath, plumbing.NewBranchReferenceName("scratch")) {
+		t.Errorf("the branch ref still exists after DeleteBranch()")
+	}
+
+	after, _ := manager.Branches(repoPath)
+	for _, branch := range after {
+		if branch.Name == "scratch" {
+			t.Errorf("Branches() still lists the deleted branch")
+		}
+	}
+}
+
+func TestDeleteBranchRefusesCurrentBranch(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	commitFile(t, manager, repoPath, "a.txt", "one\n", "first")
+
+	branches, _ := manager.Branches(repoPath)
+	current := branches[0].Name
+
+	if err := manager.DeleteBranch(repoPath, current, false); err == nil {
+		t.Errorf("DeleteBranch() on the current branch = nil error, want a refusal")
+	}
+	//Even forcing must not remove the branch HEAD points at
+	if err := manager.DeleteBranch(repoPath, current, true); err == nil {
+		t.Errorf("DeleteBranch(force) on the current branch = nil error, want a refusal")
+	}
+	if !hasLocalRef(t, manager, repoPath, plumbing.NewBranchReferenceName(current)) {
+		t.Errorf("the current branch was deleted despite the refusal")
+	}
+}
+
+func TestDeleteBranchUnmergedNeedsForce(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	commitFile(t, manager, repoPath, "a.txt", "one\n", "first")
+
+	branches, _ := manager.Branches(repoPath)
+	defaultBranch := branches[0].Name
+
+	//A commit that exists only on the feature branch makes it unmerged
+	if err := manager.Checkout(repoPath, "feature", true); err != nil {
+		t.Fatalf("Checkout(create) returned error: %v", err)
+	}
+	commitFile(t, manager, repoPath, "feature.txt", "work\n", "feature work")
+	if err := manager.Checkout(repoPath, defaultBranch, false); err != nil {
+		t.Fatalf("Checkout(back) returned error: %v", err)
+	}
+
+	err := manager.DeleteBranch(repoPath, "feature", false)
+	if !errors.Is(err, ErrUnmergedBranch) {
+		t.Fatalf("DeleteBranch() of an unmerged branch = %v, want ErrUnmergedBranch", err)
+	}
+	if !hasLocalRef(t, manager, repoPath, plumbing.NewBranchReferenceName("feature")) {
+		t.Fatalf("the branch was deleted even though the call was refused")
+	}
+
+	//Forcing must go through
+	if err := manager.DeleteBranch(repoPath, "feature", true); err != nil {
+		t.Fatalf("DeleteBranch(force) returned error: %v", err)
+	}
+	if hasLocalRef(t, manager, repoPath, plumbing.NewBranchReferenceName("feature")) {
+		t.Errorf("the branch survived a forced delete")
+	}
+}
+
+func TestDeleteBranchDropsTrackingConfig(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath, _, defaultBranch := newRepoWithRemote(t, manager, "feature")
+
+	repo, err := manager.open(repoPath)
+	if err != nil {
+		t.Fatalf("open() returned error: %v", err)
+	}
+	cfg, _ := repo.Config()
+	if _, ok := cfg.Branches["feature"]; !ok {
+		t.Fatalf("the pushed branch has no tracking config to begin with")
+	}
+
+	//Force is needed: the feature branch carries its own commit
+	if defaultBranch == "feature" {
+		t.Fatalf("unexpected default branch name for this test")
+	}
+	if err := manager.DeleteBranch(repoPath, "feature", true); err != nil {
+		t.Fatalf("DeleteBranch() returned error: %v", err)
+	}
+
+	repo, _ = manager.open(repoPath)
+	cfg, _ = repo.Config()
+	if _, ok := cfg.Branches["feature"]; ok {
+		t.Errorf("the tracking config survived the branch delete")
+	}
+}
+
+func TestDeleteBranchValidation(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	commitFile(t, manager, repoPath, "a.txt", "one\n", "first")
+
+	tests := []struct {
+		name   string
+		branch string
+	}{
+		{name: "no such branch", branch: "nonexistent"},
+		{name: "empty name", branch: ""},
+		{name: "invalid name", branch: "bad name"},
+	}
+
+	for _, test := range tests {
+		t.Run(test.name, func(t *testing.T) {
+			if err := manager.DeleteBranch(repoPath, test.branch, false); err == nil {
+				t.Errorf("DeleteBranch(%q) = nil error, want an error", test.branch)
+			}
+		})
+	}
+}
+
+/* ── Local branch rename ──────────────────────────────────────────────── */
+
+func TestRenameBranchNotCurrent(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	commitFile(t, manager, repoPath, "a.txt", "one\n", "first")
+
+	branches, _ := manager.Branches(repoPath)
+	defaultBranch := branches[0].Name
+
+	if err := manager.Checkout(repoPath, "old-name", true); err != nil {
+		t.Fatalf("Checkout(create) returned error: %v", err)
+	}
+	if err := manager.Checkout(repoPath, defaultBranch, false); err != nil {
+		t.Fatalf("Checkout(back) returned error: %v", err)
+	}
+
+	if err := manager.RenameBranch(repoPath, "old-name", "new-name"); err != nil {
+		t.Fatalf("RenameBranch() returned error: %v", err)
+	}
+
+	if hasLocalRef(t, manager, repoPath, plumbing.NewBranchReferenceName("old-name")) {
+		t.Errorf("the old branch ref still exists")
+	}
+	if !hasLocalRef(t, manager, repoPath, plumbing.NewBranchReferenceName("new-name")) {
+		t.Errorf("the new branch ref was not created")
+	}
+
+	//The current branch must not have changed
+	status, _ := manager.Status(repoPath)
+	if status.Branch != defaultBranch {
+		t.Errorf("current branch = %q, want %q", status.Branch, defaultBranch)
+	}
+}
+
+func TestRenameCurrentBranchFollowsHead(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	commitFile(t, manager, repoPath, "a.txt", "one\n", "first")
+
+	branches, _ := manager.Branches(repoPath)
+	current := branches[0].Name
+
+	if err := manager.RenameBranch(repoPath, current, "renamed-main"); err != nil {
+		t.Fatalf("RenameBranch() returned error: %v", err)
+	}
+
+	status, err := manager.Status(repoPath)
+	if err != nil {
+		t.Fatalf("Status() returned error: %v", err)
+	}
+	if status.Branch != "renamed-main" {
+		t.Errorf("current branch = %q, want %q", status.Branch, "renamed-main")
+	}
+	if status.Detached {
+		t.Errorf("HEAD became detached after renaming the current branch")
+	}
+	if status.Head == nil {
+		t.Errorf("HEAD no longer resolves to a commit after the rename")
+	}
+
+	//A commit must still be possible on the renamed branch
+	commitFile(t, manager, repoPath, "b.txt", "two\n", "after rename")
+}
+
+func TestRenameBranchCarriesUpstreamConfig(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath, _, _ := newRepoWithRemote(t, manager, "feature")
+
+	if err := manager.RenameBranch(repoPath, "feature", "feature-renamed"); err != nil {
+		t.Fatalf("RenameBranch() returned error: %v", err)
+	}
+
+	repo, err := manager.open(repoPath)
+	if err != nil {
+		t.Fatalf("open() returned error: %v", err)
+	}
+	cfg, _ := repo.Config()
+
+	if _, ok := cfg.Branches["feature"]; ok {
+		t.Errorf("the old branch config was left behind")
+	}
+	renamed, ok := cfg.Branches["feature-renamed"]
+	if !ok {
+		t.Fatalf("the renamed branch has no tracking config")
+	}
+	if renamed.Name != "feature-renamed" {
+		t.Errorf("config Name = %q, want %q", renamed.Name, "feature-renamed")
+	}
+	if renamed.Remote != "origin" {
+		t.Errorf("config Remote = %q, want origin", renamed.Remote)
+	}
+}
+
+func TestRenameBranchValidation(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	commitFile(t, manager, repoPath, "a.txt", "one\n", "first")
+
+	branches, _ := manager.Branches(repoPath)
+	existing := branches[0].Name
+
+	if err := manager.Checkout(repoPath, "other", true); err != nil {
+		t.Fatalf("Checkout(create) returned error: %v", err)
+	}
+	if err := manager.Checkout(repoPath, existing, false); err != nil {
+		t.Fatalf("Checkout(back) returned error: %v", err)
+	}
+
+	tests := []struct {
+		name    string
+		oldName string
+		newName string
+	}{
+		{name: "source missing", oldName: "nonexistent", newName: "whatever"},
+		{name: "target already exists", oldName: "other", newName: existing},
+		{name: "same name", oldName: "other", newName: "other"},
+		{name: "invalid target", oldName: "other", newName: "bad name"},
+		{name: "empty target", oldName: "other", newName: ""},
+		{name: "empty source", oldName: "", newName: "fine"},
+	}
+
+	for _, test := range tests {
+		t.Run(test.name, func(t *testing.T) {
+			if err := manager.RenameBranch(repoPath, test.oldName, test.newName); err == nil {
+				t.Errorf("RenameBranch(%q, %q) = nil error, want an error", test.oldName, test.newName)
+			}
+		})
+	}
+
+	//None of the refused calls may have changed anything
+	if !hasLocalRef(t, manager, repoPath, plumbing.NewBranchReferenceName("other")) {
+		t.Errorf("a refused rename removed the source branch")
+	}
+}
+
+/* ── Remote branch deletion ───────────────────────────────────────────── */
+
+func TestDeleteRemoteBranch(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath, bare, _ := newRepoWithRemote(t, manager, "feature")
+
+	if !bareHasBranch(t, bare, "feature") {
+		t.Fatalf("the remote does not have the feature branch to begin with")
+	}
+
+	if err := manager.DeleteRemoteBranch(repoPath, "origin", "feature", &TransportRequest{}); err != nil {
+		t.Fatalf("DeleteRemoteBranch() returned error: %v", err)
+	}
+
+	if bareHasBranch(t, bare, "feature") {
+		t.Errorf("the branch still exists on the remote")
+	}
+
+	//The local tracking ref must be pruned so the UI stops listing it
+	if hasLocalRef(t, manager, repoPath, plumbing.NewRemoteReferenceName("origin", "feature")) {
+		t.Errorf("the remote-tracking ref was not pruned")
+	}
+
+	after, _ := manager.Branches(repoPath)
+	for _, branch := range after {
+		if branch.IsRemote && branch.Short == "feature" {
+			t.Errorf("Branches() still lists the deleted remote branch")
+		}
+	}
+
+	//The local branch of the same name is a separate thing and must survive
+	if !hasLocalRef(t, manager, repoPath, plumbing.NewBranchReferenceName("feature")) {
+		t.Errorf("deleting the remote branch also removed the local branch")
+	}
+}
+
+func TestDeleteRemoteBranchValidation(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath, _, _ := newRepoWithRemote(t, manager, "feature")
+
+	if err := manager.DeleteRemoteBranch(repoPath, "nosuchremote", "feature", &TransportRequest{}); !errors.Is(err, ErrNoRemote) {
+		t.Errorf("DeleteRemoteBranch() with an unknown remote = %v, want ErrNoRemote", err)
+	}
+	if err := manager.DeleteRemoteBranch(repoPath, "origin", "bad name", &TransportRequest{}); err == nil {
+		t.Errorf("DeleteRemoteBranch() with an invalid branch name = nil error, want an error")
+	}
+	if err := manager.DeleteRemoteBranch(repoPath, "origin", "", &TransportRequest{}); err == nil {
+		t.Errorf("DeleteRemoteBranch() with an empty branch name = nil error, want an error")
+	}
+}
+
+/* ── Remote branch rename ─────────────────────────────────────────────── */
+
+func TestRenameRemoteBranch(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath, bare, _ := newRepoWithRemote(t, manager, "feature")
+
+	if err := manager.RenameRemoteBranch(repoPath, "origin", "feature", "feature-v2", &TransportRequest{}); err != nil {
+		t.Fatalf("RenameRemoteBranch() returned error: %v", err)
+	}
+
+	if !bareHasBranch(t, bare, "feature-v2") {
+		t.Errorf("the new branch name was not created on the remote")
+	}
+	if bareHasBranch(t, bare, "feature") {
+		t.Errorf("the old branch name still exists on the remote")
+	}
+
+	//The local tracking refs must mirror the change without needing a fetch
+	if !hasLocalRef(t, manager, repoPath, plumbing.NewRemoteReferenceName("origin", "feature-v2")) {
+		t.Errorf("the new remote-tracking ref was not created locally")
+	}
+	if hasLocalRef(t, manager, repoPath, plumbing.NewRemoteReferenceName("origin", "feature")) {
+		t.Errorf("the old remote-tracking ref was not removed locally")
+	}
+}
+
+func TestRenameRemoteBranchPreservesCommits(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath, bare, _ := newRepoWithRemote(t, manager, "feature")
+
+	//Record what the remote branch pointed at before the rename
+	repo, _ := manager.open(repoPath)
+	before, err := repo.Reference(plumbing.NewRemoteReferenceName("origin", "feature"), false)
+	if err != nil {
+		t.Fatalf("cannot read the remote-tracking ref: %v", err)
+	}
+
+	if err := manager.RenameRemoteBranch(repoPath, "origin", "feature", "feature-v2", &TransportRequest{}); err != nil {
+		t.Fatalf("RenameRemoteBranch() returned error: %v", err)
+	}
+
+	bareRepo, err := gogit.PlainOpen(bare)
+	if err != nil {
+		t.Fatalf("cannot open the bare remote: %v", err)
+	}
+	after, err := bareRepo.Reference(plumbing.NewBranchReferenceName("feature-v2"), false)
+	if err != nil {
+		t.Fatalf("the renamed branch is missing on the remote: %v", err)
+	}
+
+	if after.Hash() != before.Hash() {
+		t.Errorf("renamed branch points at %s, want the original commit %s", after.Hash(), before.Hash())
+	}
+}
+
+func TestRenameRemoteBranchValidation(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath, _, _ := newRepoWithRemote(t, manager, "feature")
+
+	tests := []struct {
+		name    string
+		remote  string
+		oldName string
+		newName string
+	}{
+		{name: "unknown remote", remote: "nosuchremote", oldName: "feature", newName: "x"},
+		{name: "source missing on remote", remote: "origin", oldName: "nonexistent", newName: "x"},
+		{name: "same name", remote: "origin", oldName: "feature", newName: "feature"},
+		{name: "invalid target", remote: "origin", oldName: "feature", newName: "bad name"},
+		{name: "empty target", remote: "origin", oldName: "feature", newName: ""},
+	}
+
+	for _, test := range tests {
+		t.Run(test.name, func(t *testing.T) {
+			if err := manager.RenameRemoteBranch(repoPath, test.remote, test.oldName, test.newName, &TransportRequest{}); err == nil {
+				t.Errorf("RenameRemoteBranch() with %s = nil error, want an error", test.name)
+			}
+		})
+	}
+}
+
+/* ── Helpers ──────────────────────────────────────────────────────────── */
+
+func TestSplitRemoteRef(t *testing.T) {
+	tests := []struct {
+		name       string
+		fullRef    string
+		wantRemote string
+		wantShort  string
+	}{
+		{name: "simple remote branch", fullRef: "refs/remotes/origin/master", wantRemote: "origin", wantShort: "master"},
+		{name: "nested branch name", fullRef: "refs/remotes/origin/feature/login", wantRemote: "origin", wantShort: "feature/login"},
+		{name: "non-origin remote", fullRef: "refs/remotes/upstream/dev", wantRemote: "upstream", wantShort: "dev"},
+		{name: "local branch", fullRef: "refs/heads/master", wantRemote: "", wantShort: "master"},
+		{name: "local nested branch", fullRef: "refs/heads/feature/login", wantRemote: "", wantShort: "feature/login"},
+		{name: "remote with no branch part", fullRef: "refs/remotes/origin", wantRemote: "", wantShort: "origin"},
+	}
+
+	for _, test := range tests {
+		t.Run(test.name, func(t *testing.T) {
+			remote, short := splitRemoteRef(test.fullRef)
+			if remote != test.wantRemote {
+				t.Errorf("splitRemoteRef(%q) remote = %q, want %q", test.fullRef, remote, test.wantRemote)
+			}
+			if short != test.wantShort {
+				t.Errorf("splitRemoteRef(%q) short = %q, want %q", test.fullRef, short, test.wantShort)
+			}
+		})
+	}
+}
+
+func TestRemoteOrName(t *testing.T) {
+	tests := []struct {
+		name   string
+		remote string
+		want   string
+	}{
+		{name: "explicit", remote: "upstream", want: "upstream"},
+		{name: "empty defaults to origin", remote: "", want: "origin"},
+		{name: "whitespace defaults to origin", remote: "   ", want: "origin"},
+		{name: "padded", remote: " upstream ", want: "upstream"},
+	}
+
+	for _, test := range tests {
+		t.Run(test.name, func(t *testing.T) {
+			if got := remoteOrName(test.remote); got != test.want {
+				t.Errorf("remoteOrName(%q) = %q, want %q", test.remote, got, test.want)
+			}
+		})
+	}
+}
+
+// TestBranchesReportRemoteAndShort checks the fields the front-end needs to
+// address a remote branch unambiguously.
+func TestBranchesReportRemoteAndShort(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath, _, defaultBranch := newRepoWithRemote(t, manager, "feature")
+
+	branches, err := manager.Branches(repoPath)
+	if err != nil {
+		t.Fatalf("Branches() returned error: %v", err)
+	}
+
+	sawLocal, sawRemote := false, false
+	for _, branch := range branches {
+		if !branch.IsRemote && branch.Name == defaultBranch {
+			sawLocal = true
+			if branch.Short != defaultBranch {
+				t.Errorf("local branch Short = %q, want %q", branch.Short, defaultBranch)
+			}
+			if branch.Remote != "" {
+				t.Errorf("local branch Remote = %q, want empty", branch.Remote)
+			}
+		}
+		if branch.IsRemote && branch.Short == "feature" {
+			sawRemote = true
+			if branch.Remote != "origin" {
+				t.Errorf("remote branch Remote = %q, want origin", branch.Remote)
+			}
+			if branch.Name != "origin/feature" {
+				t.Errorf("remote branch Name = %q, want origin/feature", branch.Name)
+			}
+		}
+	}
+
+	if !sawLocal {
+		t.Errorf("Branches() did not report the local default branch")
+	}
+	if !sawRemote {
+		t.Errorf("Branches() did not report the remote feature branch")
+	}
+}

+ 5 - 0
src/mod/git/errors.go

@@ -31,6 +31,11 @@ var (
 	//ErrAuthRequired is returned when the remote rejected or demanded
 	//credentials. The AGI layer turns this into authRequired = true.
 	ErrAuthRequired = errors.New("authentication required")
+
+	//ErrUnmergedBranch is returned when deleting a local branch that still holds
+	//commits unreachable from HEAD. The AGI layer turns this into
+	//unmerged = true so the caller can confirm and retry with force.
+	ErrUnmergedBranch = errors.New("branch has commits that are not merged into the current branch")
 )
 
 // authErrorFragments are lower-cased substrings that identify an authentication

+ 19 - 1
src/mod/git/history.go

@@ -46,9 +46,16 @@ func (m *Manager) Log(realpath string, limit int) ([]CommitInfo, error) {
 	}
 	defer iter.Close()
 
+	//Index tags once so each commit can be labelled without a per-commit lookup
+	tagMap, _ := buildTagMap(repo)
+
 	commits := []CommitInfo{}
 	err = iter.ForEach(func(commit *object.Commit) error {
-		commits = append(commits, *commitToInfo(commit))
+		info := commitToInfo(commit)
+		if tags, ok := tagMap[commit.Hash]; ok {
+			info.Tags = tags
+		}
+		commits = append(commits, *info)
 		if len(commits) >= limit {
 			return storerStop
 		}
@@ -87,6 +94,8 @@ func (m *Manager) Branches(realpath string) ([]BranchInfo, error) {
 			Hash:      ref.Hash().String(),
 			IsRemote:  false,
 			IsCurrent: ref.Name().Short() == currentBranch,
+			//Short mirrors Name for a local branch so callers can always use it
+			Short: ref.Name().Short(),
 		})
 		return nil
 	})
@@ -107,11 +116,15 @@ func (m *Manager) Branches(realpath string) ([]BranchInfo, error) {
 		if strings.HasSuffix(ref.Name().Short(), "/HEAD") {
 			return nil
 		}
+
+		remote, short := splitRemoteRef(ref.Name().String())
 		branches = append(branches, BranchInfo{
 			Name:     ref.Name().Short(),
 			FullRef:  ref.Name().String(),
 			Hash:     ref.Hash().String(),
 			IsRemote: true,
+			Remote:   remote,
+			Short:    short,
 		})
 		return nil
 	})
@@ -189,6 +202,11 @@ func shortLocalName(name string) string {
 // validateBranchName rejects the ref name characters git itself forbids, since
 // the value arrives from a browser text field.
 func validateBranchName(branch string) error {
+	//An empty name must never reach a ref operation: it would build a malformed
+	//ref such as "refs/heads/", which as a push refspec is silently accepted.
+	if strings.TrimSpace(branch) == "" {
+		return errors.New("branch name cannot be empty")
+	}
 	if strings.HasPrefix(branch, "-") || strings.HasPrefix(branch, "/") || strings.HasSuffix(branch, "/") {
 		return errors.New("invalid branch name: " + branch)
 	}

+ 585 - 0
src/mod/git/history_actions.go

@@ -0,0 +1,585 @@
+package git
+
+/*
+	history_actions.go
+
+	The operations behind the History tab's commit context menu, matching what
+	GitHub Desktop offers: checkout, reset, branch/tag creation, revert,
+	cherry-pick and message amend.
+
+	Revert and cherry-pick deserve a note. go-git has no merge engine, so instead
+	of attempting a three-way merge that could silently produce a wrong result,
+	this package uses a "clean or refuse" strategy: a change is applied only when
+	the files it touches still hold the exact content it expects, and otherwise
+	the whole operation is refused with a readable message. That safely covers
+	the common cases (reverting the latest commit, or an older commit whose files
+	were not touched since) and never fabricates a bad tree.
+*/
+
+import (
+	"bytes"
+	"errors"
+	"fmt"
+	"io"
+	"os"
+	"path/filepath"
+	"strings"
+
+	gogit "github.com/go-git/go-git/v5"
+	"github.com/go-git/go-git/v5/plumbing"
+	"github.com/go-git/go-git/v5/plumbing/object"
+)
+
+// maxApplyBytes caps the size of a single blob revert/cherry-pick will rewrite,
+// so one enormous asset cannot exhaust memory.
+const maxApplyBytes = 50 * 1024 * 1024
+
+// CheckoutCommit checks a commit out in detached HEAD state. The working tree
+// must be clean, so no uncommitted work is silently discarded.
+func (m *Manager) CheckoutCommit(realpath string, hash string) error {
+	repo, tree, err := m.worktree(realpath)
+	if err != nil {
+		return err
+	}
+
+	commit, err := resolveCommit(repo, hash)
+	if err != nil {
+		return err
+	}
+	if err := requireCleanWorktree(tree); err != nil {
+		return err
+	}
+
+	return tree.Checkout(&gogit.CheckoutOptions{Hash: commit.Hash})
+}
+
+// ResetToCommit moves the current branch to a commit. mode is "soft" (move HEAD
+// only), "mixed" (also reset the index) or "hard" (also reset the working tree).
+func (m *Manager) ResetToCommit(realpath string, hash string, mode string) error {
+	repo, tree, err := m.worktree(realpath)
+	if err != nil {
+		return err
+	}
+
+	commit, err := resolveCommit(repo, hash)
+	if err != nil {
+		return err
+	}
+
+	resetMode, err := parseResetMode(mode)
+	if err != nil {
+		return err
+	}
+
+	//A hard reset throws away working tree changes; guard so it cannot happen
+	//by surprise when the user has uncommitted work they forgot about.
+	if resetMode == gogit.HardReset {
+		if err := requireCleanWorktree(tree); err != nil {
+			return errors.New("hard reset would discard your uncommitted changes — commit or discard them first")
+		}
+	}
+
+	return tree.Reset(&gogit.ResetOptions{
+		Commit: commit.Hash,
+		Mode:   resetMode,
+	})
+}
+
+// CreateBranchAt creates a branch pointing at a commit and checks it out.
+func (m *Manager) CreateBranchAt(realpath string, branch string, hash string) error {
+	branch = strings.TrimSpace(branch)
+	if err := validateBranchName(branch); err != nil {
+		return err
+	}
+
+	repo, tree, err := m.worktree(realpath)
+	if err != nil {
+		return err
+	}
+
+	commit, err := resolveCommit(repo, hash)
+	if err != nil {
+		return err
+	}
+
+	referenceName := plumbing.NewBranchReferenceName(branch)
+	if _, rerr := repo.Reference(referenceName, false); rerr == nil {
+		return errors.New("a branch named " + branch + " already exists")
+	}
+
+	if err := repo.Storer.SetReference(plumbing.NewHashReference(referenceName, commit.Hash)); err != nil {
+		return err
+	}
+
+	return tree.Checkout(&gogit.CheckoutOptions{
+		Branch: referenceName,
+		Keep:   true,
+	})
+}
+
+// CreateTag creates a tag at a commit. A non-empty message produces an
+// annotated tag (signed by name / email, falling back to the repository's git
+// config), otherwise a lightweight one.
+func (m *Manager) CreateTag(realpath string, tag string, hash string, message string, name string, email string) error {
+	tag = strings.TrimSpace(tag)
+	if err := validateTagName(tag); err != nil {
+		return err
+	}
+
+	repo, err := m.open(realpath)
+	if err != nil {
+		return err
+	}
+
+	commit, err := resolveCommit(repo, hash)
+	if err != nil {
+		return err
+	}
+
+	var options *gogit.CreateTagOptions
+	if strings.TrimSpace(message) != "" {
+		signature, serr := resolveSignature(repo, name, email)
+		if serr != nil {
+			return serr
+		}
+		options = &gogit.CreateTagOptions{
+			Tagger:  signature,
+			Message: message,
+		}
+	}
+
+	_, err = repo.CreateTag(tag, commit.Hash, options)
+	if errors.Is(err, gogit.ErrTagExists) {
+		return errors.New("a tag named " + tag + " already exists")
+	}
+	return err
+}
+
+// TagsForCommit returns the names of tags pointing at a commit, resolving
+// annotated tag objects to the commit they wrap.
+func (m *Manager) TagsForCommit(realpath string, hash string) ([]string, error) {
+	repo, err := m.open(realpath)
+	if err != nil {
+		return nil, err
+	}
+	commit, err := resolveCommit(repo, hash)
+	if err != nil {
+		return nil, err
+	}
+
+	tagMap, err := buildTagMap(repo)
+	if err != nil {
+		return nil, err
+	}
+	return tagMap[commit.Hash], nil
+}
+
+// RevertCommit creates a new commit that undoes a commit's changes. It is the
+// reverse transition: from the commit's tree back to its parent's tree.
+func (m *Manager) RevertCommit(realpath string, hash string, req *CommitRequest) (string, error) {
+	repo, tree, err := m.worktree(realpath)
+	if err != nil {
+		return "", err
+	}
+
+	commit, err := resolveCommit(repo, hash)
+	if err != nil {
+		return "", err
+	}
+	if err := requireCleanWorktree(tree); err != nil {
+		return "", errors.New("commit or discard your changes before reverting")
+	}
+
+	commitTree, err := commit.Tree()
+	if err != nil {
+		return "", err
+	}
+
+	//Reverting the changes means going from the commit back to its parent. The
+	//root commit has no parent, so its parent state is the empty tree.
+	var parentTree *object.Tree
+	if commit.NumParents() > 0 {
+		parent, perr := commit.Parent(0)
+		if perr != nil {
+			return "", perr
+		}
+		if parentTree, err = parent.Tree(); err != nil {
+			return "", err
+		}
+	}
+
+	if err := m.applyTransition(tree, commitTree, parentTree); err != nil {
+		return "", err
+	}
+
+	message := req.Message
+	if strings.TrimSpace(message) == "" {
+		message = "Revert \"" + commitSubject(commit) + "\"\n\nThis reverts commit " + commit.Hash.String() + "."
+	}
+
+	return m.commitStaged(repo, tree, message, req, nil)
+}
+
+// CherryPickCommit applies a commit's changes onto the current HEAD. It is the
+// forward transition: from the commit's parent tree to the commit's tree.
+func (m *Manager) CherryPickCommit(realpath string, hash string, req *CommitRequest) (string, error) {
+	repo, tree, err := m.worktree(realpath)
+	if err != nil {
+		return "", err
+	}
+
+	commit, err := resolveCommit(repo, hash)
+	if err != nil {
+		return "", err
+	}
+	if err := requireCleanWorktree(tree); err != nil {
+		return "", errors.New("commit or discard your changes before cherry-picking")
+	}
+
+	commitTree, err := commit.Tree()
+	if err != nil {
+		return "", err
+	}
+
+	var parentTree *object.Tree
+	if commit.NumParents() > 0 {
+		parent, perr := commit.Parent(0)
+		if perr != nil {
+			return "", perr
+		}
+		if parentTree, err = parent.Tree(); err != nil {
+			return "", err
+		}
+	}
+
+	if err := m.applyTransition(tree, parentTree, commitTree); err != nil {
+		return "", err
+	}
+
+	message := req.Message
+	if strings.TrimSpace(message) == "" {
+		message = commit.Message
+	}
+
+	//A cherry-pick keeps the original author but records the current user as the
+	//committer, exactly like git does.
+	originalAuthor := commit.Author
+	return m.commitStaged(repo, tree, message, req, &originalAuthor)
+}
+
+// AmendCommitMessage rewrites the message of the HEAD commit, keeping its tree,
+// parents and author. Only a branch tip can be amended.
+func (m *Manager) AmendCommitMessage(realpath string, message string, req *CommitRequest) (string, error) {
+	if strings.TrimSpace(message) == "" {
+		return "", errors.New("commit message cannot be empty")
+	}
+
+	repo, err := m.open(realpath)
+	if err != nil {
+		return "", err
+	}
+
+	head, err := repo.Head()
+	if err != nil {
+		if errors.Is(err, plumbing.ErrReferenceNotFound) {
+			return "", ErrUnbornBranch
+		}
+		return "", err
+	}
+	if !head.Name().IsBranch() {
+		return "", errors.New("HEAD is detached — check out a branch before amending")
+	}
+
+	headCommit, err := repo.CommitObject(head.Hash())
+	if err != nil {
+		return "", err
+	}
+
+	committer, err := resolveSignature(repo, req.Name, req.Email)
+	if err != nil {
+		return "", err
+	}
+
+	amended := &object.Commit{
+		Author:       headCommit.Author,
+		Committer:    *committer,
+		Message:      message,
+		TreeHash:     headCommit.TreeHash,
+		ParentHashes: headCommit.ParentHashes,
+	}
+
+	encoded := repo.Storer.NewEncodedObject()
+	if err := amended.Encode(encoded); err != nil {
+		return "", err
+	}
+	newHash, err := repo.Storer.SetEncodedObject(encoded)
+	if err != nil {
+		return "", err
+	}
+
+	if err := repo.Storer.SetReference(plumbing.NewHashReference(head.Name(), newHash)); err != nil {
+		return "", err
+	}
+	return newHash.String(), nil
+}
+
+/*
+applyTransition rewrites the working tree so that, for every path whose content
+differs between fromTree and toTree, the file becomes its toTree version.
+
+Before touching a file it checks the current (clean) working tree still matches
+the fromTree version. If any file has diverged the whole operation is refused,
+so a revert or cherry-pick either applies cleanly in full or not at all.
+*/
+func (m *Manager) applyTransition(tree *gogit.Worktree, fromTree *object.Tree, toTree *object.Tree) error {
+	paths, err := unionTreePaths(fromTree, toTree)
+	if err != nil {
+		return err
+	}
+
+	repoRoot := tree.Filesystem.Root()
+	applied := 0
+
+	for _, path := range paths {
+		fromContent, fromExists, ferr := treeBytes(fromTree, path)
+		if ferr != nil {
+			return ferr
+		}
+		toContent, toExists, terr := treeBytes(toTree, path)
+		if terr != nil {
+			return terr
+		}
+
+		//Unchanged by this transition — nothing to do
+		if fromExists == toExists && bytes.Equal(fromContent, toContent) {
+			continue
+		}
+
+		//The clean working tree must still hold the "from" version, otherwise
+		//applying the change would need a real merge.
+		currentContent, currentExists, cerr := worktreeBytes(repoRoot, path)
+		if cerr != nil {
+			return cerr
+		}
+		if currentExists != fromExists || !bytes.Equal(currentContent, fromContent) {
+			return errors.New("cannot apply cleanly — " + path + " has changed since that commit; a manual merge is needed")
+		}
+
+		fullPath := filepath.Join(repoRoot, filepath.FromSlash(path))
+		if toExists {
+			if err := os.MkdirAll(filepath.Dir(fullPath), 0775); err != nil {
+				return err
+			}
+			if err := os.WriteFile(fullPath, toContent, 0664); err != nil {
+				return err
+			}
+		} else if err := os.Remove(fullPath); err != nil && !os.IsNotExist(err) {
+			return err
+		}
+
+		if _, err := tree.Add(path); err != nil {
+			return errors.New("cannot stage " + path + ": " + err.Error())
+		}
+		applied++
+	}
+
+	if applied == 0 {
+		return errors.New("this commit introduces no change to apply")
+	}
+	return nil
+}
+
+// commitStaged writes a commit from the current index. author is used when the
+// original author should be preserved (cherry-pick), otherwise the caller's or
+// the repository's identity is used for both roles.
+func (m *Manager) commitStaged(repo *gogit.Repository, tree *gogit.Worktree, message string, req *CommitRequest, author *object.Signature) (string, error) {
+	if req == nil {
+		req = &CommitRequest{}
+	}
+
+	committer, err := resolveSignature(repo, req.Name, req.Email)
+	if err != nil {
+		return "", err
+	}
+
+	commitAuthor := committer
+	if author != nil {
+		//Preserve the original author identity and date
+		authorCopy := *author
+		commitAuthor = &authorCopy
+	}
+
+	hash, err := tree.Commit(message, &gogit.CommitOptions{
+		Author:    commitAuthor,
+		Committer: committer,
+	})
+	if err != nil {
+		if errors.Is(err, gogit.ErrEmptyCommit) {
+			return "", errors.New("nothing to commit — the change is already present")
+		}
+		return "", err
+	}
+	return hash.String(), nil
+}
+
+// resolveCommit validates a hash and loads its commit object.
+func resolveCommit(repo *gogit.Repository, hash string) (*object.Commit, error) {
+	hash = strings.TrimSpace(hash)
+	if !commitHashPattern.MatchString(hash) {
+		return nil, errors.New("not a commit hash: " + hash)
+	}
+	commit, err := repo.CommitObject(plumbing.NewHash(hash))
+	if err != nil {
+		return nil, errors.New("no such commit: " + hash)
+	}
+	return commit, nil
+}
+
+// requireCleanWorktree refuses when there are uncommitted changes.
+func requireCleanWorktree(tree *gogit.Worktree) error {
+	status, err := tree.Status()
+	if err != nil {
+		return err
+	}
+	if !status.IsClean() {
+		return errors.New("the working tree has uncommitted changes")
+	}
+	return nil
+}
+
+// parseResetMode maps the front-end vocabulary onto go-git's reset modes.
+func parseResetMode(mode string) (gogit.ResetMode, error) {
+	switch strings.ToLower(strings.TrimSpace(mode)) {
+	case "", "mixed":
+		return gogit.MixedReset, nil
+	case "soft":
+		return gogit.SoftReset, nil
+	case "hard":
+		return gogit.HardReset, nil
+	default:
+		return gogit.MixedReset, errors.New("unknown reset mode: " + mode)
+	}
+}
+
+// validateTagName rejects the ref-name characters git forbids in a tag.
+func validateTagName(tag string) error {
+	if tag == "" {
+		return errors.New("tag name cannot be empty")
+	}
+	if err := plumbing.NewTagReferenceName(tag).Validate(); err != nil {
+		return errors.New("invalid tag name: " + tag)
+	}
+	return nil
+}
+
+// commitSubject returns the first line of a commit message.
+func commitSubject(commit *object.Commit) string {
+	subject := commit.Message
+	if index := strings.IndexByte(subject, '\n'); index >= 0 {
+		subject = subject[:index]
+	}
+	return strings.TrimSpace(subject)
+}
+
+// buildTagMap indexes every tag by the commit hash it ultimately points at,
+// following annotated tag objects to their target.
+func buildTagMap(repo *gogit.Repository) (map[plumbing.Hash][]string, error) {
+	tagMap := map[plumbing.Hash][]string{}
+
+	iter, err := repo.Tags()
+	if err != nil {
+		return tagMap, err
+	}
+	defer iter.Close()
+
+	err = iter.ForEach(func(ref *plumbing.Reference) error {
+		name := ref.Name().Short()
+
+		//Annotated tags are their own object wrapping the commit; lightweight
+		//tags point straight at it.
+		if tagObject, terr := repo.TagObject(ref.Hash()); terr == nil {
+			if commit, cerr := tagObject.Commit(); cerr == nil {
+				tagMap[commit.Hash] = append(tagMap[commit.Hash], name)
+				return nil
+			}
+		}
+		tagMap[ref.Hash()] = append(tagMap[ref.Hash()], name)
+		return nil
+	})
+	return tagMap, err
+}
+
+// unionTreePaths lists every file path present in either tree.
+func unionTreePaths(a *object.Tree, b *object.Tree) ([]string, error) {
+	seen := map[string]struct{}{}
+
+	for _, tree := range []*object.Tree{a, b} {
+		if tree == nil {
+			continue
+		}
+		iter := tree.Files()
+		err := iter.ForEach(func(file *object.File) error {
+			seen[file.Name] = struct{}{}
+			return nil
+		})
+		iter.Close()
+		if err != nil {
+			return nil, err
+		}
+	}
+
+	paths := make([]string, 0, len(seen))
+	for path := range seen {
+		paths = append(paths, path)
+	}
+	return paths, nil
+}
+
+// treeBytes reads a path from a tree, reporting whether it exists.
+func treeBytes(tree *object.Tree, path string) ([]byte, bool, error) {
+	if tree == nil {
+		return nil, false, nil
+	}
+
+	file, err := tree.File(path)
+	if err != nil {
+		return nil, false, nil
+	}
+	if file.Size > maxApplyBytes {
+		return nil, true, fmt.Errorf("%s is too large to apply", path)
+	}
+
+	reader, err := file.Reader()
+	if err != nil {
+		return nil, true, err
+	}
+	defer reader.Close()
+
+	content, err := io.ReadAll(reader)
+	if err != nil {
+		return nil, true, err
+	}
+	return content, true, nil
+}
+
+// worktreeBytes reads a path from the working tree, reporting whether it exists.
+func worktreeBytes(repoRoot string, path string) ([]byte, bool, error) {
+	fullPath := filepath.Join(repoRoot, filepath.FromSlash(path))
+
+	info, err := os.Stat(fullPath)
+	if err != nil {
+		if os.IsNotExist(err) {
+			return nil, false, nil
+		}
+		return nil, false, err
+	}
+	if info.IsDir() {
+		return nil, false, nil
+	}
+
+	content, err := os.ReadFile(fullPath)
+	if err != nil {
+		return nil, false, err
+	}
+	return content, true, nil
+}

+ 593 - 0
src/mod/git/history_actions_test.go

@@ -0,0 +1,593 @@
+package git
+
+import (
+	"os"
+	"path/filepath"
+	"strings"
+	"testing"
+)
+
+// headHash returns the current HEAD commit hash of a repository.
+func headHash(t *testing.T, manager *Manager, repoPath string) string {
+	t.Helper()
+	status, err := manager.Status(repoPath)
+	if err != nil {
+		t.Fatalf("Status() returned error: %v", err)
+	}
+	if status.Head == nil {
+		t.Fatalf("HEAD is unborn, want a commit")
+	}
+	return status.Head.Hash
+}
+
+func TestCheckoutCommitDetachesHead(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	first := commitFile(t, manager, repoPath, "a.txt", "one\n", "first")
+	commitFile(t, manager, repoPath, "a.txt", "two\n", "second")
+
+	if err := manager.CheckoutCommit(repoPath, first); err != nil {
+		t.Fatalf("CheckoutCommit() returned error: %v", err)
+	}
+
+	status, err := manager.Status(repoPath)
+	if err != nil {
+		t.Fatalf("Status() returned error: %v", err)
+	}
+	if !status.Detached {
+		t.Errorf("Detached = false after checking out a commit, want true")
+	}
+	if status.Head.Hash != first {
+		t.Errorf("HEAD = %q, want %q", status.Head.Hash, first)
+	}
+
+	//The working tree must reflect the older commit
+	content, _ := os.ReadFile(filepath.Join(repoPath, "a.txt"))
+	if string(content) != "one\n" {
+		t.Errorf("working tree = %q, want the first commit's content", string(content))
+	}
+}
+
+func TestCheckoutCommitRefusesDirtyTree(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	first := commitFile(t, manager, repoPath, "a.txt", "one\n", "first")
+	commitFile(t, manager, repoPath, "a.txt", "two\n", "second")
+
+	writeFile(t, repoPath, "a.txt", "uncommitted\n")
+	if err := manager.CheckoutCommit(repoPath, first); err == nil {
+		t.Errorf("CheckoutCommit() with a dirty tree = nil error, want a refusal")
+	}
+}
+
+func TestResetToCommitModes(t *testing.T) {
+	tests := []struct {
+		name           string
+		mode           string
+		wantWorktree   string // file content after reset
+		wantChangeSeen bool   // is the reverted change reported as pending?
+	}{
+		//soft/mixed keep the newer file on disk, so the difference reappears as
+		//an uncommitted change; hard rewinds the file too.
+		{name: "soft", mode: "soft", wantWorktree: "two\n", wantChangeSeen: true},
+		{name: "mixed", mode: "mixed", wantWorktree: "two\n", wantChangeSeen: true},
+		{name: "hard", mode: "hard", wantWorktree: "one\n", wantChangeSeen: false},
+	}
+
+	for _, test := range tests {
+		t.Run(test.name, func(t *testing.T) {
+			manager := newTestManager(t)
+			repoPath := newTestRepo(t, manager)
+			first := commitFile(t, manager, repoPath, "a.txt", "one\n", "first")
+			commitFile(t, manager, repoPath, "a.txt", "two\n", "second")
+
+			if err := manager.ResetToCommit(repoPath, first, test.mode); err != nil {
+				t.Fatalf("ResetToCommit(%s) returned error: %v", test.mode, err)
+			}
+
+			if got := headHash(t, manager, repoPath); got != first {
+				t.Errorf("HEAD = %q, want the first commit %q", got, first)
+			}
+
+			content, _ := os.ReadFile(filepath.Join(repoPath, "a.txt"))
+			if string(content) != test.wantWorktree {
+				t.Errorf("working tree = %q, want %q", string(content), test.wantWorktree)
+			}
+
+			status, _ := manager.Status(repoPath)
+			if status.Clean == test.wantChangeSeen {
+				t.Errorf("Clean = %v, want %v", status.Clean, !test.wantChangeSeen)
+			}
+		})
+	}
+}
+
+func TestResetHardRefusesDirtyTree(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	first := commitFile(t, manager, repoPath, "a.txt", "one\n", "first")
+	commitFile(t, manager, repoPath, "a.txt", "two\n", "second")
+
+	writeFile(t, repoPath, "b.txt", "unsaved work\n")
+	if err := manager.ResetToCommit(repoPath, first, "hard"); err == nil {
+		t.Errorf("hard reset with a dirty tree = nil error, want a refusal")
+	}
+}
+
+func TestResetToCommitValidation(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	hash := commitFile(t, manager, repoPath, "a.txt", "one\n", "first")
+
+	if err := manager.ResetToCommit(repoPath, hash, "sideways"); err == nil {
+		t.Errorf("ResetToCommit() with an unknown mode = nil error, want an error")
+	}
+	if err := manager.ResetToCommit(repoPath, "abc1234", "mixed"); err == nil {
+		t.Errorf("ResetToCommit() with a short hash = nil error, want an error")
+	}
+}
+
+func TestCreateBranchAt(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	first := commitFile(t, manager, repoPath, "a.txt", "one\n", "first")
+	commitFile(t, manager, repoPath, "a.txt", "two\n", "second")
+
+	if err := manager.CreateBranchAt(repoPath, "legacy", first); err != nil {
+		t.Fatalf("CreateBranchAt() returned error: %v", err)
+	}
+
+	status, err := manager.Status(repoPath)
+	if err != nil {
+		t.Fatalf("Status() returned error: %v", err)
+	}
+	if status.Branch != "legacy" {
+		t.Errorf("current branch = %q, want %q", status.Branch, "legacy")
+	}
+	if status.Head.Hash != first {
+		t.Errorf("new branch points at %q, want the first commit %q", status.Head.Hash, first)
+	}
+}
+
+func TestCreateBranchAtRejectsExistingName(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	hash := commitFile(t, manager, repoPath, "a.txt", "one\n", "first")
+
+	branches, _ := manager.Branches(repoPath)
+	existing := branches[0].Name
+
+	if err := manager.CreateBranchAt(repoPath, existing, hash); err == nil {
+		t.Errorf("CreateBranchAt() with an existing name = nil error, want an error")
+	}
+	if err := manager.CreateBranchAt(repoPath, "bad name", hash); err == nil {
+		t.Errorf("CreateBranchAt() with an invalid name = nil error, want an error")
+	}
+}
+
+func TestCreateTagLightweightAndAnnotated(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	hash := commitFile(t, manager, repoPath, "a.txt", "one\n", "first")
+
+	if err := manager.CreateTag(repoPath, "v1.0", hash, "", "T", "t@e.com"); err != nil {
+		t.Fatalf("CreateTag() lightweight returned error: %v", err)
+	}
+	if err := manager.CreateTag(repoPath, "v1.0-annotated", hash, "first release", "T", "t@e.com"); err != nil {
+		t.Fatalf("CreateTag() annotated returned error: %v", err)
+	}
+
+	tags, err := manager.TagsForCommit(repoPath, hash)
+	if err != nil {
+		t.Fatalf("TagsForCommit() returned error: %v", err)
+	}
+	if len(tags) != 2 {
+		t.Fatalf("TagsForCommit() = %v, want two tags", tags)
+	}
+
+	found := map[string]bool{}
+	for _, tag := range tags {
+		found[tag] = true
+	}
+	if !found["v1.0"] || !found["v1.0-annotated"] {
+		t.Errorf("TagsForCommit() = %v, want both the lightweight and annotated tags", tags)
+	}
+}
+
+func TestCreateTagValidation(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	hash := commitFile(t, manager, repoPath, "a.txt", "one\n", "first")
+
+	if err := manager.CreateTag(repoPath, "v1.0", hash, "", "T", "t@e.com"); err != nil {
+		t.Fatalf("CreateTag() returned error: %v", err)
+	}
+
+	tests := []struct {
+		name string
+		tag  string
+	}{
+		{name: "duplicate", tag: "v1.0"},
+		{name: "empty", tag: ""},
+		{name: "with space", tag: "v 1.0"},
+		{name: "with tilde", tag: "v~1"},
+	}
+
+	for _, test := range tests {
+		t.Run(test.name, func(t *testing.T) {
+			if err := manager.CreateTag(repoPath, test.tag, hash, "", "T", "t@e.com"); err == nil {
+				t.Errorf("CreateTag(%q) = nil error, want an error", test.tag)
+			}
+		})
+	}
+}
+
+func TestTagsForCommitEmpty(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	hash := commitFile(t, manager, repoPath, "a.txt", "one\n", "first")
+
+	tags, err := manager.TagsForCommit(repoPath, hash)
+	if err != nil {
+		t.Fatalf("TagsForCommit() returned error: %v", err)
+	}
+	if len(tags) != 0 {
+		t.Errorf("TagsForCommit() = %v, want none", tags)
+	}
+}
+
+func TestRevertLatestCommit(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	commitFile(t, manager, repoPath, "a.txt", "original\n", "first")
+	commitFile(t, manager, repoPath, "a.txt", "changed\n", "second")
+	second := headHash(t, manager, repoPath)
+
+	revertHash, err := manager.RevertCommit(repoPath, second, &CommitRequest{
+		Name:  "Test User",
+		Email: "test@arozos.local",
+	})
+	if err != nil {
+		t.Fatalf("RevertCommit() returned error: %v", err)
+	}
+	if revertHash == "" {
+		t.Fatalf("RevertCommit() returned an empty hash")
+	}
+
+	//The file must be back to its state before the reverted commit
+	content, _ := os.ReadFile(filepath.Join(repoPath, "a.txt"))
+	if string(content) != "original\n" {
+		t.Errorf("after revert a.txt = %q, want %q", string(content), "original\n")
+	}
+
+	status, _ := manager.Status(repoPath)
+	if !status.Clean {
+		t.Errorf("working tree is not clean after revert: %+v", status.Changes)
+	}
+	if status.Head.Subject != `Revert "second"` {
+		t.Errorf("revert commit subject = %q, want %q", status.Head.Subject, `Revert "second"`)
+	}
+}
+
+func TestRevertAddedFileDeletesIt(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	commitFile(t, manager, repoPath, "keep.txt", "keep\n", "first")
+	commitFile(t, manager, repoPath, "added.txt", "new file\n", "add a file")
+	second := headHash(t, manager, repoPath)
+
+	if _, err := manager.RevertCommit(repoPath, second, &CommitRequest{Name: "T", Email: "t@e.com"}); err != nil {
+		t.Fatalf("RevertCommit() returned error: %v", err)
+	}
+
+	if _, err := os.Stat(filepath.Join(repoPath, "added.txt")); !os.IsNotExist(err) {
+		t.Errorf("reverting the commit that added the file did not remove it")
+	}
+	if _, err := os.Stat(filepath.Join(repoPath, "keep.txt")); err != nil {
+		t.Errorf("revert removed an unrelated file: %v", err)
+	}
+}
+
+func TestRevertOlderUntouchedCommit(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	commitFile(t, manager, repoPath, "a.txt", "aaa\n", "add a")
+	addACommit := headHash(t, manager, repoPath)
+	commitFile(t, manager, repoPath, "b.txt", "bbb\n", "add b unrelated")
+
+	//Reverting the older commit that added a.txt is clean because nothing has
+	//touched a.txt since.
+	if _, err := manager.RevertCommit(repoPath, addACommit, &CommitRequest{Name: "T", Email: "t@e.com"}); err != nil {
+		t.Fatalf("RevertCommit() of an older untouched commit returned error: %v", err)
+	}
+
+	if _, err := os.Stat(filepath.Join(repoPath, "a.txt")); !os.IsNotExist(err) {
+		t.Errorf("a.txt should be gone after reverting the commit that added it")
+	}
+	//The unrelated later file must be untouched
+	content, _ := os.ReadFile(filepath.Join(repoPath, "b.txt"))
+	if string(content) != "bbb\n" {
+		t.Errorf("b.txt = %q, want it left alone", string(content))
+	}
+}
+
+func TestRevertRefusesWhenFileChangedSince(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	commitFile(t, manager, repoPath, "a.txt", "v1\n", "first")
+	target := headHash(t, manager, repoPath)
+	commitFile(t, manager, repoPath, "a.txt", "v2\n", "second touches the same file")
+
+	//a.txt was changed again after the target commit, so a clean revert is
+	//impossible and the operation must refuse rather than corrupt the file.
+	if _, err := manager.RevertCommit(repoPath, target, &CommitRequest{Name: "T", Email: "t@e.com"}); err == nil {
+		t.Errorf("RevertCommit() of a commit whose file changed since = nil error, want a refusal")
+	}
+
+	//Nothing should have been written
+	status, _ := manager.Status(repoPath)
+	if !status.Clean {
+		t.Errorf("a refused revert left the tree dirty: %+v", status.Changes)
+	}
+}
+
+func TestRevertRefusesDirtyTree(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	commitFile(t, manager, repoPath, "a.txt", "one\n", "first")
+	hash := headHash(t, manager, repoPath)
+	writeFile(t, repoPath, "a.txt", "uncommitted\n")
+
+	if _, err := manager.RevertCommit(repoPath, hash, &CommitRequest{Name: "T", Email: "t@e.com"}); err == nil {
+		t.Errorf("RevertCommit() with a dirty tree = nil error, want a refusal")
+	}
+}
+
+func TestCherryPickAppliesToAnotherBranch(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	base := commitFile(t, manager, repoPath, "a.txt", "base\n", "base")
+
+	//A feature commit that adds a file, on a branch off the base
+	if err := manager.Checkout(repoPath, "feature", true); err != nil {
+		t.Fatalf("Checkout(create) returned error: %v", err)
+	}
+	commitFile(t, manager, repoPath, "feature.txt", "feature work\n", "add feature")
+	featureCommit := headHash(t, manager, repoPath)
+
+	//Back to the base branch, cherry-pick the feature commit
+	if err := manager.CheckoutCommit(repoPath, base); err != nil {
+		t.Fatalf("CheckoutCommit(base) returned error: %v", err)
+	}
+	if err := manager.Checkout(repoPath, "main-line", true); err != nil {
+		t.Fatalf("Checkout(create main-line) returned error: %v", err)
+	}
+
+	pickHash, err := manager.CherryPickCommit(repoPath, featureCommit, &CommitRequest{Name: "T", Email: "t@e.com"})
+	if err != nil {
+		t.Fatalf("CherryPickCommit() returned error: %v", err)
+	}
+	if pickHash == "" {
+		t.Fatalf("CherryPickCommit() returned an empty hash")
+	}
+
+	content, err := os.ReadFile(filepath.Join(repoPath, "feature.txt"))
+	if err != nil {
+		t.Fatalf("the cherry-picked file is missing: %v", err)
+	}
+	if string(content) != "feature work\n" {
+		t.Errorf("feature.txt = %q, want the cherry-picked content", string(content))
+	}
+
+	//The original commit message is preserved
+	status, _ := manager.Status(repoPath)
+	if status.Head.Subject != "add feature" {
+		t.Errorf("cherry-pick subject = %q, want %q", status.Head.Subject, "add feature")
+	}
+}
+
+func TestCherryPickPreservesOriginalAuthor(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	base := commitFile(t, manager, repoPath, "a.txt", "base\n", "base")
+
+	if err := manager.Checkout(repoPath, "feature", true); err != nil {
+		t.Fatalf("Checkout(create) returned error: %v", err)
+	}
+	writeFile(t, repoPath, "feature.txt", "work\n")
+	if _, err := manager.Commit(repoPath, &CommitRequest{
+		Message: "feature commit",
+		Files:   []string{"feature.txt"},
+		Name:    "Original Author",
+		Email:   "original@example.com",
+	}); err != nil {
+		t.Fatalf("Commit() returned error: %v", err)
+	}
+	featureCommit := headHash(t, manager, repoPath)
+
+	if err := manager.CheckoutCommit(repoPath, base); err != nil {
+		t.Fatalf("CheckoutCommit(base) returned error: %v", err)
+	}
+	if err := manager.Checkout(repoPath, "target", true); err != nil {
+		t.Fatalf("Checkout(create) returned error: %v", err)
+	}
+
+	if _, err := manager.CherryPickCommit(repoPath, featureCommit, &CommitRequest{
+		Name:  "Picker",
+		Email: "picker@example.com",
+	}); err != nil {
+		t.Fatalf("CherryPickCommit() returned error: %v", err)
+	}
+
+	status, _ := manager.Status(repoPath)
+	if status.Head.AuthorName != "Original Author" {
+		t.Errorf("author = %q, want the original author preserved", status.Head.AuthorName)
+	}
+	if status.Head.AuthorEmail != "original@example.com" {
+		t.Errorf("author email = %q, want the original preserved", status.Head.AuthorEmail)
+	}
+}
+
+func TestCherryPickRefusesConflict(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	base := commitFile(t, manager, repoPath, "shared.txt", "base\n", "base")
+
+	//Feature edits shared.txt
+	if err := manager.Checkout(repoPath, "feature", true); err != nil {
+		t.Fatalf("Checkout(create) returned error: %v", err)
+	}
+	commitFile(t, manager, repoPath, "shared.txt", "feature edit\n", "feature edits shared")
+	featureCommit := headHash(t, manager, repoPath)
+
+	//Target branch edits shared.txt differently, so the pre-image no longer
+	//matches and a clean cherry-pick is impossible.
+	if err := manager.CheckoutCommit(repoPath, base); err != nil {
+		t.Fatalf("CheckoutCommit(base) returned error: %v", err)
+	}
+	if err := manager.Checkout(repoPath, "target", true); err != nil {
+		t.Fatalf("Checkout(create) returned error: %v", err)
+	}
+	commitFile(t, manager, repoPath, "shared.txt", "target edit\n", "target edits shared")
+
+	if _, err := manager.CherryPickCommit(repoPath, featureCommit, &CommitRequest{Name: "T", Email: "t@e.com"}); err == nil {
+		t.Errorf("CherryPickCommit() onto a diverged file = nil error, want a refusal")
+	}
+
+	status, _ := manager.Status(repoPath)
+	if !status.Clean {
+		t.Errorf("a refused cherry-pick left the tree dirty: %+v", status.Changes)
+	}
+}
+
+func TestAmendCommitMessage(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	commitFile(t, manager, repoPath, "a.txt", "one\n", "typo in mesage")
+	original := headHash(t, manager, repoPath)
+
+	newHash, err := manager.AmendCommitMessage(repoPath, "fixed message", &CommitRequest{
+		Name:  "T",
+		Email: "t@e.com",
+	})
+	if err != nil {
+		t.Fatalf("AmendCommitMessage() returned error: %v", err)
+	}
+	if newHash == original {
+		t.Errorf("amend produced the same hash %q, want a new commit object", newHash)
+	}
+
+	status, _ := manager.Status(repoPath)
+	if status.Head.Subject != "fixed message" {
+		t.Errorf("HEAD subject = %q, want the amended message", status.Head.Subject)
+	}
+	if status.Head.Hash != newHash {
+		t.Errorf("HEAD = %q, want the amended commit %q", status.Head.Hash, newHash)
+	}
+
+	//The file content, i.e. the tree, must be unchanged
+	content, _ := os.ReadFile(filepath.Join(repoPath, "a.txt"))
+	if string(content) != "one\n" {
+		t.Errorf("amend altered the tree, a.txt = %q", string(content))
+	}
+
+	//Only one commit should exist — amend replaces, not appends
+	log, _ := manager.Log(repoPath, 10)
+	if len(log) != 1 {
+		t.Errorf("log has %d commits after amend, want 1", len(log))
+	}
+}
+
+func TestAmendPreservesAuthorAcrossMessageChange(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	writeFile(t, repoPath, "a.txt", "one\n")
+	if _, err := manager.Commit(repoPath, &CommitRequest{
+		Message: "original",
+		Files:   []string{"a.txt"},
+		Name:    "First Author",
+		Email:   "first@example.com",
+	}); err != nil {
+		t.Fatalf("Commit() returned error: %v", err)
+	}
+
+	if _, err := manager.AmendCommitMessage(repoPath, "reworded", &CommitRequest{
+		Name:  "Someone Else",
+		Email: "else@example.com",
+	}); err != nil {
+		t.Fatalf("AmendCommitMessage() returned error: %v", err)
+	}
+
+	status, _ := manager.Status(repoPath)
+	if status.Head.AuthorName != "First Author" {
+		t.Errorf("author = %q, want the original author preserved through amend", status.Head.AuthorName)
+	}
+}
+
+func TestAmendValidation(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	commitFile(t, manager, repoPath, "a.txt", "one\n", "first")
+
+	if _, err := manager.AmendCommitMessage(repoPath, "  ", &CommitRequest{}); err == nil {
+		t.Errorf("AmendCommitMessage() with a blank message = nil error, want an error")
+	}
+}
+
+func TestAmendRefusesDetachedHead(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+	first := commitFile(t, manager, repoPath, "a.txt", "one\n", "first")
+	commitFile(t, manager, repoPath, "a.txt", "two\n", "second")
+
+	if err := manager.CheckoutCommit(repoPath, first); err != nil {
+		t.Fatalf("CheckoutCommit() returned error: %v", err)
+	}
+	if _, err := manager.AmendCommitMessage(repoPath, "new message", &CommitRequest{}); err == nil {
+		t.Errorf("AmendCommitMessage() on a detached HEAD = nil error, want an error")
+	}
+}
+
+func TestParseResetMode(t *testing.T) {
+	tests := []struct {
+		name      string
+		mode      string
+		wantError bool
+	}{
+		{name: "soft", mode: "soft"},
+		{name: "mixed", mode: "mixed"},
+		{name: "hard", mode: "hard"},
+		{name: "empty defaults to mixed", mode: ""},
+		{name: "uppercase", mode: "HARD"},
+		{name: "padded", mode: "  soft  "},
+		{name: "unknown", mode: "medium", wantError: true},
+	}
+
+	for _, test := range tests {
+		t.Run(test.name, func(t *testing.T) {
+			_, err := parseResetMode(test.mode)
+			if test.wantError && err == nil {
+				t.Errorf("parseResetMode(%q) = nil error, want an error", test.mode)
+			}
+			if !test.wantError && err != nil {
+				t.Errorf("parseResetMode(%q) returned error: %v", test.mode, err)
+			}
+		})
+	}
+}
+
+func TestHistoryActionsOnNonRepo(t *testing.T) {
+	manager := newTestManager(t)
+	plain := t.TempDir()
+	dummy := strings.Repeat("a", 40)
+
+	if err := manager.CheckoutCommit(plain, dummy); err != ErrNotARepo {
+		t.Errorf("CheckoutCommit() on a plain folder = %v, want ErrNotARepo", err)
+	}
+	if err := manager.CreateTag(plain, "v1", dummy, "", "T", "t@e.com"); err != ErrNotARepo {
+		t.Errorf("CreateTag() on a plain folder = %v, want ErrNotARepo", err)
+	}
+	if _, err := manager.TagsForCommit(plain, dummy); err != ErrNotARepo {
+		t.Errorf("TagsForCommit() on a plain folder = %v, want ErrNotARepo", err)
+	}
+}

+ 3 - 0
src/mod/git/history_test.go

@@ -163,6 +163,9 @@ func TestValidateBranchName(t *testing.T) {
 		{name: "with slash", branch: "feature/login"},
 		{name: "with dash", branch: "fix-123"},
 		{name: "with dot", branch: "v3.0.2"},
+		//An empty name would build the malformed ref "refs/heads/"
+		{name: "empty", branch: "", wantError: true},
+		{name: "whitespace only", branch: "   ", wantError: true},
 		{name: "leading dash", branch: "-x", wantError: true},
 		{name: "leading slash", branch: "/x", wantError: true},
 		{name: "trailing slash", branch: "x/", wantError: true},

+ 47 - 2
src/mod/git/ignore_test.go

@@ -101,10 +101,12 @@ func TestAppendIgnoreRules(t *testing.T) {
 			want:     "*.tmp\n\n" + ignoreHeader + "\n*.log\n",
 		},
 		{
-			name:     "header is not repeated",
+			//A second call joins the existing block with no blank line between
+			//the rules — this is the case that used to grow a gap per call.
+			name:     "second call appends without a blank line",
 			existing: ignoreHeader + "\n*.tmp\n",
 			added:    []string{"*.log"},
-			want:     ignoreHeader + "\n*.tmp\n\n*.log\n",
+			want:     ignoreHeader + "\n*.tmp\n*.log\n",
 		},
 		{
 			name:     "several rules",
@@ -112,6 +114,12 @@ func TestAppendIgnoreRules(t *testing.T) {
 			added:    []string{"a", "b"},
 			want:     ignoreHeader + "\na\nb\n",
 		},
+		{
+			name:     "adds a missing trailing newline before joining",
+			existing: ignoreHeader + "\n*.tmp",
+			added:    []string{"*.log"},
+			want:     ignoreHeader + "\n*.tmp\n*.log\n",
+		},
 	}
 
 	for _, test := range tests {
@@ -169,6 +177,43 @@ func TestAddIgnoreRulesPreservesExistingContent(t *testing.T) {
 	}
 }
 
+// TestAddIgnoreRulesRepeatedCallsHaveNoBlankLines reproduces the reported bug:
+// ignoring several folders one at a time must not leave a blank line between
+// every rule.
+func TestAddIgnoreRulesRepeatedCallsHaveNoBlankLines(t *testing.T) {
+	manager := newTestManager(t)
+	repoPath := newTestRepo(t, manager)
+
+	//Seed the file with the user's own content, as in the report
+	writeFile(t, repoPath, gitignoreName, "# Runtime state\ndata/\n")
+
+	for _, rule := range []string{"/.metadata", "/img/.metadata", "/previews/.metadata"} {
+		if _, err := manager.AddIgnoreRules(repoPath, []string{rule}); err != nil {
+			t.Fatalf("AddIgnoreRules(%q) returned error: %v", rule, err)
+		}
+	}
+
+	raw, err := os.ReadFile(filepath.Join(repoPath, gitignoreName))
+	if err != nil {
+		t.Fatalf("cannot read .gitignore: %v", err)
+	}
+
+	want := "# Runtime state\ndata/\n\n" + ignoreHeader + "\n/.metadata\n/img/.metadata\n/previews/.metadata\n"
+	if string(raw) != want {
+		t.Errorf("after three separate calls .gitignore =\n%q\nwant\n%q", string(raw), want)
+	}
+
+	//There must be exactly one blank line in the whole file: the one before the
+	//GitApp block. None between the appended rules.
+	if strings.Contains(string(raw), "\n\n"+ignoreHeader+"\n\n") {
+		t.Errorf("a blank line crept in right after the header: %q", string(raw))
+	}
+	blocks := strings.Split(strings.TrimRight(string(raw), "\n"), "\n\n")
+	if len(blocks) != 2 {
+		t.Errorf("expected 2 blocks separated by a single blank line, got %d: %q", len(blocks), string(raw))
+	}
+}
+
 func TestAddIgnoreRulesSkipsDuplicates(t *testing.T) {
 	manager := newTestManager(t)
 	repoPath := newTestRepo(t, manager)

+ 6 - 2
src/mod/git/types.go

@@ -49,15 +49,18 @@ type CommitInfo struct {
 	AuthorEmail string   `json:"authorEmail"`
 	Timestamp   int64    `json:"timestamp"` //Author time, unix seconds
 	Parents     []string `json:"parents"`
+	Tags        []string `json:"tags,omitempty"` //Tag names pointing at this commit
 }
 
 // BranchInfo is one entry of the branch switcher dropdown.
 type BranchInfo struct {
-	Name      string `json:"name"`
-	FullRef   string `json:"fullRef"`
+	Name      string `json:"name"`    //Display name, e.g. "master" or "origin/master"
+	FullRef   string `json:"fullRef"` //Fully qualified ref name
 	Hash      string `json:"hash"`
 	IsRemote  bool   `json:"isRemote"`
 	IsCurrent bool   `json:"isCurrent"`
+	Remote    string `json:"remote,omitempty"` //Owning remote, remote-tracking branches only
+	Short     string `json:"short,omitempty"`  //Branch name without the remote prefix
 }
 
 // RemoteInfo is a configured git remote.
@@ -139,6 +142,7 @@ type OperationResult struct {
 	Success      bool   `json:"success"`
 	Error        string `json:"error,omitempty"`
 	AuthRequired bool   `json:"authRequired,omitempty"` //Remote rejected the credentials (or wanted some)
+	Unmerged     bool   `json:"unmerged,omitempty"`     //Branch delete refused: it holds unmerged commits, retry with force
 	Hash         string `json:"hash,omitempty"`         //New commit hash, set by Commit
 	Message      string `json:"message,omitempty"`      //Human readable note, e.g. "already up to date"
 }

+ 77 - 0
src/web/GitApp/backend/branchaction.agi

@@ -0,0 +1,77 @@
+/*
+	GitApp — branch action backend
+
+	Drives the branch dropdown's right-click menu: deleting and renaming both
+	local branches and branches on a remote.
+
+	Remote operations are network pushes, so they can come back with
+	authRequired and be retried with credentials, exactly like push and pull.
+
+	POST opr      = delete | rename | deleteremote | renameremote
+	     repo     = virtual path of the repository
+	     branch   = branch name (without any remote prefix)
+	     newName  = new branch name          (rename, renameremote)
+	     remote   = remote name              (deleteremote, renameremote)
+	     force    = "true" to delete a branch holding unmerged commits (delete)
+	     username = HTTPS user name          (remote operations)
+	     token    = HTTPS token / password   (remote operations)
+	     remember = "true" to store the credential once it works
+*/
+
+requirelib("git");
+
+HTTP_HEADER = "application/json; charset=utf-8";
+
+//buildOptions collects the optional credential fields. Absent fields are left
+//out so the git library falls back to the user's stored credential.
+function buildOptions() {
+    var options = {};
+
+    if (typeof username != "undefined" && username != "") {
+        options.username = username;
+    }
+    if (typeof token != "undefined" && token != "") {
+        options.token = token;
+    }
+    if (typeof remember != "undefined" && remember == "true") {
+        options.remember = true;
+    }
+    return options;
+}
+
+function remoteName() {
+    if (typeof remote != "undefined" && remote != "") {
+        return remote;
+    }
+    return "origin";
+}
+
+if (typeof repo == "undefined" || repo == "") {
+    sendJSONResp({ success: false, error: "repository path is required" });
+} else if (typeof branch == "undefined" || branch.trim() == "") {
+    sendJSONResp({ success: false, error: "a branch name is required" });
+} else if (opr == "delete") {
+    sendJSONResp(git.deleteBranch(repo, branch.trim(),
+        typeof force != "undefined" && force == "true"));
+
+} else if (opr == "rename") {
+    if (typeof newName == "undefined" || newName.trim() == "") {
+        sendJSONResp({ success: false, error: "a new branch name is required" });
+    } else {
+        sendJSONResp(git.renameBranch(repo, branch.trim(), newName.trim()));
+    }
+
+} else if (opr == "deleteremote") {
+    sendJSONResp(git.deleteRemoteBranch(repo, remoteName(), branch.trim(), buildOptions()));
+
+} else if (opr == "renameremote") {
+    if (typeof newName == "undefined" || newName.trim() == "") {
+        sendJSONResp({ success: false, error: "a new branch name is required" });
+    } else {
+        sendJSONResp(git.renameRemoteBranch(repo, remoteName(),
+            branch.trim(), newName.trim(), buildOptions()));
+    }
+
+} else {
+    sendJSONResp({ success: false, error: "unknown operation: " + opr });
+}

+ 68 - 0
src/web/GitApp/backend/commitaction.agi

@@ -0,0 +1,68 @@
+/*
+	GitApp — commit action backend
+
+	Drives the History tab's right-click menu. Every action is scoped to a
+	single commit identified by its hash.
+
+	POST opr     = checkout | reset | branch | tag | revert | cherrypick | amend
+	     repo    = virtual path of the repository
+	     hash    = target commit hash
+	     mode    = reset mode: soft | mixed | hard        (reset only)
+	     branch  = new branch name                        (branch only)
+	     tag     = new tag name                           (tag only)
+	     message = tag annotation / new commit message    (tag, amend)
+*/
+
+requirelib("git");
+
+HTTP_HEADER = "application/json; charset=utf-8";
+
+if (typeof repo == "undefined" || repo == "") {
+    sendJSONResp({ success: false, error: "repository path is required" });
+} else if (opr == "amend") {
+    //Amend targets HEAD, so it is the one action that needs a message but not a
+    //hash.
+    if (typeof message == "undefined" || message.trim() == "") {
+        sendJSONResp({ success: false, error: "a commit message is required" });
+    } else {
+        sendJSONResp(git.amendMessage(repo, message.trim()));
+    }
+} else if (typeof hash == "undefined" || hash == "") {
+    sendJSONResp({ success: false, error: "a commit hash is required" });
+} else if (opr == "checkout") {
+    sendJSONResp(git.checkoutCommit(repo, hash));
+
+} else if (opr == "reset") {
+    var resetMode = "mixed";
+    if (typeof mode != "undefined" && mode != "") {
+        resetMode = mode;
+    }
+    sendJSONResp(git.resetToCommit(repo, hash, resetMode));
+
+} else if (opr == "branch") {
+    if (typeof branch == "undefined" || branch.trim() == "") {
+        sendJSONResp({ success: false, error: "a branch name is required" });
+    } else {
+        sendJSONResp(git.createBranchAt(repo, branch.trim(), hash));
+    }
+
+} else if (opr == "tag") {
+    if (typeof tag == "undefined" || tag.trim() == "") {
+        sendJSONResp({ success: false, error: "a tag name is required" });
+    } else {
+        var annotation = "";
+        if (typeof message != "undefined") {
+            annotation = message.trim();
+        }
+        sendJSONResp(git.createTag(repo, tag.trim(), hash, annotation));
+    }
+
+} else if (opr == "revert") {
+    sendJSONResp(git.revertCommit(repo, hash, {}));
+
+} else if (opr == "cherrypick") {
+    sendJSONResp(git.cherryPickCommit(repo, hash, {}));
+
+} else {
+    sendJSONResp({ success: false, error: "unknown operation: " + opr });
+}

+ 14 - 0
src/web/GitApp/script/gitapp.css

@@ -520,6 +520,20 @@ button i.icon {
     text-overflow: ellipsis;
 }
 
+/* Tag chip shown before a commit subject */
+.commitentry .taglabel {
+    display: inline-block;
+    vertical-align: middle;
+    margin-right: 5px;
+    padding: 0 6px;
+    border-radius: 9px;
+    background: var(--status-renamed);
+    color: #ffffff;
+    font-size: 10px;
+    font-weight: 600;
+    line-height: 16px;
+}
+
 .commitentry .meta {
     font-size: 11px;
     color: var(--muted);

+ 583 - 5
src/web/GitApp/script/gitapp.js

@@ -262,8 +262,12 @@ function renderFileList() {
         });
 
         //The path is rendered right-to-left so a long folder chain truncates on
-        //the left and the file name always stays visible.
-        var label = $("<div class='fname'></div>").attr("title", change.path).text(change.path);
+        //the left and the file name always stays visible. A leading Left-to-Right
+        //Mark keeps names that start with a neutral character (".gitignore") from
+        //having that character reordered to the visual end by the RTL bidi rules.
+        var label = $("<div class='fname'></div>")
+            .attr("title", change.path)
+            .text("‎" + change.path);
 
         row.append(box).append(label).append(statusMark(change));
         row.on("click", function() {
@@ -437,6 +441,22 @@ function remoteHostLabel() {
     return "";
 }
 
+//remoteUrlByName finds a named remote's URL, so a sign-in prompt raised by a
+//branch operation names the remote it is actually talking to rather than
+//whichever one happens to be first.
+function remoteUrlByName(name) {
+    if (!state.status || !state.status.remotes) {
+        return "";
+    }
+    for (var i = 0; i < state.status.remotes.length; i++) {
+        var remote = state.status.remotes[i];
+        if (remote.name === name && remote.urls.length > 0) {
+            return remote.urls[0];
+        }
+    }
+    return remoteHostLabel();
+}
+
 /* ── Diff pane ────────────────────────────────────────────────────────── */
 
 function showWorktreeDiff(path) {
@@ -801,19 +821,33 @@ function renderCommitList() {
         return;
     }
 
+    var headHash = (state.status && state.status.head) ? state.status.head.hash : null;
+
     state.commits.forEach(function(commit) {
         var entry = $("<div class='commitentry'></div>");
         if (commit.hash === state.activeCommit) {
             entry.addClass("active");
         }
 
-        entry.append($("<div class='subject'></div>").text(commit.subject));
+        var subject = $("<div class='subject'></div>").text(commit.subject);
+        //Tags on this commit are shown as small labels, like GitHub Desktop
+        if (commit.tags && commit.tags.length > 0) {
+            commit.tags.forEach(function(tag) {
+                subject.prepend($("<span class='taglabel'></span>").text(tag));
+            });
+        }
+        entry.append(subject);
         entry.append($("<div class='meta'></div>").text(
             commit.authorName + " · " + formatTime(commit.timestamp) + " · " + commit.shortHash));
 
         entry.on("click", function() {
             selectCommit(commit.hash);
         });
+        entry.on("contextmenu", function(event) {
+            event.preventDefault();
+            selectCommit(commit.hash);
+            openCommitContextMenu(commit, commit.hash === headHash, event.clientX, event.clientY);
+        });
         list.append(entry);
     });
 }
@@ -853,6 +887,317 @@ function formatTime(unixSeconds) {
     return date.toLocaleDateString() + " " + date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
 }
 
+/* ── Commit context menu (History tab) ────────────────────────────────── */
+
+/*
+    openCommitContextMenu builds the right-click menu for one commit, mirroring
+    GitHub Desktop. isHead marks the tip of the current branch, which gates the
+    actions that only make sense there (amend) and the ones that would be a
+    no-op on it (reset/checkout to where you already are).
+
+    "Reorder commit" needs an interactive rebase, which go-git cannot do, so it
+    is shown disabled — exactly as it appears greyed in GitHub Desktop when it
+    is unavailable.
+*/
+function openCommitContextMenu(commit, isHead, clientX, clientY) {
+    var menu = $("#fileContextMenu").empty();
+    var branchAttached = state.status && state.status.branch && !state.status.detached;
+
+    menu.append(menuItem("Amend commit message…", function() {
+        openAmendDialog(commit);
+    }, {
+        disabled: !(isHead && branchAttached),
+        title: isHead ? "" : "Only the latest commit on a branch can be amended"
+    }));
+
+    menu.append(menuItem("Reset to commit…", function() {
+        openResetDialog(commit);
+    }, { disabled: !branchAttached, title: branchAttached ? "" : "Check out a branch first" }));
+
+    menu.append(menuItem("Checkout commit", function() {
+        commitAction("checkout", { hash: commit.hash }, "Checking out…");
+    }, { disabled: isHead }));
+
+    //Interactive rebase is not available through go-git
+    menu.append(menuItem("Reorder commit", null, {
+        disabled: true,
+        title: "Reordering commits is not supported"
+    }));
+
+    menu.append(menuItem("Revert changes in commit", function() {
+        confirmDialog("Revert this commit?",
+            "A new commit will be created that undoes the changes in \"" + commit.subject + "\".",
+            function() {
+                commitAction("revert", { hash: commit.hash }, "Reverting…");
+            });
+    }));
+
+    menu.append(menuDivider());
+
+    menu.append(menuItem("Create branch from commit", function() {
+        openBranchFromCommitDialog(commit);
+    }));
+
+    menu.append(menuItem("Create Tag…", function() {
+        openCreateTagDialog(commit);
+    }));
+
+    menu.append(menuItem("Cherry-pick commit…", function() {
+        confirmDialog("Cherry-pick this commit?",
+            "The changes in \"" + commit.subject + "\" will be applied on top of your current branch.",
+            function() {
+                commitAction("cherrypick", { hash: commit.hash }, "Cherry-picking…");
+            });
+    }, { disabled: isHead, title: isHead ? "This commit is already the branch tip" : "" }));
+
+    menu.append(menuDivider());
+
+    menu.append(menuItem("Copy SHA", function() {
+        copyToClipboard(commit.hash, "commit SHA");
+    }, { title: commit.hash }));
+
+    var tag = (commit.tags && commit.tags.length > 0) ? commit.tags[0] : "";
+    menu.append(menuItem(tag ? "Copy tag (" + tag + ")" : "Copy tag", function() {
+        copyToClipboard(tag, "tag name");
+    }, { disabled: tag === "" }));
+
+    var webUrl = commitWebUrl(commit.hash);
+    menu.append(menuItem(webUrl ? "View on " + webUrl.host : "View on remote", function() {
+        window.open(webUrl.url, "_blank", "noopener");
+    }, { disabled: !webUrl, title: webUrl ? webUrl.url : "No web-viewable remote is configured" }));
+
+    placeMenu(menu, clientX, clientY);
+}
+
+/* ── Commit action plumbing ───────────────────────────────────────────── */
+
+//commitAction posts one commitaction.agi operation and refreshes on success.
+function commitAction(operation, params, busyMessage, afterwards) {
+    var payload = { opr: operation, repo: state.repo };
+    for (var key in params) {
+        if (params.hasOwnProperty(key)) {
+            payload[key] = params[key];
+        }
+    }
+
+    setBusy(busyMessage);
+    call("commitaction.agi", payload, function(reply) {
+        clearBusy();
+        if (!reply.success) {
+            setStatus(reply.error, true);
+            return;
+        }
+
+        var outcome = reply.message || "Done";
+        //A history action can move HEAD, change branch or rewrite commits, so
+        //refresh both the working-tree status and the commit list.
+        state.activeFile = null;
+        refreshStatus(function() {
+            loadHistory();
+            setStatus(outcome);
+        });
+
+        if (typeof afterwards === "function") {
+            afterwards(reply);
+        }
+    });
+}
+
+/*
+    commitWebUrl turns the repository's first remote into a web URL for a commit,
+    or null when there is no http/ssh remote to build one from. Host families
+    that use a different commit path (GitLab) are handled explicitly; everything
+    else falls back to the widespread "/commit/<sha>" convention.
+*/
+function commitWebUrl(hash) {
+    if (!state.status || !state.status.remotes || state.status.remotes.length === 0) {
+        return null;
+    }
+    var urls = state.status.remotes[0].urls;
+    if (!urls || urls.length === 0) {
+        return null;
+    }
+
+    var base = remoteToWebBase(urls[0]);
+    if (!base) {
+        return null;
+    }
+
+    var commitPath = base.host.indexOf("gitlab") !== -1 ? "/-/commit/" : "/commit/";
+    return { host: base.host, url: base.url + commitPath + hash };
+}
+
+//remoteToWebBase normalises an https or scp-style git remote into a browsable
+//https base URL and its host.
+function remoteToWebBase(remoteUrl) {
+    remoteUrl = (remoteUrl || "").trim();
+    if (remoteUrl === "") {
+        return null;
+    }
+
+    var host = "";
+    var path = "";
+
+    //Three remote forms: http(s) URL, ssh:// URL (may carry a :port before the
+    //path), and scp-style git@host:path (the colon is the path separator, so it
+    //has no port to strip).
+    var httpsMatch = remoteUrl.match(/^https?:\/\/([^/]+)\/(.+)$/i);
+    var sshUrlMatch = remoteUrl.match(/^ssh:\/\/(?:[^@]+@)?([^:/]+)(?::\d+)?\/(.+)$/i);
+    var scpMatch = remoteUrl.match(/^(?:[^@]+@)?([^:/]+):(.+)$/i);
+
+    if (httpsMatch) {
+        host = httpsMatch[1].split("@").pop(); // drop any user:pass@ prefix
+        path = httpsMatch[2];
+    } else if (sshUrlMatch) {
+        host = sshUrlMatch[1];
+        path = sshUrlMatch[2];
+    } else if (scpMatch) {
+        host = scpMatch[1];
+        path = scpMatch[2];
+    } else {
+        return null;
+    }
+
+    host = host.replace(/:\d+$/, "");                 // drop a port on http(s) hosts
+    path = path.replace(/\.git$/i, "").replace(/\/+$/, "");
+    return { host: host, url: "https://" + host + "/" + path };
+}
+
+/* ── Commit action dialogs ────────────────────────────────────────────── */
+
+function openAmendDialog(commit) {
+    var box = $("<div></div>");
+    box.append($("<h3></h3>").text("Amend commit message"));
+    box.append($("<div class='desc'></div>").text(
+        "This rewrites the latest commit's message. Its changes and author are kept."));
+
+    var summary = $("<input type='text'>").val(commit.subject);
+    box.append($("<div class='field'></div>")
+        .append($("<label></label>").text("Message"))
+        .append(summary));
+
+    var actions = $("<div class='modalactions'></div>");
+    actions.append($("<button>Cancel</button>").on("click", closeModal));
+    actions.append($("<button class='primary'>Amend</button>").on("click", function() {
+        if (summary.val().trim() === "") {
+            return;
+        }
+        closeModal();
+        commitAction("amend", { message: summary.val().trim() }, "Amending…");
+    }));
+    box.append(actions);
+
+    openModal(box);
+    summary.trigger("focus");
+}
+
+function openResetDialog(commit) {
+    var box = $("<div></div>");
+    box.append($("<h3></h3>").text("Reset to commit"));
+    box.append($("<div class='desc'></div>").text(
+        "Move the current branch back to \"" + commit.subject + "\" (" + commit.shortHash + ")."));
+
+    //One radio group for the three reset modes, mixed selected by default
+    var modes = [
+        { value: "soft", label: "Soft — keep all changes staged" },
+        { value: "mixed", label: "Mixed — keep changes, unstaged (default)" },
+        { value: "hard", label: "Hard — discard all changes since this commit" }
+    ];
+    var group = $("<div class='field'></div>");
+    modes.forEach(function(mode) {
+        var id = "resetmode_" + mode.value;
+        var row = $("<div class='field inline'></div>");
+        var radio = $("<input type='radio' name='resetmode'>").attr("id", id).val(mode.value);
+        if (mode.value === "mixed") {
+            radio.prop("checked", true);
+        }
+        row.append(radio).append($("<label></label>").attr("for", id).text(mode.label));
+        group.append(row);
+    });
+    box.append(group);
+
+    var warning = $("<div class='modalerror hidden'></div>").text(
+        "A hard reset permanently discards every change since the selected commit.");
+    box.append(warning);
+    group.find("input[type=radio]").on("change", function() {
+        warning.toggleClass("hidden", $("input[name=resetmode]:checked").val() !== "hard");
+    });
+
+    var actions = $("<div class='modalactions'></div>");
+    actions.append($("<button>Cancel</button>").on("click", closeModal));
+    actions.append($("<button class='primary'>Reset</button>").on("click", function() {
+        var mode = $("input[name=resetmode]:checked").val();
+        closeModal();
+        commitAction("reset", { hash: commit.hash, mode: mode }, "Resetting…");
+    }));
+    box.append(actions);
+
+    openModal(box);
+}
+
+function openBranchFromCommitDialog(commit) {
+    var box = $("<div></div>");
+    box.append($("<h3></h3>").text("Create a branch"));
+    box.append($("<div class='desc'></div>").text(
+        "The new branch will start at \"" + commit.subject + "\" (" + commit.shortHash + ")."));
+
+    var name = $("<input type='text' placeholder='feature/my-change'>");
+    box.append($("<div class='field'></div>")
+        .append($("<label></label>").text("Branch name"))
+        .append(name));
+
+    var actions = $("<div class='modalactions'></div>");
+    actions.append($("<button>Cancel</button>").on("click", closeModal));
+    actions.append($("<button class='primary'>Create branch</button>").on("click", function() {
+        if (name.val().trim() === "") {
+            return;
+        }
+        closeModal();
+        commitAction("branch", { branch: name.val().trim(), hash: commit.hash }, "Creating branch…");
+    }));
+    box.append(actions);
+
+    openModal(box);
+    name.trigger("focus");
+}
+
+function openCreateTagDialog(commit) {
+    var box = $("<div></div>");
+    box.append($("<h3></h3>").text("Create a tag"));
+    box.append($("<div class='desc'></div>").text(
+        "Tag \"" + commit.subject + "\" (" + commit.shortHash + ")."));
+
+    var name = $("<input type='text' placeholder='v1.0.0'>");
+    var message = $("<input type='text' placeholder='Optional annotation'>");
+
+    box.append($("<div class='field'></div>")
+        .append($("<label></label>").text("Tag name"))
+        .append(name));
+    box.append($("<div class='field'></div>")
+        .append($("<label></label>").text("Message"))
+        .append(message)
+        .append($("<div class='hint'></div>").text(
+            "Leave empty for a lightweight tag; add a message for an annotated one.")));
+
+    var actions = $("<div class='modalactions'></div>");
+    actions.append($("<button>Cancel</button>").on("click", closeModal));
+    actions.append($("<button class='primary'>Create tag</button>").on("click", function() {
+        if (name.val().trim() === "") {
+            return;
+        }
+        closeModal();
+        commitAction("tag", {
+            tag: name.val().trim(),
+            hash: commit.hash,
+            message: message.val().trim()
+        }, "Creating tag…");
+    }));
+    box.append(actions);
+
+    openModal(box);
+    name.trigger("focus");
+}
+
 /* ── Commit ───────────────────────────────────────────────────────────── */
 
 function doCommit() {
@@ -921,11 +1266,242 @@ function loadBranches() {
                 closePopovers();
                 checkoutBranch(branch.name, false);
             });
+            item.on("contextmenu", function(event) {
+                event.preventDefault();
+                event.stopPropagation();
+                openBranchContextMenu(branch, event.clientX, event.clientY);
+            });
             list.append(item);
         });
     });
 }
 
+/* ── Branch context menu ──────────────────────────────────────────────── */
+
+/*
+    openBranchContextMenu builds the right-click menu for one row of the branch
+    dropdown. A local branch can be renamed or deleted locally; a remote-tracking
+    row acts on the branch as it exists on the server, which means a network push
+    and therefore the same credential retry flow as push and pull.
+*/
+function openBranchContextMenu(branch, clientX, clientY) {
+    var menu = $("#fileContextMenu").empty();
+    //The branch name without any remote prefix; the backend never wants the prefix
+    var shortName = branch.short || branch.name;
+
+    if (branch.isRemote) {
+        var remote = branch.remote || "origin";
+
+        menu.append(menuItem("Rename branch on " + remote + "…", function() {
+            openBranchRenameDialog(branch, shortName, true);
+        }));
+
+        menu.append(menuItem("Delete branch on " + remote + "…", function() {
+            confirmDialog("Delete " + branch.name + " on the remote?",
+                "The branch will be removed from " + remote +
+                " for everyone. Your local branches are not affected.",
+                function() {
+                    deleteRemoteBranch(remote, shortName);
+                });
+        }));
+    } else {
+        menu.append(menuItem("Rename branch…", function() {
+            openBranchRenameDialog(branch, shortName, false);
+        }));
+
+        menu.append(menuItem("Delete branch…", function() {
+            confirmDialog("Delete branch " + shortName + "?",
+                "The local branch will be removed. Any branch of the same name on a remote is not affected.",
+                function() {
+                    deleteLocalBranch(shortName, false);
+                });
+        }, {
+            disabled: branch.isCurrent,
+            title: branch.isCurrent ? "Switch to another branch before deleting this one" : ""
+        }));
+    }
+
+    menu.append(menuDivider());
+
+    menu.append(menuItem("Copy branch name", function() {
+        copyToClipboard(branch.name, "branch name");
+    }, { title: branch.name }));
+
+    placeMenu(menu, clientX, clientY);
+}
+
+/*
+    deleteLocalBranch removes a local branch, and when the branch still holds
+    unmerged commits asks for confirmation before repeating the call with force —
+    the same protection `git branch -d` gives over `-D`.
+*/
+function deleteLocalBranch(branch, force) {
+    setBusy("Deleting branch…");
+    call("branchaction.agi", {
+        opr: "delete",
+        repo: state.repo,
+        branch: branch,
+        force: force ? "true" : "false"
+    }, function(reply) {
+        clearBusy();
+
+        if (reply.success) {
+            afterBranchChange(reply.message || "Deleted branch " + branch);
+            return;
+        }
+
+        if (reply.unmerged) {
+            confirmDialog("Delete " + branch + " anyway?",
+                "This branch has commits that are not merged into your current branch. " +
+                "Deleting it will lose them.",
+                function() {
+                    deleteLocalBranch(branch, true);
+                });
+            return;
+        }
+        setStatus(reply.error, true);
+    });
+}
+
+//deleteRemoteBranch removes a branch on the server, retrying with credentials
+//when the remote asks for them.
+function deleteRemoteBranch(remote, branch, credentials) {
+    var payload = {
+        opr: "deleteremote",
+        repo: state.repo,
+        remote: remote,
+        branch: branch
+    };
+    applyCredentials(payload, credentials);
+
+    setBusy("Deleting " + remote + "/" + branch + "…");
+    call("branchaction.agi", payload, function(reply) {
+        clearBusy();
+
+        if (reply.success) {
+            afterBranchChange(reply.message || "Deleted " + remote + "/" + branch);
+            return;
+        }
+        if (reply.authRequired) {
+            openCredentialDialog(remoteUrlByName(remote), function(entered) {
+                deleteRemoteBranch(remote, branch, entered);
+            });
+            return;
+        }
+        setStatus(reply.error, true);
+    });
+}
+
+function renameLocalBranch(oldName, newName) {
+    setBusy("Renaming branch…");
+    call("branchaction.agi", {
+        opr: "rename",
+        repo: state.repo,
+        branch: oldName,
+        newName: newName
+    }, function(reply) {
+        clearBusy();
+        if (!reply.success) {
+            setStatus(reply.error, true);
+            return;
+        }
+        afterBranchChange(reply.message || "Renamed to " + newName);
+    });
+}
+
+function renameRemoteBranch(remote, oldName, newName, credentials) {
+    var payload = {
+        opr: "renameremote",
+        repo: state.repo,
+        remote: remote,
+        branch: oldName,
+        newName: newName
+    };
+    applyCredentials(payload, credentials);
+
+    setBusy("Renaming " + remote + "/" + oldName + "…");
+    call("branchaction.agi", payload, function(reply) {
+        clearBusy();
+
+        if (reply.success) {
+            afterBranchChange(reply.message || "Renamed to " + remote + "/" + newName);
+            return;
+        }
+        if (reply.authRequired) {
+            openCredentialDialog(remoteUrlByName(remote), function(entered) {
+                renameRemoteBranch(remote, oldName, newName, entered);
+            });
+            return;
+        }
+        setStatus(reply.error, true);
+    });
+}
+
+//applyCredentials copies the sign-in dialog's answer onto a request payload.
+function applyCredentials(payload, credentials) {
+    if (!credentials) {
+        return;
+    }
+    payload.username = credentials.username;
+    payload.token = credentials.token;
+    payload.remember = credentials.remember ? "true" : "false";
+}
+
+/*
+    afterBranchChange refreshes everything a branch change can affect. Renaming or
+    deleting the checked-out branch moves HEAD, so the toolbar, the changes list
+    and the history all need rereading, and the branch dropdown is rebuilt if it
+    is still open.
+*/
+function afterBranchChange(message) {
+    state.activeFile = null;
+    refreshStatus(function() {
+        if (state.tab === "history") {
+            loadHistory();
+        }
+        if ($("#branchPopover").hasClass("open")) {
+            loadBranches();
+        }
+        setStatus(message);
+    });
+}
+
+function openBranchRenameDialog(branch, shortName, isRemote) {
+    var remote = branch.remote || "origin";
+
+    var box = $("<div></div>");
+    box.append($("<h3></h3>").text(isRemote ? "Rename branch on " + remote : "Rename branch"));
+    box.append($("<div class='desc'></div>").text(isRemote
+        ? "The branch is pushed under the new name and the old name is then removed from " + remote + "."
+        : "Renaming keeps the branch's commits and its upstream configuration."));
+
+    var name = $("<input type='text'>").val(shortName);
+    box.append($("<div class='field'></div>")
+        .append($("<label></label>").text("New name"))
+        .append(name));
+
+    var actions = $("<div class='modalactions'></div>");
+    actions.append($("<button>Cancel</button>").on("click", closeModal));
+    actions.append($("<button class='primary'>Rename</button>").on("click", function() {
+        var newName = name.val().trim();
+        if (newName === "" || newName === shortName) {
+            closeModal();
+            return;
+        }
+        closeModal();
+
+        if (isRemote) {
+            renameRemoteBranch(remote, shortName, newName);
+        } else {
+            renameLocalBranch(shortName, newName);
+        }
+    }));
+    box.append(actions);
+
+    openModal(box);
+    name.trigger("focus");
+}
+
 function checkoutBranch(branch, create) {
     setBusy("Switching branch…");
     call("branch.agi", {
@@ -1984,12 +2560,14 @@ $(document).ready(function() {
             event.preventDefault();
             return;
         }
-        if ($(event.target).closest(".filerow").length === 0) {
+        //The file rows and the commit entries open their own menus; a right
+        //click anywhere else dismisses whatever is open.
+        if ($(event.target).closest(".filerow, .commitentry").length === 0) {
             closeContextMenu();
         }
     });
 
-    $("#fileList").on("scroll", closeContextMenu);
+    $("#fileList, #commitList, #branchList, #repoList").on("scroll", closeContextMenu);
     $(window).on("blur", closeContextMenu);
     $("#modalMask").on("click", function(event) {
         if (event.target === this) {

+ 79 - 2
src/web/Terminal/docs/api.json

@@ -1188,14 +1188,63 @@
     {
      "name": "git.log",
      "sig": "git.log(vpath, limit)",
-     "desc": "Commits reachable from HEAD, newest first (default limit 50). Each has hash, shortHash, subject, message, authorName, authorEmail, timestamp and parents.",
+     "desc": "Commits reachable from HEAD, newest first (default limit 50). Each has hash, shortHash, subject, message, authorName, authorEmail, timestamp and parents. Each commit also carries a tags array of tag names pointing at it.",
      "ret": "array",
      "example": "var commits = git.log(\"user:/Desktop/myproject\", 10);\ncommits.forEach(function(c) {\n    console.log(c.shortHash + \" \" + c.subject);\n});"
     },
+    {
+     "name": "git.checkoutCommit",
+     "sig": "git.checkoutCommit(vpath, hash)",
+     "desc": "Check a commit out in detached HEAD state. Refuses when the working tree has uncommitted changes.",
+     "ret": "object",
+     "example": "requirelib(\"git\");\ngit.checkoutCommit(\"user:/Desktop/myproject\", commitHash);"
+    },
+    {
+     "name": "git.resetToCommit",
+     "sig": "git.resetToCommit(vpath, hash, mode)",
+     "desc": "Move the current branch to a commit. mode is \"soft\" (HEAD only), \"mixed\" (also the index, the default) or \"hard\" (also the working tree). A hard reset refuses when there are uncommitted changes.",
+     "ret": "object",
+     "example": "requirelib(\"git\");\ngit.resetToCommit(\"user:/Desktop/myproject\", commitHash, \"soft\");"
+    },
+    {
+     "name": "git.createBranchAt",
+     "sig": "git.createBranchAt(vpath, branch, hash)",
+     "desc": "Create a branch pointing at a commit and check it out.",
+     "ret": "object",
+     "example": "requirelib(\"git\");\ngit.createBranchAt(\"user:/Desktop/myproject\", \"hotfix\", commitHash);"
+    },
+    {
+     "name": "git.createTag",
+     "sig": "git.createTag(vpath, tag, hash, message)",
+     "desc": "Tag a commit. A non-empty message produces an annotated tag, otherwise a lightweight one.",
+     "ret": "object",
+     "example": "requirelib(\"git\");\ngit.createTag(\"user:/Desktop/myproject\", \"v1.0\", commitHash, \"First release\");"
+    },
+    {
+     "name": "git.revertCommit",
+     "sig": "git.revertCommit(vpath, hash, options)",
+     "desc": "Create a new commit undoing a commit's changes. Uses a clean-or-refuse strategy: since go-git has no merge engine, the revert is applied only when the affected files still match the reverted commit, otherwise it is refused rather than producing a wrong result. options may carry name and email.",
+     "ret": "object",
+     "example": "requirelib(\"git\");\nvar result = git.revertCommit(\"user:/Desktop/myproject\", commitHash, {});\nif (!result.success) { console.log(result.error); }"
+    },
+    {
+     "name": "git.cherryPickCommit",
+     "sig": "git.cherryPickCommit(vpath, hash, options)",
+     "desc": "Apply a commit's changes onto the current HEAD, preserving the original author. Uses the same clean-or-refuse strategy as revert. options may carry name and email for the committer.",
+     "ret": "object",
+     "example": "requirelib(\"git\");\ngit.cherryPickCommit(\"user:/Desktop/myproject\", commitHash, {});"
+    },
+    {
+     "name": "git.amendMessage",
+     "sig": "git.amendMessage(vpath, message, options)",
+     "desc": "Rewrite the message of the HEAD commit, keeping its tree, parents and author. Only a branch tip can be amended.",
+     "ret": "object",
+     "example": "requirelib(\"git\");\ngit.amendMessage(\"user:/Desktop/myproject\", \"Corrected commit message\", {});"
+    },
     {
      "name": "git.branches",
      "sig": "git.branches(vpath)",
-     "desc": "Local and remote-tracking branches: name, fullRef, hash, isRemote, isCurrent.",
+     "desc": "Local and remote-tracking branches: name, fullRef, hash, isRemote, isCurrent, plus remote and short — for origin/feature/login those are \"origin\" and \"feature/login\", which is what the branch management calls expect. For a local branch short equals name and remote is empty.",
      "ret": "array",
      "example": "var branches = git.branches(\"user:/Desktop/myproject\");"
     },
@@ -1206,6 +1255,34 @@
      "ret": "object",
      "example": "git.checkout(\"user:/Desktop/myproject\", \"feature/login\", true);"
     },
+    {
+     "name": "git.deleteBranch",
+     "sig": "git.deleteBranch(vpath, branch, force)",
+     "desc": "Delete a local branch. The checked-out branch is never deleted. A branch holding commits unreachable from HEAD is refused with unmerged:true unless force is set, mirroring git branch -d versus -D.",
+     "ret": "object",
+     "example": "requirelib(\"git\");\nvar result = git.deleteBranch(\"user:/Desktop/myproject\", \"old-feature\", false);\nif (result.unmerged) {\n    //confirm with the user, then force\n    git.deleteBranch(\"user:/Desktop/myproject\", \"old-feature\", true);\n}"
+    },
+    {
+     "name": "git.renameBranch",
+     "sig": "git.renameBranch(vpath, oldName, newName)",
+     "desc": "Rename a local branch. Its upstream configuration moves with it, and HEAD follows when the renamed branch is the checked-out one.",
+     "ret": "object",
+     "example": "requirelib(\"git\");\ngit.renameBranch(\"user:/Desktop/myproject\", \"feature\", \"feature-v2\");"
+    },
+    {
+     "name": "git.deleteRemoteBranch",
+     "sig": "git.deleteRemoteBranch(vpath, remote, branch, options)",
+     "desc": "Delete a branch on the remote — a network push with an empty source refspec. The local remote-tracking ref is pruned too, so the branch stops appearing in git.branches(); any local branch of the same name is left alone. Options: username, token, remember.",
+     "ret": "object",
+     "example": "requirelib(\"git\");\nvar result = git.deleteRemoteBranch(\"user:/Desktop/myproject\", \"origin\", \"stale\", {});\nif (!result.success && result.authRequired) { /* prompt and retry */ }"
+    },
+    {
+     "name": "git.renameRemoteBranch",
+     "sig": "git.renameRemoteBranch(vpath, remote, oldName, newName, options)",
+     "desc": "Rename a branch on the remote. Git cannot rename a remote ref, so this pushes the new name then deletes the old one — in that order, so an interrupted rename leaves the branch under both names rather than losing it. Options: username, token, remember.",
+     "ret": "object",
+     "example": "requirelib(\"git\");\ngit.renameRemoteBranch(\"user:/Desktop/myproject\", \"origin\", \"feature\", \"feature-v2\", {});"
+    },
     {
      "name": "git.remotes",
      "sig": "git.remotes(vpath)",