Git designed for AI agents.
graft-resolve: the syntax check judges what the merge broke; invalid references leave the corpus
Federico Eliac81c6a13a922
diff --git a/doc/graft/RESOLVE.md b/doc/graft/RESOLVE.mdindex a0fb01f..1335192 100644--- a/doc/graft/RESOLVE.md+++ b/doc/graft/RESOLVE.md@@ -275,13 +275,27 @@ asks for a JSON answer:- The answer must parse. graft-resolve parses it with the tree-sitter grammarof its language, chosen by extension: TypeScript (`.ts`, `.mts`, `.cts`),TSX (`.tsx`), JavaScript (`.js`, `.mjs`, `.cjs`, `.jsx`), Python (`.py`,- `.pyi`), Go (`.go`), Rust (`.rs`) and Java (`.java`). Any ERROR or MISSING- node rejects the answer, and the reason gives the line and column of the- first one. This is a parse, not a build: names, types and imports are not+ `.pyi`), Go (`.go`), Rust (`.rs`) and Java (`.java`). The check asks+ whether the merge broke the syntax: when both sides parse, an answer with+ any ERROR or MISSING node is rejected, and the reason gives the line and+ column of the first one. When a side does not parse, the grammar cannot+ judge the file, and the answer gets the conflict-marker rule only. Examples:+ Flow annotations in a `.js` file; files that a repository declares to be+ another language; syntax newer than the grammar, such as a Java annotation+ on varargs, or Rust's `dyn 'a + Trait`; test files that are invalid on+ purpose. This is a parse, not a build: names, types and imports are notchecked, and a few things a compiler refuses still parse (a JSX closing tagthat does not match its opening tag, for one). Every other file gets theconflict-marker rule only. The check is always on for `llm` answers anddoes not apply to the other strategies.++ Measured on the human resolutions of the benchmark corpus (3183 cases),+ the check rejects none of the valid ones. 10 human resolutions fail it,+ each with both sides parsing, and all 10 are broken: 6 were committed with+ conflict markers, and 4 do not compile (confirmed with gofmt and by brace+ count). The check gives no verdict on 83 files where a side does not parse:+ 76 JavaScript (Flow, and TypeScript test baselines), 3 Go (tests that are+ invalid on purpose), 2 Java and 2 Rust (syntax newer than the grammar).- The configured checks still run afterwards.- For large files the strategy sends only the conflict hunks with context andreassembles the file locally.diff --git a/tools/graft-agents/cmd/graft-resolve/bench.go b/tools/graft-agents/cmd/graft-resolve/bench.goindex d1262e5..19cf6db 100644--- a/tools/graft-agents/cmd/graft-resolve/bench.go+++ b/tools/graft-agents/cmd/graft-resolve/bench.go@@ -11,6 +11,7 @@ import ("os""os/signal""path/filepath"+ "sort""strings""syscall""time"@@ -42,8 +43,12 @@ func runBench(args []string, stdout, stderr io.Writer) int {return benchRun(ctx, args[1:], stdout, stderr)case "rejudge":return benchRejudge(ctx, args[1:], stdout, stderr)+ case "syntax":+ return benchSyntax(ctx, args[1:], stdout, stderr)+ case "filter":+ return benchFilter(ctx, args[1:], stdout, stderr)}- fmt.Fprintf(stderr, "graft-resolve bench: unknown subcommand %q, want mine, run or rejudge\n", args[0])+ fmt.Fprintf(stderr, "graft-resolve bench: unknown subcommand %q, want mine, run, rejudge, syntax or filter\n", args[0])return 2}@@ -62,6 +67,10 @@ func benchMine(ctx context.Context, args []string, stdout, stderr io.Writer) intreturn 2}+ if !syntax.Available {+ fmt.Fprintln(stderr, "graft-resolve bench mine: this graft-resolve was built without cgo, and mining checks the syntax of the human resolutions; build it with CGO_ENABLED=1 and a C compiler")+ return 1+ }corpus, err := bench.LoadCorpus(*corpusPath)if err != nil {fmt.Fprintf(stderr, "graft-resolve bench mine: %v\n", err)@@ -315,3 +324,120 @@ func writeReport(report bench.Report, jsonOut, mdOut string, stdout io.Writer) e}return report.WriteMarkdown(out)}++// benchSyntax runs the syntax check on every human resolution of a manifest, with no model call:+//+// graft-resolve bench syntax --manifest FILE --clones DIR [--json-out FILE]+//+// It prints the checked and failed counts per language and every failure.+func benchSyntax(ctx context.Context, args []string, stdout, stderr io.Writer) int {+ fs := flag.NewFlagSet("graft-resolve bench syntax", flag.ContinueOnError)+ fs.SetOutput(stderr)+ manifestPath := fs.String("manifest", "", "manifest written by bench mine")+ clones := fs.String("clones", "", "directory of the clones of the corpus repositories")+ jsonOut := fs.String("json-out", "", "counts and failures as JSON")+ if err := fs.Parse(args); err != nil {+ return 2+ }+ if *manifestPath == "" || *clones == "" || fs.NArg() != 0 {+ fmt.Fprintln(stderr, "graft-resolve bench syntax: --manifest and --clones are required")+ return 2+ }+ if !syntax.Available {+ fmt.Fprintln(stderr, "graft-resolve bench syntax: this graft-resolve was built without cgo; build it with CGO_ENABLED=1")+ return 1+ }+ manifest, err := bench.LoadManifest(*manifestPath)+ if err != nil {+ fmt.Fprintf(stderr, "graft-resolve bench syntax: %v\n", err)+ return 1+ }+ stats, findings, err := bench.HumanSyntax(ctx, manifest.Cases, func(repo string) string { return bench.CloneDir(*clones, repo) })+ if err != nil {+ fmt.Fprintf(stderr, "graft-resolve bench syntax: %v\n", err)+ return 1+ }+ if *jsonOut != "" {+ data, err := json.MarshalIndent(map[string]any{"languages": stats, "failures": findings}, "", " ")+ if err == nil {+ err = os.WriteFile(*jsonOut, append(data, '\n'), 0o644)+ }+ if err != nil {+ fmt.Fprintf(stderr, "graft-resolve bench syntax: %v\n", err)+ return 1+ }+ }+ langs := make([]string, 0, len(stats))+ for l := range stats {+ langs = append(langs, l)+ }+ sort.Strings(langs)+ for _, l := range langs {+ s := stats[l]+ fmt.Fprintf(stdout, "%s: %d with both sides parsing, %d of them fail (%.1f%%); %d with a side the grammar does not parse (no verdict)\n",+ l, s.Checked, s.Failed, 100*float64(s.Failed)/float64(max(1, s.Checked)), s.Unchecked)+ }+ for _, f := range findings {+ if f.Unchecked {+ fmt.Fprintf(stdout, "no verdict: %s %s %s %s: %s\n", f.ID, f.Repo, f.Merge, f.Path, f.Reason)+ continue+ }+ fmt.Fprintf(stdout, "fails: %s %s %s %s (conflict markers: %v): %s\n", f.ID, f.Repo, f.Merge, f.Path, f.Markers, f.Reason)+ }+ return 0+}++// benchFilter leaves out the cases of a manifest whose human resolution is not a valid reference+// (bench mine applies the same rule to what it mines):+//+// graft-resolve bench filter --manifest IN --clones DIR --manifest-out OUT+func benchFilter(ctx context.Context, args []string, stdout, stderr io.Writer) int {+ fs := flag.NewFlagSet("graft-resolve bench filter", flag.ContinueOnError)+ fs.SetOutput(stderr)+ manifestPath := fs.String("manifest", "", "manifest to filter")+ clones := fs.String("clones", "", "directory of the clones of the corpus repositories")+ outPath := fs.String("manifest-out", "", "filtered manifest to write")+ if err := fs.Parse(args); err != nil {+ return 2+ }+ if *manifestPath == "" || *clones == "" || *outPath == "" || fs.NArg() != 0 {+ fmt.Fprintln(stderr, "graft-resolve bench filter: --manifest, --clones and --manifest-out are required")+ return 2+ }+ manifest, err := bench.LoadManifest(*manifestPath)+ if err != nil {+ fmt.Fprintf(stderr, "graft-resolve bench filter: %v\n", err)+ return 1+ }+ kept, stats, err := bench.Filter(ctx, manifest.Cases, func(repo string) string { return bench.CloneDir(*clones, repo) })+ if err != nil {+ fmt.Fprintf(stderr, "graft-resolve bench filter: %v\n", err)+ return 1+ }+ for repo, s := range manifest.Stats {+ for reason, n := range stats {+ if strings.HasPrefix(reason, repo+": ") {+ s.InvalidReference += n+ s.Kept -= n+ }+ }+ manifest.Stats[repo] = s+ }+ manifest.Cases = kept+ if err := bench.SaveManifest(*outPath, manifest); err != nil {+ fmt.Fprintf(stderr, "graft-resolve bench filter: %v\n", err)+ return 1+ }+ reasons := make([]string, 0, len(stats))+ for r := range stats {+ reasons = append(reasons, r)+ }+ sort.Strings(reasons)+ left := 0+ for _, r := range reasons {+ fmt.Fprintf(stdout, "left out %d: %s\n", stats[r], r)+ left += stats[r]+ }+ fmt.Fprintf(stdout, "%d of %d cases kept in %s\n", len(kept), len(kept)+left, *outPath)+ return 0+}diff --git a/tools/graft-agents/cmd/graft-resolve/bench_nocgo_test.go b/tools/graft-agents/cmd/graft-resolve/bench_nocgo_test.gonew file mode 100644index 0000000..c42e921--- /dev/null+++ b/tools/graft-agents/cmd/graft-resolve/bench_nocgo_test.go@@ -0,0 +1,26 @@+//go:build !cgo++package main++import (+ "bytes"+ "strings"+ "testing"+)++// TestBenchRefusesWithoutCgo: without the grammars, mining could not validate the human+// resolutions and the syntax check would reject every answer, so bench mine, run and syntax refuse+// to start, naming the build requirement.+func TestBenchRefusesWithoutCgo(t *testing.T) {+ dir := t.TempDir()+ for _, args := range [][]string{+ {"bench", "mine", "--corpus", dir + "/corpus.json", "--clones", dir, "--manifest", dir + "/m.json"},+ {"bench", "run", "--manifest", dir + "/m.json", "--clones", dir},+ {"bench", "syntax", "--manifest", dir + "/m.json", "--clones", dir},+ } {+ var stdout, stderr bytes.Buffer+ if code := run(args, nil, &stdout, &stderr); code != 1 || !strings.Contains(stderr.String(), "CGO_ENABLED=1") {+ t.Errorf("%s exited %d: %s", args[1], code, stderr.String())+ }+ }+}diff --git a/tools/graft-agents/cmd/graft-resolve/bench_test.go b/tools/graft-agents/cmd/graft-resolve/bench_test.goindex ec6aefc..0704ada 100644--- a/tools/graft-agents/cmd/graft-resolve/bench_test.go+++ b/tools/graft-agents/cmd/graft-resolve/bench_test.go@@ -1,3 +1,5 @@+//go:build cgo+package mainimport (@@ -10,7 +12,6 @@ import ("testing""github.com/feder-cr/git-ai/tools/graft-agents/resolve/bench"- "github.com/feder-cr/git-ai/tools/graft-agents/resolve/syntax")// gitIn runs git in dir with a fixed identity, given on the command line.@@ -99,13 +100,6 @@ func TestBenchMineAndRun(t *testing.T) {stdout.Reset()stderr.Reset()- if !syntax.Available {- // Without cgo the syntax check would reject every answer: the run refuses to start.- if code := run([]string{"bench", "run", "--manifest", manifest, "--clones", clones}, nil, &stdout, &stderr); code != 1 || !strings.Contains(stderr.String(), "without cgo") {- t.Fatalf("run without cgo exited %d: %s", code, stderr.String())- }- return- }jsonOut := filepath.Join(work, "report.json")if code := run([]string{"bench", "run", "--manifest", manifest, "--clones", clones, "--label", "trivial", "--json-out", jsonOut}, nil, &stdout, &stderr); code != 0 {t.Fatalf("run exited %d: %s", code, stderr.String())diff --git a/tools/graft-agents/resolve/bench/bench_test.go b/tools/graft-agents/resolve/bench/bench_test.goindex 43bf29f..1aefa18 100644--- a/tools/graft-agents/resolve/bench/bench_test.go+++ b/tools/graft-agents/resolve/bench/bench_test.go@@ -1,237 +1,13 @@package benchimport (- "context"- "errors""fmt"- "os"- "os/exec"- "path/filepath""strings""testing"- "time""github.com/feder-cr/git-ai/tools/graft-agents/protocol"- "github.com/feder-cr/git-ai/tools/graft-agents/resolve")-// fixture is a repository with crafted merges.-type fixture struct {- t *testing.T- dir string- now int64-}--func newFixture(t *testing.T) *fixture {- t.Helper()- if _, err := exec.LookPath("git"); err != nil {- t.Skip("git is not installed")- }- f := &fixture{t: t, dir: t.TempDir(), now: 1767225600}- f.git("init", "-q", "-b", "main")- return f-}--// git runs git in the fixture with a fixed identity and date, given on the command line so that no-// configuration file is touched.-func (f *fixture) git(args ...string) string {- f.t.Helper()- f.now += 60- cmd := exec.Command("git", append([]string{"-C", f.dir, "-c", "user.name=Bench", "-c", "[email protected]",- "-c", "commit.gpgsign=false", "-c", "init.defaultBranch=main"}, args...)...)- date := time.Unix(f.now, 0).UTC().Format(time.RFC3339)- cmd.Env = append(os.Environ(), "GIT_AUTHOR_DATE="+date, "GIT_COMMITTER_DATE="+date, "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_SYSTEM=/dev/null")- out, err := cmd.CombinedOutput()- if err != nil {- f.t.Fatalf("git %s: %v: %s", strings.Join(args, " "), err, out)- }- return strings.TrimSpace(string(out))-}--func (f *fixture) write(name, content string) {- f.t.Helper()- p := filepath.Join(f.dir, name)- if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {- f.t.Fatal(err)- }- if err := os.WriteFile(p, []byte(content), 0o644); err != nil {- f.t.Fatal(err)- }-}--func (f *fixture) commit(msg string, files map[string]string) string {- f.t.Helper()- for name, content := range files {- f.write(name, content)- }- f.git("add", "-A")- f.git("commit", "-q", "-m", msg)- return f.git("rev-parse", "HEAD")-}--// conflictMerge merges branch into the current branch, which conflicts, and commits the human-// resolution.-func (f *fixture) conflictMerge(branch string, resolved map[string]string) string {- f.t.Helper()- cmd := exec.Command("git", "-C", f.dir, "-c", "user.name=Bench", "-c", "[email protected]", "merge", "--no-ff", "-q", branch)- cmd.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_SYSTEM=/dev/null")- if out, err := cmd.CombinedOutput(); err == nil {- f.t.Fatalf("merge of %s did not conflict: %s", branch, out)- }- return f.commit("Merge "+branch, resolved)-}--const (- goBase = "package a\n\nfunc A() int {\n\treturn 1\n}\n"- goOurs = "package a\n\nfunc A() int {\n\treturn 2\n}\n"- goTheirs = "package a\n\nfunc A() int {\n\treturn 3\n}\n"- goHuman = "package a\n\nfunc A() int {\n\treturn 2 + 3\n}\n"-)--// buildHistory creates: a conflicting merge of a.go resolved by hand (one case), a conflicting-// merge of b.py where the human took one side (not a case), a conflict in notes.txt (no family),-// and a clean merge.-func buildHistory(f *fixture) (mergeA string) {- f.commit("base", map[string]string{"a.go": goBase, "b.py": "x = 1\n", "notes.txt": "one\n"})-- f.git("checkout", "-q", "-b", "feature")- f.commit("feature: A returns 3", map[string]string{"a.go": goTheirs})- f.git("checkout", "-q", "main")- f.commit("main: A returns 2", map[string]string{"a.go": goOurs})- mergeA = f.conflictMerge("feature", map[string]string{"a.go": goHuman})-- f.git("checkout", "-q", "-b", "feature2")- f.commit("feature2", map[string]string{"b.py": "x = 3\n", "notes.txt": "three\n"})- f.git("checkout", "-q", "main")- f.commit("main2", map[string]string{"b.py": "x = 2\n", "notes.txt": "two\n"})- f.conflictMerge("feature2", map[string]string{"b.py": "x = 2\n", "notes.txt": "two and three\n"})-- f.git("checkout", "-q", "-b", "feature3")- f.commit("feature3", map[string]string{"c.go": "package c\n"})- f.git("checkout", "-q", "main")- f.commit("main3", map[string]string{"d.go": "package d\n"})- f.git("merge", "--no-ff", "-q", "-m", "clean merge", "feature3")- return mergeA-}--func TestMineKeepsRealResolutions(t *testing.T) {- f := newFixture(t)- mergeA := buildHistory(f)- head := f.git("rev-parse", "HEAD")-- cases, stats, err := Mine(context.Background(), Repo{Name: "fixture", Commit: head, License: "MIT"}, f.dir, MineOptions{})- if err != nil {- t.Fatal(err)- }- if len(cases) != 1 {- t.Fatalf("got %d cases, want 1: %+v (stats %+v)", len(cases), cases, stats)- }- c := cases[0]- if c.Merge != mergeA || c.Path != "a.go" || c.Family != FamilyGo || c.Kind != protocol.KindContent || c.License != "MIT" {- t.Fatalf("unexpected case %+v", c)- }- if c.BaseBlob == nil || c.OursBlob == nil || c.TheirsBlob == nil || c.HumanBlob == nil {- t.Fatalf("missing sides in %+v", c)- }- want := MineStats{Merges: 3, ConflictingMerges: 2, ConflictingFiles: 3, OtherFamily: 1, OneSide: 1, Kept: 1}- if stats != want {- t.Fatalf("stats %+v, want %+v", stats, want)- }-- // The manifest replays identically.- file := filepath.Join(t.TempDir(), "manifest.json")- if err := SaveManifest(file, Manifest{Version: ManifestVersion, Cases: cases}); err != nil {- t.Fatal(err)- }- m, err := LoadManifest(file)- if err != nil {- t.Fatal(err)- }- if len(m.Cases) != 1 || m.Cases[0].ID != c.ID || *m.Cases[0].HumanBlob != *c.HumanBlob {- t.Fatalf("manifest round trip changed the case: %+v", m.Cases)- }-}--// TestMineSkipsUnrelatedHistories mines a repository that absorbed another one with a merge of-// unrelated histories, which git merge-tree refuses: the merge is skipped and counted, and the-// conflicting merge after it is still mined.-func TestMineSkipsUnrelatedHistories(t *testing.T) {- f := newFixture(t)- f.commit("base", map[string]string{"a.go": "package a\n\nvar x = 1\n"})- f.git("checkout", "-q", "--orphan", "other")- f.git("rm", "-q", "-r", "--cached", ".")- f.commit("other root", map[string]string{"b.py": "y = 1\n"})- f.git("checkout", "-q", "-f", "main")- f.git("merge", "-q", "--no-ff", "--allow-unrelated-histories", "-m", "absorb other", "other")-- f.git("checkout", "-q", "-b", "feature")- f.commit("three", map[string]string{"a.go": "package a\n\nvar x = 3\n"})- f.git("checkout", "-q", "main")- f.commit("two", map[string]string{"a.go": "package a\n\nvar x = 2\n"})- f.conflictMerge("feature", map[string]string{"a.go": "package a\n\nvar x = 2 + 3\n"})- head := f.git("rev-parse", "HEAD")-- cases, stats, err := Mine(context.Background(), Repo{Name: "fixture", Commit: head, License: "MIT"}, f.dir, MineOptions{})- if err != nil {- t.Fatal(err)- }- want := MineStats{Merges: 2, ConflictingMerges: 1, SkippedMergeBases: 1, ConflictingFiles: 1, Kept: 1}- if stats != want || len(cases) != 1 {- t.Fatalf("stats %+v (%d cases), want %+v and 1 case", stats, len(cases), want)- }-}--// fixedStrategy answers every file with content, or fails with err.-type fixedStrategy struct {- content []byte- err error-}--func (s fixedStrategy) Resolve(_ context.Context, _ resolve.File, _ protocol.Request) (resolve.Resolution, bool, error) {- if s.err != nil {- return resolve.Resolution{}, false, s.err- }- return resolve.Resolution{Action: protocol.ActionWrite, Mode: protocol.ModeFile, Content: s.content}, true, nil-}--func TestRunnerOutcomes(t *testing.T) {- f := newFixture(t)- buildHistory(f)- head := f.git("rev-parse", "HEAD")- cases, _, err := Mine(context.Background(), Repo{Name: "fixture", Commit: head, License: "MIT"}, f.dir, MineOptions{})- if err != nil {- t.Fatal(err)- }-- for _, tc := range []struct {- name string- strategy resolve.Strategy- want string- exact bool- }{- {"correct", fixedStrategy{content: []byte(goHuman)}, OutcomeCorrect, true},- {"correct after normalizing", fixedStrategy{content: []byte(strings.ReplaceAll(goHuman, "\n", " \r\n") + "\n\n")}, OutcomeCorrect, false},- {"wrong", fixedStrategy{content: []byte(goOurs)}, OutcomeWrong, false},- {"rejected by the marker rule", fixedStrategy{content: []byte("<<<<<<< ours\nx\n=======\ny\n>>>>>>> theirs\n")}, OutcomeRejected, false},- {"model error", fixedStrategy{err: errors.New("provider: 500")}, OutcomeModelError, false},- {"budget", fixedStrategy{err: resolve.ErrBudgetExhausted}, OutcomeNotRun, false},- } {- t.Run(tc.name, func(t *testing.T) {- res, err := resolve.NewResolver([]resolve.Binding{{Name: "fake", Strategy: tc.strategy}}, nil, time.Minute)- if err != nil {- t.Fatal(err)- }- results, err := Runner{Resolver: res, Clone: func(string) string { return f.dir }}.Run(context.Background(), cases)- if err != nil {- t.Fatal(err)- }- if len(results) != 1 || results[0].Outcome != tc.want || results[0].Exact != tc.exact {- t.Fatalf("results %+v, want outcome %s exact %v", results, tc.want, tc.exact)- }- })- }-}-func TestNotSentReason(t *testing.T) {big := strings.Repeat("x", 3000)for _, tc := range []struct {@@ -341,12 +117,12 @@ func TestSampleIsStratifiedAndStable(t *testing.T) {func TestReportCounts(t *testing.T) {rep := NewReport("test", []Result{{Family: FamilyGo, Outcome: OutcomeCorrect, Exact: true},- {Family: FamilyGo, Outcome: OutcomeWrong},- {Family: FamilyPython, Outcome: OutcomeRejected, HumanSyntaxError: "syntax check: a.py does not parse"},+ {Family: FamilyGo, Outcome: OutcomeWrong, BlankLinesOnly: true, SyntaxUnchecked: true},+ {Family: FamilyPython, Outcome: OutcomeRejected},{Family: FamilyPython, Outcome: OutcomeNotSent, Reason: NotSentGenerated},})- if rep.Total.HumanSyntax != 1 || rep.Families[FamilyPython].HumanSyntax != 1 {- t.Fatalf("human syntax failures %+v", rep.Families)+ if rep.Total.BlankLinesOnly != 1 || rep.Families[FamilyGo].SyntaxUnchecked != 1 {+ t.Fatalf("counts %+v", rep.Families)}if rep.Total.Cases != 4 || rep.Total.Accepted() != 2 || rep.Total.ErrorRate() != 0.5 {t.Fatalf("totals %+v", rep.Total)@@ -358,7 +134,8 @@ func TestReportCounts(t *testing.T) {if err := rep.WriteMarkdown(&b); err != nil {t.Fatal(err)}- if !strings.Contains(b.String(), "| total | 4 | 1 (1) | 1 | 1 | 1 |") || !strings.Contains(b.String(), "reject the right answer: 1 (go 0, python 1)") {+ if !strings.Contains(b.String(), "| total | 4 | 1 (1) | 1 | 1 | 1 |") || !strings.Contains(b.String(), "blank lines only (counted as wrong): 1 (go 1, python 0)") ||+ !strings.Contains(b.String(), "does not parse with the grammar (a dialect such as Flow, or code the grammar does not cover): 1 (go 1, python 0)") {t.Fatalf("markdown:\n%s", b.String())}}@@ -376,3 +153,17 @@ func TestCommittedCorpusLoads(t *testing.T) {}}}++func TestBlankLinesOnly(t *testing.T) {+ human := []byte("a\n\nb\n c\n")+ for result, want := range map[string]bool{+ "a\nb\n c\n": true, // a blank line less+ "a\n\n\nb\n\n c\n": true, // blank lines more+ "a\nb\nc\n": false, // indentation counts+ "a\nb\n d\n": false,+ } {+ if got := blankLinesOnly([]byte(result), human); got != want {+ t.Errorf("blankLinesOnly(%q) = %v, want %v", result, got, want)+ }+ }+}diff --git a/tools/graft-agents/resolve/bench/humansyntax.go b/tools/graft-agents/resolve/bench/humansyntax.gonew file mode 100644index 0000000..0975a1c--- /dev/null+++ b/tools/graft-agents/resolve/bench/humansyntax.go@@ -0,0 +1,93 @@+package bench++import (+ "context"+ "errors"++ "github.com/feder-cr/git-ai/tools/graft-agents/resolve/syntax"+)++// SyntaxFinding is a human resolution that fails the syntax check of the llm answers.+type SyntaxFinding struct {+ ID string `json:"id"`+ Repo string `json:"repo"`+ Merge string `json:"merge"`+ Path string `json:"path"`+ Language string `json:"language"`+ Reason string `json:"reason"`+ // Markers says the human resolution still has conflict markers.+ Markers bool `json:"markers"`+ // Unchecked marks a case the check gives no verdict on: Reason then names the side that does+ // not parse and its first error.+ Unchecked bool `json:"unchecked,omitempty"`+}++// SyntaxStats counts, per language, how the syntax check of the llm answers (syntax.CheckMerge)+// treats the human resolutions: Checked when both sides parse, of which Failed do not parse+// themselves (a check rejecting a human resolution would reject a correct AI one just the same,+// unless the human one is broken); Unchecked when a side does not parse, so the check gives no+// verdict on the file.+type SyntaxStats struct {+ Checked int `json:"checked"`+ Failed int `json:"failed"`+ Unchecked int `json:"unchecked"`+}++// HumanSyntax runs the syntax check of the llm answers on the human resolution of every case+// (a deleted file has none), with both sides, and returns the counts by language (LanguageOf),+// every failure, and every case without a verdict. Paths with no grammar are not counted.+func HumanSyntax(ctx context.Context, cases []Case, clone func(repo string) string) (map[string]SyntaxStats, []SyntaxFinding, error) {+ stats := map[string]SyntaxStats{}+ var findings []SyntaxFinding+ for _, c := range cases {+ if c.HumanBlob == nil {+ continue+ }+ if _, ok := syntax.LanguageOf(c.Path); !ok {+ continue+ }+ g := gitRepo{dir: clone(c.Repo)}+ var blobs [3][]byte+ for i, e := range []*entry{c.HumanBlob, c.OursBlob, c.TheirsBlob} {+ if e == nil {+ continue+ }+ b, err := g.blob(ctx, e.OID)+ if err != nil {+ return nil, nil, err+ }+ blobs[i] = b+ }+ lang := LanguageOf(c.Path)+ s := stats[lang]+ checked, err := syntax.CheckMerge(ctx, c.Path, blobs[0], blobs[1], blobs[2])+ var se *syntax.Error+ switch {+ case !checked && err == nil:+ s.Unchecked+++ // Name the side the grammar does not parse, and where.+ f := SyntaxFinding{ID: c.ID, Repo: c.Repo, Merge: c.Merge, Path: c.Path, Language: lang, Unchecked: true}+ for i, side := range []string{"ours", "theirs"} {+ if blobs[i+1] == nil {+ continue+ }+ if err := syntax.Check(ctx, c.Path, blobs[i+1]); err != nil {+ f.Reason = side + ": " + err.Error()+ break+ }+ }+ findings = append(findings, f)+ case err == nil:+ s.Checked+++ case errors.As(err, &se):+ s.Checked+++ s.Failed+++ findings = append(findings, SyntaxFinding{ID: c.ID, Repo: c.Repo, Merge: c.Merge, Path: c.Path, Language: lang,+ Reason: se.Error(), Markers: hasMarkers(blobs[0])})+ default:+ return nil, nil, err+ }+ stats[lang] = s+ }+ return stats, findings, nil+}diff --git a/tools/graft-agents/resolve/bench/judge.go b/tools/graft-agents/resolve/bench/judge.goindex bd37b8c..46aee9e 100644--- a/tools/graft-agents/resolve/bench/judge.go+++ b/tools/graft-agents/resolve/bench/judge.go@@ -23,6 +23,22 @@ func normalize(content []byte) []byte {// judge reports whether a result equals the human resolution after normalization, and whether it// is byte-identical. A nil content is a deletion.+// blankLinesOnly reports whether two contents differ only in blank lines once normalized:+// a wrong result that is the human resolution with blank lines added or removed. It is reported+// beside the wrong count, which it stays part of; indentation and every other character count.+func blankLinesOnly(result, human []byte) bool {+ strip := func(b []byte) string {+ var out []string+ for _, line := range strings.Split(string(normalize(b)), "\n") {+ if line != "" {+ out = append(out, line)+ }+ }+ return strings.Join(out, "\n")+ }+ return strip(result) == strip(human)+}+func judge(result, human []byte, resultDeleted, humanDeleted bool) (correct, exact bool) {if resultDeleted || humanDeleted {return resultDeleted == humanDeleted, resultDeleted == humanDeleteddiff --git a/tools/graft-agents/resolve/bench/mine.go b/tools/graft-agents/resolve/bench/mine.goindex 530a762..625f945 100644--- a/tools/graft-agents/resolve/bench/mine.go+++ b/tools/graft-agents/resolve/bench/mine.go@@ -7,6 +7,7 @@ import ("fmt""github.com/feder-cr/git-ai/tools/graft-agents/protocol"+ "github.com/feder-cr/git-ai/tools/graft-agents/resolve/syntax")// DefaultMaxMerges bounds the merges replayed per repository when the corpus sets no bound.@@ -32,7 +33,10 @@ type MineStats struct {// OneSide counts conflicting files whose human resolution is one of the two sides, which// measures nothing about merging.OneSide int `json:"one_side"`- Kept int `json:"kept"`+ // InvalidReference counts conflicting files whose human resolution is not a valid reference+ // (invalidReference: committed conflict markers, or broken syntax where both sides parse).+ InvalidReference int `json:"invalid_reference"`+ Kept int `json:"kept"`}// caseID returns the stable ID of a case.@@ -44,6 +48,10 @@ func caseID(repo, merge, p string) string {// Mine replays the merges of repo, cloned at dir, and returns the cases: the conflicting files of// a benchmark family whose human resolution differs from both sides.func Mine(ctx context.Context, repo Repo, dir string, opts MineOptions) ([]Case, MineStats, error) {+ // The validity of a human resolution needs the syntax check (invalidReference).+ if !syntax.Available {+ return nil, MineStats{}, syntax.ErrUnavailable+ }g := gitRepo{dir: dir}maxMerges := repo.MaxMergesif maxMerges <= 0 {@@ -123,6 +131,14 @@ func Mine(ctx context.Context, repo Repo, dir string, opts MineOptions) ([]Case,continue}c.Kind = kindOf(c)+ reason, err := invalidReference(ctx, g, c)+ if err != nil {+ return nil, stats, fmt.Errorf("merge %s, %s: %w", merge, p, err)+ }+ if reason != "" {+ stats.InvalidReference+++ continue+ }stats.Kept++cases = append(cases, c)diff --git a/tools/graft-agents/resolve/bench/mine_test.go b/tools/graft-agents/resolve/bench/mine_test.gonew file mode 100644index 0000000..6fe7aff--- /dev/null+++ b/tools/graft-agents/resolve/bench/mine_test.go@@ -0,0 +1,284 @@+//go:build cgo++package bench++import (+ "context"+ "errors"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/feder-cr/git-ai/tools/graft-agents/protocol"+ "github.com/feder-cr/git-ai/tools/graft-agents/resolve"+)++// fixture is a repository with crafted merges.+type fixture struct {+ t *testing.T+ dir string+ now int64+}++func newFixture(t *testing.T) *fixture {+ t.Helper()+ if _, err := exec.LookPath("git"); err != nil {+ t.Skip("git is not installed")+ }+ f := &fixture{t: t, dir: t.TempDir(), now: 1767225600}+ f.git("init", "-q", "-b", "main")+ return f+}++// git runs git in the fixture with a fixed identity and date, given on the command line so that no+// configuration file is touched.+func (f *fixture) git(args ...string) string {+ f.t.Helper()+ f.now += 60+ cmd := exec.Command("git", append([]string{"-C", f.dir, "-c", "user.name=Bench", "-c", "[email protected]",+ "-c", "commit.gpgsign=false", "-c", "init.defaultBranch=main"}, args...)...)+ date := time.Unix(f.now, 0).UTC().Format(time.RFC3339)+ cmd.Env = append(os.Environ(), "GIT_AUTHOR_DATE="+date, "GIT_COMMITTER_DATE="+date, "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_SYSTEM=/dev/null")+ out, err := cmd.CombinedOutput()+ if err != nil {+ f.t.Fatalf("git %s: %v: %s", strings.Join(args, " "), err, out)+ }+ return strings.TrimSpace(string(out))+}++func (f *fixture) write(name, content string) {+ f.t.Helper()+ p := filepath.Join(f.dir, name)+ if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {+ f.t.Fatal(err)+ }+ if err := os.WriteFile(p, []byte(content), 0o644); err != nil {+ f.t.Fatal(err)+ }+}++func (f *fixture) commit(msg string, files map[string]string) string {+ f.t.Helper()+ for name, content := range files {+ f.write(name, content)+ }+ f.git("add", "-A")+ f.git("commit", "-q", "-m", msg)+ return f.git("rev-parse", "HEAD")+}++// conflictMerge merges branch into the current branch, which conflicts, and commits the human+// resolution.+func (f *fixture) conflictMerge(branch string, resolved map[string]string) string {+ f.t.Helper()+ cmd := exec.Command("git", "-C", f.dir, "-c", "user.name=Bench", "-c", "[email protected]", "merge", "--no-ff", "-q", branch)+ cmd.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_SYSTEM=/dev/null")+ if out, err := cmd.CombinedOutput(); err == nil {+ f.t.Fatalf("merge of %s did not conflict: %s", branch, out)+ }+ return f.commit("Merge "+branch, resolved)+}++const (+ goBase = "package a\n\nfunc A() int {\n\treturn 1\n}\n"+ goOurs = "package a\n\nfunc A() int {\n\treturn 2\n}\n"+ goTheirs = "package a\n\nfunc A() int {\n\treturn 3\n}\n"+ goHuman = "package a\n\nfunc A() int {\n\treturn 2 + 3\n}\n"+)++// buildHistory creates: a conflicting merge of a.go resolved by hand (one case), a conflicting+// merge of b.py where the human took one side (not a case), a conflict in notes.txt (no family),+// and a clean merge.+func buildHistory(f *fixture) (mergeA string) {+ f.commit("base", map[string]string{"a.go": goBase, "b.py": "x = 1\n", "notes.txt": "one\n"})++ f.git("checkout", "-q", "-b", "feature")+ f.commit("feature: A returns 3", map[string]string{"a.go": goTheirs})+ f.git("checkout", "-q", "main")+ f.commit("main: A returns 2", map[string]string{"a.go": goOurs})+ mergeA = f.conflictMerge("feature", map[string]string{"a.go": goHuman})++ f.git("checkout", "-q", "-b", "feature2")+ f.commit("feature2", map[string]string{"b.py": "x = 3\n", "notes.txt": "three\n"})+ f.git("checkout", "-q", "main")+ f.commit("main2", map[string]string{"b.py": "x = 2\n", "notes.txt": "two\n"})+ f.conflictMerge("feature2", map[string]string{"b.py": "x = 2\n", "notes.txt": "two and three\n"})++ f.git("checkout", "-q", "-b", "feature3")+ f.commit("feature3", map[string]string{"c.go": "package c\n"})+ f.git("checkout", "-q", "main")+ f.commit("main3", map[string]string{"d.go": "package d\n"})+ f.git("merge", "--no-ff", "-q", "-m", "clean merge", "feature3")+ return mergeA+}++func TestMineKeepsRealResolutions(t *testing.T) {+ f := newFixture(t)+ mergeA := buildHistory(f)+ head := f.git("rev-parse", "HEAD")++ cases, stats, err := Mine(context.Background(), Repo{Name: "fixture", Commit: head, License: "MIT"}, f.dir, MineOptions{})+ if err != nil {+ t.Fatal(err)+ }+ if len(cases) != 1 {+ t.Fatalf("got %d cases, want 1: %+v (stats %+v)", len(cases), cases, stats)+ }+ c := cases[0]+ if c.Merge != mergeA || c.Path != "a.go" || c.Family != FamilyGo || c.Kind != protocol.KindContent || c.License != "MIT" {+ t.Fatalf("unexpected case %+v", c)+ }+ if c.BaseBlob == nil || c.OursBlob == nil || c.TheirsBlob == nil || c.HumanBlob == nil {+ t.Fatalf("missing sides in %+v", c)+ }+ want := MineStats{Merges: 3, ConflictingMerges: 2, ConflictingFiles: 3, OtherFamily: 1, OneSide: 1, Kept: 1}+ if stats != want {+ t.Fatalf("stats %+v, want %+v", stats, want)+ }++ // The manifest replays identically.+ file := filepath.Join(t.TempDir(), "manifest.json")+ if err := SaveManifest(file, Manifest{Version: ManifestVersion, Cases: cases}); err != nil {+ t.Fatal(err)+ }+ m, err := LoadManifest(file)+ if err != nil {+ t.Fatal(err)+ }+ if len(m.Cases) != 1 || m.Cases[0].ID != c.ID || *m.Cases[0].HumanBlob != *c.HumanBlob {+ t.Fatalf("manifest round trip changed the case: %+v", m.Cases)+ }+}++// TestMineSkipsUnrelatedHistories mines a repository that absorbed another one with a merge of+// unrelated histories, which git merge-tree refuses: the merge is skipped and counted, and the+// conflicting merge after it is still mined.+func TestMineSkipsUnrelatedHistories(t *testing.T) {+ f := newFixture(t)+ f.commit("base", map[string]string{"a.go": "package a\n\nvar x = 1\n"})+ f.git("checkout", "-q", "--orphan", "other")+ f.git("rm", "-q", "-r", "--cached", ".")+ f.commit("other root", map[string]string{"b.py": "y = 1\n"})+ f.git("checkout", "-q", "-f", "main")+ f.git("merge", "-q", "--no-ff", "--allow-unrelated-histories", "-m", "absorb other", "other")++ f.git("checkout", "-q", "-b", "feature")+ f.commit("three", map[string]string{"a.go": "package a\n\nvar x = 3\n"})+ f.git("checkout", "-q", "main")+ f.commit("two", map[string]string{"a.go": "package a\n\nvar x = 2\n"})+ f.conflictMerge("feature", map[string]string{"a.go": "package a\n\nvar x = 2 + 3\n"})+ head := f.git("rev-parse", "HEAD")++ cases, stats, err := Mine(context.Background(), Repo{Name: "fixture", Commit: head, License: "MIT"}, f.dir, MineOptions{})+ if err != nil {+ t.Fatal(err)+ }+ want := MineStats{Merges: 2, ConflictingMerges: 1, SkippedMergeBases: 1, ConflictingFiles: 1, Kept: 1}+ if stats != want || len(cases) != 1 {+ t.Fatalf("stats %+v (%d cases), want %+v and 1 case", stats, len(cases), want)+ }+}++// fixedStrategy answers every file with content, or fails with err.+type fixedStrategy struct {+ content []byte+ err error+}++func (s fixedStrategy) Resolve(_ context.Context, _ resolve.File, _ protocol.Request) (resolve.Resolution, bool, error) {+ if s.err != nil {+ return resolve.Resolution{}, false, s.err+ }+ return resolve.Resolution{Action: protocol.ActionWrite, Mode: protocol.ModeFile, Content: s.content}, true, nil+}++func TestRunnerOutcomes(t *testing.T) {+ f := newFixture(t)+ buildHistory(f)+ head := f.git("rev-parse", "HEAD")+ cases, _, err := Mine(context.Background(), Repo{Name: "fixture", Commit: head, License: "MIT"}, f.dir, MineOptions{})+ if err != nil {+ t.Fatal(err)+ }++ for _, tc := range []struct {+ name string+ strategy resolve.Strategy+ want string+ exact bool+ }{+ {"correct", fixedStrategy{content: []byte(goHuman)}, OutcomeCorrect, true},+ {"correct after normalizing", fixedStrategy{content: []byte(strings.ReplaceAll(goHuman, "\n", " \r\n") + "\n\n")}, OutcomeCorrect, false},+ {"wrong", fixedStrategy{content: []byte(goOurs)}, OutcomeWrong, false},+ {"rejected by the marker rule", fixedStrategy{content: []byte("<<<<<<< ours\nx\n=======\ny\n>>>>>>> theirs\n")}, OutcomeRejected, false},+ {"model error", fixedStrategy{err: errors.New("provider: 500")}, OutcomeModelError, false},+ {"budget", fixedStrategy{err: resolve.ErrBudgetExhausted}, OutcomeNotRun, false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ res, err := resolve.NewResolver([]resolve.Binding{{Name: "fake", Strategy: tc.strategy}}, nil, time.Minute)+ if err != nil {+ t.Fatal(err)+ }+ results, err := Runner{Resolver: res, Clone: func(string) string { return f.dir }}.Run(context.Background(), cases)+ if err != nil {+ t.Fatal(err)+ }+ if len(results) != 1 || results[0].Outcome != tc.want || results[0].Exact != tc.exact {+ t.Fatalf("results %+v, want outcome %s exact %v", results, tc.want, tc.exact)+ }+ })+ }+}++// TestMineLeavesOutInvalidReferences mines two conflicting merges whose human resolutions are not+// valid references: one committed with the conflict markers, one that breaks the Go syntax although+// both sides parse. Neither is kept, and both are counted.+func TestMineLeavesOutInvalidReferences(t *testing.T) {+ f := newFixture(t)+ f.commit("base", map[string]string{"a.go": goBase, "b.go": goBase})+ f.git("checkout", "-q", "-b", "feature")+ f.commit("feature", map[string]string{"a.go": goTheirs, "b.go": goTheirs})+ f.git("checkout", "-q", "main")+ f.commit("main", map[string]string{"a.go": goOurs, "b.go": goOurs})+ f.conflictMerge("feature", map[string]string{+ "a.go": "package a\n\n<<<<<<< HEAD\nfunc A() int { return 2 }\n=======\nfunc A() int { return 3 }\n>>>>>>> feature\n",+ "b.go": "package a\n\nfunc A() int { return 2 +\n",+ })+ head := f.git("rev-parse", "HEAD")++ cases, stats, err := Mine(context.Background(), Repo{Name: "fixture", Commit: head, License: "MIT"}, f.dir, MineOptions{})+ if err != nil {+ t.Fatal(err)+ }+ if len(cases) != 0 || stats.InvalidReference != 2 || stats.Kept != 0 {+ t.Fatalf("cases %d, stats %+v: want both left out as invalid references", len(cases), stats)+ }++ // Filter applies the same rule to a manifest mined before it.+ g := gitRepo{dir: f.dir}+ var all []Case+ for _, p := range []string{"a.go", "b.go"} {+ c := Case{ID: p, Repo: "fixture", Family: FamilyGo, Path: p}+ for _, side := range []struct {+ rev string+ dst **entry+ }{{"HEAD^1", &c.OursBlob}, {"HEAD^2", &c.TheirsBlob}, {"HEAD", &c.HumanBlob}} {+ e, err := g.entryAt(context.Background(), side.rev, p)+ if err != nil {+ t.Fatal(err)+ }+ *side.dst = e+ }+ all = append(all, c)+ }+ kept, fstats, err := Filter(context.Background(), all, func(string) string { return f.dir })+ if err != nil {+ t.Fatal(err)+ }+ if len(kept) != 0 || fstats["fixture: "+InvalidMarkers] != 1 || fstats["fixture: "+InvalidSyntax] != 1 {+ t.Fatalf("kept %d, stats %v", len(kept), fstats)+ }+}diff --git a/tools/graft-agents/resolve/bench/nocgo_test.go b/tools/graft-agents/resolve/bench/nocgo_test.gonew file mode 100644index 0000000..5663abd--- /dev/null+++ b/tools/graft-agents/resolve/bench/nocgo_test.go@@ -0,0 +1,22 @@+//go:build !cgo++package bench++import (+ "context"+ "errors"+ "testing"++ "github.com/feder-cr/git-ai/tools/graft-agents/resolve/syntax"+)++// TestMineRefusesWithoutCgo: mining checks the syntax of the human resolutions, so a build without+// the grammars refuses to mine instead of keeping references it cannot validate.+func TestMineRefusesWithoutCgo(t *testing.T) {+ if _, _, err := Mine(context.Background(), Repo{Name: "x"}, t.TempDir(), MineOptions{}); !errors.Is(err, syntax.ErrUnavailable) {+ t.Fatalf("err = %v, want syntax.ErrUnavailable", err)+ }+ if _, _, err := Filter(context.Background(), nil, nil); !errors.Is(err, syntax.ErrUnavailable) {+ t.Fatalf("Filter: err = %v, want syntax.ErrUnavailable", err)+ }+}diff --git a/tools/graft-agents/resolve/bench/reference.go b/tools/graft-agents/resolve/bench/reference.gonew file mode 100644index 0000000..dd25df5--- /dev/null+++ b/tools/graft-agents/resolve/bench/reference.go@@ -0,0 +1,83 @@+package bench++import (+ "context"+ "errors"+ "fmt"++ "github.com/feder-cr/git-ai/tools/graft-agents/resolve"+ "github.com/feder-cr/git-ai/tools/graft-agents/resolve/syntax"+)++// Reasons a human resolution is not a valid reference. A merge commit is not always a correct+// resolution: some were committed with the conflict markers still in the file, or broke the+// syntax and were fixed in a later commit. Judged against such a reference, a correct answer+// would count as wrong, so such cases are left out of the corpus (and counted).+const (+ InvalidMarkers = "the human resolution contains conflict markers"+ InvalidSyntax = "the human resolution does not parse although both sides do"+)++// invalidReference returns why the human resolution of c is not a valid reference, or "" when it+// is. It reads the blobs of the human resolution and both sides.+func invalidReference(ctx context.Context, g gitRepo, c Case) (string, error) {+ if c.HumanBlob == nil {+ return "", nil // a deletion+ }+ human, err := g.blob(ctx, c.HumanBlob.OID)+ if err != nil {+ return "", err+ }+ if hasMarkers(human) {+ return InvalidMarkers, nil+ }+ var sides [][]byte+ for _, e := range []*entry{c.OursBlob, c.TheirsBlob} {+ if e == nil {+ continue+ }+ b, err := g.blob(ctx, e.OID)+ if err != nil {+ return "", err+ }+ sides = append(sides, b)+ }+ checked, err := syntax.CheckMerge(ctx, c.Path, human, sides...)+ var se *syntax.Error+ switch {+ case errors.As(err, &se) && checked:+ return InvalidSyntax, nil+ case err != nil:+ return "", fmt.Errorf("checking the reference of %s: %w", c.Path, err)+ }+ return "", nil+}++// FilterStats counts what Filter left out, by reason.+type FilterStats map[string]int++// Filter returns the cases of a manifest whose human resolution is a valid reference, with the+// cases left out counted by reason. Mine applies the same rule to the cases it keeps; Filter+// applies it to a manifest mined before the rule.+func Filter(ctx context.Context, cases []Case, clone func(repo string) string) ([]Case, FilterStats, error) {+ if !syntax.Available {+ return nil, nil, syntax.ErrUnavailable+ }+ stats := FilterStats{}+ var kept []Case+ for _, c := range cases {+ reason, err := invalidReference(ctx, gitRepo{dir: clone(c.Repo)}, c)+ if err != nil {+ return nil, nil, fmt.Errorf("case %s: %w", c.ID, err)+ }+ if reason != "" {+ stats[c.Repo+": "+reason]+++ continue+ }+ kept = append(kept, c)+ }+ return kept, stats, nil+}++// hasMarkers is the marker rule of the resolver answers (resolve.HasConflictMarkers).+func hasMarkers(b []byte) bool { return resolve.HasConflictMarkers(b) }diff --git a/tools/graft-agents/resolve/bench/report.go b/tools/graft-agents/resolve/bench/report.goindex f56925e..6840ab3 100644--- a/tools/graft-agents/resolve/bench/report.go+++ b/tools/graft-agents/resolve/bench/report.go@@ -19,8 +19,11 @@ type Counts struct {Model int `json:"model_error"`NotRun int `json:"not_run_cap"`Abstained int `json:"abstained"`- // HumanSyntax counts the cases whose human resolution fails the syntax check.- HumanSyntax int `json:"human_fails_syntax"`+ // BlankLinesOnly counts the wrong results that differ from the human resolution in blank+ // lines only (part of Wrong); SyntaxUnchecked the accepted results the syntax check gave no+ // verdict on, because a side does not parse.+ BlankLinesOnly int `json:"wrong_blank_lines_only"`+ SyntaxUnchecked int `json:"syntax_unchecked"`}// Accepted is the number of results that would land: correct and wrong.@@ -37,8 +40,11 @@ func (c Counts) ErrorRate() float64 {func (c *Counts) add(r Result) {c.Cases++- if r.HumanSyntaxError != "" {- c.HumanSyntax+++ if r.BlankLinesOnly {+ c.BlankLinesOnly+++ }+ if r.SyntaxUnchecked {+ c.SyntaxUnchecked++}switch r.Outcome {case OutcomeCorrect:@@ -168,12 +174,17 @@ func (rep Report) WriteMarkdown(w io.Writer) error {}fmt.Fprintf(&b, "\nRows marked low n have fewer than %d cases; their rates are not significant. The llm strategy declines a modify-delete or mode conflict (a side is absent), which goes to the agent as abstained: the content row is what the model attempted.\n", LowN)b.WriteString("\nThe error rate is wrong / (correct + wrong): the share of the results that would land and differ from the human resolution. Correct means equal after normalizing line endings and trailing whitespace; exact means byte-identical.\n")- syntaxParts := make([]string, 0, len(families))- for _, f := range families {- syntaxParts = append(syntaxParts, fmt.Sprintf("%s %d", f, rep.Families[f].HumanSyntax))+ perFamily := func(value func(Counts) int) string {+ parts := make([]string, 0, len(families))+ for _, f := range families {+ parts = append(parts, fmt.Sprintf("%s %d", f, value(rep.Families[f])))+ }+ return strings.Join(parts, ", ")}- fmt.Fprintf(&b, "\nHuman resolutions that fail the syntax check themselves, where the check would reject the right answer: %d (%s).\n",- rep.Total.HumanSyntax, strings.Join(syntaxParts, ", "))+ fmt.Fprintf(&b, "\nWrong results that differ from the human resolution in blank lines only (counted as wrong): %d (%s).\n",+ rep.Total.BlankLinesOnly, perFamily(func(c Counts) int { return c.BlankLinesOnly }))+ fmt.Fprintf(&b, "\nAccepted results the syntax check gave no verdict on, because a side does not parse with the grammar (a dialect such as Flow, or code the grammar does not cover): %d (%s).\n",+ rep.Total.SyntaxUnchecked, perFamily(func(c Counts) int { return c.SyntaxUnchecked }))if len(rep.NotSent) > 0 {reasons := make([]string, 0, len(rep.NotSent))for r := range rep.NotSent {diff --git a/tools/graft-agents/resolve/bench/run.go b/tools/graft-agents/resolve/bench/run.goindex 7cf2e44..131c451 100644--- a/tools/graft-agents/resolve/bench/run.go+++ b/tools/graft-agents/resolve/bench/run.go@@ -47,16 +47,18 @@ type Result struct {Path string `json:"path"`Outcome string `json:"outcome"`Exact bool `json:"exact,omitempty"`- Strategy string `json:"strategy,omitempty"`+ // BlankLinesOnly marks a wrong result that differs from the human resolution in blank lines+ // only; it is still wrong, and the report counts it apart.+ BlankLinesOnly bool `json:"blank_lines_only,omitempty"`+ // SyntaxUnchecked marks an accepted resolution the syntax check gave no verdict on: a side+ // does not parse, so the grammar cannot judge the file (syntax.CheckMerge).+ SyntaxUnchecked bool `json:"syntax_unchecked,omitempty"`+ Strategy string `json:"strategy,omitempty"`// Answer is the action of an accepted resolution ("write" or "delete"); with// Runner.AnswersDir its content is stored for audit and Rejudge.Answer string `json:"answer,omitempty"`Reason string `json:"reason,omitempty"`Seconds float64 `json:"seconds"`- // HumanSyntaxError is set when the human resolution of a case that was sent fails the- // syntax check itself: the check would reject the right answer there (a grammar gap, or a- // human merge that did not parse).- HumanSyntaxError string `json:"human_syntax_error,omitempty"`}// Sample returns n cases of cases, stratified by family: each family's cases are shuffled with the@@ -179,15 +181,6 @@ func (r Runner) runCase(ctx context.Context, c Case, maxBytes int64) (Result, erreturn res, nil}- if human != nil {- if err := syntax.Check(ctx, c.Path, human); err != nil {- if ctx.Err() != nil {- return res, ctx.Err()- }- res.HumanSyntaxError = err.Error()- }- }-oursMessage, err := g.message(ctx, c.Ours)if err != nil {return res, err@@ -232,20 +225,42 @@ func (r Runner) runCase(ctx context.Context, c Case, maxBytes int64) (Result, erreturn res, err}}+ if f.Action == protocol.ActionWrite {+ if _, ok := syntax.LanguageOf(c.Path); ok {+ checked, err := syntax.CheckMerge(ctx, c.Path, f.Content, sideBytes(sides["ours"]), sideBytes(sides["theirs"]))+ if err != nil && ctx.Err() != nil {+ return res, ctx.Err()+ }+ res.SyntaxUnchecked = !checked+ }+ }judgeResult(&res, f.Content, f.Action == protocol.ActionDelete, human, c.HumanBlob == nil)return res, nil}+// sideBytes returns the content of a present side, nil for an absent one.+func sideBytes(s *protocol.Side) []byte {+ if s == nil {+ return nil+ }+ if s.Content == nil {+ return []byte{}+ }+ return s.Content+}+func answerPath(dir, id string) string { return filepath.Join(dir, id+".answer") }// judgeResult sets the outcome of an accepted resolution from the judge.func judgeResult(res *Result, content []byte, deleted bool, human []byte, humanDeleted bool) {correct, exact := judge(content, human, deleted, humanDeleted)res.Exact = exact+ res.BlankLinesOnly = falseif correct {res.Outcome = OutcomeCorrect} else {res.Outcome = OutcomeWrong+ res.BlankLinesOnly = !deleted && !humanDeleted && blankLinesOnly(content, human)}}diff --git a/tools/graft-agents/resolve/builtin.go b/tools/graft-agents/resolve/builtin.goindex 349126a..30b150f 100644--- a/tools/graft-agents/resolve/builtin.go+++ b/tools/graft-agents/resolve/builtin.go@@ -87,6 +87,18 @@ func regularFile(s *protocol.Side) bool {return s != nil && (s.Mode == protocol.ModeFile || s.Mode == protocol.ModeExecutable)}+// sideContent returns the content of a regular side, and nil for an absent side or one that is+// not a regular file (the syntax check skips those).+func sideContent(s *protocol.Side) []byte {+ if !regularFile(s) {+ return nil+ }+ if s.Content == nil {+ return []byte{}+ }+ return s.Content+}+// regularText reports whether a side is a regular file whose content is text// (no NUL byte, the same heuristic as git).func regularText(s *protocol.Side) bool {diff --git a/tools/graft-agents/resolve/llm_core.go b/tools/graft-agents/resolve/llm_core.goindex 2066526..6c1e561 100644--- a/tools/graft-agents/resolve/llm_core.go+++ b/tools/graft-agents/resolve/llm_core.go@@ -372,10 +372,10 @@ func llmCheckAnswer(a llmAnswer, opt LLMOptions) error {}// llmHasConflictMarkers reports whether a line starts with a Git conflict-// marker. It shares hasConflictMarkers, which follows the server-side answer+// marker. It shares HasConflictMarkers, which follows the server-side answer// validation, so an answer the server would accept is never rejected here.func llmHasConflictMarkers(s string) bool {- return hasConflictMarkers([]byte(s))+ return HasConflictMarkers([]byte(s))}func llmIsBinary(bs ...[]byte) bool {diff --git a/tools/graft-agents/resolve/llm_syntax_test.go b/tools/graft-agents/resolve/llm_syntax_test.goindex 41bb2e4..4458a7a 100644--- a/tools/graft-agents/resolve/llm_syntax_test.go+++ b/tools/graft-agents/resolve/llm_syntax_test.go@@ -97,3 +97,19 @@ func TestOtherStrategiesAreNotSyntaxChecked(t *testing.T) {t.Fatalf("union answer rejected: %v", err)}}++// TestLLMAnswerForFileTheGrammarCannotReadIsNotSyntaxChecked: when a side does not parse (Flow in+// a .js file), the grammar cannot judge the file, so the answer is not rejected for its syntax.+func TestLLMAnswerForFileTheGrammarCannotReadIsNotSyntaxChecked(t *testing.T) {+ flow := func(v string) *protocol.Side {+ return wp19Side(protocol.ModeFile, "// @flow\nimport type {N} from './n';\nconst x: ?string = "+v+";\n")+ }+ wp19SetAnswer(func(context.Context, llm.Request) (*llm.Response, error) {+ return wp19Answer("// @flow\nimport type {N} from './n';\nconst x: ?string = '2';\n"), nil+ })+ r := wp19Build(t, wp3Config)+ f := protocol.FileConflict{Path: "a.js", Kind: protocol.KindContent, Base: flow("'0'"), Ours: flow("'1'"), Theirs: flow("'3'")}+ if _, err := r.Resolve(context.Background(), wp19Request(f)); err != nil {+ t.Fatalf("answer for a Flow file rejected: %v", err)+ }+}diff --git a/tools/graft-agents/resolve/resolve.go b/tools/graft-agents/resolve/resolve.goindex 558a0b6..127ff8e 100644--- a/tools/graft-agents/resolve/resolve.go+++ b/tools/graft-agents/resolve/resolve.go@@ -66,7 +66,8 @@ type Strategy interface {}// syntaxChecked is implemented by the strategies whose answers always get the syntax check-// (package syntax): the llm strategy. The check runs before the configured checks.+// (syntax.CheckMerge): the llm strategy. The check runs before the configured checks, and+// rejects an answer that does not parse when both sides it merges parse.type syntaxChecked interface {syntaxChecked()}@@ -387,7 +388,7 @@ func (r *Resolver) resolveFile(ctx context.Context, req protocol.Request, f Filecontinue}if _, ok := b.Strategy.(syntaxChecked); ok && res.Action == protocol.ActionWrite && res.Mode != protocol.ModeSymlink {- if err := syntax.Check(ctx, f.Path, res.Content); err != nil {+ if _, err := syntax.CheckMerge(ctx, f.Path, res.Content, sideContent(f.Ours), sideContent(f.Theirs)); err != nil {if ctxErr := ctx.Err(); ctxErr != nil {return protocol.ResolvedFile{}, "", nil, ctxErr}@@ -510,18 +511,19 @@ func checkResolution(res Resolution, maxBytes int64) error {if int64(len(res.Content)) > maxBytes {return fmt.Errorf("content of %d bytes exceeds the %d byte limit", len(res.Content), maxBytes)}- if !isBinary(res.Content) && hasConflictMarkers(res.Content) {+ if !isBinary(res.Content) && HasConflictMarkers(res.Content) {return errors.New("content contains conflict markers")}return nil}-// hasConflictMarkers mirrors the server's acceptance rule+// HasConflictMarkers reports whether content has a conflict marker line. It mirrors the+// server's acceptance rule// (internal/graft/resolver/validate.go): a line is a conflict marker if it// starts with "<<<<<<< " or ">>>>>>> ", or if it is "=======" followed by// whitespace only. A trailing carriage return is ignored. A longer run of '='// such as a Markdown setext or RST title underline is not a marker.-func hasConflictMarkers(content []byte) bool {+func HasConflictMarkers(content []byte) bool {for _, line := range bytes.Split(content, []byte("\n")) {line = bytes.TrimSuffix(line, []byte{'\r'})switch {diff --git a/tools/graft-agents/resolve/resolve_test.go b/tools/graft-agents/resolve/resolve_test.goindex 01d1c96..b56c70c 100644--- a/tools/graft-agents/resolve/resolve_test.go+++ b/tools/graft-agents/resolve/resolve_test.go@@ -501,7 +501,7 @@ func TestHasConflictMarkers(t *testing.T) {"<<<<<<< HEAD\n", "x\n=======\ny", ">>>>>>> branch\n","=======\r\n", "x\n======= \t\ny\n", "<<<<<<< HEAD\r\n", "=======",} {- if !hasConflictMarkers([]byte(s)) {+ if !HasConflictMarkers([]byte(s)) {t.Errorf("markers not found in %q", s)}}@@ -509,7 +509,7 @@ func TestHasConflictMarkers(t *testing.T) {"<<<<<<<HEAD\n", "a=======b\n", " ======= indented\n", "x >>>>>>> y\n", "","=======zz\n", "Changelog\n=========\n", "Title\n==========\r\nbody\n", "======== x\n",} {- if hasConflictMarkers([]byte(s)) {+ if HasConflictMarkers([]byte(s)) {t.Errorf("false positive in %q", s)}}diff --git a/tools/graft-agents/resolve/syntax/syntax.go b/tools/graft-agents/resolve/syntax/syntax.goindex 36d84b9..52a70f9 100644--- a/tools/graft-agents/resolve/syntax/syntax.go+++ b/tools/graft-agents/resolve/syntax/syntax.go@@ -66,6 +66,30 @@ func (e *Error) Error() string {return fmt.Sprintf("syntax check: %s does not parse as %s: %s at line %d, column %d", e.Path, e.Language, what, e.Line, e.Column)}+// CheckMerge checks that a merge result did not break the syntax: result must parse when every+// side it merges parses. A side that does not parse means the grammar cannot judge this file+// (a dialect it lacks, such as Flow in a .js file; a newer language version; a test of invalid+// code): then the result is not checked and checked is false, and only the marker rule applies.+// A path with no grammar is not checked either. A nil side (absent) is skipped.+func CheckMerge(ctx context.Context, p string, result []byte, sides ...[]byte) (checked bool, err error) {+ if _, ok := LanguageOf(p); !ok {+ return false, nil+ }+ for _, side := range sides {+ if side == nil {+ continue+ }+ if err := Check(ctx, p, side); err != nil {+ var se *Error+ if errors.As(err, &se) {+ return false, nil+ }+ return false, err+ }+ }+ return true, Check(ctx, p, result)+}+// Check parses content as the language of p and returns an *Error for the first ERROR or MISSING// node of the tree. It returns nil when content parses, and when p has no grammar. It fails with// ctx's error when ctx ends during the parse.diff --git a/tools/graft-agents/resolve/syntax/syntax_test.go b/tools/graft-agents/resolve/syntax/syntax_test.goindex ca74e34..e72d95f 100644--- a/tools/graft-agents/resolve/syntax/syntax_test.go+++ b/tools/graft-agents/resolve/syntax/syntax_test.go@@ -118,3 +118,35 @@ func TestCheckHonoursContext(t *testing.T) {t.Fatalf("err = %v, want context.Canceled", err)}}++func TestCheckMergeJudgesOnlyWhatTheGrammarUnderstands(t *testing.T) {+ ctx := context.Background()+ good := []byte("package a\n\nvar x = 1\n")+ bad := []byte("package a\n\nvar x = \n")++ // Both sides parse: a result that does not parse is the merge's fault.+ checked, err := CheckMerge(ctx, "a.go", bad, good, good)+ var se *Error+ if !checked || !errors.As(err, &se) {+ t.Fatalf("checked %v, err %v: want a syntax error", checked, err)+ }+ if checked, err := CheckMerge(ctx, "a.go", good, good, good); !checked || err != nil {+ t.Fatalf("checked %v, err %v: want a pass", checked, err)+ }+ // A side the grammar rejects: no verdict, whatever the result is.+ if checked, err := CheckMerge(ctx, "a.go", bad, good, bad); checked || err != nil {+ t.Fatalf("checked %v, err %v: want no verdict", checked, err)+ }+ // Flow is not JavaScript: a Flow file's sides do not parse, so it gets no verdict.+ flow := []byte("// @flow\nimport type {Node} from './node';\nfunction f(x: ?string): number { return 1; }\n")+ if checked, err := CheckMerge(ctx, "a.js", []byte("(("), flow, flow); checked || err != nil {+ t.Fatalf("Flow: checked %v, err %v: want no verdict", checked, err)+ }+ // An absent side is skipped; a path without a grammar is not checked.+ if checked, err := CheckMerge(ctx, "a.go", bad, nil, good); !checked || err == nil {+ t.Fatalf("absent side: checked %v, err %v", checked, err)+ }+ if checked, err := CheckMerge(ctx, "a.md", bad, good, good); checked || err != nil {+ t.Fatalf("no grammar: checked %v, err %v", checked, err)+ }+}