Files
magpie/internal/provider/workplace_test.go
T
JoeyWu-tech 497100488a provider, library: a .git is a repository only when git takes it for one (#3675)
TestPluginToldWhereTheAgentWorks was red on any machine with an empty
.git above its temp folder. GitOnDisk took the first .git it met going
up as a repository, and on this box /tmp/.git is an empty folder (owned
by nobody), so every folder under /tmp read "yes". git passes such a
folder over and goes on up: git rev-parse under it says "not a git
repository".

GitOnDisk now reads each .git on the way as git's own search does
(repo_discovery_find_dir in git 2.56's setup.c), through GitAt:
- A folder counts when git takes it for a repository (is_git_directory):
  a HEAD git takes (a link into refs/, "ref: refs/...", or a commit's
  id), and objects and refs folders, in the folder its commondir names
  for a linked worktree. Any other folder, an empty one say, is passed
  over and the walk goes on up.
- A file counts when it is "gitdir: <folder>" naming such a folder,
  relative to the .git's own folder (a linked worktree's, a
  submodule's). Any other file, one over git's 1 MB, or one that is
  neither file nor folder is "no": git stops there with "not a git
  repository" (a worktree whose repository has gone) or "invalid
  gitfile format". (git 2.34 passed a .git that is neither file nor
  folder over; 2.55 and 2.56, CI's, stop at it.)
- A .git it can't read is unknown, and the header is left off. git
  passes such a folder over and stops at such a file, but either way
  it can't tell an empty .git from a repository it isn't let into
  (another user's, through a shared magpie), and a failed read is
  unknown here.
A bare repository kept as a folder's .git (git init --bare .git) is
still "yes": git finds one there, though no work tree. Not mirrored:
the filesystem boundary, GIT_CEILING_DIRECTORIES and safe.directory's
ownership check. Cost: the same one stat per folder on the way up; at
a .git, a read of HEAD (255 bytes at most) and stats of commondir,
objects and refs.

What a user sees: a request to a plugin provider from an agent that
doesn't say whether its folder is a repository (Codex, Pi) was told
"yes" for a project under a stray empty .git, under a worktree whose
repository was deleted, or under a .git file that names nothing. The
community ZCode plugin then tells the model "- <git label>: yes" and
Command Code's sends isGitRepo: true, so the model may run git commands
that fail with "not a git repository". They are now told "no", and
with a .git on the way magpie can't read, nothing (ZCode's plugin
leaves the line out, Command Code's sends false). Claude Code's and
OpenCode's requests say it themselves and are passed on as they say it,
so nothing changes for them; Claude Code 2.1.310's own check takes any
.git, an empty one too.

The only caller of GitOnDisk is tellWorkPlace (workdir.go), which needs
no change. The library's skill groups had the same first-.git walk:
gitRepoOf took the first .git within four folders of a linked skill for
its checkout, so an empty one between a skill and its clone left the
skill in no group, and gave one imported from there no From. gitRepoOf
now asks provider.GitAt, passes such a .git over to the clone's, and
reads the origin from the folder GitAt names (a linked worktree's
common one), which replaces gitdirConfig. gitdirConfig also took
"gitdir:" with no space after it, or with spaces around the line,
which git doesn't take; such a .git now traces to nothing, as git finds
nothing there. Checkouts git made are traced as before; the test's
fake ones had only a config and now have a HEAD, objects and refs.
Every other .git folder in the Go code is one a walk skips when it
copies, hashes or checks a skill (carry.go, skillcheck.go, skills.go,
skill_edits.go), or the one magpie removes from its own fetch of a
skill (skillgit.go), not a decision about a repository. The Claude
bridge's claudeWorkDir takes the temp folder for one in no repository;
Claude Code decides that for itself, and its git status is off for
every run (CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS), so it stays.

TestPluginToldWhereTheAgentWorks gets a real repository for "in a
repository" (HEAD, objects, refs; an empty .git was all it had) and a
case under an empty .git in its own temp folder, so it fails without
this on any machine. Its "not in one" cases, and the new provider
tests' "no" ones, still need no repository above the temp folder, as
the test did before. TestGitOnDiskIsWhatGitFinds lays out each kind of
.git by hand; TestGitOnDiskAgreesWithGit asks git rev-parse
--git-common-dir in each of those folders and in ones git made (init,
worktree add, a worktree whose record was removed, --separate-git-dir,
init --bare .git), for yes or no and where;
TestGitOnDiskUnreadIsUnknown locks a .git folder and a worktree's .git
file. provider-plugins.md and library.md say the same.

What was run (tree 9a4504d9, on origin/main 56602426, go1.26.8,
linux/amd64, Linux 5.15), outside graftcp, umask 077, git 2.34.1, with
the box's empty /tmp/.git above the tests' temp folders:
- TestPluginToldWhereTheAgentWorks -count=5, Bun 1.4.2: 5 of 5 ok.
  TestGitOnDisk* and TestSkillRepo*, -count=3: 15 of 15 ok. The same
  and TestPluginToldWhereTheAgentWorks, -race -count=2: 12 of 12, no
  race. internal/library and internal/provider whole: ok.
- 56602426's workplace.go and skill_from.go put back under the new
  tests: TestPluginToldWhereTheAgentWorks red 5 of 5, at
  plugin_workdir_test.go:125 both "not in one" and "not in one, under
  an empty .git": the plugin was told git "yes", want "no";
  TestSkillRepoTraced red, "write-a-prd: repo "", want
  "mattpocock/skills"".
- gofmt -l clean. go vet -tags nogui for linux, windows and darwin, go
  vet for windows, go build -tags nogui for linux and darwin and go
  build for windows: exit 0 each. go vet and go build without the tag
  on linux: exit 1 (no libsoup-3.0 or gio-unix-2.0 here).
- go test -tags nogui -count=1 -timeout 45m ./... (Bun 1.4.2, log
  kept; 8m37s, load 32 at its start): 73 packages ok, and 14 tests red
  in 4 packages, none of them this commit's tests or what they cover.
  internal/gateway ran to its end (504s), so
  TestPluginToldWhereTheAgentWorks passed in it; internal/library and
  internal/provider ok. The reds: agent TestCodexDriftReached and
  TestCodexBehindReverseProxy (#3398); TestInstalledVersion,
  TestCursorFolderFromTheEditorIsNotTheCLI,
  TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI, TestOmpDetectedWithPiDir
  and TestZedAppPath (#3141);
  TestReasonixCLIRequiresSupportedNativeVersion and
  TestReasonixCLIRecoversAfterProbeTimeout (#3641: go build's own VCS
  stamping meets the same /tmp/.git, which this doesn't change); edit
  TestWriteAtomicReadOnlyHardLink and testenv TestProgram (umask
  077, #3640); gui TestGatewayHeldByAContainer and
  TestGatewayFixQuitsOnlyAMagpie (#3649).

This commit is 595b361c rebased: the same internal/ patch-id, and
the same row in docs/subsystems/library.md, put in by git's 3-way
merge, as main's 33ccc618 (#2794) rewrote the Skills row, a line of its
context three rows above. The rest is what was run for 595b361c, at
tree d56bed31 on origin/main 098ac969, the same code (not this tree):
- main's GitOnDisk and gitRepoOf under the new tests (098ac969's
  workplace.go and skill_from.go put back):
  TestPluginToldWhereTheAgentWorks -count=5, Bun 1.4.2: red 5 of 5,
  "not in one" and "not in one, under an empty .git" told git "yes".
  With TMPDIR=/var/tmp/3675-clean, no .git above it: red 5 of 5 on the
  new case alone. TestSkillRepoTraced: red, write-a-prd: repo "", want
  "mattpocock/skills".
- Broken by hand, one at a time in workplace.go, each red in the
  GitOnDisk tests on what it breaks, and green again restored:
    any .git folder taken, main's rule for folders: "yes" under an
      empty .git, a zeroed HEAD and a HEAD alone, and for a locked .git
    a gitfile naming no repository, or not a gitfile, walked past:
      "yes" from the repository above it
    HEAD's content not read: "yes" for the zeroed HEAD; objects and
      refs not looked for: "yes" for a HEAD alone
    a HEAD at a commit not taken, or commondir not read: "no" for both
      linked worktrees; a worktree's own folder named, not its common
      one: the repository at .../worktrees/wt where git finds .../.git
    a HEAD linked into refs/ refused: "no"; a relative gitdir read
      from magpie's folder: "no" for the submodule; no 1 MB cap: "yes"
    ENOTDIR taken for a failed read: unknown for a gitfile naming a
      file; a .git it can't read walked past: "no" for both locked ones

Not tried: CI's git 2.55.0 (ubuntu) and 2.56.0 (macOS, Windows) under
TestGitOnDiskAgreesWithGit, which met git 2.34.1 alone; macOS and
Windows at all (Windows CI only compiles the tests); a real ZCode or
Command Code plugin end to end; a shared magpie told another user's
folder; the Library page itself.

Landed by yetone in a batch of Coffemon's patches from the issues.
What was run, go1.26.8, on origin/main cc81ad4ea, then again at
70a0c387c (gofmt, the three vets, the changed tests, umask 077):
- mote (macOS 27): gofmt -l clean; go vet, GOOS=linux go vet -tags
  nogui and GOOS=windows go vet ./...: ok. edit and testenv at umask
  077; agent, provider, library and gateway with an empty .git above
  TMPDIR; davsync, imagemcp, plugin, library, edit, testenv whole; the
  changed tests in agent, provider, gateway and gui; the timing tests
  -count=10 (gateway, davsync, imagemcp) and -count=5 (agent): all ok.
  TestCoreScriptBudget ok: core 1,536,751 of 1,537,034, app.js
  1,312,975 of 1,315,316, no budget raised.
- Red on the old code: on origin/main, TestWriteAtomicReadOnlyHardLink
  at umask 077 and two Reasonix tests under an empty .git; on Linux
  (wsl-run) TestProgram at umask 077 with the old program.go. With
  each fix's code taken back to main's, the Gemini imageConfig tests,
  TestPluginToldWhereTheAgentWorks, TestSkillRepoTraced,
  TestTaggedHooksAlone, TestMainURL/TestMainView and update-auto,
  plugin-github-hooks, plugins-more-discover, plugin-namesake were
  red. Broken by hand: claudeKeyed always true (both
  OwnEndpointNeverAsked tests red), claudeAsk a no-op
  (TestClaudeFirstWriteAsksTheProxy red), GitAt taking any .git folder
  (the three TestGitOnDisk tests red).
- GUI: 123 files (plugins*, update-*, panel/tray/start/context, i18n,
  gui-zh-tw/ja/de and every file that evals app.js parts) in WebKit on
  Linux (wsl-run). 11 files had reds (click-scroll, panel-fold,
  plugin-card-update, plugin-github, plugin-move*, segs-glide,
  tray-totals, update-*), and run again side by side they fail the
  same on origin/main d80d75f30 (79 pass, 26 fail here; 78 and 27
  there). They are click-scroll guards ("the click must not scroll
  the page"), varying by language from run to run (#4385).
  copilot-ghe's route-after-close red is #1949, seen on main 244d80e23
  too. In Chromium on mote, Chromium segfaulted partway through files
  (#4125): context-map, context-scroll-end and context-tune fail the
  same on origin/main 0911a65e7, so the batch's own files
  (plugin-namesake, update-auto, plugins-more-discover,
  plugin-github-hooks) ran in Chromium on Linux: 62 of 62.
- Full suite (go test -tags nogui -count=1 -timeout 45m ./..., mote)
  at 472a0608f (on 70a0c387c): every package ok but internal/gateway,
  whose five reds were #4362's (Antigravity turned-away and
  TestCodexSpentGrokFailingIsTold), fixed on main in d80d75f30. After
  the rebase on 244d80e23 the five pass, and gofmt, the three vets
  and the targeted runs above were run again: ok. In Linux the
  sign-in, copilot, plugin-github*, plugins-more-discover,
  plugin-namesake, plugin-gateway, update-auto, quota-refresh-order
  and i18n files ran in both engines: 475 pass, 4 fail (copilot-ghe
  #1949, plugin-github's click scroll, both red on main too).
- Rebased again on c7171a256, over its budget fix e94bf7a08: gofmt, vet of
  gui, gateway, provider and plugin, TestCoreScriptBudget (core
  1,536,265 of 1,536,586 with the batch's last commit, statusTErr and settingsErr), the Gemini,
  GitOnDisk and plugin tests, and in Linux both engines i18n-keys,
  update-mirror, plugin-namesake, plugins-more-discover,
  plugin-github-hooks and update-auto (138 of 138): ok.
Not tried: the whole GUI suite (mote's WebKit wouldn't launch and its
Chromium segfaulted, #4125); macOS WebKit; the real app's window.
2026-10-30 15:53:22 +08:00

277 lines
10 KiB
Go

package provider
import (
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
)
// gitCase is a folder and what git finds from there: whether it is in a
// git repository, and the folder that holds the repository's config,
// objects and refs, "" for none.
type gitCase struct{ name, dir, want, repo string }
// gitFixtures lays out under root, by hand, a .git of each kind git's own
// search meets, and gives a folder under each with what git finds there.
func gitFixtures(t *testing.T, root string) []gitCase {
t.Helper()
dir := func(p string) string {
t.Helper()
p = filepath.Join(root, filepath.FromSlash(p))
if err := os.MkdirAll(p, 0o755); err != nil {
t.Fatal(err)
}
return p
}
at := func(p string) string { return filepath.Join(root, filepath.FromSlash(p)) }
put := func(p, body string) {
t.Helper()
if err := os.WriteFile(filepath.Join(dir(filepath.Dir(p)), filepath.Base(p)), []byte(body), 0o644); err != nil {
t.Fatal(err)
}
}
// a repository as git init lays one out, what git looks for in it
repo := func(git string) {
put(git+"/HEAD", "ref: refs/heads/main\n")
dir(git + "/objects")
dir(git + "/refs/heads")
}
repo("repo/.git")
dir("empty/.git")
dir("repo/inner/.git")
// a linked worktree (git worktree add): a HEAD of its own, at a
// commit, and the rest in the repository's folder, which commondir
// names
put("repo/.git/worktrees/wt/HEAD", "7c4b0b9e1d1c4f6a8e2b3d5f6a7b8c9d0e1f2a3b\n")
put("repo/.git/worktrees/wt/commondir", "../..\n")
put("repo/.git/worktrees/wt/gitdir", filepath.Join(root, "wt", ".git")+"\n")
put("wt/.git", "gitdir: "+filepath.Join(root, "repo", ".git", "worktrees", "wt")+"\n")
// a worktree left behind by its repository
put("stale/.git", "gitdir: "+filepath.Join(root, "gone", ".git", "worktrees", "stale")+"\n")
// a submodule: its .git names its folder in the superproject's,
// relative to itself
repo("super/.git")
repo("super/.git/modules/sub")
put("super/sub/.git", "gitdir: ../.git/modules/sub\n")
put("super/gone/.git", "gitdir: ../.git/modules/gone\n")
put("garbage/.git", "not a gitfile\n")
put("repo/garbage/.git", "not a gitfile\n")
put("tofile/target", "a file\n")
put("tofile/.git", "gitdir: target\n")
// a gitfile over git's 1 MB, whatever it names
put("big/.git", "gitdir: "+filepath.Join(root, "repo", ".git")+strings.Repeat("\n", 1<<20))
// everything but a HEAD git takes (one a crash zeroed), and a HEAD
// with nothing beside it
put("zeroed/.git/HEAD", "\x00\x00\x00\x00")
dir("zeroed/.git/objects")
dir("zeroed/.git/refs")
put("headonly/.git/HEAD", "ref: refs/heads/main\n")
// a bare repository kept as a folder's .git (git init --bare .git)
repo("bare/.git")
put("bare/.git/config", "[core]\n\trepositoryformatversion = 0\n\tbare = true\n")
cases := []gitCase{
{"in a repository", dir("repo/sub"), "yes", at("repo/.git")},
{"under an empty .git", dir("empty/sub"), "no", ""},
{"under an empty .git in a repository", dir("repo/inner/sub"), "yes", at("repo/.git")},
{"a linked worktree", dir("wt/sub"), "yes", at("repo/.git")},
{"a worktree whose repository has gone", dir("stale/sub"), "no", ""},
{"a submodule", dir("super/sub/deep"), "yes", at("super/.git/modules/sub")},
{"a submodule whose folder in the superproject's .git has gone", dir("super/gone/sub"), "no", ""},
{"a .git file that names no repository", dir("garbage/sub"), "no", ""},
{"a .git file that names no repository, in a repository", dir("repo/garbage/sub"), "no", ""},
{"a .git file that names a file", dir("tofile/sub"), "no", ""},
{"a .git file over 1 MB", dir("big/sub"), "no", ""},
{"a .git whose HEAD git doesn't take", dir("zeroed/sub"), "no", ""},
{"a .git with a HEAD alone", dir("headonly/sub"), "no", ""},
{"a bare repository as .git", dir("bare/sub"), "yes", at("bare/.git")},
}
// a HEAD that is a link into refs/ (core.preferSymlinkRefs)
dir("linked/.git/objects")
dir("linked/.git/refs/heads")
switch err := os.Symlink("refs/heads/main", filepath.Join(root, "linked", ".git", "HEAD")); {
case err == nil:
cases = append(cases, gitCase{"a HEAD that links into refs/", dir("linked/sub"), "yes", at("linked/.git")})
case runtime.GOOS != "windows":
t.Fatal(err)
}
return cases
}
// repoFrom is the folder that holds the repository a walk up from dir
// with GitAt comes to, as GitOnDisk's and the library's gitRepoOf's do:
// "" for none.
func repoFrom(t *testing.T, dir string) string {
t.Helper()
for d := dir; ; d = filepath.Dir(d) {
git, common, err := GitAt(filepath.Join(d, ".git"))
if err != nil {
t.Fatalf("%s: %v", d, err)
}
if git != "" || filepath.Dir(d) == d {
return common
}
}
}
// resolved is path with its links resolved, as git says a folder: "" for
// none.
func resolved(t *testing.T, path string) string {
t.Helper()
if path == "" {
return ""
}
p, err := filepath.EvalSymlinks(path)
if err != nil {
t.Fatal(err)
}
return p
}
// Whether a folder is in a git repository is what git finds from there
// (#3675): an empty .git, as the one in /tmp that made every folder under
// it a repository, is passed over, and so is a .git folder whose HEAD git
// doesn't take; a .git file that names no repository is none, as git
// stops there. GitAt names the folder that holds the repository: a linked
// worktree's is the common one, where the library reads its origin.
func TestGitOnDiskIsWhatGitFinds(t *testing.T) {
for _, c := range gitFixtures(t, t.TempDir()) {
if got := GitOnDisk(c.dir); got != c.want {
t.Errorf("%s: %q, want %q", c.name, got, c.want)
}
if got := repoFrom(t, c.dir); got != c.repo {
t.Errorf("%s: the repository at %q, want %q", c.name, got, c.repo)
}
}
}
// git itself finds what GitOnDisk says, and the repository where GitAt
// says it is (git rev-parse --git-common-dir), from each folder of
// gitFixtures and from repositories git made: a plain one, a linked
// worktree, one left behind, a separate git dir and a bare one kept as
// .git. Neither the machine's git config nor a GIT_ variable of the
// environment the test runs in is read.
func TestGitOnDiskAgreesWithGit(t *testing.T) {
git, err := exec.LookPath("git")
if err != nil {
t.Skip("git isn't installed")
}
env := []string{"GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=" + filepath.Join(t.TempDir(), "gitconfig")}
for _, kv := range os.Environ() {
if !strings.HasPrefix(kv, "GIT_") {
env = append(env, kv)
}
}
run := func(dir string, args ...string) (string, error) {
cmd := exec.Command(git, append([]string{"-c", "user.name=t", "-c", "user.email=t@example.com", "-c", "init.defaultBranch=main", "-c", "commit.gpgsign=false"}, args...)...)
cmd.Dir, cmd.Env = dir, env
out, err := cmd.Output()
if exit := (*exec.ExitError)(nil); errors.As(err, &exit) {
err = fmt.Errorf("%w: %s", err, exit.Stderr)
}
return string(out), err
}
must := func(dir string, args ...string) {
t.Helper()
if _, err := run(dir, args...); err != nil {
t.Fatalf("git %v: %v", args, err)
}
}
root := t.TempDir()
cases := gitFixtures(t, filepath.Join(root, "by-hand"))
made := filepath.Join(root, "made")
repo := filepath.Join(made, "repo")
if err := os.MkdirAll(filepath.Join(made, "modules"), 0o755); err != nil {
t.Fatal(err)
}
must(made, "init", "-q", repo)
must(repo, "commit", "-q", "--allow-empty", "-m", "first")
must(repo, "worktree", "add", "-q", "--detach", filepath.Join(made, "wt"))
must(repo, "worktree", "add", "-q", "--detach", filepath.Join(made, "stale"))
if err := os.RemoveAll(filepath.Join(repo, ".git", "worktrees", "stale")); err != nil {
t.Fatal(err)
}
must(made, "init", "-q", "--separate-git-dir", filepath.Join(made, "modules", "sep"), filepath.Join(made, "sep"))
must(made, "init", "-q", "--bare", filepath.Join(made, "bare", ".git"))
for _, c := range []gitCase{
{"git init", "repo", "yes", "repo/.git"},
{"git worktree add", "wt", "yes", "repo/.git"},
{"git worktree add, its record in the repository removed", "stale", "no", ""},
{"git init --separate-git-dir", "sep", "yes", "modules/sep"},
{"git init --bare .git", "bare", "yes", "bare/.git"},
} {
c.dir = filepath.Join(made, c.dir, "sub")
if err := os.MkdirAll(c.dir, 0o755); err != nil {
t.Fatal(err)
}
if c.repo != "" {
c.repo = filepath.Join(made, filepath.FromSlash(c.repo))
}
cases = append(cases, c)
}
for _, c := range cases {
found, repo := "yes", ""
out, err := run(c.dir, "rev-parse", "--git-common-dir")
if exit := (*exec.ExitError)(nil); errors.As(err, &exit) && exit.ExitCode() == 128 {
found = "no"
} else if err != nil {
t.Fatalf("%s: git rev-parse: %v", c.name, err)
} else {
// relative to the folder it was asked in, when it isn't whole
if repo = strings.TrimSpace(out); !filepath.IsAbs(repo) {
repo = filepath.Join(c.dir, repo)
}
repo = resolved(t, repo)
}
if found != c.want || repo != resolved(t, c.repo) {
t.Errorf("%s: git finds %q at %q, want %q at %q", c.name, found, repo, c.want, c.repo)
}
if got := GitOnDisk(c.dir); got != found {
t.Errorf("%s: %q, git finds %q", c.name, got, found)
}
if got := resolved(t, repoFrom(t, c.dir)); got != repo {
t.Errorf("%s: the repository at %q, git finds it at %q", c.name, got, repo)
}
}
}
// A .git that can't be read is unknown, never "no" (nor the "yes" any
// .git was before): magpie may not be the user it belongs to, through a
// shared magpie, and can't tell an empty one from a repository it isn't
// let into.
func TestGitOnDiskUnreadIsUnknown(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("a folder isn't locked by its mode")
}
if os.Geteuid() == 0 {
t.Skip("root reads a folder whatever its mode")
}
root := t.TempDir()
gitFixtures(t, root)
for _, c := range []struct{ name, dir string }{
{"a .git folder it can't open", "repo/sub"},
{"a worktree's .git file it can't read", "wt/sub"},
} {
dir := filepath.Join(root, filepath.FromSlash(c.dir))
locked := filepath.Join(filepath.Dir(dir), ".git")
fi, err := os.Stat(locked)
if err != nil {
t.Fatal(err)
}
if err := os.Chmod(locked, 0); err != nil {
t.Fatal(err)
}
got := GitOnDisk(dir)
if err := os.Chmod(locked, fi.Mode().Perm()); err != nil {
t.Fatal(err)
}
if got != "" {
t.Errorf("%s: %q, want unknown", c.name, got)
}
}
}