Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

11.8 KB
Raw Blame
package gitlink

import (
	"context"
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"reflect"
	"sort"
	"strings"
	"sync"
	"testing"
	"time"
)

var t0 = time.Date(2026, 9, 27, 12, 0, 0, 0, time.UTC)

func TestOpenRepoResolvesRootAndDirs(t *testing.T) {
	r := newTestRepo(t)
	r.write("sub/dir/x.txt", "x")
	repo, err := OpenRepo(context.Background(), Git{Dir: filepath.Join(r.root, "sub", "dir"), Env: r.env})
	if err != nil {
		t.Fatal(err)
	}
	wantRoot, _ := filepath.EvalSymlinks(r.root)
	gotRoot, _ := filepath.EvalSymlinks(repo.Root)
	if gotRoot != wantRoot {
		t.Fatalf("root %q, want %q", repo.Root, r.root)
	}
	if filepath.Base(repo.GitDir) != ".git" || filepath.Base(repo.CommonDir) != ".git" {
		t.Fatalf("git dir %q common %q", repo.GitDir, repo.CommonDir)
	}
	if !filepath.IsAbs(repo.CommonDir) {
		t.Fatalf("common dir %q is not absolute", repo.CommonDir)
	}
}

func TestOpenRepoOutsideRepository(t *testing.T) {
	r := newTestRepo(t)
	outside := t.TempDir()
	_, err := OpenRepo(context.Background(), Git{Dir: outside, Env: append(r.env, "GIT_CEILING_DIRECTORIES="+filepath.Dir(outside))})
	if !errors.Is(err, ErrNotRepository) {
		t.Fatalf("got %v, want ErrNotRepository", err)
	}
}

func TestOpenRepoInLinkedWorktreeSharesCommonDir(t *testing.T) {
	r := newTestRepo(t)
	r.write("a.txt", "a")
	r.commitAt("init", t0)
	wt := filepath.Join(filepath.Dir(r.root), "wt")
	r.git("worktree", "add", "-q", "-b", "feature", wt)
	repo, err := OpenRepo(context.Background(), Git{Dir: wt, Env: r.env})
	if err != nil {
		t.Fatal(err)
	}
	main := r.open()
	same := func(a, b string) bool {
		ra, _ := filepath.EvalSymlinks(a)
		rb, _ := filepath.EvalSymlinks(b)
		return ra == rb
	}
	if !same(repo.CommonDir, main.CommonDir) {
		t.Fatalf("worktree common dir %q, main %q", repo.CommonDir, main.CommonDir)
	}
	if same(repo.GitDir, main.GitDir) {
		t.Fatal("a linked worktree has its own git dir")
	}
}

func TestChangedFilesCoversRenamesRootAndMerges(t *testing.T) {
	r := newTestRepo(t)
	ctx := context.Background()
	r.write("a.go", "package a\n\nfunc A() {}\n")
	r.write("dir/b.go", "package b\n")
	r.commitAt("root", t0)
	changed := func() []string {
		t.Helper()
		c, err := ResolveCommit(ctx, r.gitClient(), "HEAD")
		if err != nil {
			t.Fatal(err)
		}
		files, err := ChangedFiles(ctx, r.gitClient(), c)
		if err != nil {
			t.Fatal(err)
		}
		sort.Strings(files)
		return files
	}
	got := changed()
	if !reflect.DeepEqual(got, []string{"a.go", "dir/b.go"}) {
		t.Fatalf("root commit files %q", got)
	}

	r.git("mv", "a.go", "renamed.go")
	r.write("dir/b.go", "package b\n\nvar X = 1\n")
	r.commitAt("rename", t0.Add(time.Minute))
	got = changed()
	if !reflect.DeepEqual(got, []string{"a.go", "dir/b.go", "renamed.go"}) {
		t.Fatalf("rename commit files %q", got)
	}

	// A clean merge changes nothing it did not bring in from a parent.
	r.git("checkout", "-q", "-b", "side")
	r.write("side.txt", "side")
	r.write("conflict.txt", "side\n")
	r.commitAt("side", t0.Add(2*time.Minute))
	r.git("checkout", "-q", "main")
	r.write("main.txt", "main")
	r.commitAt("main", t0.Add(3*time.Minute))
	r.git("checkout", "-q", "-b", "clean")
	r.git("merge", "-q", "--no-ff", "--no-edit", "side")
	if got := changed(); len(got) != 0 {
		t.Fatalf("clean merge files %q", got)
	}

	// A conflicted merge changes the resolution and any edit made while merging, not the files
	// either side brought.
	r.git("checkout", "-q", "main")
	r.write("conflict.txt", "main\n")
	r.commitAt("main conflict", t0.Add(4*time.Minute))
	cmd := r.gitClient()
	if _, err := cmd.Run(ctx, nil, "merge", "-q", "--no-edit", "side"); err == nil {
		t.Fatal("expected a conflict")
	}
	r.write("conflict.txt", "resolved\n")
	r.write("dir/b.go", "package b\n\n// edited while merging\n")
	r.commitAt("merge", t0.Add(5*time.Minute))
	if got := changed(); !reflect.DeepEqual(got, []string{"conflict.txt", "dir/b.go"}) {
		t.Fatalf("conflicted merge files %q", got)
	}
}

func TestChangedFilesKeepsUnusualNames(t *testing.T) {
	r := newTestRepo(t)
	name := "sp ace/tab\tand\"quote.txt"
	if strings.ContainsAny(name, "\t\"") && os.PathSeparator == '\\' {
		t.Skip("name not representable on this filesystem")
	}
	r.write(name, "x")
	r.commitAt("odd", t0)
	c, err := ResolveCommit(context.Background(), r.gitClient(), "HEAD")
	if err != nil {
		t.Fatal(err)
	}
	got, err := ChangedFiles(context.Background(), r.gitClient(), c)
	if err != nil {
		t.Fatal(err)
	}
	if !reflect.DeepEqual(got, []string{name}) {
		t.Fatalf("got %q", got)
	}
}

func TestResolveCommitReadsParentTime(t *testing.T) {
	r := newTestRepo(t)
	r.write("a", "1")
	r.commitAt("first", t0)
	r.write("a", "2")
	sha := r.commitAt("second\n\nbody", t0.Add(90*time.Minute))
	c, err := ResolveCommit(context.Background(), r.gitClient(), "")
	if err != nil {
		t.Fatal(err)
	}
	if c.SHA != sha || c.Subject != "second" || !c.CommitTime.Equal(t0.Add(90*time.Minute)) || !c.ParentTime.Equal(t0) || len(c.Parents) != 1 {
		t.Fatalf("got %+v", c)
	}
	if _, err := ResolveCommit(context.Background(), r.gitClient(), "does-not-exist"); err == nil {
		t.Fatal("want an error for an unknown revision")
	}
}

func TestAddLinksCreatesMergesAndIsIdempotent(t *testing.T) {
	r := newTestRepo(t)
	ctx := context.Background()
	r.write("a", "1")
	sha := r.commitAt("c", t0)
	g := r.gitClient()

	if note, err := ReadNote(ctx, g, sha); err != nil || note != "" {
		t.Fatalf("fresh repo note %q, %v", note, err)
	}
	changed, err := AddLinks(ctx, g, sha, []Link{{Harness: "codex", SessionID: "s1"}})
	if err != nil || !changed {
		t.Fatalf("first add: %v %v", changed, err)
	}
	// A person's own note line on the same commit survives Beacon's update.
	r.git("notes", "--ref="+NotesRef, "append", "-m", "Reviewed-by: someone", sha)
	changed, err = AddLinks(ctx, g, sha, []Link{{Harness: "codex", SessionID: "s1"}, {Harness: "claude_code", SessionID: "s2"}})
	if err != nil || !changed {
		t.Fatalf("second add: %v %v", changed, err)
	}
	changed, err = AddLinks(ctx, g, sha, []Link{{Harness: "claude_code", SessionID: "s2"}})
	if err != nil || changed {
		t.Fatalf("repeat add changed=%v err=%v", changed, err)
	}
	note, _ := ReadNote(ctx, g, sha)
	want := "beacon:codex/s1\nReviewed-by: someone\nbeacon:claude_code/s2"
	if note != want {
		t.Fatalf("note %q, want %q", note, want)
	}
	if refs := r.git("for-each-ref", "--format=%(refname)", "refs/notes/"); refs != NotesRef {
		t.Fatalf("leftover refs:\n%s", refs)
	}
	if changed, err := AddLinks(ctx, g, sha, []Link{{Harness: "Bad Harness", SessionID: "x"}}); err != nil || changed {
		t.Fatalf("invalid links must be ignored: %v %v", changed, err)
	}
}

func TestAddLinksConcurrentWritersLoseNothing(t *testing.T) {
	r := newTestRepo(t)
	ctx := context.Background()
	// Every commit's note lives in the one notes ref, so any two writers race on the same
	// compare-and-swap; four writers on each of two commits keep that race (same commit and
	// across commits) without paying for a long queue of retries.
	var shas []string
	for i := range 2 {
		r.write("f", fmt.Sprint(i))
		shas = append(shas, r.commitAt(fmt.Sprint("c", i), t0.Add(time.Duration(i)*time.Minute)))
	}
	g := r.gitClient()
	const writers = 4
	var wg sync.WaitGroup
	errs := make(chan error, writers*len(shas))
	for w := 0; w < writers; w++ {
		for _, sha := range shas {
			wg.Add(1)
			go func(w int, sha string) {
				defer wg.Done()
				// Retries are bounded, so a writer may legitimately give up under this much
				// contention; it must then say so rather than drop the link silently.
				for attempt := 0; attempt < 10; attempt++ {
					_, err := AddLinks(ctx, g, sha, []Link{{Harness: "codex", SessionID: fmt.Sprint("w", w)}})
					if err == nil {
						return
					}
					if !errors.Is(err, errRefMoved) {
						errs <- err
						return
					}
				}
				errs <- fmt.Errorf("writer %d never landed on %s", w, sha)
			}(w, sha)
		}
	}
	wg.Wait()
	close(errs)
	for err := range errs {
		t.Fatal(err)
	}
	for _, sha := range shas {
		note, err := ReadNote(ctx, g, sha)
		if err != nil {
			t.Fatal(err)
		}
		got := keys(ParseNote(note))
		sort.Strings(got)
		var want []string
		for w := 0; w < writers; w++ {
			want = append(want, fmt.Sprint("codex/w", w))
		}
		if !reflect.DeepEqual(got, want) {
			t.Fatalf("%s: links %v, want %v", sha[:7], got, want)
		}
	}
	if refs := r.git("for-each-ref", "--format=%(refname)", "refs/notes/"); refs != NotesRef {
		t.Fatalf("leftover transaction refs:\n%s", refs)
	}
}

func TestAddLinksWaitsForPackedRefsLock(t *testing.T) {
	r := newTestRepo(t)
	r.write("f", "1")
	sha := r.commitAt("c", t0)
	// With git told not to wait for packed-refs.lock at all, the transaction's ref deletion only
	// survives another writer holding the lock if Beacon passes its own, longer wait.
	r.git("config", "core.packedRefsTimeout", "0")
	lock := filepath.Join(r.root, ".git", "packed-refs.lock")
	if err := os.WriteFile(lock, nil, 0o644); err != nil {
		t.Fatal(err)
	}
	// Hold the lock until the swap has landed -- the deletion runs right after it -- and a moment
	// longer, so the deletion meets the held lock.
	released := make(chan struct{})
	go func() {
		defer close(released)
		deadline := time.Now().Add(10 * time.Second)
		for time.Now().Before(deadline) {
			if _, err := os.Stat(filepath.Join(r.root, ".git", filepath.FromSlash(NotesRef))); err == nil {
				break
			}
			time.Sleep(5 * time.Millisecond)
		}
		time.Sleep(100 * time.Millisecond)
		_ = os.Remove(lock)
	}()
	if _, err := AddLinks(context.Background(), r.gitClient(), sha, []Link{{Harness: "codex", SessionID: "s"}}); err != nil {
		t.Fatal(err)
	}
	<-released
	if refs := r.git("for-each-ref", "--format=%(refname)", "refs/notes/"); refs != NotesRef {
		t.Fatalf("leftover transaction refs:\n%s", refs)
	}
}

func TestAddLinksCleanupKeepsCallerDeadline(t *testing.T) {
	r := newTestRepo(t)
	r.write("f", "1")
	sha := r.commitAt("c", t0)
	if err := os.WriteFile(filepath.Join(r.root, ".git", "packed-refs.lock"), nil, 0o644); err != nil {
		t.Fatal(err)
	}
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	start := time.Now()
	if _, err := AddLinks(ctx, r.gitClient(), sha, []Link{{Harness: "codex", SessionID: "s"}}); err != nil {
		t.Fatal(err)
	}
	// The deadline plus one second of lock wait, not the five a caller without a deadline gets.
	if elapsed := time.Since(start); elapsed > 4*time.Second {
		t.Fatalf("AddLinks took %v under a 1s deadline", elapsed)
	}
}

func TestListLinked(t *testing.T) {
	r := newTestRepo(t)
	ctx := context.Background()
	g := r.gitClient()
	if got, err := ListLinked(ctx, g, "", 10); err != nil || len(got) != 0 {
		t.Fatalf("empty repo: %v %v", got, err)
	}
	r.write("a", "1")
	first := r.commitAt("first", t0)
	r.write("a", "2")
	r.commitAt("second (unlinked)", t0.Add(time.Minute))
	r.write("a", "3")
	third := r.commitAt("third", t0.Add(2*time.Minute))
	if _, err := AddLinks(ctx, g, first, []Link{{Harness: "cursor", SessionID: "c1"}}); err != nil {
		t.Fatal(err)
	}
	if _, err := AddLinks(ctx, g, third, []Link{{Harness: "codex", SessionID: "x"}, {Harness: "claude_code", SessionID: "y"}}); err != nil {
		t.Fatal(err)
	}
	// A note on the ref that is not Beacon's is not a linked commit.
	r.git("notes", "--ref="+NotesRef, "add", "-m", "just text", "HEAD~1")
	// A displayRef the user configured must not leak into the parsed output.
	r.git("notes", "--ref=refs/notes/commits", "add", "-m", "beacon:codex/forged", third)
	r.git("config", "notes.displayRef", "refs/notes/commits")

	got, err := ListLinked(ctx, g, "", 10)
	if err != nil {
		t.Fatal(err)
	}
	if len(got) != 2 || got[0].SHA != third || got[1].SHA != first {
		t.Fatalf("got %+v", got)
	}
	if !reflect.DeepEqual(keys(got[0].Links), []string{"codex/x", "claude_code/y"}) || got[0].Subject != "third" {
		t.Fatalf("third: %+v", got[0])
	}
	if !got[1].CommitTime.Equal(t0) {
		t.Fatalf("commit time %v", got[1].CommitTime)
	}
	// The limit counts commits walked, linked or not.
	if got, _ := ListLinked(ctx, g, "", 2); len(got) != 1 || got[0].SHA != third {
		t.Fatalf("limit 2: %+v", got)
	}
}