diff --git a/cmd/agentsync/import_test.go b/cmd/agentsync/import_test.go index 3cf356c..4a978a2 100644 --- a/cmd/agentsync/import_test.go +++ b/cmd/agentsync/import_test.go @@ -246,6 +246,9 @@ func TestRunImport_UpdateRefusesAnUncommittedCapture(t *testing.T) { t.Errorf("the report does not mention %q:\n%s", want, stdout) } } + if strings.Contains(stdout, "Git reported:") { + t.Errorf("an uncommitted capture got a Git diagnostic:\n%s", stdout) + } // The remedy works. commitRepo(t, repoRoot) @@ -258,6 +261,48 @@ func TestRunImport_UpdateRefusesAnUncommittedCapture(t *testing.T) { } } +func TestRunImport_UpdateReportsMissingHEADObject(t *testing.T) { + t.Setenv("LC_ALL", "C") + base, repoRoot := importFixture(t) + src := projectAgent(t, base, "proj", "researcher", "current\n") + dest := backupPath(t, repoRoot, "proj", "researcher") + mustWriteT(t, dest, "old capture\n") + commitRepo(t, repoRoot) + testfs.DeleteHeadCommit(t, repoRoot) + + args := importArgs(t, repoRoot, base, "--apply", "--update") + for _, jsonOutput := range []bool{false, true} { + runArgs := args + if jsonOutput { + runArgs = append(args, "--json") + } + code, stdout, stderr := runCLI(t, runArgs...) + if code != exitConflict { + t.Fatalf("exit = %d, want %d\nstdout:\n%s\nstderr:\n%s", code, exitConflict, stdout, stderr) + } + reason := stdout + if jsonOutput { + var report importReport + if err := json.Unmarshal([]byte(stdout), &report); err != nil || len(report.Items) != 1 { + t.Fatalf("expected one reported capture, got %+v (%v)\n%s", report.Items, err, stdout) + } + reason = report.Items[0].Reason + } + if !strings.Contains(reason, "Git reported: fatal: not a tree object") { + t.Errorf("the refusal does not name the Git failure:\n%s", reason) + } + if strings.Contains(reason, "commit project-agents/ first") { + t.Errorf("the refusal advises committing to a broken repo:\n%s", reason) + } + if got := readFileT(t, dest); got != "old capture\n" { + t.Errorf("capture was changed to %q", got) + } + if got := readFileT(t, src); got != "current\n" { + t.Errorf("project file was changed to %q", got) + } + } +} + // TestRunImport_SecondUpdateDoesNotDestroyTheFirst is the defect reproduced // against the built binary, driven the same way here: two ordinary commands, // no hand-editing. diff --git a/cmd/agentsync/link_test.go b/cmd/agentsync/link_test.go index 32bb123..edf527a 100644 --- a/cmd/agentsync/link_test.go +++ b/cmd/agentsync/link_test.go @@ -127,6 +127,9 @@ func TestRunLink_ApplyLinksAndIsIdempotent(t *testing.T) { if code != exitOK { t.Fatalf("exit = %d, want %d\nstdout:\n%s\nstderr:\n%s", code, exitOK, stdout, stderr) } + if strings.Contains(stdout, "Git reported:") { + t.Errorf("a non-repository got a Git diagnostic:\n%s", stdout) + } assertIsLink(t, path, target) code, stdout, stderr = runCLI(t, linkArgs(t, repoRoot, base, "--apply")...) @@ -427,21 +430,47 @@ func TestRunLink_AgentNameCannotEscapeTheProject(t *testing.T) { // gate being silently off: git exits non-zero, a repository plainly exists, and // the adoptable file must survive. func TestRunLink_TrackedProjectWithAnUnaskableGitIsRefused(t *testing.T) { + requireGit(t) + t.Setenv("LC_ALL", "C") + t.Setenv("GIT_CONFIG_NOSYSTEM", "1") + t.Setenv("GIT_CONFIG_GLOBAL", os.DevNull) base, repoRoot := linkFixture(t) const body = "canonical shared agent\n" globalAgent(t, repoRoot, "shared", body) path := projectAgentPath(base, "proj", "shared") mustWriteT(t, path, body) - mustWriteT(t, filepath.Join(base, "proj", ".git"), "gitdir: /nonexistent-agentsync-test\n") - - code, stdout, stderr := runCLI(t, linkArgs(t, repoRoot, base, "--apply")...) - if code != exitAtRisk { - t.Fatalf("exit = %d, want %d\nstdout:\n%s\nstderr:\n%s", code, exitAtRisk, stdout, stderr) - } - if !strings.Contains(stdout, "blocked") { - t.Errorf("the report does not say the project was refused:\n%s", stdout) + project := filepath.Join(base, "proj") + commitRepo(t, project) + testfs.DubiousOwnership(t, project) + + args := linkArgs(t, repoRoot, base, "--apply") + for _, jsonOutput := range []bool{false, true} { + runArgs := args + if jsonOutput { + runArgs = append(args, "--json") + } + code, stdout, stderr := runCLI(t, runArgs...) + if code != exitAtRisk { + t.Fatalf("exit = %d, want %d\nstdout:\n%s\nstderr:\n%s", code, exitAtRisk, stdout, stderr) + } + reason := stdout + if jsonOutput { + var report linkReport + if err := json.Unmarshal([]byte(stdout), &report); err != nil || len(report.Blocked) != 1 { + t.Fatalf("expected one blocked project, got %+v (%v)\n%s", report.Blocked, err, stdout) + } + reason = report.Blocked[0].Reason + } else if !strings.Contains(stdout, "blocked") { + t.Errorf("the report does not say the project was refused:\n%s", stdout) + } + if !strings.Contains(reason, "Git reported: fatal: detected dubious ownership") { + t.Errorf("the refusal does not name the Git failure:\n%s", reason) + } + assertIsRegular(t, path, "a project whose git could not be asked must not be linked into") + if got := readFileT(t, path); got != body { + t.Errorf("project file was changed to %q", got) + } } - assertIsRegular(t, path, "a project whose git could not be asked must not be linked into") } // --- the home guard --------------------------------------------------------- diff --git a/internal/importer/importer_test.go b/internal/importer/importer_test.go index 5df610d..095363c 100644 --- a/internal/importer/importer_test.go +++ b/internal/importer/importer_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/agentic-tooling/agentsync/internal/scan" + "github.com/agentic-tooling/agentsync/internal/testfs" ) // --- fixtures --------------------------------------------------------------- @@ -704,30 +705,43 @@ func TestNewPlan_UpdateRefusesWhenGitCannotAnswer(t *testing.T) { func TestApply_UpdateRefusesWhenGitCannotAnswerAtWriteTime(t *testing.T) { requireGit(t) - f := newFixture(t) - f.project("solo", "bespoke", "the current project file\n") - dest := f.backup("solo", "bespoke", "an older capture\n") - f.commitRepo() - - // Planned while git could answer, so this really is an authorised - // update rather than a conflict the planner already rejected. - plan := f.plan(Options{Update: UpdateAll()}) - assertActions(t, plan, map[string]Action{"solo/bespoke": ActionUpdate}) - - noGit(t) - - written, errs := plan.Apply() - if len(written) != 0 { - t.Errorf("wrote %v, want nothing", written) - } - if len(errs) != 1 { - t.Fatalf("errors = %v, want exactly one refusal", errs) - } - if !strings.Contains(errs[0].Error(), "refusing to replace") { - t.Errorf("error = %v, want a refusal to replace", errs[0]) - } - if got := mustRead(t, dest); got != "an older capture\n" { - t.Errorf("destination = %q — it was replaced without the gate being satisfied", got) + for _, tc := range []struct { + name string + breakGit func(*fixture) + diagnostic string + }{ + {"git unavailable", func(f *fixture) { noGit(f.t) }, ""}, + {"packed refs corrupt", func(f *fixture) { testfs.CorruptPackedRefs(f.t, f.repoRoot) }, "packed-refs"}, + } { + t.Run(tc.name, func(t *testing.T) { + f := newFixture(t) + f.project("solo", "bespoke", "the current project file\n") + dest := f.backup("solo", "bespoke", "an older capture\n") + f.commitRepo() + + plan := f.plan(Options{Update: UpdateAll()}) + assertActions(t, plan, map[string]Action{"solo/bespoke": ActionUpdate}) + tc.breakGit(f) + + written, errs := plan.Apply() + if len(written) != 0 { + t.Errorf("wrote %v, want nothing", written) + } + if len(errs) != 1 { + t.Fatalf("errors = %v, want exactly one refusal", errs) + } + reason := errs[0].Error() + if !strings.Contains(reason, "refusing to replace") { + t.Errorf("error = %q, want a refusal to replace", reason) + } + _, reported, hasDiagnostic := strings.Cut(reason, "Git reported: ") + if hasDiagnostic != (tc.diagnostic != "") || !strings.Contains(reported, tc.diagnostic) { + t.Errorf("error = %q, want Git diagnostic %q", reason, tc.diagnostic) + } + if got := mustRead(t, dest); got != "an older capture\n" { + t.Errorf("destination = %q — it was replaced without the gate being satisfied", got) + } + }) } } diff --git a/internal/importer/plan.go b/internal/importer/plan.go index ac949ee..11d038b 100644 --- a/internal/importer/plan.go +++ b/internal/importer/plan.go @@ -499,13 +499,18 @@ func judgeDest(item Item, opts Options) (verdict, error) { // a corrupt object store, no repository at all — then lands on the refusing side // without any call site remembering to handle it. func commitGate(dest string) (Refusal, string) { - switch scan.CommittedInHEAD(dest) { + committed, diagnostic := scan.CommittedInHEADWithDiagnostic(dest) + switch committed { case scan.CommittedYes: return RefusalNone, "" case scan.CommittedNo: return RefusalUncommitted, "the captured copy's current bytes are in no commit — it is untracked, or it has been edited since it was last committed — so replacing it would leave them nowhere at all; commit project-agents/ first, then re-run" default: - return RefusalCommitUnknown, "git could not say whether the captured copy's current bytes are committed, and an unanswered question is not permission to replace what may be the only copy" + reason := "git could not say whether the captured copy's current bytes are committed, and an unanswered question is not permission to replace what may be the only copy" + if diagnostic != "" { + reason += ". Git reported: " + diagnostic + } + return RefusalCommitUnknown, reason } } diff --git a/internal/linker/plan.go b/internal/linker/plan.go index 0082e64..0920b11 100644 --- a/internal/linker/plan.go +++ b/internal/linker/plan.go @@ -607,10 +607,14 @@ func gitGate(project, dir string, excludeLocal bool) gate { default: note.Note = "git could not be asked about this directory" + reason := "git could not say whether this directory is tracked, and a symlink committed into one breaks every other clone; refusing rather than assuming it is not" + if g.Diagnostic != "" { + reason += ". Git reported: " + g.Diagnostic + } return gate{note: note, blocked: &Blocked{ Project: project, Dir: dir, - Reason: "git could not say whether this directory is tracked, and a symlink committed into one breaks every other clone; refusing rather than assuming it is not", + Reason: reason, }} } @@ -633,11 +637,14 @@ func gitGate(project, dir string, excludeLocal bool) gate { if g.GitDir == "" || g.Rel == "" { note.Note = "git did not name this repository's git directory, so no local exclusion could be planned" + reason := fmt.Sprintf("--%s was given but git did not name this repository's git directory, so the links could not be made local; refusing rather than linking into a directory git can see", ExcludeLocalFlag) + if g.GitDirDiagnostic != "" { + reason += ". Git reported: " + g.GitDirDiagnostic + } return gate{note: note, blocked: &Blocked{ Project: project, Dir: dir, - Reason: fmt.Sprintf("--%s was given but git did not name this repository's git directory, so the links could not be made local; refusing rather than linking into a directory git can see", - ExcludeLocalFlag), + Reason: reason, }} } diff --git a/internal/linker/plan_test.go b/internal/linker/plan_test.go index 5a8e846..7ee17c2 100644 --- a/internal/linker/plan_test.go +++ b/internal/linker/plan_test.go @@ -51,10 +51,17 @@ func gitWithoutGitDir(t *testing.T) { t.Fatalf("git not on PATH: %v", err) } bin := t.TempDir() - script := "#!/bin/sh\nfor a in \"$@\"; do [ \"$a\" = --absolute-git-dir ] && exit 128; done\nexec '" + real + "' \"$@\"\n" + script := `#!/bin/sh +if [ "$2" = --absolute-git-dir ]; then + printf '%s\n' 'fatal: git directory unavailable' >&2 + exit 128 +fi +exec "$AGENTSYNC_TEST_REAL_GIT" "$@" +` if err := os.WriteFile(filepath.Join(bin, "git"), []byte(script), 0o755); err != nil { t.Fatal(err) } + t.Setenv("AGENTSYNC_TEST_REAL_GIT", real) t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) } @@ -68,6 +75,9 @@ func TestNewPlan_ExcludeLocalWithoutAGitDirIsRefused(t *testing.T) { if len(plan.Blocked) != 1 || !strings.Contains(plan.Blocked[0].Reason, "git directory") { t.Fatalf("blocked = %+v, want the project refused for want of a git directory", plan.Blocked) } + if !strings.Contains(plan.Blocked[0].Reason, "Git reported: fatal: git directory unavailable") { + t.Errorf("blocked reason omitted the Git diagnostic: %s", plan.Blocked[0].Reason) + } if len(plan.Excludes) != 0 || len(plan.Writes()) != 0 { t.Errorf("planned excludes %v and writes %v with nowhere to exclude into", plan.Excludes, plan.Writes()) } diff --git a/internal/scan/git.go b/internal/scan/git.go index 2395a3a..1b6388d 100644 --- a/internal/scan/git.go +++ b/internal/scan/git.go @@ -3,12 +3,12 @@ package scan import ( "bytes" "errors" - "io" "os" "os/exec" "path/filepath" "strings" "sync" + "unicode" ) // Tracked records whether a file is committed in the git repository that owns @@ -59,25 +59,42 @@ const ( gitNo ) -// runGit executes git in dir and reports which of the three outcomes occurred. -// Trimmed stdout is returned for the gitYes case. -func runGit(dir string, args ...string) (string, gitAnswer) { - out, ans, _ := runGitCode(dir, args...) - return out, ans +type gitResult struct { + output string + answer gitAnswer + code int + diagnostic string } -// runGitCode is runGit plus the process exit code. -// -// gitNo alone is not enough for a caller that must not guess. git exits -// non-zero both when it is answering "no" — check-ignore finding no match, -// rev-parse failing to verify an unborn HEAD, both documented as 1 — and when -// it could not answer at all, which is 128 and covers a corrupt object store, -// an unreadable .git, and safe.directory refusing a checkout it considers -// dubiously owned. Those two mean opposite things on a write path, and only -// the exit code separates them. -// -// The code is meaningful only when the answer is gitNo; it is 0 otherwise. -func runGitCode(dir string, args ...string) (string, gitAnswer, int) { +const maxGitDiagnosticBytes = 512 + +type gitStderr struct { + prefix [maxGitDiagnosticBytes]byte + used int +} + +func (s *gitStderr) Write(p []byte) (int, error) { + s.used += copy(s.prefix[s.used:], p) + return len(p), nil +} + +func (s *gitStderr) diagnostic() string { + line := string(s.prefix[:s.used]) + if end := strings.IndexAny(line, "\r\n\u0085\u2028\u2029"); end >= 0 { + line = line[:end] + } + line = strings.ToValidUTF8(line, "") + return strings.TrimSpace(strings.Map(func(r rune) rune { + if unicode.IsControl(r) || unicode.Is(unicode.Cf, r) { + return -1 + } + return r + }, line)) +} + +// runGit returns stdout on success and bounded stderr on a non-zero exit. +// A non-zero exit can be a clean negative or a failure, so each probe interprets the code. +func runGit(dir string, args ...string) gitResult { cmd := exec.Command("git", args...) // cmd.Dir rather than `git -C`: the working directory is the thing that // actually selects the repository, and it cannot be confused with a @@ -85,24 +102,25 @@ func runGitCode(dir string, args ...string) (string, gitAnswer, int) { cmd.Dir = dir var out bytes.Buffer + var stderr gitStderr cmd.Stdout = &out - cmd.Stderr = io.Discard + cmd.Stderr = &stderr err := cmd.Run() if err == nil { - return strings.TrimSpace(out.String()), gitYes, 0 + return gitResult{output: strings.TrimSpace(out.String()), answer: gitYes} } var exitErr *exec.ExitError if errors.As(err, &exitErr) { // A non-zero exit is git answering the question — or reporting that // it could not. The caller decides which, from the code. - return "", gitNo, exitErr.ExitCode() + return gitResult{answer: gitNo, code: exitErr.ExitCode(), diagnostic: stderr.diagnostic()} } // git is missing, not executable, or the directory is gone: we did not // get an answer. - return "", gitUnavailable, 0 + return gitResult{} } // gitSaidNo is the exit code git uses for a real negative answer. Anything @@ -118,6 +136,8 @@ type gitRoot struct { // repository whose HEAD is unborn), and gitUnavailable when git could // not be run. status gitAnswer + + diagnostic string } // gitProber answers "is this committed?" and caches the per-directory repo @@ -150,8 +170,8 @@ func (g *gitProber) root(dir string) gitRoot { } func probeGitRoot(dir string) gitRoot { - top, ans := runGit(dir, "rev-parse", "--show-toplevel") - switch ans { + result := runGit(dir, "rev-parse", "--show-toplevel") + switch result.answer { case gitUnavailable: return gitRoot{status: gitUnavailable} case gitNo: @@ -177,11 +197,12 @@ func probeGitRoot(dir string) gitRoot { // remedy that is wrong, and a remedy that cannot work is worse // than "git could not say", because the user carries it out. if hasGitEntry(dir) { - return gitRoot{status: gitUnavailable} + return gitRoot{status: gitUnavailable, diagnostic: result.diagnostic} } // Genuinely not inside a repository. return gitRoot{status: gitNo} } + top := result.output if top == "" { // git succeeded but told us nothing usable (bare repo, odd // worktree). Do not guess. @@ -236,15 +257,15 @@ func probeGitRoot(dir string) gitRoot { // and in InspectDir below: distinguishing unreadable refs from an unborn // HEAD requires filesystem corroboration in the style of hasGitEntry, // rather than relying on the exit code alone. - _, ans, code := runGitCode(top, "rev-parse", "--verify", "--quiet", "HEAD") + result = runGit(top, "rev-parse", "--verify", "--quiet", "HEAD") switch { - case ans == gitYes: + case result.answer == gitYes: // HEAD resolves; the repository has at least one commit. - case ans == gitNo && code == gitSaidNo: + case result.answer == gitNo && result.code == gitSaidNo: // Unborn HEAD. A real "no". return gitRoot{status: gitNo} default: - return gitRoot{status: gitUnavailable} + return gitRoot{status: gitUnavailable, diagnostic: result.diagnostic} } return gitRoot{top: top, status: gitYes} @@ -269,38 +290,20 @@ func (g *gitProber) tracked(path string) Tracked { case gitNo: return TrackedNo } + answer, _ := trackedInTree(loc.root, loc.rel) + return answer +} - // ls-tree has no negative exit. It exits 0 and prints nothing when the - // pathspec matches nothing — verified against git 2.50 — so the empty - // output below is the whole of "not in HEAD", and a non-zero exit here - // is never an answer. It is git failing: a commit object that is not in - // the store, safe.directory, an unreadable pack. Confirmed reachable - // with --show-toplevel and rev-parse --verify HEAD both still exiting 0: - // delete the HEAD commit object and only ls-tree notices. - // - // This collapsed into TrackedNo, which over-reported risk rather than - // under-reporting it — Entry.AtRisk is State.AtRisk() && Tracked != - // TrackedYes, so a false TrackedNo makes a file at risk, the safe - // direction. It is fixed for the reason the reported reason has to be - // true, not because anything was unsafe: TrackedUnknown is also != - // TrackedYes, so nothing about risk classification changes. - // - // What does change is CommittedInHEAD, which turns TrackedNo into - // CommittedNo and TrackedUnknown into CommittedUnknown. Both refuse an - // --update, and only the second one's message is true when the object - // store is damaged. - // - // InspectDir's ls-tree already refuses on any non-zero for exactly this - // reason; the two now agree. - out, ans := runGit(loc.root, "ls-tree", "-r", "--name-only", "-z", "HEAD", "--", loc.rel) - if ans != gitYes { - return TrackedUnknown +// ls-tree returns empty stdout for an absent path. Every non-zero exit is a failure to read the tree. +func trackedInTree(root, rel string) (Tracked, string) { + result := runGit(root, "ls-tree", "-r", "--name-only", "-z", "HEAD", "--", rel) + if result.answer != gitYes { + return TrackedUnknown, result.diagnostic } - if strings.TrimSpace(out) == "" { - // git succeeded and matched nothing: the path is not in HEAD. - return TrackedNo + if result.output == "" { + return TrackedNo, "" } - return TrackedYes + return TrackedYes, "" } // located is one path expressed the way git wants to be asked about it: the @@ -312,9 +315,10 @@ func (g *gitProber) tracked(path string) Tracked { // repository (so there is a real negative answer without asking anything), and // gitUnavailable when the question could not be formed at all. type located struct { - root string - rel string - status gitAnswer + root string + rel string + status gitAnswer + diagnostic string } // locate resolves path into the repository-relative form every query below @@ -329,7 +333,7 @@ func (g *gitProber) locate(path string) located { root := g.root(dir) switch root.status { case gitUnavailable: - return located{status: gitUnavailable} + return located{status: gitUnavailable, diagnostic: root.diagnostic} case gitNo: return located{status: gitNo} } @@ -415,10 +419,6 @@ func (c Committed) String() string { // every other outcome refuses. Making CommittedUnknown the zero value keeps // a forgotten case on the refusing side. // -// Moving this into the calling package was rejected: it would duplicate -// runGitCode's exit-code handling into a second place, which is exactly how -// that bug class came to have four members. -// // # Why the blob has to be asked for separately // // Without question 3 this returns CommittedYes for a path whose blob is missing @@ -460,56 +460,43 @@ func (c Committed) String() string { // an update that could have proceeded, and the remedy — any ordinary git // command in the repo — is one the user is being told to run anyway. func CommittedInHEAD(path string) Committed { + answer, _ := CommittedInHEADWithDiagnostic(path) + return answer +} + +// CommittedInHEADWithDiagnostic also returns the failed Git probe's diagnostic, when available. +func CommittedInHEADWithDiagnostic(path string) (Committed, string) { var g gitProber loc := g.locate(path) switch loc.status { case gitUnavailable: - return CommittedUnknown + return CommittedUnknown, loc.diagnostic case gitNo: - // No repository at all, so nothing here is in any commit. - return CommittedNo + return CommittedNo, "" } - // The path question first. It shares the prober, so the repository - // lookup it needs is already cached from locate above. - switch g.tracked(path) { + tracked, diagnostic := trackedInTree(loc.root, loc.rel) + switch tracked { case TrackedUnknown: - return CommittedUnknown + return CommittedUnknown, diagnostic case TrackedNo: - return CommittedNo + return CommittedNo, "" } - // Then the content question. --quiet implies --exit-code: 0 when the - // working file matches HEAD, 1 when it differs. Anything else is git - // failing rather than answering — the causes runGitCode's doc - // enumerates, plus, uniquely on this query, a blob that git needed to - // read in order to compare and could not. - _, ans, code := runGitCode(loc.root, "diff", "--quiet", "HEAD", "--", loc.rel) + diff := runGit(loc.root, "diff", "--quiet", "HEAD", "--", loc.rel) switch { - case ans == gitYes: - // Both questions said yes. Everything above was answered from the - // index and the tree; nothing has yet opened the blob itself. - // - // This is the one probe in the file that deliberately does NOT - // apply the gitSaidNo discipline, and applying it here would be - // the bug rather than the fix. `cat-file -e` on a blob missing - // from the object store exits **1**, not 128 — measured against - // git 2.50 — so a `code == gitSaidNo` arm would read a damaged - // repository as a clean negative and hand back CommittedNo. That - // is a definite answer about content that is in fact unaccounted - // for. ls-tree has already established the path is in HEAD, so - // there is no ordinary negative left for this question to have: - // every non-zero is a repository that cannot produce the bytes, - // and every non-zero is therefore CommittedUnknown. - if _, ans := runGit(loc.root, "cat-file", "-e", "HEAD:"+loc.rel); ans != gitYes { - return CommittedUnknown + case diff.answer == gitYes: + // A missing blob may exit 1 even though the tree still references it. + blob := runGit(loc.root, "cat-file", "-e", "HEAD:"+loc.rel) + if blob.answer != gitYes { + return CommittedUnknown, blob.diagnostic } - return CommittedYes - case ans == gitNo && code == gitSaidNo: - return CommittedNo + return CommittedYes, "" + case diff.answer == gitNo && diff.code == gitSaidNo: + return CommittedNo, "" default: - return CommittedUnknown + return CommittedUnknown, diff.diagnostic } } @@ -571,6 +558,9 @@ type DirGit struct { Tracking DirTracking + // Diagnostic describes the Git failure behind DirUnknown, when available. + Diagnostic string + // Root is the repository's worktree root, resolved. Empty when there is // no repository or the question could not be asked. Root string @@ -580,6 +570,9 @@ type DirGit struct { // when git declined to name it. GitDir string + // GitDirDiagnostic describes a failed GitDir lookup for callers that need a local exclusion. + GitDirDiagnostic string + // Rel is Dir relative to Root, slash-separated — the form a git // pathspec and a .git/info/exclude pattern both want. Rel string @@ -604,8 +597,8 @@ func InspectDir(dir string) DirGit { return d } - top, ans := runGit(probe, "rev-parse", "--show-toplevel") - switch ans { + result := runGit(probe, "rev-parse", "--show-toplevel") + switch result.answer { case gitUnavailable: return d case gitNo: @@ -621,11 +614,13 @@ func InspectDir(dir string) DirGit { // "no repository" turns the gate off for every project in exactly // the environments that need it most. if hasGitEntry(probe) { + d.Diagnostic = result.diagnostic return d } d.Tracking = DirNoRepo return d } + top := result.output if top == "" { // git succeeded and told us nothing usable (a bare repo, an odd // worktree). Do not guess. @@ -648,9 +643,9 @@ func InspectDir(dir string) DirGit { // caller that needs it — linker's --exclude-local — blocks on // `GitDir == ""` rather than proceeding without an exclusion, so the // ambiguity never reaches a decision that could go the permissive way. - if gitDir, ans := runGit(probe, "rev-parse", "--absolute-git-dir"); ans == gitYes && gitDir != "" { - d.GitDir = gitDir - } + result = runGit(probe, "rev-parse", "--absolute-git-dir") + d.GitDir = result.output + d.GitDirDiagnostic = result.diagnostic rel, err := filepath.Rel(top, resolveMissing(dir)) if err != nil || !contains(rel) { @@ -673,40 +668,36 @@ func InspectDir(dir string) DirGit { // reaches the ignore check as though it had no commits, and lands on // DirVisible or DirIgnored — the permissive side. Distinguishing these // cases remains an unresolved limitation of this exit-code check. - _, ans, code := runGitCode(top, "rev-parse", "--verify", "--quiet", "HEAD") + result = runGit(top, "rev-parse", "--verify", "--quiet", "HEAD") switch { - case ans == gitYes: - // ls-tree exits 0 and prints nothing when a pathspec matches - // nothing, so a non-zero exit here is never "not tracked" — it is - // git failing, most plainly on a commit whose object is missing. - // Falling through to the ignore check on that would hand back - // DirVisible or DirIgnored for a directory that is genuinely - // tracked, which is the same silent pass by a different route. - out, ans := runGit(top, "ls-tree", "-r", "--name-only", "-z", "HEAD", "--", d.Rel) - if ans != gitYes { + case result.answer == gitYes: + tracked, diagnostic := trackedInTree(top, d.Rel) + switch tracked { + case TrackedUnknown: + d.Diagnostic = diagnostic return d - } - if strings.TrimSpace(out) != "" { + case TrackedYes: d.Tracking = DirTracked return d } - case ans == gitNo && code == gitSaidNo: + case result.answer == gitNo && result.code == gitSaidNo: // Unborn HEAD. Nothing is committed; carry on to the ignore check. default: + d.Diagnostic = result.diagnostic return d } // check-ignore exits 0 for ignored and 1 for not ignored. Anything else // non-zero is git failing rather than answering, and a failure here must // not read as "not ignored". - _, ans, code = runGitCode(top, "check-ignore", "-q", "--", d.Rel) + result = runGit(top, "check-ignore", "-q", "--", d.Rel) switch { - case ans == gitYes: + case result.answer == gitYes: d.Tracking = DirIgnored - case ans == gitNo && code == gitSaidNo: + case result.answer == gitNo && result.code == gitSaidNo: d.Tracking = DirVisible default: - return d + d.Diagnostic = result.diagnostic } return d } diff --git a/internal/scan/git_test.go b/internal/scan/git_test.go index 95afcc7..b667765 100644 --- a/internal/scan/git_test.go +++ b/internal/scan/git_test.go @@ -1,13 +1,105 @@ package scan import ( + "os" "os/exec" "path/filepath" + "strconv" + "strings" "testing" "github.com/agentic-tooling/agentsync/internal/testfs" ) +func TestGitStderrDiagnostic(t *testing.T) { + t.Run("bounded across writes with split UTF-8", func(t *testing.T) { + prefix := strings.Repeat("x", 511) + var stderr gitStderr + for _, chunk := range []string{prefix, "é" + strings.Repeat("y", 4096), "\nignored"} { + if n, err := stderr.Write([]byte(chunk)); n != len(chunk) || err != nil { + t.Fatalf("Write consumed %d of %d bytes, error %v", n, len(chunk), err) + } + } + if got := stderr.diagnostic(); got != prefix { + t.Errorf("diagnostic length = %d, want exactly 511 ASCII bytes before the split rune", len(got)) + } + }) + + for _, tc := range []struct{ name, stderr, want string }{ + {"control and formatting characters", " f\x00a\x1bt\u009ba\u202el\u200d: café \r\nhint: another line", "fatal: café"}, + {"newline", "fatal: first\nhint: second", "fatal: first"}, + {"Unicode line separator", "fatal: first\u2028hint: second", "fatal: first"}, + {"empty first line", "\x1b\t\nhint: second", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + var stderr gitStderr + if _, err := stderr.Write([]byte(tc.stderr)); err != nil { + t.Fatal(err) + } + if got := stderr.diagnostic(); got != tc.want { + t.Errorf("diagnostic = %q, want %q", got, tc.want) + } + }) + } +} + +func TestGitProbeDiagnosticsFollowTheVerdict(t *testing.T) { + requireGit(t) + repo := filepath.Join(t.TempDir(), "project") + testfs.GitRepo(t, repo, "agent.md", "committed\n") + file := filepath.Join(repo, "agent.md") + visible := filepath.Join(repo, "visible") + mustMkdir(t, visible) + + realGit, err := exec.LookPath("git") + if err != nil { + t.Fatal(err) + } + bin := t.TempDir() + script := `#!/bin/sh +if [ "$1" = "$AGENTSYNC_TEST_PROBE" ]; then + printf '%s\n' "$1 diagnostic" 'ignored second line' >&2 + exit "$AGENTSYNC_TEST_PROBE_EXIT" +fi +exec "$AGENTSYNC_TEST_REAL_GIT" "$@" +` + if err := os.WriteFile(filepath.Join(bin, "git"), []byte(script), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("AGENTSYNC_TEST_REAL_GIT", realGit) + t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) + + for _, tc := range []struct { + name, probe string + exit int + want Committed + diagnostic string + }{ + {"diff failure", "diff", 128, CommittedUnknown, "diff diagnostic"}, + {"diff negative", "diff", 1, CommittedNo, ""}, + {"blob failure", "cat-file", 1, CommittedUnknown, "cat-file diagnostic"}, + {"blob success", "cat-file", 0, CommittedYes, ""}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("AGENTSYNC_TEST_PROBE", tc.probe) + t.Setenv("AGENTSYNC_TEST_PROBE_EXIT", strconv.Itoa(tc.exit)) + got, diagnostic := CommittedInHEADWithDiagnostic(file) + if got != tc.want || diagnostic != tc.diagnostic { + t.Errorf("committed = %v, diagnostic = %q, want %v and %q", got, diagnostic, tc.want, tc.diagnostic) + } + }) + } + + t.Run("ignore check failure", func(t *testing.T) { + t.Setenv("AGENTSYNC_TEST_PROBE", "check-ignore") + t.Setenv("AGENTSYNC_TEST_PROBE_EXIT", "128") + got := InspectDir(visible) + if got.Tracking != DirUnknown || got.Diagnostic != "check-ignore diagnostic" { + t.Errorf("tracking = %v, diagnostic = %q, want unknown and the ignore check diagnostic", got.Tracking, got.Diagnostic) + } + }) +} + // requireGit skips the test when git is not usable, so the suite still runs in // a container without it. func requireGit(t *testing.T) { @@ -652,6 +744,9 @@ func TestProbeGitRoot_RefusedRepoIsNotAbsentRepo(t *testing.T) { if got := CommittedInHEAD(file); got != CommittedUnknown { t.Errorf("CommittedInHEAD under dubious ownership = %v, want %v", got, CommittedUnknown) } + if _, diagnostic := CommittedInHEADWithDiagnostic(file); !strings.Contains(diagnostic, "dubious ownership") { + t.Errorf("root discovery diagnostic = %q, want dubious ownership", diagnostic) + } }) // The other half of the same guard: hasGitEntry must not turn a @@ -726,6 +821,9 @@ func TestProbeGitRoot_UnbornHeadIsTheOnlyNo(t *testing.T) { t.Errorf("CommittedInHEAD = %v, want %v: %v routes import --update to \"commit project-agents/ first\", which cannot be carried out in a repo whose refs will not parse", got, CommittedUnknown, CommittedNo) } + if _, diagnostic := CommittedInHEADWithDiagnostic(file); !strings.Contains(diagnostic, "packed-refs") { + t.Errorf("HEAD verification diagnostic = %q, want packed-refs", diagnostic) + } }) // InspectDir asks the identical query, and the two sites are only worth @@ -742,9 +840,13 @@ func TestProbeGitRoot_UnbornHeadIsTheOnlyNo(t *testing.T) { testfs.CorruptPackedRefs(t, project) - if got := InspectDir(agents).Tracking; got != DirUnknown { + got := InspectDir(agents) + if got.Tracking != DirUnknown { t.Errorf("InspectDir with an unparseable packed-refs = %v, want %v: falling through to the ignore check would let link write into a directory its own git tracks", - got, DirUnknown) + got.Tracking, DirUnknown) + } + if !strings.Contains(got.Diagnostic, "packed-refs") { + t.Errorf("directory HEAD verification diagnostic = %q, want packed-refs", got.Diagnostic) } }) } diff --git a/internal/testfs/git.go b/internal/testfs/git.go index 6abc6a8..aa85687 100644 --- a/internal/testfs/git.go +++ b/internal/testfs/git.go @@ -315,7 +315,7 @@ func DubiousOwnership(t testing.TB, dir string) { t.Setenv("GIT_TEST_ASSUME_DIFFERENT_OWNER", "1") // Deliberately NOT run under GitEnv, unlike every other check in this - // file. The code under test is scan.runGitCode, which sets no Env and + // file. The code under test is scan.runGit, which sets no Env and // therefore inherits the developer's real gitconfig — so the fixture has // to be verified in the same conditions the production probe will meet, // or it could confirm a refusal the probe never sees.