package thin import ( "context" "encoding/json" "errors" "os" "os/exec" "path/filepath" "slices" "strings" "testing" "amadan.net/oficina/equipo/internal/runner/provider/claude" "amadan.net/oficina/equipo/internal/runner/workspace" "amadan.net/oficina/equipo/internal/wire" ) // pathForge serves the index: every repository is a local bare repository, // read over file:// like the local forge in the headless suite. type pathForge struct { countingForge root string } func (f *pathForge) path(repo string) string { return filepath.Join(f.root, strings.ReplaceAll(strings.TrimPrefix(repo, "amadan.net/"), "/", "__")+".git") } func (f *pathForge) Remote(_ context.Context, repo string, _ Use) (workspace.Remote, error) { if !slices.Contains(f.repos, repo) { return workspace.Remote{}, workspace.ErrGitPassword } return workspace.Remote{URL: f.path(repo)}, nil } // A reachable repository with no commits yet is in the catalog, marked // empty: it is not an access failure. A repository with commits but no // branch at HEAD, and one the forge cannot serve, stay out as before. // The first commit is seen on the next delta, and reads of an empty // repository say it is empty rather than failing. func TestIndexListsEmptyRepository(t *testing.T) { root := t.TempDir() f := &pathForge{root: filepath.Join(root, "forge")} const ( full = "amadan.net/oficina/sample" empty = "amadan.net/paulca/threatmin" headless = "amadan.net/paulca/detached" gone = "amadan.net/paulca/gone" ) f.repos = []string{full, empty, headless, gone} seed := filepath.Join(root, "seed") os.MkdirAll(seed, 0700) os.WriteFile(filepath.Join(seed, "README.md"), []byte("# Sample\n\nA sample.\n"), 0600) hostileGit(t, seed, "init", "-q", "-b", "main") hostileGit(t, seed, "add", "-A") hostileGit(t, seed, "commit", "-q", "-m", "seed") os.MkdirAll(f.root, 0700) hostileGit(t, root, "clone", "-q", "--bare", seed, f.path(full)) hostileGit(t, root, "init", "-q", "--bare", "-b", "main", f.path(empty)) // Commits on dev only, HEAD naming a main that does not exist. hostileGit(t, root, "clone", "-q", "--bare", seed, f.path(headless)) hostileGit(t, f.path(headless), "branch", "-m", "main", "dev") hostileGit(t, f.path(headless), "symbolic-ref", "HEAD", "refs/heads/main") os.MkdirAll(filepath.Join(root, "work"), 0700) x := &Index{Forge: f, Clones: &Clones{Root: filepath.Join(root, "work"), Git: "git", Forge: f}} ctx := context.Background() x.Refresh(ctx) byRepo := map[string]wire.RepoInfo{} for _, e := range x.Catalog() { byRepo[e.Repo] = e } if e, ok := byRepo[full]; !ok || e.Empty || e.DefaultBranch != "main" { t.Fatalf("full repository: %+v", e) } e, ok := byRepo[empty] if !ok || !e.Empty || e.DefaultBranch != "" || e.HeadSHA != "" || !slices.Equal(e.Names, []string{"threatmin"}) || e.Hints == nil { t.Fatalf("empty repository: %+v (present %v)", e, ok) } if _, ok := byRepo[headless]; ok { t.Fatal("a repository with commits but no default branch is listed") } if _, ok := byRepo[gone]; ok { t.Fatal("a repository the forge cannot serve is listed") } for _, read := range []func() (string, error){ func() (string, error) { return x.ReadFile(ctx, empty, "README.md", 1) }, func() (string, error) { return x.SearchCode(ctx, empty, "x") }, } { if _, err := read(); !errors.Is(err, ErrEmptyRepo) { t.Fatalf("read of an empty repository: %v", err) } } // The first commit arrives; a delta (what a grant check or a new // repository kicks) sees it without waiting for the hourly refresh. hostileGit(t, seed, "push", "-q", f.path(empty), "main") x.Delta(ctx) for _, e := range x.Catalog() { if e.Repo == empty && (e.Empty || e.DefaultBranch != "main" || len(e.HeadSHA) != 40) { t.Fatalf("after the first commit: %+v", e) } } if out, err := x.ReadFile(ctx, empty, "README.md", 1); err != nil || !strings.Contains(out, "1\t# Sample") { t.Fatalf("read after the first commit: %q %v", out, err) } } // The coordinator's read tools on an empty repository: the instance's // "empty" answer reaches the model as it is, not as a failed read; and if // the instance authorised a read the runner's own index finds empty, the // model is told it is empty, never "Could not read that". func TestBridgeReadsOfEmptyRepository(t *testing.T) { const repo = "amadan.net/paulca/threatmin" x := &Index{Clones: &Clones{Root: t.TempDir(), Git: "git"}} x.catalog = []wire.RepoInfo{{Repo: repo, Names: []string{"threatmin"}, Hints: []string{}, Empty: true}} answer := wire.ToolResult{Code: "empty", Repo: repo, Text: "paulca/threatmin has no commits yet."} b := &bridge{Index: x, trip: func(context.Context, wire.ToolCall) wire.ToolResult { return answer }} for _, name := range []string{wire.ToolReadFile, wire.ToolSearchCode} { args := `{"repo":"paulca/threatmin","path":"README.md"}` if name == wire.ToolSearchCode { args = `{"repo":"paulca/threatmin","query":"x"}` } if text, isErr := b.Call(context.Background(), "p", "t", 1, name, "u1", json.RawMessage(args)); isErr || text != answer.Text { t.Fatalf("%s, instance says empty: %q %v", name, text, isErr) } } answer = wire.ToolResult{Code: "read", Repo: repo} text, isErr := b.Call(context.Background(), "p", "t", 1, wire.ToolReadFile, "u2", json.RawMessage(`{"repo":"paulca/threatmin","path":"README.md"}`)) if isErr || text != toolEmptyRead || text == toolReadError { t.Fatalf("runner finds it empty: %q %v", text, isErr) } } // Engineering's first task in an empty repository pushes only its own // task branch: the default branch still has no commits, so the // repository stays empty for the index and its reads. A branch that is // not Equipo's (someone pushed elsewhere) is history to read, as before. func TestEmptyRepositoryWithTaskBranch(t *testing.T) { root := t.TempDir() f := &pathForge{root: filepath.Join(root, "forge")} const ( empty = "amadan.net/paulca/barber" other = "amadan.net/paulca/other" ) f.repos = []string{empty, other} os.MkdirAll(f.root, 0700) seed := filepath.Join(root, "seed") os.MkdirAll(seed, 0700) os.WriteFile(filepath.Join(seed, "index.html"), []byte("

Barber

\n"), 0600) hostileGit(t, seed, "init", "-q", "-b", "main") hostileGit(t, seed, "add", "-A") hostileGit(t, seed, "commit", "-q", "-m", "mockups") for _, repo := range []string{empty, other} { hostileGit(t, root, "init", "-q", "--bare", "-b", "main", f.path(repo)) } hostileGit(t, seed, "push", "-q", f.path(empty), "main:refs/heads/equipo/tk1-barber-mockups") hostileGit(t, seed, "push", "-q", f.path(other), "main:refs/heads/dev") os.MkdirAll(filepath.Join(root, "work"), 0700) c := &Clones{Root: filepath.Join(root, "work"), Git: "git", Forge: f} ctx := context.Background() if _, err := c.DefaultBranch(ctx, empty); !errors.Is(err, ErrEmptyRepo) { t.Fatalf("empty but for a task branch: %v", err) } if _, err := c.DefaultBranch(ctx, other); !errors.Is(err, ErrNoCreate) { t.Fatalf("another branch beside an unborn default: %v", err) } x := &Index{Forge: f, Clones: c} x.Refresh(ctx) cat := x.Catalog() if len(cat) != 1 || cat[0].Repo != empty || !cat[0].Empty { t.Fatalf("catalog %+v", cat) } if _, err := x.ReadFile(ctx, empty, "index.html", 1); !errors.Is(err, ErrEmptyRepo) { t.Fatalf("read: %v", err) } } // Review reads a change as its diff: an initial commit (no base) is // read against the empty tree, so Review sees every file it adds. With // no base and a commit that has a parent there is nothing to say. func TestChangeDiffOfInitialCommit(t *testing.T) { root := t.TempDir() gitDir := filepath.Join(root, "repo.git") hostileGit(t, root, "init", "-q", "--bare", "-b", "main", gitDir) seed := filepath.Join(root, "seed") os.MkdirAll(seed, 0700) os.WriteFile(filepath.Join(seed, "index.html"), []byte("

Barber

\n"), 0600) hostileGit(t, seed, "init", "-q", "-b", "main") hostileGit(t, seed, "add", "-A") hostileGit(t, seed, "commit", "-q", "-m", "mockups") os.WriteFile(filepath.Join(seed, "book.html"), []byte("Back\n"), 0600) hostileGit(t, seed, "add", "-A") hostileGit(t, seed, "commit", "-q", "-m", "book") hostileGit(t, seed, "push", "-q", gitDir, "main") out, _ := exec.Command("git", "--git-dir="+gitDir, "rev-parse", "main", "main^").Output() shas := strings.Fields(string(out)) ctx := context.Background() diff, err := changeDiff(ctx, "git", gitDir, "", shas[1], wire.MaxDiffBytes) if err != nil || !strings.Contains(diff, "+

Barber

") || !strings.Contains(diff, "new file mode") { t.Fatalf("initial commit diff %q %v", diff, err) } if diff, err := changeDiff(ctx, "git", gitDir, "", shas[0], wire.MaxDiffBytes); err != nil || diff != "" { t.Fatalf("no base, not an initial commit: %q %v", diff, err) } if diff, err := changeDiff(ctx, "git", gitDir, shas[1], shas[0], wire.MaxDiffBytes); err != nil || !strings.Contains(diff, "+Back") || strings.Contains(diff, "Barber") { t.Fatalf("with a base %q %v", diff, err) } } // Engineering is told when the repository has no commits: /workspace // starts empty and its work is the first commit, not "the tip of its // default branch". func TestStepPromptEmptyRepository(t *testing.T) { e := &Engineer{} r := stepRow{DispatchCommand: wire.DispatchCommand{Person: "owner@example.com", Repo: "amadan.net/paulca/barber", Title: "Mockups", Branch: "equipo/tk1-mockups"}} empty, full := e.stepPrompt(r, true, claude.LinuxWorkspaceRoot), e.stepPrompt(r, false, claude.LinuxWorkspaceRoot) if !strings.Contains(empty, stepEmptyRepo) || strings.Contains(empty, "tip of its default branch") { t.Fatalf("empty: %s", empty) } if strings.Contains(full, stepEmptyRepo) || !strings.Contains(full, "at the tip of its default branch. Make the smallest change") { t.Fatalf("full: %s", full) } } // Merge inspection in an empty repository: the default branch is unborn, // so there is no tip and nothing landed; the task branch's head is read // as usual. A hub whose HEAD a rebuild pointed at the task branch itself // still has an unborn default: a task branch is never the default, for // the merge, the index and Engineering alike. func TestUnbornDefaultForMerge(t *testing.T) { root := t.TempDir() f := &pathForge{root: filepath.Join(root, "forge")} const repo, branch = "amadan.net/paulca/barber", "equipo/tk1-barber-mockups" f.repos = []string{repo} os.MkdirAll(f.root, 0700) seed := filepath.Join(root, "seed") os.MkdirAll(seed, 0700) os.WriteFile(filepath.Join(seed, "index.html"), []byte("

Barber

\n"), 0600) hostileGit(t, seed, "init", "-q", "-b", "main") hostileGit(t, seed, "add", "-A") hostileGit(t, seed, "commit", "-q", "-m", "mockups") hostileGit(t, root, "init", "-q", "--bare", "-b", "main", f.path(repo)) hostileGit(t, seed, "push", "-q", f.path(repo), "main:refs/heads/"+branch) out, _ := exec.Command("git", "-C", seed, "rev-parse", "HEAD").Output() commit := strings.TrimSpace(string(out)) os.MkdirAll(filepath.Join(root, "work"), 0700) c := &Clones{Root: filepath.Join(root, "work"), Git: "git", Forge: f} e := &Engineer{Clones: c, Forge: f} ctx := context.Background() for _, rebuilt := range []bool{false, true} { if rebuilt { hostileGit(t, f.path(repo), "symbolic-ref", "HEAD", "refs/heads/"+branch) } def, tip, heads, err := c.Heads(ctx, repo, []string{branch}) if !errors.Is(err, ErrEmptyRepo) || def != "main" || tip != "" || heads[branch] != commit { t.Fatalf("rebuilt=%v heads: %q %q %v %v", rebuilt, def, tip, heads, err) } st, err := e.inspectMerge(ctx, repo, branch, commit) if err != nil || !st.Unborn || st.Landed || st.Tip != "" || st.Head != commit || st.Default != "main" { t.Fatalf("rebuilt=%v inspect %+v %v", rebuilt, st, err) } if _, err := c.DefaultBranch(ctx, repo); !errors.Is(err, ErrEmptyRepo) { t.Fatalf("rebuilt=%v default branch: %v", rebuilt, err) } } // The first merge made main: no longer empty, for the merge and reads. hostileGit(t, f.path(repo), "update-ref", "refs/heads/main", commit) hostileGit(t, f.path(repo), "symbolic-ref", "HEAD", "refs/heads/main") st, err := e.inspectMerge(ctx, repo, branch, commit) if err != nil || st.Unborn || !st.Landed || st.Default != "main" { t.Fatalf("after the first merge %+v %v", st, err) } if b, err := c.DefaultBranch(ctx, repo); err != nil || b != "main" { t.Fatalf("default after the first merge: %q %v", b, err) } } // amadan-13's threatmin, verbatim: after the first task's push and a hub // rebuild, ls-remote --symref answers // // ref: refs/heads/equipo/tk5fen4uajpn-… HEAD // 47a897b… HEAD // 47a897b… refs/heads/equipo/tk5fen4uajpn-… // // and no refs/heads/main. Merge inspection reads that in one ls-remote // (the hub limits an agent's git requests): HEAD names a task branch and // main is absent, so the default is unborn, named main, with the task // branch's head as read. HEAD naming nothing (an unborn main) is the // same. When main exists it is the default, wherever HEAD points. func TestHeadsReadsAnUnbornDefaultInOneCall(t *testing.T) { root := t.TempDir() f := &pathForge{root: filepath.Join(root, "forge")} const repo, branch = "amadan.net/paulca/threatmin", "equipo/tk5fen4uajpn-create-two-clickable-barber-app-mockups" f.repos = []string{repo} os.MkdirAll(f.root, 0700) seed := filepath.Join(root, "seed") os.MkdirAll(seed, 0700) os.WriteFile(filepath.Join(seed, "index.html"), []byte("

Barber

\n"), 0600) hostileGit(t, seed, "init", "-q", "-b", "main") hostileGit(t, seed, "add", "-A") hostileGit(t, seed, "commit", "-q", "-m", "mockups") out, _ := exec.Command("git", "-C", seed, "rev-parse", "HEAD").Output() sha := strings.TrimSpace(string(out)) bare := f.path(repo) hostileGit(t, root, "init", "-q", "--bare", "-b", "main", bare) hostileGit(t, seed, "push", "-q", bare, "main:refs/heads/"+branch) // A git that counts its ls-remote calls. calls := filepath.Join(root, "calls") git := filepath.Join(root, "git") real, _ := exec.LookPath("git") os.WriteFile(git, []byte("#!/bin/sh\nfor a in \"$@\"; do [ \"$a\" = ls-remote ] && echo x >> "+calls+"; done\nexec "+real+" \"$@\"\n"), 0700) count := func() int { raw, _ := os.ReadFile(calls); os.Remove(calls); return strings.Count(string(raw), "x") } os.MkdirAll(filepath.Join(root, "work"), 0700) c := &Clones{Root: filepath.Join(root, "work"), Git: git, Forge: f} e := &Engineer{Clones: c, Forge: f} ctx := context.Background() for _, rebuilt := range []bool{true, false} { if rebuilt { hostileGit(t, bare, "symbolic-ref", "HEAD", "refs/heads/"+branch) ls, _ := exec.Command("git", "ls-remote", "--symref", bare).Output() want := "ref: refs/heads/" + branch + "\tHEAD\n" + sha + "\tHEAD\n" + sha + "\trefs/heads/" + branch + "\n" if string(ls) != want { t.Fatalf("not amadan-13's answer:\n%s", ls) } } else { hostileGit(t, bare, "symbolic-ref", "HEAD", "refs/heads/main") } count() def, tip, heads, err := c.Heads(ctx, repo, []string{branch}) if n := count(); !errors.Is(err, ErrEmptyRepo) || def != "main" || tip != "" || heads[branch] != sha || n != 1 { t.Fatalf("rebuilt=%v heads: %q %q %v %v in %d ls-remote calls", rebuilt, def, tip, heads, err, n) } st, err := e.inspectMerge(ctx, repo, branch, sha) if n := count(); err != nil || !st.Unborn || st.Default != "main" || st.Head != sha || st.Landed || n != 1 { t.Fatalf("rebuilt=%v inspect %+v %v in %d ls-remote calls", rebuilt, st, err, n) } } // The first merge made main and kept the task branch (branch_closed: // false), HEAD still at the task branch: main is the default, landed. hostileGit(t, bare, "update-ref", "refs/heads/main", sha) hostileGit(t, bare, "symbolic-ref", "HEAD", "refs/heads/"+branch) def, tip, heads, err := c.Heads(ctx, repo, []string{branch}) if err != nil || def != "main" || tip != sha || heads[branch] != sha { t.Fatalf("main beside a kept branch: %q %q %v %v", def, tip, heads, err) } e.O.Runner.GitPath = git if st, err := e.inspectMerge(ctx, repo, branch, sha); err != nil || st.Unborn || !st.Landed || st.Default != "main" || st.MergeSHA != sha { t.Fatalf("the kept branch reads as merged: %+v %v", st, err) } }