Add show_diff chat tool and diff card

The Pipelines MCP server gains show_diff: it runs Git in a repository
inside the operator's home (default: the chat's directory) and records
the per-file patches. Without base it shows uncommitted work against
HEAD; with base it shows everything since the merge base (a pull
request preview), optionally committed changes only. Bounded at 300
files, 256 KiB per patch and 1 MiB total, with partial diffs labelled;
diff bodies share the per-chat retention budget with HTML views.

The chat draws the item as a card listing each changed file with its
stat; a row opens the existing file diff viewer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-21 17:08:02 +00:00
parent 79e5183469
commit 059eb1bb0d
15 changed files with 1077 additions and 16 deletions
+236
View File
@@ -0,0 +1,236 @@
package server
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"unicode"
"git.a-wan.net/alan/pipelines/internal/chattools"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/workenv"
)
// The show_diff bounds. A larger diff is shown partially, never cut silently:
// files past the count are omitted (and counted), and a patch over the per-file
// or total size keeps its entry with a no-patch reason.
const (
showDiffMaxFiles = 300
showDiffMaxFileBytes = 256 << 10
showDiffMaxBytes = 1 << 20
showDiffTimeout = 30 * time.Second
// The empty tree is the base of a repository without commits.
gitEmptyTree = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
)
type showDiffRequest struct {
Path string
Base string
CommittedOnly bool
Title string
}
// runShowDiff compares a repository inside the operator's home and records
// the per-file patches as one diff item.
func (s *chatToolService) runShowDiff(ctx context.Context, sessionID string, in showDiffRequest) (*protocol.ChatShownItem, chattools.Result) {
fail := func(err error) (*protocol.ChatShownItem, chattools.Result) {
return nil, chattools.Result{Text: "Nothing was shown: " + err.Error(), IsError: true}
}
base := strings.TrimSpace(in.Base)
if in.CommittedOnly && base == "" {
return fail(errors.New("committed_only needs a base to compare against"))
}
if base != "" && !validGitRevision(base) {
return fail(fmt.Errorf("base %q is not a branch, tag or commit name", base))
}
directory, err := s.resolveDiffDirectory(ctx, sessionID, in.Path)
if err != nil {
return fail(err)
}
ctx, cancel := context.WithTimeout(ctx, showDiffTimeout)
defer cancel()
git := gitRunner{ctx: ctx, directory: directory}
top, err := git.output("rev-parse", "--show-toplevel")
if err != nil {
return fail(fmt.Errorf("%s is not inside a Git repository", directory))
}
git.directory = strings.TrimSpace(top)
body := protocol.ChatShownDiffBody{Repo: git.directory, Base: base, CommittedOnly: in.CommittedOnly}
head, headErr := git.output("rev-parse", "--verify", "--quiet", "HEAD^{commit}")
head = strings.TrimSpace(head)
if branch, err := git.output("symbolic-ref", "--quiet", "--short", "HEAD"); err == nil {
body.Head = strings.TrimSpace(branch)
} else if head != "" {
body.Head = shortCommit(head)
}
var compare string
switch {
case base != "":
if headErr != nil || head == "" {
return fail(errors.New("this repository has no commits yet, so there is nothing to compare with " + base))
}
target, err := git.output("rev-parse", "--verify", "--quiet", "--end-of-options", base+"^{commit}")
if err != nil {
return fail(fmt.Errorf("base %q is not a commit in %s", base, git.directory))
}
mergeBase, err := git.output("merge-base", strings.TrimSpace(target), head)
if err != nil {
return fail(fmt.Errorf("%s and HEAD share no history", base))
}
compare = strings.TrimSpace(mergeBase)
case headErr == nil && head != "":
compare = head
default:
compare = gitEmptyTree
}
if compare != gitEmptyTree {
body.BaseCommit = shortCommit(compare)
}
revisions := []string{compare}
if in.CommittedOnly {
revisions = append(revisions, head)
}
changes, err := collectGitDiff(git, revisions, !in.CommittedOnly)
if err != nil {
return fail(err)
}
body.Changes = changes
diffBytes := 0
for _, file := range changes.Files {
added, removed := patchLineCounts(file.Patch)
body.Additions += added
body.Deletions += removed
diffBytes += len(file.Patch)
}
body.Files = len(changes.Files) + changes.Omitted
item := protocol.ChatShownItem{Kind: protocol.ChatShownDiff, Title: in.Title, Diff: &body, DiffBytes: diffBytes}
return &item, chattools.Result{Text: showDiffSummary(body)}
}
func showDiffSummary(body protocol.ChatShownDiffBody) string {
against := "HEAD"
switch {
case body.Base != "" && body.CommittedOnly:
against = fmt.Sprintf("%s (merge base %s), committed changes only", body.Base, body.BaseCommit)
case body.Base != "":
against = fmt.Sprintf("%s (merge base %s), including uncommitted work", body.Base, body.BaseCommit)
case body.BaseCommit == "":
against = "an empty repository"
}
if body.Files == 0 {
return fmt.Sprintf("Shown in the operator's Pipelines chat: no changes in %s against %s.", body.Repo, against)
}
text := fmt.Sprintf("Shown in the operator's Pipelines chat: %d changed %s (+%d -%d) in %s against %s.",
body.Files, plural(body.Files, "file", "files"), body.Additions, body.Deletions, body.Repo, against)
if body.Changes != nil && body.Changes.Status != "complete" {
text += " The diff is partial: " + body.Changes.Diagnostic
}
return text
}
func plural(n int, one, many string) string {
if n == 1 {
return one
}
return many
}
// resolveDiffDirectory applies the home containment of show_file to a
// directory, defaulting to the chat's working directory.
func (s *chatToolService) resolveDiffDirectory(ctx context.Context, sessionID, requested string) (string, error) {
requested = strings.TrimSpace(requested)
home, err := s.home()
if err != nil {
return "", err
}
realHome, err := filepath.EvalSymlinks(filepath.Clean(home))
if err != nil {
return "", errors.New("the operator's home directory is not available")
}
if requested == "" || (!filepath.IsAbs(requested) && !strings.HasPrefix(requested, "~")) {
directory := s.chatSessionDirectory(ctx, sessionID)
if directory == "" {
return "", errors.New("this chat has no recorded working directory; pass the repository's absolute path")
}
requested = filepath.Join(directory, requested)
}
target, err := expandHomePath(filepath.Clean(home), requested)
if err != nil {
return "", err
}
_, realTarget, err := resolveInsideHome(realHome, target)
if err != nil {
if strings.Contains(err.Error(), "outside the home directory") {
return "", errors.New(requested + " is outside the operator's home directory; only repositories inside home can be shown")
}
return "", err
}
info, err := os.Stat(realTarget)
if err != nil {
return "", describePathError(requested, err)
}
if !info.IsDir() {
return "", errors.New(requested + " is not a directory; pass the repository directory")
}
return realTarget, nil
}
// validGitRevision accepts a plain revision name: no option prefix, range,
// whitespace or control character, so it can only name one commit.
func validGitRevision(name string) bool {
if name == "" || len(name) > 200 || strings.HasPrefix(name, "-") || strings.Contains(name, "..") {
return false
}
for _, r := range name {
if unicode.IsSpace(r) || unicode.IsControl(r) {
return false
}
}
return true
}
// gitRunner runs git in one directory with the operator's environment and no
// pager, external diff, text conversion or path quoting.
type gitRunner struct {
ctx context.Context
directory string
}
func (g gitRunner) command(args ...string) *exec.Cmd {
full := append([]string{"-c", "core.quotepath=false", "-c", "core.fsmonitor=false", "-C", g.directory}, args...)
cmd := exec.CommandContext(g.ctx, "git", full...)
cmd.Env = append(workenv.CommandEnv(g.ctx, g.directory), "GIT_PAGER=cat", "GIT_OPTIONAL_LOCKS=0", "LC_ALL=C")
return cmd
}
func (g gitRunner) output(args ...string) (string, error) {
var stdout, stderr bytes.Buffer
cmd := g.command(args...)
cmd.Stdout, cmd.Stderr = &stdout, &stderr
if err := cmd.Run(); err != nil {
return "", fmt.Errorf("git %s: %v: %s", args[0], err, strings.TrimSpace(stderr.String()))
}
return stdout.String(), nil
}
// patch returns one file's patch. A `diff --no-index` exits 1 when the files
// differ, which is its success.
func (g gitRunner) patch(noIndex bool, args ...string) (string, error) {
var stdout, stderr bytes.Buffer
cmd := g.command(args...)
cmd.Stdout, cmd.Stderr = &stdout, &stderr
err := cmd.Run()
var exit *exec.ExitError
if err != nil && !(noIndex && errors.As(err, &exit) && exit.ExitCode() == 1) {
return "", fmt.Errorf("git diff: %v: %s", err, strings.TrimSpace(stderr.String()))
}
return stdout.String(), nil
}
+146
View File
@@ -0,0 +1,146 @@
package server
import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
type gitDiffEntry struct {
path string
kind string
untracked bool
}
// collectGitDiff lists the files changed between revisions (one revision: the
// work tree against it; two: those commits) plus, when includeUntracked, the
// untracked files Git does not ignore, and reads each file's patch within the
// show_diff bounds.
func collectGitDiff(git gitRunner, revisions []string, includeUntracked bool) (*protocol.StageFileChanges, error) {
nameArgs := append([]string{"diff", "--name-status", "-z", "--no-renames"}, revisions...)
names, err := git.output(append(nameArgs, "--")...)
if err != nil {
return nil, err
}
entries := parseNameStatus(names)
if includeUntracked {
others, err := git.output("ls-files", "--others", "--exclude-standard", "-z")
if err != nil {
return nil, err
}
for _, path := range strings.Split(others, "\x00") {
if path != "" {
entries = append(entries, gitDiffEntry{path: path, kind: "added", untracked: true})
}
}
}
sort.SliceStable(entries, func(i, j int) bool { return entries[i].path < entries[j].path })
changes := &protocol.StageFileChanges{Status: "complete", Files: []protocol.FileChange{}}
used := 0
var partial []string
for i, entry := range entries {
if i >= showDiffMaxFiles {
changes.Omitted = len(entries) - showDiffMaxFiles
partial = append(partial, fmt.Sprintf("%d more files are not listed (the limit is %d)", changes.Omitted, showDiffMaxFiles))
break
}
file := protocol.FileChange{Path: entry.path, Kind: entry.kind}
patch, reason, err := readEntryPatch(git, revisions, entry)
if err != nil {
return nil, err
}
switch {
case reason != "":
case isBinaryPatch(patch):
file.Binary, reason = true, "binary"
case len(patch) > showDiffMaxFileBytes:
reason = "file_size"
case used+len(patch) > showDiffMaxBytes:
reason = "budget"
}
if reason == "" {
file.Patch = patch
used += len(patch)
} else {
file.NoPatch, file.NoPatchReason = true, reason
file.Truncated = reason != "binary"
}
if reason == "file_size" || reason == "budget" {
partial = appendOnce(partial, "some patches were left out by the size limit")
}
changes.Files = append(changes.Files, file)
}
if len(partial) > 0 {
changes.Status = "partial"
changes.Diagnostic = strings.Join(partial, "; ") + "."
}
return changes, nil
}
// readEntryPatch returns one file's patch, or the no-patch reason when its
// content is not read.
func readEntryPatch(git gitRunner, revisions []string, entry gitDiffEntry) (string, string, error) {
flags := []string{"diff", "--no-color", "--no-ext-diff", "--no-textconv", "--no-renames"}
if entry.untracked {
info, err := os.Lstat(filepath.Join(git.directory, entry.path))
if err != nil {
return "", "git_status", nil
}
if info.Mode().IsRegular() && info.Size() > showDiffMaxFileBytes {
return "", "file_size", nil
}
patch, err := git.patch(true, append(flags, "--no-index", "--", os.DevNull, entry.path)...)
return patch, "", err
}
args := append(append(flags, revisions...), "--", ":(literal)"+entry.path)
patch, err := git.patch(false, args...)
return patch, "", err
}
// parseNameStatus reads `git diff --name-status -z --no-renames`: a status
// letter, then the path, each NUL-terminated.
func parseNameStatus(out string) []gitDiffEntry {
fields := strings.Split(out, "\x00")
var entries []gitDiffEntry
for i := 0; i+1 < len(fields); i += 2 {
status, path := fields[i], fields[i+1]
if status == "" || path == "" {
continue
}
kind := "modified"
switch status[0] {
case 'A':
kind = "added"
case 'D':
kind = "deleted"
}
entries = append(entries, gitDiffEntry{path: path, kind: kind})
}
return entries
}
func isBinaryPatch(patch string) bool {
for _, line := range strings.Split(patch, "\n") {
if strings.HasPrefix(line, "@@") {
return false
}
if strings.HasPrefix(line, "Binary files ") || line == "GIT binary patch" {
return true
}
}
return false
}
func appendOnce(list []string, value string) []string {
for _, existing := range list {
if existing == value {
return list
}
}
return append(list, value)
}
+199
View File
@@ -0,0 +1,199 @@
package server
import (
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// showDiffRepo makes a repository inside the fixture home: main has a.txt, the
// checked-out feature branch modifies it and adds b.txt in commits, and the
// work tree has an unstaged change to b.txt plus an untracked u.txt.
func showDiffRepo(t *testing.T, home string) string {
t.Helper()
repo := filepath.Join(home, "repo")
if err := os.MkdirAll(repo, 0o755); err != nil {
t.Fatal(err)
}
git := func(args ...string) {
t.Helper()
cmd := exec.Command("git", append([]string{"-c", "user.name=t", "-c", "user.email=t@example.com", "-c", "commit.gpgsign=false", "-C", repo}, args...)...)
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git %v: %v\n%s", args, err, out)
}
}
write := func(name, content string) {
t.Helper()
if err := os.WriteFile(filepath.Join(repo, name), []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
git("init", "-q", "-b", "main")
write("a.txt", "one\ntwo\n")
git("add", ".")
git("commit", "-q", "-m", "base")
git("switch", "-q", "-c", "feature")
write("a.txt", "one\nTWO\n")
write("b.txt", "new\n")
git("add", ".")
git("commit", "-q", "-m", "feature")
write("b.txt", "new\nmore\n")
write("u.txt", "untracked\n")
return repo
}
func diffItem(t *testing.T, f *chatToolFixture, session string) protocol.ChatShownItem {
t.Helper()
items := f.items(t, session)
if len(items) == 0 {
t.Fatal("no item recorded")
}
item := items[len(items)-1]
if item.Kind != protocol.ChatShownDiff || item.Diff == nil || item.Diff.Changes == nil {
t.Fatalf("want a diff item, got %+v", item)
}
return item
}
func diffPaths(item protocol.ChatShownItem) map[string]string {
paths := map[string]string{}
for _, file := range item.Diff.Changes.Files {
paths[file.Path] = file.Kind
}
return paths
}
func TestShowDiffComparesAgainstHeadOrABase(t *testing.T) {
f := newChatToolFixture(t)
repo := showDiffRepo(t, f.home)
token := f.token(t, chatToolSessionScope+"ses_d")
r := f.call(token, "show_diff", `{"path":"`+repo+`"}`)
if r.IsError {
t.Fatal(r.Text)
}
item := diffItem(t, f, "ses_d")
if got := diffPaths(item); len(got) != 2 || got["b.txt"] != "modified" || got["u.txt"] != "added" {
t.Fatalf("uncommitted diff lists the work tree change and the untracked file: %v", got)
}
if item.Diff.Head != "feature" || item.Diff.Base != "" || item.Diff.Additions != 2 || item.Diff.Deletions != 0 {
t.Fatalf("summary: %+v", item.Diff)
}
if !strings.Contains(r.Text, "2 changed files (+2 -0)") {
t.Fatalf("model text: %s", r.Text)
}
if r := f.call(token, "show_diff", `{"path":"~/repo","base":"main","title":"PR preview"}`); r.IsError {
t.Fatal(r.Text)
}
item = diffItem(t, f, "ses_d")
if got := diffPaths(item); len(got) != 3 || got["a.txt"] != "modified" || got["b.txt"] != "added" || got["u.txt"] != "added" {
t.Fatalf("a base diff covers the branch and uncommitted work: %v", got)
}
if item.Title != "PR preview" || item.Diff.Base != "main" || item.Diff.BaseCommit == "" || item.DiffBytes == 0 {
t.Fatalf("summary: %+v", item)
}
for _, file := range item.Diff.Changes.Files {
if file.Path == "a.txt" && !strings.Contains(file.Patch, "-two\n+TWO") {
t.Fatalf("a.txt patch: %q", file.Patch)
}
}
if r := f.call(token, "show_diff", `{"path":"`+repo+`","base":"main","committed_only":true}`); r.IsError {
t.Fatal(r.Text)
}
item = diffItem(t, f, "ses_d")
got := diffPaths(item)
if len(got) != 2 || got["a.txt"] != "modified" || got["b.txt"] != "added" {
t.Fatalf("committed_only leaves out the work tree: %v", got)
}
for _, file := range item.Diff.Changes.Files {
if file.Path == "b.txt" && strings.Contains(file.Patch, "more") {
t.Fatal("committed_only must not include the unstaged line")
}
}
}
func TestShowDiffRefusals(t *testing.T) {
f := newChatToolFixture(t)
repo := showDiffRepo(t, f.home)
plain := filepath.Join(f.home, "plain")
if err := os.MkdirAll(plain, 0o755); err != nil {
t.Fatal(err)
}
outside := t.TempDir()
token := f.token(t, chatToolSessionScope+"ses_r")
for _, tc := range []struct{ args, want string }{
{`{"path":"` + outside + `"}`, "outside the operator's home"},
{`{"path":"` + plain + `"}`, "not inside a Git repository"},
{`{"path":"` + repo + `","base":"--output=/tmp/x"}`, "is not a branch"},
{`{"path":"` + repo + `","base":"main..feature"}`, "is not a branch"},
{`{"path":"` + repo + `","base":"nope"}`, "is not a commit"},
{`{"path":"` + repo + `","committed_only":true}`, "needs a base"},
{`{}`, "no recorded working directory"},
} {
r := f.call(token, "show_diff", tc.args)
if !r.IsError || !strings.Contains(r.Text, tc.want) {
t.Errorf("%s: want refusal %q, got %+v", tc.args, tc.want, r)
}
}
if items := f.items(t, "ses_r"); len(items) != 0 {
t.Fatalf("refusals record nothing: %+v", items)
}
}
func TestShowDiffLeavesOutOversizedPatchesAndSaysSo(t *testing.T) {
f := newChatToolFixture(t)
repo := showDiffRepo(t, f.home)
big := strings.Repeat("line of text\n", (showDiffMaxFileBytes/13)+10)
if err := os.WriteFile(filepath.Join(repo, "big.txt"), []byte(big), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(repo, "blob.bin"), []byte{0, 1, 2, 0, 3}, 0o644); err != nil {
t.Fatal(err)
}
token := f.token(t, chatToolSessionScope+"ses_big")
r := f.call(token, "show_diff", `{"path":"`+repo+`"}`)
if r.IsError {
t.Fatal(r.Text)
}
item := diffItem(t, f, "ses_big")
if item.Diff.Changes.Status != "partial" || !strings.Contains(r.Text, "partial") {
t.Fatalf("an oversized patch makes the diff partial: %+v / %s", item.Diff.Changes, r.Text)
}
for _, file := range item.Diff.Changes.Files {
switch file.Path {
case "big.txt":
if file.Patch != "" || file.NoPatchReason != "file_size" || !file.Truncated {
t.Fatalf("big.txt: %+v", file)
}
case "blob.bin":
if !file.Binary || file.Patch != "" {
t.Fatalf("blob.bin: %+v", file)
}
}
}
}
func TestShowDiffBodiesShareTheRetentionBudget(t *testing.T) {
f := newChatToolFixture(t)
ctx := context.Background()
body := func() *protocol.ChatShownDiffBody {
return &protocol.ChatShownDiffBody{Repo: "/r", Files: 1, Changes: &protocol.StageFileChanges{Status: "complete", Files: []protocol.FileChange{{Path: "a", Kind: "modified", Patch: "@@"}}}}
}
for i, id := range []string{"old", "new"} {
item := protocol.ChatShownItem{ID: id, Kind: protocol.ChatShownDiff, CreatedAt: int64(i + 1), Diff: body(), DiffBytes: protocol.ChatShownHTMLBudget/2 + 1}
if err := f.store.AppendChatShownItem(ctx, "ses_ret", item); err != nil {
t.Fatal(err)
}
}
items := f.items(t, "ses_ret")
if len(items) != 2 || !items[0].Expired || items[0].Diff == nil || items[0].Diff.Changes != nil || items[1].Expired || items[1].Diff.Changes == nil {
t.Fatalf("the older diff drops its patches past the budget: %+v", items)
}
}
+4
View File
@@ -26,6 +26,8 @@ func (s *chatToolService) run(ctx context.Context, sessionID, tool string, argum
HeightHint int `json:"height_hint"`
Message string `json:"message"`
Priority string `json:"priority"`
Base string `json:"base"`
Committed bool `json:"committed_only"`
}
if err := json.Unmarshal(arguments, &in); err != nil {
return fail("The arguments must be a JSON object matching the %s schema: %v", tool, err)
@@ -72,6 +74,8 @@ func (s *chatToolService) run(ctx context.Context, sessionID, tool string, argum
}
item := protocol.ChatShownItem{Kind: protocol.ChatShownHTML, Title: title, HTML: in.HTML, HTMLBytes: len(in.HTML), HeightHint: clampHeightHint(in.HeightHint)}
return &item, chattools.Result{Text: fmt.Sprintf("Shown in the operator's Pipelines chat (%s, sandboxed: scripts and network are disabled).", humanBytes(int64(len(in.HTML))))}
case chattools.ToolShowDiff:
return s.runShowDiff(ctx, sessionID, showDiffRequest{Path: in.Path, Base: in.Base, CommittedOnly: in.Committed, Title: title})
case chattools.ToolNotify:
return s.runNotify(ctx, sessionID, title, in.Message, in.Priority)
}