Git designed for AI agents.
gitai land: never-send rules, the conflict package, and the agent's re-land (c1 WP5, WP6)
Federico Eliaf707b5bb1392
diff --git a/doc/graft/CONFIGURATION.md b/doc/graft/CONFIGURATION.mdindex d5d155d..4f7fddd 100644--- a/doc/graft/CONFIGURATION.md+++ b/doc/graft/CONFIGURATION.md@@ -191,10 +191,20 @@ here. The protocol, the validation rules and `graft-resolve` are described in| `paths_allow` | array of strings | empty (every path) | Globs of paths that may be sent to the resolver, with the syntax of policy refs. || `paths_deny` | array of strings | empty | Globs of paths that are never sent. Deny wins over allow. || `actors` | array of strings | empty (every caller that may land) | Globs of the identities that may request resolution: agent names, or `shared` for the shared token. Without `[[graft.agent]]` no caller has an identity, so a non-empty list admits nobody (the server warns at startup). |+| `lockfiles` | array of strings | empty | Base names of lockfiles, besides the built-in `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, `poetry.lock`, `Cargo.lock` and `go.sum`. A conflicting lockfile is never sent to the resolver: it goes to the agent. |+| `generated_markers` | array of strings | empty | Go regular expressions, besides the built-in `Code generated .* DO NOT EDIT\.`, `@generated`, `DO NOT EDIT` and `(?i)auto-generated`, searched in the first 10 lines of every side. A match marks the file generated, and it is never sent. A path that the tip's `.gitattributes` marks `linguist-generated` is generated as well. |+| `minified.globs` | array of strings | empty | Base-name globs of minified files, besides the built-in `*.min.js`, `*.min.mjs`, `*.min.css` and `*.bundle.js`. Such files are never sent. |+| `minified.average_line_bytes` | int | `300` | A side larger than 2 KiB whose average line is longer is minified. |+| `minified.longest_line_bytes` | int | `5000` | A side larger than 2 KiB with a longer line is minified. |++A file that is never sent goes to the agent with its reason in the conflict+package: large (a side over `max_file_bytes`), binary (a NUL byte), lockfile,+generated or minified, checked in that order (see [RESOLVE.md](RESOLVE.md)).Startup fails when both or neither of `command` and `url` are set, the URL has-another scheme, `timeout` is not a duration, a bound is negative, or a glob is-empty or invalid.+another scheme, `timeout` is not a duration, a bound or a threshold is+negative, a glob is empty or invalid, a lockfile is not a base name, or a+generated marker is not a valid regular expression.### `[graft.storage]`diff --git a/doc/graft/PLAN10.md b/doc/graft/PLAN10.mdindex 27b0478..07c41b1 100644--- a/doc/graft/PLAN10.md+++ b/doc/graft/PLAN10.md@@ -527,3 +527,12 @@ way.resolution whose encoded request would exceed it, with a clear error, instead of atransport failure.* **Order.** WP1 to WP4 first; WP96 of PLAN9 after them.+* **Per-file outcomes of a refusal** (PM, WP6). The resolver protocol gains an optional+ `files` list in the error response (HTTP 422 body, command-mode stdout): the outcome of+ every requested file, `resolved`, `rejected` or `failed`. The server trusts it only+ when it has exactly one entry per requested path with a known outcome, and otherwise+ marks every sent file failed with the overall reason. Backward compatible both ways.+* **Later improvement, not now** (PM). Since nothing lands partially, the files a+ resolver resolved in a failed request are wasted work for the agent. The package could+ offer the resolver's resolved content to the agent (for example as blobs written to the+ repository, referenced by OID), so that the agent re-lands with it where it agrees.diff --git a/doc/graft/RESOLVE.md b/doc/graft/RESOLVE.mdindex 1335192..7094526 100644--- a/doc/graft/RESOLVE.md+++ b/doc/graft/RESOLVE.md@@ -66,13 +66,17 @@ A client asks for resolution per call:## Flow1. `UserLand` attempts the land as usual (rebase or merge onto the tip).-2. On a merge conflict, when every condition above holds, the server computes- for each conflicting path the base, ours and theirs sides (merge base of- the tip and the landed commit; blobs and modes read through the object- reader).-3. It sends the request to the resolver (protocol below) and validates the- answer (see [Validation](#validation)).-4. It builds the merged tree from the merge-tree result, writes the resolved+2. On a merge conflict the server lists the conflicting files with their base,+ ours and theirs sides (merge base of the tip and the landed commit; blobs+ and modes read through the object reader). The whole request is refused+ when resolution is not enabled, the actor may not resolve, there are more+ than `max_files` files, or the history is criss-cross.+3. It decides for each file whether it may be sent (see+ [What is never sent](#what-is-never-sent)), sends the others to the+ resolver in one request (protocol below), and validates the answer (see+ [Validation](#validation)).+4. Only when every file is resolved, it builds the merged tree from the+ merge-tree result, writes the resolvedfiles as new blobs or deletes them, and creates a merge commit with parents`[tip, commit]`. The message is `merge_message` or`Merge <short commit> into <branch>`. Trailers:@@ -88,9 +92,12 @@ A client asks for resolution per call:in the meantime, the server retries from the top and resolves againagainst the new tip.-Any failure (no resolver, denied path, invalid answer, timeout, unresolvable-conflict) returns the normal `merge_conflict` error and the reason is logged.-The branch is never left in a partial state.+Otherwise (resolution disabled or refused, a file that is never sent, an+invalid answer, a timeout, an unresolvable file) the land fails with the+normal `merge_conflict` error, the reason is logged, and the error carries the+conflict package as a second detail (see+[The conflict package and the re-land](#the-conflict-package-and-the-re-land)).+Nothing lands partially: the branch is never left in a partial state.Every resolution is logged at info level as `graft: conflicts of landresolved`, with the branch, the tip, the landed commit, the merge commit, the@@ -145,10 +152,43 @@ Response (resolver to server):Failure signals:-- The command exits non-zero. Its stderr is the reason.-- HTTP `422` with `{"error": "..."}`. The conflict is unresolvable.+- The command exits non-zero. Its stderr is the reason, unless its stdout is+ an error response (below).+- HTTP `422` with an error response. The conflict is unresolvable.- Any other HTTP status, or invalid JSON, is a failure.+The error response may give the outcome of every file of the request:++```json+{"error": "unresolved conflict: ...",+ "files": [{"path": "a/b.go", "outcome": "rejected", "reason": "syntax check: ..."},+ {"path": "c.go", "outcome": "resolved"}]}+```++`outcome` is `resolved` (resolved, but the request was not resolved as a+whole), `rejected` (a result failed a rule or a check) or `failed`. The server+uses the list only when it has exactly one entry per requested path, each with+a known outcome; otherwise every sent file fails with the overall reason.+`graft-resolve` writes this response on a refusal, on stdout in command mode+and as the 422 body in HTTP mode. A resolver without `files` keeps working.++A second operation, `check`, asks the resolver to check an agent's resolution+with the checks of its own answers (see+[The conflict package and the re-land](#the-conflict-package-and-the-re-land)).+The request is a resolve request with `"operation": "check"` and the agent's+files in `resolution` (the shape of the response's `files`). The answer is:++```json+{"version": 1, "operation": "check", "resolver": "graft-resolve",+ "files": [{"path": "a/b.go", "ok": false, "reason": "syntax check: ...", "syntax": "checked"}]}+```++with one verdict per file of `resolution`, in its order. `syntax` is+`checked`, `unchecked` (a side does not parse with the grammar) or `none` (no+grammar, or a deletion). An absent `operation` means `resolve`, so existing+resolvers keep working; one that answers a `check` with anything but a check+response makes the server refuse the resolution.+## ValidationThe server accepts an answer only if all of these hold:@@ -170,6 +210,89 @@ The server accepts an answer only if all of these hold:A rejected answer is a failure, not a partial merge.+## What is never sent++The server decides for each conflicting file, before the request, whether it+may be sent. A file that may not goes to the agent, and the conflict package+gives the reason. The other files are still sent. In order:++1. The path: a line break or NUL byte (a commit trailer cannot carry it), not+ valid UTF-8 (the protocol cannot carry it), or denied by `paths_allow` /+ `paths_deny`, for the path and for every path a side comes from (a rename+ brings a side from another path).+2. The sides: no side under the name (a file/directory conflict), no base and+ a missing side, or a side that is not a file (a submodule).+3. large: a side over `max_file_bytes`, decided from its size before it is+ read.+4. binary: a NUL byte in a side.+5. lockfile: the base name is `package-lock.json`, `yarn.lock`,+ `pnpm-lock.yaml`, `poetry.lock`, `Cargo.lock`, `go.sum`, or one of+ `lockfiles`.+6. generated: `linguist-generated` is set for the path by the tip's+ attributes (one `git check-attr --source <tip>` for all paths), or a side's+ first 10 lines match `Code generated .* DO NOT EDIT\.`, `@generated`,+ `DO NOT EDIT`, `(?i)auto-generated` or one of `generated_markers`.+7. minified: the base name matches `*.min.js`, `*.min.mjs`, `*.min.css`,+ `*.bundle.js` or one of `minified.globs`, or a side larger than 2 KiB has an+ average line longer than `minified.average_line_bytes` (300) or a line+ longer than `minified.longest_line_bytes` (5000).++Secrets are not a reason: a file's content, secrets included, goes to the+resolver when the rules above let it. Use `paths_deny` for paths that must+never leave the server. `graft-resolve bench` applies the same rules (3 to 7);+both are tested against `internal/graft/resolver/testdata/never-send.json`.++## The conflict package and the re-land++When a land with `resolve_conflicts` (or with a `resolution`) fails on its+conflicts, the `merge_conflict` error carries a second detail after+`UserLandError`: a `LandConflict`. Clients that know only `UserLandError` see+the error unchanged. The package holds:++- `tip`, `commit` and `merge_base` (empty when there is none);+- both commit messages, cut to 4 KiB each, with `messages_truncated`;+- `reason`, when the server did not attempt the request at all;+- per file (at most `max_files`): the path, the kind, each side's blob OID and+ mode, the conflicting hunks, the outcome and its reason (cut to 512 bytes).++Each hunk gives line ranges of each side, 1-based and half-open (`[start,+end)`), each counting the lines of the side it names. An empty range is an+insertion point before line `start`. A file whose diff is too large to+compute (more than about 2800 changed lines on a side) has no hunks. The+outcomes are:++| outcome | meaning |+|---|---|+| `NOT_SENT` | never sent (see above); the reason says why |+| `REJECTED` | the result failed a rule or a check, e.g. a syntax error at line:column |+| `FAILED` | the resolver failed on it: a model error, `AI budget exhausted`, no strategy applied |+| `RESOLVED` | resolved, but the land failed because another file was not |+| `NOT_ATTEMPTED` | the request was not attempted; see `reason` |++The agent reads the sides by OID with `GetBlobs`, resolves every file, and+lands again with `UserLandRequest.resolution` (field 11): the `tip` and+`commit` of the package and, for every conflicting path, `write` (mode and+content) or `delete`. The server accepts it only when:++- `resolution.commit` equals `commit_id` (otherwise `InvalidArgument`);+- `resolution.tip` is the branch's current tip (otherwise the land fails+ with a fresh package for the new tip);+- it resolves exactly the conflicting paths, each once;+- every file passes the acceptance rules of an answer (modes, size, conflict+ markers);+- when a resolver is configured, the files that may be sent to it pass its+ `check`: the syntax check and the configured checks, as an `llm` answer.+ A check that cannot run fails the land, with the reason in the package.+ A file with a `syntax: unchecked` verdict lands, and is counted in+ `graft_land_resolution_syntax_unchecked_total` and the server log.++The merge commit has parents `[tip, commit]` and the trailers+`Graft-Resolved-By: agent/<actor>` (`agent` without an identity) and, when the+resolver checked it, `Graft-Checked-By: <resolver>`. Without a resolver there+is no `Graft-Checked-By`: the resolution got only the conflict-marker rule and+the server's structural validation. The resolution travels in the request, so+the whole request is bounded by the 4 MiB gRPC message limit.+## Strategies of graft-resolve`graft-resolve` tries an ordered list of strategies per file. The firstdiff --git a/internal/gitaly/config/config_graft.go b/internal/gitaly/config/config_graft.goindex 5dc93e3..468558f 100644--- a/internal/gitaly/config/config_graft.go+++ b/internal/gitaly/config/config_graft.go@@ -3,6 +3,7 @@ package configimport ("fmt""path"+ "regexp""strings""time")@@ -300,6 +301,57 @@ type GraftResolver struct {// shared token. Without [[graft.agent]] callers have no identity, and a// non-empty list admits nobody. The user of the request is never used.Actors []string `json:"actors" toml:"actors,omitempty"`+ // Lockfiles are base names of lockfiles, besides the built-in ones+ // (package-lock.json, yarn.lock, pnpm-lock.yaml, poetry.lock, Cargo.lock,+ // go.sum). A conflicting lockfile is never sent to the resolver: it goes to+ // the agent.+ Lockfiles []string `json:"lockfiles" toml:"lockfiles,omitempty"`+ // GeneratedMarkers are Go regular expressions, besides the built-in ones,+ // searched in the first 10 lines of every side of a conflicting file; a+ // match marks the file generated, and it is never sent to the resolver. A+ // path that the tip's .gitattributes marks linguist-generated is generated+ // as well.+ GeneratedMarkers []string `json:"generated_markers" toml:"generated_markers,omitempty"`+ // Minified tells minified files apart; they are never sent to the resolver.+ Minified GraftResolverMinified `json:"minified" toml:"minified,omitempty"`+}++// GraftResolverMinified are the rules that mark a conflicting file minified.+type GraftResolverMinified struct {+ // Globs are base-name globs (path.Match syntax), besides the built-in ones+ // (*.min.js, *.min.mjs, *.min.css, *.bundle.js), of minified files.+ Globs []string `json:"globs" toml:"globs,omitempty"`+ // AverageLineBytes: a side larger than 2 KiB whose average line is longer+ // is minified. Zero means DefaultGraftResolverMinifiedAverageLineBytes.+ AverageLineBytes int `json:"average_line_bytes" toml:"average_line_bytes,omitempty"`+ // LongestLineBytes: a side larger than 2 KiB with a longer line is+ // minified. Zero means DefaultGraftResolverMinifiedLongestLineBytes.+ LongestLineBytes int `json:"longest_line_bytes" toml:"longest_line_bytes,omitempty"`+}++const (+ // DefaultGraftResolverMinifiedAverageLineBytes is the default+ // GraftResolverMinified.AverageLineBytes.+ DefaultGraftResolverMinifiedAverageLineBytes = 300+ // DefaultGraftResolverMinifiedLongestLineBytes is the default+ // GraftResolverMinified.LongestLineBytes.+ DefaultGraftResolverMinifiedLongestLineBytes = 5000+)++// AverageLineBytesOrDefault returns AverageLineBytes or its default.+func (m GraftResolverMinified) AverageLineBytesOrDefault() int {+ if m.AverageLineBytes > 0 {+ return m.AverageLineBytes+ }+ return DefaultGraftResolverMinifiedAverageLineBytes+}++// LongestLineBytesOrDefault returns LongestLineBytes or its default.+func (m GraftResolverMinified) LongestLineBytesOrDefault() int {+ if m.LongestLineBytes > 0 {+ return m.LongestLineBytes+ }+ return DefaultGraftResolverMinifiedLongestLineBytes}const (@@ -380,6 +432,30 @@ func (r GraftResolver) validate() error {}}}+ for _, name := range r.Lockfiles {+ if name == "" || strings.ContainsRune(name, '/') {+ return fmt.Errorf("graft land resolver: lockfile %q must be a base name", name)+ }+ }+ for _, expr := range r.GeneratedMarkers {+ if expr == "" {+ return fmt.Errorf("graft land resolver: empty generated marker")+ }+ if _, err := regexp.Compile(expr); err != nil {+ return fmt.Errorf("graft land resolver: generated marker %q: %w", expr, err)+ }+ }+ for _, glob := range r.Minified.Globs {+ if glob == "" || strings.ContainsRune(glob, '/') {+ return fmt.Errorf("graft land resolver: minified glob %q must be a non-empty base-name glob", glob)+ }+ if _, err := path.Match(glob, ""); err != nil {+ return fmt.Errorf("graft land resolver: minified glob %q: %w", glob, err)+ }+ }+ if r.Minified.AverageLineBytes < 0 || r.Minified.LongestLineBytes < 0 {+ return fmt.Errorf("graft land resolver: minified thresholds must not be negative")+ }return nil}diff --git a/internal/gitaly/config/config_graft_resolver_test.go b/internal/gitaly/config/config_graft_resolver_test.gonew file mode 100644index 0000000..10791f3--- /dev/null+++ b/internal/gitaly/config/config_graft_resolver_test.go@@ -0,0 +1,53 @@+package config++import (+ "strings"+ "testing"++ "github.com/stretchr/testify/require"+)++func TestGraftResolverValidateSendRules(t *testing.T) {+ t.Parallel()++ valid := GraftResolver{Enabled: true, Command: []string{"graft-resolve"}}+ require.NoError(t, valid.validate())++ withRules := valid+ withRules.Lockfiles = []string{"Gemfile.lock"}+ withRules.GeneratedMarkers = []string{`^// Generated by \w+`}+ withRules.Minified = GraftResolverMinified{Globs: []string{"*.min.html"}, AverageLineBytes: 200, LongestLineBytes: 4000}+ require.NoError(t, withRules.validate())++ for name, tc := range map[string]struct {+ mutate func(*GraftResolver)+ want string+ }{+ "lockfile with a slash": {func(r *GraftResolver) { r.Lockfiles = []string{"web/yarn.lock"} }, "must be a base name"},+ "empty lockfile": {func(r *GraftResolver) { r.Lockfiles = []string{""} }, "must be a base name"},+ "bad marker": {func(r *GraftResolver) { r.GeneratedMarkers = []string{"(unclosed"} }, "generated marker"},+ "empty marker": {func(r *GraftResolver) { r.GeneratedMarkers = []string{""} }, "empty generated marker"},+ "bad minified glob": {func(r *GraftResolver) { r.Minified.Globs = []string{"[x"} }, "minified glob"},+ "minified glob path": {func(r *GraftResolver) { r.Minified.Globs = []string{"dist/*.js"} }, "base-name glob"},+ "negative threshold": {func(r *GraftResolver) { r.Minified.LongestLineBytes = -1 }, "must not be negative"},+ } {+ t.Run(name, func(t *testing.T) {+ r := valid+ tc.mutate(&r)+ err := r.validate()+ require.Error(t, err)+ require.True(t, strings.Contains(err.Error(), tc.want), "error %q lacks %q", err, tc.want)+ })+ }+}++func TestGraftResolverMinifiedDefaults(t *testing.T) {+ t.Parallel()++ var m GraftResolverMinified+ require.Equal(t, DefaultGraftResolverMinifiedAverageLineBytes, m.AverageLineBytesOrDefault())+ require.Equal(t, DefaultGraftResolverMinifiedLongestLineBytes, m.LongestLineBytesOrDefault())+ m = GraftResolverMinified{AverageLineBytes: 10, LongestLineBytes: 20}+ require.Equal(t, 10, m.AverageLineBytesOrDefault())+ require.Equal(t, 20, m.LongestLineBytesOrDefault())+}diff --git a/internal/gitaly/service/operations/land_attempt.go b/internal/gitaly/service/operations/land_attempt.goindex f1af65c..2ecdc01 100644--- a/internal/gitaly/service/operations/land_attempt.go+++ b/internal/gitaly/service/operations/land_attempt.go@@ -197,6 +197,24 @@ func (a *landingAttempt) decide(ctx context.Context, tip git.ObjectID, req *landreturn landStep{commit: commitID, tip: commitID}, nil}+ // A resolution from the caller lands as a merge commit of the tip and the change, when it was+ // made against this tip; it replaces the server's attempt to merge or rebase.+ if in.GetResolution() != nil {+ res, err := a.server.landWithResolution(ctx, in, a.repo, tip, commitID, req.committer)+ if err != nil {+ var unresolved *landUnresolvedError+ if errors.As(err, &unresolved) {+ paths := make([][]byte, 0, len(unresolved.pkg.GetFiles()))+ for _, f := range unresolved.pkg.GetFiles() {+ paths = append(paths, f.GetPath())+ }+ return landStep{}, landWithPackage(landMergeConflictError(tip, commitID, paths, err), err)+ }+ return landStep{}, err+ }+ return landStep{commit: commitID, tip: res.commit, rewritten: true, resolution: &res}, nil+ }+newTip, err := a.computeTip(ctx, in, plan, tip, commitID, req.committer)var resolution *landResolutionif err != nil {@@ -205,12 +223,13 @@ func (a *landingAttempt) decide(ctx context.Context, tip git.ObjectID, req *land}// The conflict is resolved into a merge commit. When that fails, the request gets the- // merge conflict it would have got without resolution.+ // merge conflict it would have got without resolution, with the conflict package as a+ // second detail when the server listed the conflicts.res, resolveErr := a.server.resolveLandConflicts(ctx, in, a.repo, tip, commitID, req.committer)if resolveErr != nil {a.server.logger.WithError(resolveErr).WithField("branch", string(in.GetBranch())).Info("graft: conflict resolution of land failed")- return landStep{}, err+ return landStep{}, landWithPackage(err, resolveErr)}resolution = &resdiff --git a/internal/gitaly/service/operations/land_hunks.go b/internal/gitaly/service/operations/land_hunks.gonew file mode 100644index 0000000..1e59197--- /dev/null+++ b/internal/gitaly/service/operations/land_hunks.go@@ -0,0 +1,186 @@+package operations++import (+ "bytes"+ "sort"++ "github.com/feder-cr/git-ai/proto/go/gitalypb"+)++// landHunkMaxCells bounds the table of the line diff of one side against the base (the changed+// middle of the files, after the common prefix and suffix): about 2800 changed lines on each side.+// A file whose diff is larger gets no hunks in the conflict package; the agent still has its sides.+const landHunkMaxCells = 8 << 20++// landLineEdit replaces the base lines [start, end) with n lines of a side.+type landLineEdit struct {+ start, end int+ n int+}++// landConflictHunks returns the conflicting regions of a three-way merge of base, ours and theirs,+// as line ranges of each side (LandConflictHunk). A region is the union of the base lines that one+// or both sides changed, where edits that touch or overlap are one region; it conflicts when both+// sides changed it, differently. Each range counts the lines of its own side, 1-based and+// half-open. It returns nil when a diff exceeds landHunkMaxCells.+func landConflictHunks(base, ours, theirs []byte) []*gitalypb.LandConflictHunk {+ b, o, t := landSplitLines(base), landSplitLines(ours), landSplitLines(theirs)+ oursEdits, ok := landLineDiff(b, o)+ if !ok {+ return nil+ }+ theirsEdits, ok := landLineDiff(b, t)+ if !ok {+ return nil+ }++ type sideEdit struct {+ landLineEdit+ theirs bool+ }+ all := make([]sideEdit, 0, len(oursEdits)+len(theirsEdits))+ for _, e := range oursEdits {+ all = append(all, sideEdit{landLineEdit: e})+ }+ for _, e := range theirsEdits {+ all = append(all, sideEdit{landLineEdit: e, theirs: true})+ }+ sort.SliceStable(all, func(i, j int) bool {+ if all[i].start != all[j].start {+ return all[i].start < all[j].start+ }+ return all[i].end < all[j].end+ })++ var hunks []*gitalypb.LandConflictHunk+ // delta is, per side, the lines added minus the lines removed by the edits before the region,+ // which maps a base line to the line of that side.+ var oursDelta, theirsDelta int+ for i := 0; i < len(all); {+ start, end := all[i].start, all[i].end+ j := i+ var oursLines, theirsLines int+ var oursChanged, theirsChanged bool+ var oursCovered, theirsCovered int // base lines replaced by each side's edits in the region+ for ; j < len(all) && (j == i || all[j].start <= end); j++ {+ e := all[j]+ end = max(end, e.end)+ if e.theirs {+ theirsChanged = true+ theirsLines += e.n+ theirsCovered += e.end - e.start+ } else {+ oursChanged = true+ oursLines += e.n+ oursCovered += e.end - e.start+ }+ }+ // A side's text of the region is its edits plus the base lines of the region it kept.+ oursLen := oursLines + (end - start) - oursCovered+ theirsLen := theirsLines + (end - start) - theirsCovered++ if oursChanged && theirsChanged && !landSameText(b, o, t, start, end, oursDelta, theirsDelta, oursLen, theirsLen) {+ hunks = append(hunks, &gitalypb.LandConflictHunk{+ Base: landRange(start, end),+ Ours: landRange(start+oursDelta, start+oursDelta+oursLen),+ Theirs: landRange(start+theirsDelta, start+theirsDelta+theirsLen),+ })+ }+ oursDelta += oursLen - (end - start)+ theirsDelta += theirsLen - (end - start)+ i = j+ }+ return hunks+}++// landSameText reports whether both sides wrote the same lines into the region, which is a clean+// region and not a conflict.+func landSameText(b, o, t [][]byte, start, end, oursDelta, theirsDelta, oursLen, theirsLen int) bool {+ if oursLen != theirsLen {+ return false+ }+ for k := 0; k < oursLen; k++ {+ if !bytes.Equal(o[start+oursDelta+k], t[start+theirsDelta+k]) {+ return false+ }+ }+ return true+}++// landRange returns the 1-based half-open range of the 0-based lines [start, end).+func landRange(start, end int) *gitalypb.LineRange {+ return &gitalypb.LineRange{Start: uint32(start + 1), End: uint32(end + 1)}+}++// landSplitLines splits b into lines that keep their terminator.+func landSplitLines(b []byte) [][]byte {+ if len(b) == 0 {+ return nil+ }+ parts := bytes.SplitAfter(b, []byte("\n"))+ if len(parts[len(parts)-1]) == 0 {+ parts = parts[:len(parts)-1]+ }+ return parts+}++// landLineDiff returns the line edits that turn a into b, from a longest common subsequence of the+// lines after the common prefix and suffix. It returns false when the table would exceed+// landHunkMaxCells.+func landLineDiff(a, b [][]byte) ([]landLineEdit, bool) {+ pre := 0+ for pre < len(a) && pre < len(b) && bytes.Equal(a[pre], b[pre]) {+ pre+++ }+ suf := 0+ for suf < len(a)-pre && suf < len(b)-pre && bytes.Equal(a[len(a)-1-suf], b[len(b)-1-suf]) {+ suf+++ }+ am, bm := a[pre:len(a)-suf], b[pre:len(b)-suf]+ n, m := len(am), len(bm)+ if n == 0 && m == 0 {+ return nil, true+ }+ w := m + 1+ if (n+1)*w > landHunkMaxCells {+ return nil, false+ }++ // lcs[i*w+j] is the LCS length of am[i:] and bm[j:].+ lcs := make([]int32, (n+1)*w)+ for i := n - 1; i >= 0; i-- {+ for j := m - 1; j >= 0; j-- {+ switch {+ case bytes.Equal(am[i], bm[j]):+ lcs[i*w+j] = lcs[(i+1)*w+j+1] + 1+ case lcs[(i+1)*w+j] >= lcs[i*w+j+1]:+ lcs[i*w+j] = lcs[(i+1)*w+j]+ default:+ lcs[i*w+j] = lcs[i*w+j+1]+ }+ }+ }++ var edits []landLineEdit+ cur := -1+ for i, j := 0, 0; i < n || j < m; {+ if i < n && j < m && bytes.Equal(am[i], bm[j]) {+ cur = -1+ i+++ j+++ continue+ }+ if cur < 0 {+ edits = append(edits, landLineEdit{start: pre + i, end: pre + i})+ cur = len(edits) - 1+ }+ if i < n && (j == m || lcs[(i+1)*w+j] >= lcs[i*w+j+1]) {+ i+++ edits[cur].end = pre + i+ } else {+ edits[cur].n+++ j+++ }+ }+ return edits, true+}diff --git a/internal/gitaly/service/operations/land_package.go b/internal/gitaly/service/operations/land_package.gonew file mode 100644index 0000000..da99f2c--- /dev/null+++ b/internal/gitaly/service/operations/land_package.go@@ -0,0 +1,237 @@+package operations++import (+ "bytes"+ "context"+ "errors"+ "fmt"+ "strings"+ "unicode/utf8"++ "github.com/feder-cr/git-ai/internal/git"+ "github.com/feder-cr/git-ai/internal/git/gitcmd"+ "github.com/feder-cr/git-ai/internal/git/localrepo"+ "github.com/feder-cr/git-ai/internal/graft/resolver"+ "github.com/feder-cr/git-ai/internal/structerr"+ "github.com/feder-cr/git-ai/proto/go/gitalypb"+)++// This file builds the conflict package of a land that the server did not resolve (LandConflict,+// PLAN10 3.3): every conflicting file with its sides, its conflicting hunks and what the server did+// with it, so that the agent can resolve the conflict and land again with a LandResolution.++const (+ // landPackageMessageBytes bounds each commit message of the package.+ landPackageMessageBytes = 4 << 10+ // landPackageReasonBytes bounds every reason of the package.+ landPackageReasonBytes = 512+)++// Reasons of the files the server does not send to the resolver, besides the content rules of+// resolver.SendRules.+const (+ landNotSentTrailerUnsafe = "the path holds a line break or a NUL byte, which a commit trailer cannot carry"+ landNotSentInvalidUTF8 = "the path is not valid UTF-8, which the resolver protocol cannot carry"+ landNotSentDenied = "the path may not be sent to the resolver (paths_allow, paths_deny)"+ landNotSentNotAFile = "a side is not a file (a submodule or a directory)"+ landNotSentNoSide = "the path is on neither side of the merge (a file/directory conflict)"+ landNotSentNoBaseOneSide = "the path has no base and a missing side, which no merge produces without a rename"+)++// landFileState is a conflicting file of a land and what the server did with it.+type landFileState struct {+ conflict landFileConflict+ kind string+ // sides are the contents read for the resolver and the hunks (base, ours, theirs); nil for an+ // absent side or one that was not read.+ sides [3][]byte+ read bool+ outcome gitalypb.LandConflictFile_Outcome+ reason string+}++// sent reports whether the file is sent to the resolver.+func (f *landFileState) sent() bool {+ return f.outcome == gitalypb.LandConflictFile_OUTCOME_UNSPECIFIED+}++// textRead reports whether the sides were read and are text, so that they have line hunks.+func (f *landFileState) textRead() bool {+ if !f.read {+ return false+ }+ for _, s := range f.sides {+ if bytes.IndexByte(s, 0) >= 0 {+ return false+ }+ }+ return true+}++// notSent marks the file as not sent, with its reason.+func (f *landFileState) notSent(reason string) {+ f.outcome = gitalypb.LandConflictFile_OUTCOME_NOT_SENT+ f.reason = reason+}++// landUnresolvedError is a land whose conflicts the server did not resolve. It carries the conflict+// package, which the caller attaches to the merge conflict error.+type landUnresolvedError struct {+ pkg *gitalypb.LandConflict+ cause string+ // err is the error of the resolver or of the check, when one caused the outcome, so that+ // errors.Is and errors.As still see it.+ err error+}++func (e *landUnresolvedError) Error() string {+ return "conflicts not resolved: " + e.cause+}++// Unwrap returns the error of the resolver or of the check, if any.+func (e *landUnresolvedError) Unwrap() error {+ return e.err+}++// landWithPackage adds the conflict package of resolveErr, when it carries one, to the merge+// conflict error of the land as a second detail, after UserLandError. Clients that know only+// UserLandError see the error unchanged.+func landWithPackage(mergeConflict, resolveErr error) error {+ var unresolved *landUnresolvedError+ var se structerr.Error+ if !errors.As(resolveErr, &unresolved) || !errors.As(mergeConflict, &se) {+ return mergeConflict+ }+ return se.WithDetail(unresolved.pkg)+}++// landKindOf classifies a conflicting file from the presence of its sides.+func landKindOf(c landFileConflict) string {+ switch {+ case c.ours == nil || c.theirs == nil:+ return resolver.KindModifyDelete+ case c.base == nil:+ return resolver.KindAddAdd+ case c.ours.oid == c.theirs.oid:+ return resolver.KindMode+ default:+ return resolver.KindContent+ }+}++func landKindProto(kind string) gitalypb.LandConflictFile_Kind {+ switch kind {+ case resolver.KindContent:+ return gitalypb.LandConflictFile_KIND_CONTENT+ case resolver.KindModifyDelete:+ return gitalypb.LandConflictFile_KIND_MODIFY_DELETE+ case resolver.KindAddAdd:+ return gitalypb.LandConflictFile_KIND_ADD_ADD+ case resolver.KindMode:+ return gitalypb.LandConflictFile_KIND_MODE+ }+ return gitalypb.LandConflictFile_KIND_UNSPECIFIED+}++// landPackage returns the conflict package of the files, with reason set when the request was not+// attempted at all. At most maxFiles files are listed.+func landPackage(tip, commitID, base git.ObjectID, tipMessage, commitMessage string, files []*landFileState, maxFiles int, reason string) *gitalypb.LandConflict {+ tm, tipCut := landCut([]byte(tipMessage), landPackageMessageBytes)+ cm, commitCut := landCut([]byte(commitMessage), landPackageMessageBytes)+ pkg := &gitalypb.LandConflict{+ Tip: tip.String(),+ Commit: commitID.String(),+ MergeBase: base.String(),+ TipMessage: tm,+ CommitMessage: cm,+ MessagesTruncated: tipCut || commitCut,+ Reason: landCutString(reason, landPackageReasonBytes),+ }+ for i, f := range files {+ if i == maxFiles {+ break+ }+ pf := &gitalypb.LandConflictFile{+ Path: []byte(f.conflict.path),+ Kind: landKindProto(f.kind),+ Base: landSideProto(f.conflict.base),+ Ours: landSideProto(f.conflict.ours),+ Theirs: landSideProto(f.conflict.theirs),+ Outcome: f.outcome,+ Reason: landCutString(f.reason, landPackageReasonBytes),+ }+ if f.textRead() && (f.kind == resolver.KindContent || f.kind == resolver.KindAddAdd) {+ pf.Hunks = landConflictHunks(f.sides[0], f.sides[1], f.sides[2])+ }+ pkg.Files = append(pkg.Files, pf)+ }+ return pkg+}++func landSideProto(b *landBlob) *gitalypb.LandConflictSide {+ if b == nil {+ return nil+ }+ return &gitalypb.LandConflictSide{Oid: b.oid.String(), Mode: b.mode}+}++// landCut cuts b to at most n bytes on a UTF-8 boundary and reports whether it was cut.+func landCut(b []byte, n int) ([]byte, bool) {+ if len(b) <= n {+ return b, false+ }+ cut := n+ for cut > 0 && !utf8.RuneStart(b[cut]) {+ cut--+ }+ return b[:cut], true+}++// landCutString cuts s to at most n bytes, valid UTF-8.+func landCutString(s string, n int) string {+ b, _ := landCut([]byte(s), n)+ return strings.ToValidUTF8(string(b), "")+}++// landGeneratedPaths returns the paths that the attributes of rev mark linguist-generated, with one+// git check-attr for all of them.+func landGeneratedPaths(ctx context.Context, repo *localrepo.Repo, rev git.ObjectID, paths []string) (map[string]bool, error) {+ generated := map[string]bool{}+ if len(paths) == 0 {+ return generated, nil+ }+ var stdin bytes.Buffer+ for _, p := range paths {+ stdin.WriteString(p)+ stdin.WriteByte(0)+ }+ var stdout, stderr bytes.Buffer+ if err := repo.ExecAndWait(ctx,+ gitcmd.Command{+ Name: "check-attr",+ Flags: []gitcmd.Option{+ gitcmd.Flag{Name: "-z"},+ gitcmd.Flag{Name: "--stdin"},+ gitcmd.ValueFlag{Name: "--source", Value: rev.String()},+ },+ Args: []string{"linguist-generated"},+ },+ gitcmd.WithStdin(&stdin),+ gitcmd.WithStdout(&stdout),+ gitcmd.WithStderr(&stderr),+ ); err != nil {+ return nil, fmt.Errorf("check-attr: %w, stderr: %q", err, stderr.String())+ }+ // The output is NUL-separated triples: path, attribute, value.+ fields := strings.Split(strings.TrimSuffix(stdout.String(), "\x00"), "\x00")+ if len(fields)%3 != 0 {+ return nil, fmt.Errorf("check-attr: unexpected output of %d fields", len(fields))+ }+ for i := 0; i+2 < len(fields); i += 3 {+ switch fields[i+2] {+ case "set", "true":+ generated[fields[i]] = true+ }+ }+ return generated, nil+}diff --git a/internal/gitaly/service/operations/land_package_test.go b/internal/gitaly/service/operations/land_package_test.gonew file mode 100644index 0000000..cd03967--- /dev/null+++ b/internal/gitaly/service/operations/land_package_test.go@@ -0,0 +1,389 @@+package operations++import (+ "encoding/json"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/stretchr/testify/require"+ "google.golang.org/grpc/status"++ "github.com/feder-cr/git-ai/internal/git"+ "github.com/feder-cr/git-ai/internal/git/gittest"+ "github.com/feder-cr/git-ai/internal/gitaly/config"+ "github.com/feder-cr/git-ai/internal/graft/resolver"+ "github.com/feder-cr/git-ai/proto/go/gitalypb"+)++func hunk(b0, b1, o0, o1, t0, t1 uint32) *gitalypb.LandConflictHunk {+ return &gitalypb.LandConflictHunk{+ Base: &gitalypb.LineRange{Start: b0, End: b1},+ Ours: &gitalypb.LineRange{Start: o0, End: o1},+ Theirs: &gitalypb.LineRange{Start: t0, End: t1},+ }+}++func TestLandConflictHunks(t *testing.T) {+ t.Parallel()++ for _, tc := range []struct {+ name string+ base, ours, theirs string+ want []*gitalypb.LandConflictHunk+ }{+ {+ name: "one line changed on both sides",+ base: "1\n2\n3\n", ours: "1\nO\n3\n", theirs: "1\nT\n3\n",+ want: []*gitalypb.LandConflictHunk{hunk(2, 3, 2, 3, 2, 3)},+ },+ {+ // Ours adds two lines at the top, which moves the conflict two lines down in ours only.+ name: "ranges count the lines of their own side",+ base: "1\n2\n3\n4\n", ours: "a\nb\n1\n2\nO\n4\n", theirs: "1\n2\nT\nT2\n4\n",+ want: []*gitalypb.LandConflictHunk{hunk(3, 4, 5, 6, 3, 5)},+ },+ {+ name: "non-overlapping changes merge without a hunk",+ base: "1\n2\n3\n4\n5\n", ours: "O\n2\n3\n4\n5\n", theirs: "1\n2\n3\n4\nT\n",+ },+ {+ name: "the same change on both sides is no conflict",+ base: "1\n2\n", ours: "1\nX\n", theirs: "1\nX\n",+ },+ {+ name: "both insert at the same point",+ base: "1\n2\n", ours: "1\nO\n2\n", theirs: "1\nT\n2\n",+ want: []*gitalypb.LandConflictHunk{hunk(2, 2, 2, 3, 2, 3)},+ },+ {+ name: "add/add: no base",+ base: "", ours: "o1\no2\n", theirs: "t1\n",+ want: []*gitalypb.LandConflictHunk{hunk(1, 1, 1, 3, 1, 2)},+ },+ {+ name: "two conflicts",+ base: "1\n2\n3\n4\n5\n", ours: "O1\n2\n3\n4\nO5\n", theirs: "T1\n2\n3\n4\nT5\n",+ want: []*gitalypb.LandConflictHunk{hunk(1, 2, 1, 2, 1, 2), hunk(5, 6, 5, 6, 5, 6)},+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ got := landConflictHunks([]byte(tc.base), []byte(tc.ours), []byte(tc.theirs))+ require.Len(t, got, len(tc.want))+ for i := range tc.want {+ require.Equal(t, tc.want[i].String(), got[i].String(), "hunk %d", i)+ }+ })+ }+}++// landConflictDetail returns the LandConflict detail of err, or nil.+func landConflictDetail(err error) *gitalypb.LandConflict {+ for _, detail := range status.Convert(err).Details() {+ if pkg, ok := detail.(*gitalypb.LandConflict); ok {+ return pkg+ }+ }+ return nil+}++// writeRawAnswer sets any JSON as the answer the resolver script of dir gives.+func writeRawAnswer(t *testing.T, dir string, answer any) {+ t.Helper()+ raw, err := json.Marshal(answer)+ require.NoError(t, err)+ require.NoError(t, os.WriteFile(filepath.Join(dir, "answer.json"), raw, 0o600))+}++func packageFile(t *testing.T, pkg *gitalypb.LandConflict, path string) *gitalypb.LandConflictFile {+ t.Helper()+ for _, f := range pkg.GetFiles() {+ if string(f.GetPath()) == path {+ return f+ }+ }+ require.FailNow(t, "no file in the package", "path %q", path)+ return nil+}++func TestUserLand_conflictPackage(t *testing.T) {+ t.Parallel()++ t.Run("a refusal gives every file its outcome", func(t *testing.T) {+ t.Parallel()++ // The resolver refuses with the outcome of each file on stdout, as graft-resolve does.+ dir, argv := resolverScript(t, `cat "$DIR/answer.json"; exit 1`)+ writeRawAnswer(t, dir, resolver.ErrorResponse{+ Error: "unresolved",+ Files: []resolver.FileOutcome{+ {Path: "a", Outcome: resolver.OutcomeResolved},+ {Path: "b", Outcome: resolver.OutcomeRejected, Reason: "syntax check: b does not parse"},+ },+ })+ fx := newResolveFixture(t, enabledResolver(argv))++ _, err := fx.client.UserLand(fx.ctx, fx.request("Land"))+ requireMergeConflict(t, err)+ pkg := landConflictDetail(err)+ require.NotNil(t, pkg, "the merge conflict carries the package")+ require.Equal(t, fx.tip.String(), pkg.GetTip())+ require.Equal(t, fx.commit.String(), pkg.GetCommit())+ require.Equal(t, fx.base.String(), pkg.GetMergeBase())+ require.Empty(t, pkg.GetReason())++ a, b := packageFile(t, pkg, "a"), packageFile(t, pkg, "b")+ require.Equal(t, gitalypb.LandConflictFile_OUTCOME_RESOLVED, a.GetOutcome())+ require.Equal(t, gitalypb.LandConflictFile_OUTCOME_REJECTED, b.GetOutcome())+ require.Equal(t, "syntax check: b does not parse", b.GetReason())+ require.Equal(t, gitalypb.LandConflictFile_KIND_CONTENT, b.GetKind())+ require.NotEmpty(t, b.GetOurs().GetOid())+ require.Len(t, b.GetHunks(), 1)+ requireBranchAt(t, fx.cfg, fx.repoPath, git.DefaultBranch, fx.tip)+ })++ t.Run("a malformed outcome list is not trusted in part", func(t *testing.T) {+ t.Parallel()++ dir, argv := resolverScript(t, `cat "$DIR/answer.json"; exit 1`)+ writeRawAnswer(t, dir, resolver.ErrorResponse{+ Error: "unresolved",+ Files: []resolver.FileOutcome{{Path: "a", Outcome: resolver.OutcomeResolved}}, // b is missing+ })+ fx := newResolveFixture(t, enabledResolver(argv))++ _, err := fx.client.UserLand(fx.ctx, fx.request("Land"))+ pkg := landConflictDetail(err)+ require.NotNil(t, pkg)+ for _, p := range []string{"a", "b"} {+ f := packageFile(t, pkg, p)+ require.Equal(t, gitalypb.LandConflictFile_OUTCOME_FAILED, f.GetOutcome(), p)+ require.Contains(t, f.GetReason(), "unresolved", p)+ }+ })++ t.Run("a lockfile is not sent, the other file is", func(t *testing.T) {+ t.Parallel()++ dir, argv := resolverScript(t, "")+ writeAnswer(t, dir, resolver.Response{+ Version: resolver.ProtocolVersion,+ Resolver: "graft-resolve/fake",+ Files: []resolver.ResponseFile{{Path: "a", Action: resolver.ActionWrite, Mode: resolver.ModeRegular, Content: []byte("merged-a\n")}},+ })+ fx := newResolveFixtureWith(t, enabledResolver(argv),+ []gittest.TreeEntry{{Mode: "100644", Path: "a", Content: "base\n"}, {Mode: "100644", Path: "go.sum", Content: "base\n"}},+ []gittest.TreeEntry{{Mode: "100644", Path: "a", Content: "ours\n"}, {Mode: "100644", Path: "go.sum", Content: "ours\n"}},+ []gittest.TreeEntry{{Mode: "100644", Path: "a", Content: "theirs\n"}, {Mode: "100644", Path: "go.sum", Content: "theirs\n"}},+ )++ _, err := fx.client.UserLand(fx.ctx, fx.request("Land"))+ requireMergeConflict(t, err)+ pkg := landConflictDetail(err)+ require.NotNil(t, pkg)+ require.Equal(t, gitalypb.LandConflictFile_OUTCOME_RESOLVED, packageFile(t, pkg, "a").GetOutcome())+ lock := packageFile(t, pkg, "go.sum")+ require.Equal(t, gitalypb.LandConflictFile_OUTCOME_NOT_SENT, lock.GetOutcome())+ require.Equal(t, resolver.NotSentLockfile, lock.GetReason())++ req := resolverRequest(t, dir, 1)+ require.Len(t, req.Files, 1, "the lockfile never reaches the resolver")+ require.Equal(t, "a", req.Files[0].Path)+ })++ t.Run("a disabled resolver gives a package that was not attempted", func(t *testing.T) {+ t.Parallel()++ fx := newResolveFixture(t, config.GraftResolver{})+ _, err := fx.client.UserLand(fx.ctx, fx.request("Land"))+ requireMergeConflict(t, err)+ pkg := landConflictDetail(err)+ require.NotNil(t, pkg)+ require.Contains(t, pkg.GetReason(), "not enabled")+ for _, f := range pkg.GetFiles() {+ require.Equal(t, gitalypb.LandConflictFile_OUTCOME_NOT_ATTEMPTED, f.GetOutcome())+ }+ })++ t.Run("without resolve_conflicts there is no package", func(t *testing.T) {+ t.Parallel()++ fx := newResolveFixture(t, config.GraftResolver{})+ req := fx.request("Land")+ req.ResolveConflicts = false+ _, err := fx.client.UserLand(fx.ctx, req)+ requireMergeConflict(t, err)+ require.Nil(t, landConflictDetail(err))+ })+}++// resolutionOf returns the resolution of the fixture's conflicts a and b with the given contents.+func resolutionOf(fx resolveFixture, a, b string) *gitalypb.LandResolution {+ return &gitalypb.LandResolution{+ Tip: fx.tip.String(),+ Commit: fx.commit.String(),+ Files: []*gitalypb.LandResolvedFile{+ {Path: []byte("a"), Action: gitalypb.LandResolvedFile_ACTION_WRITE, Mode: "100644", Content: []byte(a)},+ {Path: []byte("b"), Action: gitalypb.LandResolvedFile_ACTION_WRITE, Mode: "100644", Content: []byte(b)},+ },+ }+}++func TestUserLand_reland(t *testing.T) {+ t.Parallel()++ t.Run("without a resolver the resolution lands with the server's rules only", func(t *testing.T) {+ t.Parallel()++ fx := newResolveFixture(t, config.GraftResolver{})+ req := fx.request("Land")+ req.ResolveConflicts = false+ req.Resolution = resolutionOf(fx, "agent-a\n", "agent-b\n")++ resp, err := fx.client.UserLand(fx.ctx, req)+ require.NoError(t, err)+ landed := git.ObjectID(resp.GetLandedCommitId())+ requireBranchAt(t, fx.cfg, fx.repoPath, git.DefaultBranch, landed)+ require.Equal(t, "agent-a\n", fx.blobAt(t, landed, "a"))+ require.Equal(t, "agent-b\n", fx.blobAt(t, landed, "b"))+ require.Equal(t, "d\n", fx.blobAt(t, landed, "d"))++ commit, err := fx.repo.ReadCommit(fx.ctx, landed.Revision())+ require.NoError(t, err)+ require.Equal(t, []string{fx.tip.String(), fx.commit.String()}, commit.GetParentIds())+ body := string(commit.GetBody())+ require.Contains(t, body, "Graft-Resolved-By: agent\n")+ require.NotContains(t, body, "Graft-Checked-By:")+ require.Equal(t, "agent", resp.GetResolver())+ })++ t.Run("with a resolver the resolution is checked and the trailer says so", func(t *testing.T) {+ t.Parallel()++ dir, argv := resolverScript(t, "")+ writeRawAnswer(t, dir, resolver.CheckResponse{+ Version: resolver.ProtocolVersion, Operation: resolver.OperationCheck, Resolver: "graft-resolve",+ Files: []resolver.CheckFile{{Path: "a", OK: true, Syntax: resolver.SyntaxNone}, {Path: "b", OK: true, Syntax: resolver.SyntaxNone}},+ })+ fx := newResolveFixture(t, enabledResolver(argv))+ req := fx.request("Land")+ req.Resolution = resolutionOf(fx, "agent-a\n", "agent-b\n")++ resp, err := fx.client.UserLand(fx.ctx, req)+ require.NoError(t, err)+ commit, err := fx.repo.ReadCommit(fx.ctx, git.ObjectID(resp.GetLandedCommitId()).Revision())+ require.NoError(t, err)+ require.Contains(t, string(commit.GetBody()), "Graft-Checked-By: graft-resolve\n")++ check := resolverRequest(t, dir, 1)+ require.Equal(t, resolver.OperationCheck, check.Operation)+ require.Len(t, check.Resolution, 2)+ require.Equal(t, "agent-a\n", string(check.Resolution[0].Content))+ })++ t.Run("a failed check rejects the file", func(t *testing.T) {+ t.Parallel()++ dir, argv := resolverScript(t, "")+ writeRawAnswer(t, dir, resolver.CheckResponse{+ Version: resolver.ProtocolVersion, Operation: resolver.OperationCheck, Resolver: "graft-resolve",+ Files: []resolver.CheckFile{{Path: "a", OK: true, Syntax: resolver.SyntaxNone}, {Path: "b", OK: false, Reason: "check failed: tests", Syntax: resolver.SyntaxNone}},+ })+ fx := newResolveFixture(t, enabledResolver(argv))+ req := fx.request("Land")+ req.Resolution = resolutionOf(fx, "agent-a\n", "agent-b\n")++ _, err := fx.client.UserLand(fx.ctx, req)+ requireMergeConflict(t, err)+ pkg := landConflictDetail(err)+ require.NotNil(t, pkg)+ require.Equal(t, gitalypb.LandConflictFile_OUTCOME_RESOLVED, packageFile(t, pkg, "a").GetOutcome())+ b := packageFile(t, pkg, "b")+ require.Equal(t, gitalypb.LandConflictFile_OUTCOME_REJECTED, b.GetOutcome())+ require.Equal(t, "check failed: tests", b.GetReason())+ requireBranchAt(t, fx.cfg, fx.repoPath, git.DefaultBranch, fx.tip)+ })++ t.Run("a resolver that does not know the check fails closed", func(t *testing.T) {+ t.Parallel()++ dir, argv := resolverScript(t, "")+ writeAnswer(t, dir, validAnswer()) // an old resolver answers a resolve response+ fx := newResolveFixture(t, enabledResolver(argv))+ req := fx.request("Land")+ req.Resolution = resolutionOf(fx, "agent-a\n", "agent-b\n")++ _, err := fx.client.UserLand(fx.ctx, req)+ requireMergeConflict(t, err)+ pkg := landConflictDetail(err)+ require.NotNil(t, pkg)+ require.Contains(t, pkg.GetReason(), "could not be checked")+ require.Contains(t, pkg.GetReason(), "does not support the check")+ requireBranchAt(t, fx.cfg, fx.repoPath, git.DefaultBranch, fx.tip)+ })++ t.Run("conflict markers are rejected", func(t *testing.T) {+ t.Parallel()++ fx := newResolveFixture(t, config.GraftResolver{})+ req := fx.request("Land")+ req.Resolution = resolutionOf(fx, "agent-a\n", "<<<<<<< ours\nx\n=======\ny\n>>>>>>> theirs\n")++ _, err := fx.client.UserLand(fx.ctx, req)+ pkg := landConflictDetail(err)+ require.NotNil(t, pkg)+ b := packageFile(t, pkg, "b")+ require.Equal(t, gitalypb.LandConflictFile_OUTCOME_REJECTED, b.GetOutcome())+ require.Contains(t, b.GetReason(), "conflict marker")+ })++ t.Run("a moved tip gives a fresh package", func(t *testing.T) {+ t.Parallel()++ fx := newResolveFixture(t, config.GraftResolver{})+ req := fx.request("Land")+ req.Resolution = resolutionOf(fx, "agent-a\n", "agent-b\n")+ req.Resolution.Tip = fx.base.String() // made against another tip++ _, err := fx.client.UserLand(fx.ctx, req)+ requireMergeConflict(t, err)+ pkg := landConflictDetail(err)+ require.NotNil(t, pkg)+ require.Equal(t, fx.tip.String(), pkg.GetTip())+ require.Contains(t, pkg.GetReason(), "tip moved")+ requireBranchAt(t, fx.cfg, fx.repoPath, git.DefaultBranch, fx.tip)+ })++ t.Run("the resolution must resolve exactly the conflicting paths", func(t *testing.T) {+ t.Parallel()++ for name, mutate := range map[string]func(*gitalypb.LandResolution){+ "a path missing": func(r *gitalypb.LandResolution) { r.Files = r.Files[:1] },+ "a path twice": func(r *gitalypb.LandResolution) { r.Files[1].Path = []byte("a") },+ "a path not in conflict": func(r *gitalypb.LandResolution) { r.Files[1].Path = []byte("c") },+ } {+ fx := newResolveFixture(t, config.GraftResolver{})+ req := fx.request("Land")+ req.Resolution = resolutionOf(fx, "agent-a\n", "agent-b\n")+ mutate(req.Resolution)++ _, err := fx.client.UserLand(fx.ctx, req)+ pkg := landConflictDetail(err)+ require.NotNil(t, pkg, name)+ require.True(t, strings.HasPrefix(pkg.GetReason(), "the resolution "), "%s: reason %q", name, pkg.GetReason())+ }+ })++ t.Run("a resolution for another commit is an invalid argument", func(t *testing.T) {+ t.Parallel()++ fx := newResolveFixture(t, config.GraftResolver{})+ req := fx.request("Land")+ req.Resolution = resolutionOf(fx, "agent-a\n", "agent-b\n")+ req.Resolution.Commit = fx.tip.String()++ _, err := fx.client.UserLand(fx.ctx, req)+ require.Contains(t, err.Error(), "resolution is for commit")+ })+}diff --git a/internal/gitaly/service/operations/land_reland.go b/internal/gitaly/service/operations/land_reland.gonew file mode 100644index 0000000..1a0e4a7--- /dev/null+++ b/internal/gitaly/service/operations/land_reland.go@@ -0,0 +1,238 @@+package operations++import (+ "context"+ "errors"+ "fmt"+ "slices"+ "strings"++ "github.com/prometheus/client_golang/prometheus"+ "github.com/prometheus/client_golang/prometheus/promauto"++ "github.com/feder-cr/git-ai/internal/git"+ "github.com/feder-cr/git-ai/internal/git/localrepo"+ "github.com/feder-cr/git-ai/internal/graft/identity"+ "github.com/feder-cr/git-ai/internal/graft/resolver"+ "github.com/feder-cr/git-ai/internal/log"+ "github.com/feder-cr/git-ai/internal/structerr"+ "github.com/feder-cr/git-ai/proto/go/gitalypb"+)++// landResolutionSyntaxUncheckedTotal counts the files of agents' resolutions that landed without a+// syntax verdict: the resolver's grammar cannot read a side of them.+var landResolutionSyntaxUncheckedTotal = promauto.NewCounter(prometheus.CounterOpts{+ Name: "graft_land_resolution_syntax_unchecked_total",+ Help: "Files of agents' resolutions that landed without a syntax verdict, because a side does not parse with the resolver's grammar.",+})++// landAgentResolver is the resolver name of an agent's resolution in the Graft-Resolved-By trailer.+func landAgentResolver(actor string) string {+ if actor == "" {+ return "agent"+ }+ return "agent/" + actor+}++// landWithResolution lands commitID onto tip with the caller's resolution of the conflicts+// (UserLandRequest.resolution, PLAN10 3.3 and 12). It is accepted only when it was made against+// this tip and this commit and resolves exactly the paths that conflict, each once. Every file+// gets the acceptance rules of a resolver answer; when a resolver is configured, the files that+// may be sent to it also get its checks (the check operation: the syntax check and the configured+// checks), and a failing or failed check fails the land. Nothing lands partially: an unaccepted+// resolution fails with a fresh conflict package (*landUnresolvedError).+//+// The merge commit carries Graft-Resolved-By: agent/<actor> and, when the resolver checked the+// resolution, Graft-Checked-By: <resolver>.+func (s *Server) landWithResolution(+ ctx context.Context,+ in *gitalypb.UserLandRequest,+ repo *localrepo.Repo,+ tip, commitID git.ObjectID,+ committer git.Signature,+) (landResolution, error) {+ r := in.GetResolution()+ if r.GetCommit() != commitID.String() {+ return landResolution{}, structerr.NewInvalidArgument("resolution is for commit %q, not commit_id %q", r.GetCommit(), commitID)+ }++ l, err := landListConflicts(ctx, repo, tip, commitID)+ if errors.Is(err, errLandNoConflicts) {+ return landResolution{}, structerr.NewFailedPrecondition("the merge of tip %s and commit %s has no conflicts, so there is nothing to resolve: land without a resolution", tip, commitID)+ }+ if err != nil {+ return landResolution{}, err+ }+ maxFiles := s.resolveCfg.MaxFilesOrDefault()+ if r.GetTip() != tip.String() {+ return landResolution{}, l.notAttempted(maxFiles, fmt.Sprintf("the branch tip moved from %s to %s since the resolution was made: resolve the conflicts of this package", r.GetTip(), tip), nil)+ }+ if l.bases > 1 {+ return landResolution{}, l.notAttempted(maxFiles, fmt.Sprintf("the change has %d merge bases (a criss-cross history), which are not resolved", l.bases), nil)+ }++ resolved, reason := landResolutionFiles(r, l.files)+ if reason != "" {+ return landResolution{}, l.notAttempted(maxFiles, reason, nil)+ }++ maxBytes := s.resolveCfg.MaxFileBytesOrDefault()+ rejected := false+ for _, f := range l.files {+ if err := resolver.ValidateFile(resolved[f.conflict.path], maxBytes); err != nil {+ f.outcome, f.reason = gitalypb.LandConflictFile_OUTCOME_REJECTED, err.Error()+ rejected = true+ }+ }++ actor := identity.Actor(ctx, "")+ checkedBy := ""+ if !rejected && s.conflictResolver != nil {+ if checkedBy, err = s.landCheckResolution(ctx, in, repo, l, actor, resolved); err != nil {+ return landResolution{}, err+ }+ }+ for _, f := range l.files {+ if f.outcome == gitalypb.LandConflictFile_OUTCOME_REJECTED {+ rejected = true+ }+ }+ if rejected {+ for _, f := range l.files {+ if f.outcome != gitalypb.LandConflictFile_OUTCOME_REJECTED {+ f.outcome, f.reason = gitalypb.LandConflictFile_OUTCOME_RESOLVED, ""+ }+ }+ return landResolution{}, l.unresolved(maxFiles, "", "the resolution was rejected: "+landUnresolvedCause(l.files), nil)+ }++ resp := &resolver.Response{Version: resolver.ProtocolVersion, Resolver: landAgentResolver(actor)}+ for _, f := range l.files {+ resp.Files = append(resp.Files, resolved[f.conflict.path])+ }+ return s.landWriteResolution(ctx, in, repo, tip, commitID, l.mergedTree, committer, actor, resp, checkedBy)+}++// landResolutionFiles maps the files of the resolution to the conflicting paths. It returns a+// reason when the resolution does not resolve exactly the conflicting paths, each once.+func landResolutionFiles(r *gitalypb.LandResolution, files []*landFileState) (map[string]resolver.ResponseFile, string) {+ conflicting := make(map[string]bool, len(files))+ var want []string+ for _, f := range files {+ conflicting[f.conflict.path] = true+ want = append(want, f.conflict.path)+ }+ resolved := make(map[string]resolver.ResponseFile, len(r.GetFiles()))+ for _, rf := range r.GetFiles() {+ p := string(rf.GetPath())+ if !conflicting[p] {+ return nil, fmt.Sprintf("the resolution names %q, which does not conflict at this tip", p)+ }+ if _, dup := resolved[p]; dup {+ return nil, fmt.Sprintf("the resolution names %q more than once", p)+ }+ out := resolver.ResponseFile{Path: p, Mode: rf.GetMode(), Content: rf.GetContent()}+ switch rf.GetAction() {+ case gitalypb.LandResolvedFile_ACTION_WRITE:+ out.Action = resolver.ActionWrite+ case gitalypb.LandResolvedFile_ACTION_DELETE:+ out.Action = resolver.ActionDelete+ default:+ out.Action = rf.GetAction().String()+ }+ resolved[p] = out+ }+ if len(resolved) != len(conflicting) {+ var missing []string+ for _, p := range want {+ if _, ok := resolved[p]; !ok {+ missing = append(missing, p)+ }+ }+ slices.Sort(missing)+ return nil, fmt.Sprintf("the resolution does not resolve %s", strings.Join(missing, ", "))+ }+ return resolved, ""+}++// landCheckResolution runs the resolver's checks on the files of the resolution that may be sent+// to the resolver (landClassify), and sets the outcome of each checked file that fails them to+// REJECTED. It returns the checker's name for the Graft-Checked-By trailer, or "" when no file+// could be sent. The check fails closed: a check that cannot run is a *landUnresolvedError with a+// fresh package.+func (s *Server) landCheckResolution(+ ctx context.Context,+ in *gitalypb.UserLandRequest,+ repo *localrepo.Repo,+ l landListing,+ actor string,+ resolved map[string]resolver.ResponseFile,+) (string, error) {+ if err := s.landClassify(ctx, repo, l.files, l.base, l.tip, l.commitID); err != nil {+ return "", err+ }++ req := resolver.Request{+ Repository: resolver.Repository{+ Storage: in.GetRepository().GetStorageName(),+ RelativePath: in.GetRepository().GetRelativePath(),+ },+ Branch: string(in.GetBranch()),+ Tip: l.tip.String(),+ Commit: l.commitID.String(),+ Messages: resolver.Messages{Tip: l.tipMessage, Commit: l.commitMessage},+ Actor: actor,+ }+ if l.hasBase {+ req.MergeBase = l.base.String()+ }+ var checked []*landFileState+ var unchecked []string+ for _, f := range l.files {+ if !f.sent() {+ // The file may not go to the resolver: it gets the server's rules only.+ unchecked = append(unchecked, fmt.Sprintf("%s (%s)", f.conflict.path, f.reason))+ f.outcome, f.reason = gitalypb.LandConflictFile_OUTCOME_UNSPECIFIED, ""+ continue+ }+ req.Files = append(req.Files, landRequestFile(f))+ req.Resolution = append(req.Resolution, resolved[f.conflict.path])+ checked = append(checked, f)+ }+ if len(checked) == 0 {+ s.logger.WithField("unchecked", unchecked).InfoContext(ctx, "graft: no file of the agent's resolution may be sent to the resolver's checks")+ return "", nil+ }++ // Fail closed: a check that cannot run (an error, an answer that is no valid check response, a+ // resolver that does not know the check operation) fails the land with a fresh package.+ maxFiles := s.resolveCfg.MaxFilesOrDefault()+ resp, err := s.conflictResolver.Check(ctx, req)+ if err != nil {+ return "", l.notAttempted(maxFiles, fmt.Sprintf("the resolution could not be checked: %v", err), err)+ }+ if !landResolverNameValid(resp.Resolver) {+ return "", l.notAttempted(maxFiles, fmt.Sprintf("the resolution could not be checked: the check names an invalid resolver %q", resp.Resolver), nil)+ }+ syntaxUnchecked := 0+ for i, v := range resp.Files {+ f := checked[i]+ if !v.OK {+ f.outcome, f.reason = gitalypb.LandConflictFile_OUTCOME_REJECTED, v.Reason+ continue+ }+ if v.Syntax == resolver.SyntaxUnchecked {+ syntaxUnchecked+++ }+ }+ if syntaxUnchecked > 0 {+ landResolutionSyntaxUncheckedTotal.Add(float64(syntaxUnchecked))+ }+ s.logger.WithFields(log.Fields{+ "checked_by": resp.Resolver,+ "checked": len(checked),+ "syntax_unchecked": syntaxUnchecked,+ "not_checked": unchecked,+ }).InfoContext(ctx, "graft: agent's resolution checked")+ return resp.Resolver, nil+}diff --git a/internal/gitaly/service/operations/land_resolve.go b/internal/gitaly/service/operations/land_resolve.goindex 7338925..6a19124 100644--- a/internal/gitaly/service/operations/land_resolve.go+++ b/internal/gitaly/service/operations/land_resolve.go@@ -27,7 +27,8 @@ import (// resolve_conflicts, the conflicting files are sent to the configured resolver (the client of// internal/graft/resolver, which enforces the path and actor policy, the limits and every// acceptance rule of the answer). The answer is written into a merge commit with parents-// [tip, commit]. Any failure leaves the original merge conflict in place.+// [tip, commit]. Unless every file is resolved, the land fails with the original merge conflict+// and the conflict package of land_package.go.// maxResolverNameBytes bounds the name of the resolver, which is written into a commit trailer.const maxResolverNameBytes = resolver.MaxResolverNameBytes@@ -61,11 +62,15 @@ type landFileConflict struct {}// resolveLandConflicts lands commitID onto tip by resolving the files that conflict between the-// two. The result is a merge commit with parents [tip, commitID]. An error means the conflict-// could not be resolved, and the caller reports the original merge conflict.+// two. The result is a merge commit with parents [tip, commitID].//-// The policy is checked before any blob is read or the resolver is called: the actor, the number-// of conflicting files and every path must be allowed.+// Every conflicting file is decided on its own. A file that may not or cannot be sent (its path,+// its sides, or the never-send rules of resolver.SendRules) goes to the agent; the others go to+// the resolver in one request. Nothing lands partially: unless every file is resolved, the land+// fails with a *landUnresolvedError, whose conflict package says what happened to each file. A+// request the server does not attempt at all (resolution disabled, the actor not allowed, too many+// files, a criss-cross history) also gets a package, with the reason. Any other error means the+// conflicts could not even be listed, and the caller reports the merge conflict alone.func (s *Server) resolveLandConflicts(ctx context.Context,in *gitalypb.UserLandRequest,@@ -73,110 +78,237 @@ func (s *Server) resolveLandConflicts(tip, commitID git.ObjectID,committer git.Signature,) (landResolution, error) {- if s.conflictResolver == nil {- return landResolution{}, errors.New("conflict resolution is not enabled")+ l, err := landListConflicts(ctx, repo, tip, commitID)+ if err != nil {+ return landResolution{}, err}+ base, hasBase, conflicts, files := l.base, l.hasBase, l.conflicts, l.files+ tipMessage, commitMessage := l.tipMessage, l.commitMessage+ maxFiles := s.resolveCfg.MaxFilesOrDefault()+ notAttempted := func(reason string) error { return l.notAttempted(maxFiles, reason, nil) }+ criss := l.bases// The actor is the authenticated identity only. The name in the request is chosen by the// caller, so it must not decide who may resolve: without an identity the actor is empty and// only an actor list that is empty (allows everyone) admits the request.actor := identity.Actor(ctx, "")- if !s.conflictResolver.ActorAllowed(actor) {- return landResolution{}, fmt.Errorf("actor %q may not resolve conflicts", actor)+ switch {+ case s.conflictResolver == nil:+ return landResolution{}, notAttempted("conflict resolution is not enabled on this server")+ case !s.conflictResolver.ActorAllowed(actor):+ return landResolution{}, notAttempted(fmt.Sprintf("actor %q may not resolve conflicts", actor))+ case criss > 1:+ return landResolution{}, notAttempted(fmt.Sprintf("the change has %d merge bases (a criss-cross history), which are not resolved", criss))+ case len(conflicts) > maxFiles:+ return landResolution{}, notAttempted(fmt.Sprintf("%d conflicting files exceed max_files %d", len(conflicts), maxFiles))}- base, hasBase, err := landMergeBase(ctx, repo, tip, commitID)- if err != nil {+ if err := s.landClassify(ctx, repo, files, base, tip, commitID); err != nil {return landResolution{}, err}- mergedTree, conflicts, err := landMergeTree(ctx, repo, tip, commitID, base, hasBase)- if err != nil {- return landResolution{}, err- }- // A clean merge tree is not resolved here. When rebasing, the conflict may come from an- // intermediate commit that a later commit of the change undoes, so the merge of the two ends- // is clean and the landing reports the merge conflict. This is a documented limitation.- if len(conflicts) == 0 {- return landResolution{}, errors.New("the merge of the tip and the change reports no conflicting files")- }- if len(conflicts) > s.resolveCfg.MaxFilesOrDefault() {- return landResolution{}, fmt.Errorf("%d conflicting files exceed max_files", len(conflicts))- }- paths := make([]string, 0, len(conflicts))- for _, c := range conflicts {- paths = append(paths, c.path)+ var sent []resolver.File+ for _, f := range files {+ if f.sent() {+ sent = append(sent, landRequestFile(f))+ }}- for _, p := range paths {- // The paths end up in commit trailers, where a line break would inject trailers.- if !landTrailerSafe(p) {- return landResolution{}, fmt.Errorf("conflicting path %q cannot be resolved", p)++ var resp *resolver.Response+ var resolveErr error+ if len(sent) > 0 {+ req := resolver.Request{+ Version: resolver.ProtocolVersion,+ Repository: resolver.Repository{+ Storage: in.GetRepository().GetStorageName(),+ RelativePath: in.GetRepository().GetRelativePath(),+ },+ Branch: string(in.GetBranch()),+ Tip: tip.String(),+ Commit: commitID.String(),+ Messages: resolver.Messages{Tip: tipMessage, Commit: commitMessage},+ Actor: actor,+ Files: sent,}- // Git paths are bytes, but the protocol carries them as JSON strings, which hold- // Unicode text only: the resolver would see another name and its answer could never- // match. Such conflicts are not resolved.- if !utf8.ValidString(p) {- return landResolution{}, fmt.Errorf("conflicting path %q is not valid UTF-8 and cannot be sent to the resolver", p)+ if hasBase {+ req.MergeBase = base.String()}- if !s.conflictResolver.PathAllowed(p) {- return landResolution{}, fmt.Errorf("path %q may not be sent to the resolver", p)++ // The client applies the timeout, the request policy and the acceptance rules of the answer.+ resp, resolveErr = s.conflictResolver.Resolve(ctx, req)+ switch {+ case resolveErr == nil && !landResolverNameValid(resp.Resolver):+ // The name is written into the commit trailers, so it must be a plain single-line name.+ landFailSent(files, gitalypb.LandConflictFile_OUTCOME_FAILED, fmt.Sprintf("the resolver's answer names an invalid resolver %q", resp.Resolver))+ resp = nil+ case resolveErr != nil:+ landRefusalOutcomes(files, resolveErr)+ default:+ for _, f := range files {+ if f.sent() {+ f.outcome = gitalypb.LandConflictFile_OUTCOME_RESOLVED+ }+ }}}- // A rename makes a side of a conflict come from another path than the name of the conflict,- // so the policy is applied to the path of every side as well.- if err := s.landCheckSourcePaths(ctx, repo, conflicts, base, tip, commitID); err != nil {- return landResolution{}, err++ for _, f := range files {+ if f.outcome != gitalypb.LandConflictFile_OUTCOME_RESOLVED {+ return landResolution{}, l.unresolved(maxFiles, "", landUnresolvedCause(files), resolveErr)+ }}- maxBytes := s.resolveCfg.MaxFileBytesOrDefault()- files, err := landResolveFiles(ctx, repo, conflicts, maxBytes)- if err != nil {- return landResolution{}, err+ return s.landWriteResolution(ctx, in, repo, tip, commitID, l.mergedTree, committer, actor, resp, "")+}++// landListing is the conflicting files of the merge of a tip and a change, with what the conflict+// package needs.+type landListing struct {+ tip, commitID git.ObjectID+ base git.ObjectID+ hasBase bool+ // bases is the number of merge bases; more than one is a criss-cross history.+ bases int+ mergedTree git.ObjectID+ conflicts []landFileConflict+ files []*landFileState+ tipMessage, commitMessage string+}++// errLandNoConflicts is the error of landListConflicts when the merge is clean.+var errLandNoConflicts = errors.New("the merge of the tip and the change reports no conflicting files")++// landListConflicts lists the files that conflict between tip and commitID. A clean merge is an+// error: when rebasing, the conflict may come from an intermediate commit that a later commit of+// the change undoes, so the merge of the two ends is clean and the landing reports the merge+// conflict. This is a documented limitation.+func landListConflicts(ctx context.Context, repo *localrepo.Repo, tip, commitID git.ObjectID) (landListing, error) {+ l := landListing{tip: tip, commitID: commitID}+ var err error+ if l.base, l.hasBase, l.bases, err = landMergeBase(ctx, repo, tip, commitID); err != nil {+ return l, err+ }+ if l.mergedTree, l.conflicts, err = landMergeTree(ctx, repo, tip, commitID, l.base, l.hasBase); err != nil {+ return l, err+ }+ if len(l.conflicts) == 0 {+ return l, errLandNoConflicts+ }+ if l.tipMessage, err = landCommitBody(ctx, repo, tip); err != nil {+ return l, err}+ if l.commitMessage, err = landCommitBody(ctx, repo, commitID); err != nil {+ return l, err+ }+ for _, c := range l.conflicts {+ l.files = append(l.files, &landFileState{conflict: c, kind: landKindOf(c)})+ }+ return l, nil+}- tipMessage, err := landCommitBody(ctx, repo, tip)- if err != nil {- return landResolution{}, err+// unresolved returns the error of a land left unresolved, with its conflict package. err is the+// error of the resolver or of the check that caused it, if any.+func (l landListing) unresolved(maxFiles int, reason, cause string, err error) error {+ return &landUnresolvedError{+ pkg: landPackage(l.tip, l.commitID, l.base, l.tipMessage, l.commitMessage, l.files, maxFiles, reason),+ cause: cause,+ err: err,}- commitMessage, err := landCommitBody(ctx, repo, commitID)- if err != nil {- return landResolution{}, err+}++// notAttempted returns the error of a land the server did not try to resolve at all, every file+// NOT_ATTEMPTED and the package carrying the reason.+func (l landListing) notAttempted(maxFiles int, reason string, err error) error {+ for _, f := range l.files {+ f.outcome, f.reason = gitalypb.LandConflictFile_OUTCOME_NOT_ATTEMPTED, ""}+ return l.unresolved(maxFiles, reason, reason, err)+}- req := resolver.Request{- Version: resolver.ProtocolVersion,- Repository: resolver.Repository{- Storage: in.GetRepository().GetStorageName(),- RelativePath: in.GetRepository().GetRelativePath(),- },- Branch: string(in.GetBranch()),- Tip: tip.String(),- Commit: commitID.String(),- Messages: resolver.Messages{Tip: tipMessage, Commit: commitMessage},- Actor: actor,- Files: files,- Limits: resolver.Limits{MaxFileBytes: maxBytes},+// landRequestFile is the file of the resolve request for a classified file that is sent.+func landRequestFile(f *landFileState) resolver.File {+ file := resolver.File{Path: f.conflict.path, Kind: f.kind}+ for i, side := range []struct {+ blob *landBlob+ dst **resolver.Side+ }{{f.conflict.base, &file.Base}, {f.conflict.ours, &file.Ours}, {f.conflict.theirs, &file.Theirs}} {+ if side.blob != nil {+ *side.dst = &resolver.Side{OID: side.blob.oid.String(), Mode: side.blob.mode, Content: f.sides[i]}+ }}- if hasBase {- req.MergeBase = base.String()+ return file+}++// landFailSent sets the outcome and reason of every file that was sent.+func landFailSent(files []*landFileState, outcome gitalypb.LandConflictFile_Outcome, reason string) {+ for _, f := range files {+ if f.sent() {+ f.outcome, f.reason = outcome, reason+ }}+}- // The client applies the timeout, the request policy and the acceptance rules of the answer.- resp, err := s.conflictResolver.Resolve(ctx, req)- if err != nil {- return landResolution{}, fmt.Errorf("resolver failed: %w", err)+// landRefusalOutcomes sets the outcome of the sent files from the resolver's failure. A refusal+// with the outcome of every file (validated by the client) gives each its own; otherwise every+// sent file failed with the error.+func landRefusalOutcomes(files []*landFileState, err error) {+ var refusal *resolver.UnresolvableError+ if !errors.As(err, &refusal) || refusal.Files == nil {+ landFailSent(files, gitalypb.LandConflictFile_OUTCOME_FAILED, fmt.Sprintf("resolver failed: %v", err))+ return+ }+ outcomes := make(map[string]resolver.FileOutcome, len(refusal.Files))+ for _, o := range refusal.Files {+ outcomes[o.Path] = o+ }+ for _, f := range files {+ if !f.sent() {+ continue+ }+ o := outcomes[f.conflict.path]+ switch o.Outcome {+ case resolver.OutcomeResolved:+ f.outcome = gitalypb.LandConflictFile_OUTCOME_RESOLVED+ case resolver.OutcomeRejected:+ f.outcome, f.reason = gitalypb.LandConflictFile_OUTCOME_REJECTED, o.Reason+ default:+ f.outcome, f.reason = gitalypb.LandConflictFile_OUTCOME_FAILED, o.Reason+ }}+}- // The name is written into the commit trailers, so it must be a plain single-line name.- if !landResolverNameValid(resp.Resolver) {- return landResolution{}, fmt.Errorf("resolver answer names an invalid resolver %q", resp.Resolver)+// landUnresolvedCause summarizes for the log why the files were not all resolved.+func landUnresolvedCause(files []*landFileState) string {+ var parts []string+ for _, f := range files {+ if f.outcome == gitalypb.LandConflictFile_OUTCOME_RESOLVED {+ continue+ }+ parts = append(parts, fmt.Sprintf("%s: %s %s", f.conflict.path, f.outcome, f.reason))}+ return strings.Join(parts, "; ")+}+// landWriteResolution writes a resolution (the resolver's answer, or the agent's) into the merged+// tree and commits it with parents [tip, commitID]; checkedBy names the resolver that checked an+// agent's resolution, if one did. The commit message carries the trailers.+func (s *Server) landWriteResolution(+ ctx context.Context,+ in *gitalypb.UserLandRequest,+ repo *localrepo.Repo,+ tip, commitID, mergedTree git.ObjectID,+ committer git.Signature,+ actor string,+ resp *resolver.Response,+ checkedBy string,+) (landResolution, error) {tree, err := repo.ReadTree(ctx, git.Revision(mergedTree.String()), localrepo.WithRecursive())if err != nil {return landResolution{}, fmt.Errorf("reading merged tree: %w", err)}+ paths := make([]string, 0, len(resp.Files))for _, f := range resp.Files {+ paths = append(paths, f.Path)if f.Action == resolver.ActionDelete {if err := tree.Delete(f.Path); err != nil && !errors.Is(err, localrepo.ErrEntryNotFound) {return landResolution{}, fmt.Errorf("deleting %q: %w", f.Path, err)@@ -199,7 +331,7 @@ func (s *Server) resolveLandConflicts(newTip, err := repo.WriteCommit(ctx, localrepo.WriteCommitConfig{TreeID: tree.OID,- Message: landResolveCommitMessage(in, commitID, resp.Resolver, paths),+ Message: landResolveCommitMessage(in, commitID, resp.Resolver, checkedBy, paths),Parents: []git.ObjectID{tip, commitID},AuthorName: committer.Name,AuthorEmail: committer.Email,@@ -228,6 +360,7 @@ func (s *Server) resolveLandConflicts("merge_commit": newTip.String(),"actor": actor,"resolver": resp.Resolver,+ "checked_by": checkedBy,"paths": paths,"explanation": landTruncate(resp.Explanation, maxLoggedExplanationBytes),}).InfoContext(ctx, "graft: conflicts of land resolved")@@ -235,6 +368,167 @@ func (s *Server) resolveLandConflicts(return landResolution{commit: newTip, resolvedPaths: resolvedPaths, resolver: resp.Resolver}, nil}+// landClassify decides, for every file, whether it may be sent to the resolver, and reads the+// sides of those that may (and of those whose content decided against it, for the hunks of the+// package). The order: the path (a commit trailer must carry it, the protocol must carry it, the+// path policy must allow it and every path its sides come from), the shape of the sides, their+// size (from the object info, before reading), then the content rules of resolver.SendRules, with+// linguist-generated from the tip's attributes.+func (s *Server) landClassify(+ ctx context.Context,+ repo *localrepo.Repo,+ files []*landFileState,+ base, tip, commitID git.ObjectID,+) error {+ rules := s.conflictResolver.SendRules()+ listings := map[git.ObjectID]map[git.ObjectID][]string{}+ for _, f := range files {+ c := f.conflict+ switch {+ case !landTrailerSafe(c.path):+ f.notSent(landNotSentTrailerUnsafe)+ continue+ case !utf8.ValidString(c.path):+ f.notSent(landNotSentInvalidUTF8)+ continue+ case !s.conflictResolver.PathAllowed(c.path):+ f.notSent(landNotSentDenied)+ continue+ case landShapeReason(c) != "":+ f.notSent(landShapeReason(c))+ continue+ }+ // A rename makes a side come from another path than the name of the conflict, so the+ // policy is applied to the path of every side as well.+ denied, err := s.landDeniedSource(ctx, repo, listings, c, base, tip, commitID)+ if err != nil {+ return err+ }+ if denied != "" {+ f.notSent(denied)+ continue+ }++ tooLarge := false+ for _, b := range []*landBlob{c.base, c.ours, c.theirs} {+ if b == nil {+ continue+ }+ switch b.mode {+ case resolver.ModeRegular, resolver.ModeExecutable, resolver.ModeSymlink:+ default:+ f.notSent(landNotSentNotAFile)+ }+ if !f.sent() {+ break+ }+ info, err := repo.ReadObjectInfo(ctx, b.oid.Revision())+ if err != nil {+ return fmt.Errorf("reading size of %q: %w", c.path, err)+ }+ if rules.TooLarge(info.Size) {+ tooLarge = true+ }+ }+ if !f.sent() {+ continue+ }+ if tooLarge {+ f.notSent(resolver.NotSentLarge)+ continue+ }+ for i, b := range []*landBlob{c.base, c.ours, c.theirs} {+ if b == nil {+ continue+ }+ content, err := repo.ReadObject(ctx, b.oid)+ if err != nil {+ return fmt.Errorf("reading blob of %q: %w", c.path, err)+ }+ if content == nil {+ content = []byte{}+ }+ f.sides[i] = content+ }+ f.read = true+ }++ // The content rules, with linguist-generated read for every remaining path at once.+ var candidates []string+ for _, f := range files {+ if f.sent() {+ candidates = append(candidates, f.conflict.path)+ }+ }+ generated, err := landGeneratedPaths(ctx, repo, tip, candidates)+ if err != nil {+ return err+ }+ for _, f := range files {+ if !f.sent() {+ continue+ }+ if reason := rules.Reason(f.conflict.path, generated[f.conflict.path], f.sides[0], f.sides[1], f.sides[2]); reason != "" {+ f.notSent(reason)+ }+ }+ return nil+}++// landShapeReason returns why the shape of the sides keeps a conflict from the resolver, or "". A+// file/directory conflict has no version of the file on either side under its name. A conflict+// whose base is absent while one side is absent is not a conflict between two versions of a file,+// since no merge produces it without a rename; it cannot be answered reliably, so it fails closed.+func landShapeReason(c landFileConflict) string {+ switch {+ case c.ours == nil && c.theirs == nil:+ return landNotSentNoSide+ case c.base == nil && (c.ours == nil || c.theirs == nil):+ return landNotSentNoBaseOneSide+ }+ return ""+}++// landDeniedSource returns the reason when a side of the conflict comes from a path that may not+// be sent, and "" when every side's path may. merge-tree names a conflict after the path of the+// merged tree, but with a rename a side comes from another path: the base and one side may live+// under the old name. Without this check the content of a denied path could reach the resolver+// under an allowed name.+//+// A side lives at the name of the conflict when the tree of its commit holds the same blob there.+// Otherwise every path of that tree holding the blob is a possible source, and all of them must be+// allowed. A side whose blob is in no path of its tree is not sent, nor is a base when the merge+// has none to look it up in. Only trees are read, no blob.+func (s *Server) landDeniedSource(+ ctx context.Context,+ repo *localrepo.Repo,+ listings map[git.ObjectID]map[git.ObjectID][]string,+ c landFileConflict,+ base, tip, commitID git.ObjectID,+) (string, error) {+ for _, side := range []landSide{{c.base, base}, {c.ours, tip}, {c.theirs, commitID}} {+ if side.blob == nil {+ continue+ }+ if side.rev == "" {+ return "the path has a base side but the merge has no merge base to find it in", nil+ }+ sources, err := landSourcePaths(ctx, repo, listings, side.rev, side.blob.oid, c.path)+ if err != nil {+ return "", err+ }+ if len(sources) == 0 {+ return fmt.Sprintf("a side is in no path of %s", side.rev), nil+ }+ for _, p := range sources {+ if !landTrailerSafe(p) || !s.conflictResolver.PathAllowed(p) {+ return fmt.Sprintf("a side comes from path %q, which may not be sent to the resolver", p), nil+ }+ }+ }+ return "", nil+}+// landTrailerSafe reports whether s can be written as a single line of a commit trailer: it must// hold no line break and no NUL byte.func landTrailerSafe(s string) bool {@@ -272,47 +566,9 @@ type landSide struct {rev git.ObjectID}-// landCheckSourcePaths applies the path policy to the path every side of every conflict comes-// from. merge-tree names a conflict after the path of the merged tree, but with a rename a side-// comes from another path: the base and one side may live under the old name. Without this check-// the content of a denied path could reach the resolver under an allowed name.-//-// A side lives at the name of the conflict when the tree of its commit holds the same blob there.-// Otherwise every path of that tree holding the blob is a possible source, and all of them must-// be allowed. A side whose blob is in no path of its tree is refused, as is any side when there is-// no merge base to look it up in. Only trees are read, no blob.-func (s *Server) landCheckSourcePaths(- ctx context.Context,- repo *localrepo.Repo,- conflicts []landFileConflict,- base, tip, commitID git.ObjectID,-) error {- listings := map[git.ObjectID]map[git.ObjectID][]string{}- for _, c := range conflicts {- for _, side := range []landSide{{c.base, base}, {c.ours, tip}, {c.theirs, commitID}} {- if side.blob == nil {- continue- }- if side.rev == "" {- return fmt.Errorf("conflicting path %q has a base but the merge has none", c.path)- }-- sources, err := landSourcePaths(ctx, repo, listings, side.rev, side.blob.oid, c.path)- if err != nil {- return err- }- for _, p := range sources {- if !landTrailerSafe(p) || !s.conflictResolver.PathAllowed(p) {- return fmt.Errorf("conflicting path %q comes from path %q, which may not be sent to the resolver", c.path, p)- }- }- }- }- return nil-}-// landSourcePaths returns the paths of the tree of rev that the blob of a side of the conflict p-// may come from. listings caches the listing of every tree read, by commit.+// may come from, none when the blob is in no path. listings caches the listing of every tree+// read, by commit.func landSourcePaths(ctx context.Context,repo *localrepo.Repo,@@ -338,11 +594,7 @@ func landSourcePaths(listings[rev] = listing}- sources := listing[blob]- if len(sources) == 0 {- return nil, fmt.Errorf("a side of conflicting path %q is in no path of %s", p, rev)- }- return sources, nil+ return listing[blob], nil}// landListTree lists the tree of rev recursively and returns the paths of every object it holds.@@ -391,7 +643,7 @@ func landListTree(ctx context.Context, repo *localrepo.Repo, rev git.ObjectID) (// landResolveCommitMessage returns the message of the resolution commit: the merge message or// the default one, followed by the Graft-Resolved trailers.-func landResolveCommitMessage(in *gitalypb.UserLandRequest, commitID git.ObjectID, resolverName string, paths []string) string {+func landResolveCommitMessage(in *gitalypb.UserLandRequest, commitID git.ObjectID, resolverName, checkedBy string, paths []string) string {subject := strings.TrimRight(string(in.GetMergeMessage()), "\n")if subject == "" {subject = fmt.Sprintf("Merge %s into %s", landShortOID(commitID), string(in.GetBranch()))@@ -401,6 +653,11 @@ func landResolveCommitMessage(in *gitalypb.UserLandRequest, commitID git.ObjectIb.WriteString(subject)b.WriteString("\n\n")b.WriteString("Graft-Resolved-By: " + resolverName + "\n")+ // An agent's resolution records whether the resolver's checks ran on it: without a resolver+ // it got only the marker rule and the server's structural validation.+ if checkedBy != "" {+ b.WriteString("Graft-Checked-By: " + checkedBy + "\n")+ }for _, p := range paths {b.WriteString("Graft-Resolved-Path: " + p + "\n")}@@ -426,10 +683,11 @@ func landCommitBody(ctx context.Context, repo *localrepo.Repo, commit git.Objectreturn string(c.GetBody()), nil}-// landMergeBase returns the merge base of a and b. Unrelated histories have none. Criss-cross-// histories have several merge bases, and the base the resolver is given would then differ from-// the base of the recursive merge strategy. Such landings are not resolved.-func landMergeBase(ctx context.Context, repo *localrepo.Repo, a, b git.ObjectID) (git.ObjectID, bool, error) {+// landMergeBase returns the merge base of a and b. Unrelated histories have none. A criss-cross+// history has several merge bases, whose number is returned: the base the resolver would be given+// would differ from the base of the recursive merge strategy, so such landings are not resolved,+// and hasBase is false.+func landMergeBase(ctx context.Context, repo *localrepo.Repo, a, b git.ObjectID) (base git.ObjectID, hasBase bool, bases int, err error) {var stdout, stderr bytes.Bufferif err := repo.ExecAndWait(ctx,gitcmd.Command{Name: "merge-base", Flags: []gitcmd.Option{gitcmd.Flag{Name: "--all"}}, Args: []string{a.String(), b.String()}},@@ -437,28 +695,25 @@ func landMergeBase(ctx context.Context, repo *localrepo.Repo, a, b git.ObjectID)gitcmd.WithStderr(&stderr),); err != nil {if exitStatus, ok := command.ExitStatus(err); ok && exitStatus == 1 {- return "", false, nil+ return "", false, 0, nil}- return "", false, fmt.Errorf("merge-base: %w, stderr: %q", err, stderr.String())+ return "", false, 0, fmt.Errorf("merge-base: %w, stderr: %q", err, stderr.String())}- bases := strings.Fields(stdout.String())- if len(bases) == 0 {- return "", false, nil- }- if len(bases) > 1 {- return "", false, fmt.Errorf("the change has %d merge bases (criss-cross history), which are not resolved", len(bases))+ all := strings.Fields(stdout.String())+ if len(all) != 1 {+ return "", false, len(all), nil}objectHash, err := repo.ObjectHash(ctx)if err != nil {- return "", false, fmt.Errorf("detecting object hash: %w", err)+ return "", false, 0, fmt.Errorf("detecting object hash: %w", err)}- base, err := objectHash.FromHex(bases[0])+ base, err = objectHash.FromHex(all[0])if err != nil {- return "", false, fmt.Errorf("parsing merge base: %w", err)+ return "", false, 0, fmt.Errorf("parsing merge base: %w", err)}- return base, true, nil+ return base, true, 1, nil}// landMergeTree runs merge-tree of tip and commitID. It returns the tree of the merge, which holds@@ -556,97 +811,6 @@ func landMergeTree(return treeOID, conflicts, nil}-// landResolveFiles returns the base, ours and theirs versions of the conflicting files.-func landResolveFiles(- ctx context.Context,- repo *localrepo.Repo,- conflicts []landFileConflict,- maxBytes int64,-) ([]resolver.File, error) {- files := make([]resolver.File, 0, len(conflicts))- for _, c := range conflicts {- f := resolver.File{Path: c.path}-- var err error- if f.Base, err = landReadSide(ctx, repo, c.base, c.path, maxBytes); err != nil {- return nil, err- }- if f.Ours, err = landReadSide(ctx, repo, c.ours, c.path, maxBytes); err != nil {- return nil, err- }- if f.Theirs, err = landReadSide(ctx, repo, c.theirs, c.path, maxBytes); err != nil {- return nil, err- }-- if err := landCheckSides(f); err != nil {- return nil, err- }-- f.Kind = landConflictKind(f)- files = append(files, f)- }- return files, nil-}--// landCheckSides rejects the shapes of the sides that the conflict cannot have for a file that-// both ends can answer. A file/directory conflict has no version of the file on one side under-// its name, so no side is present and the file is not sent. A conflict whose base is absent while-// one side is absent is not a conflict between two versions of a file, since no merge produces it-// without a rename. It cannot be answered reliably, so it fails closed.-func landCheckSides(f resolver.File) error {- if f.Ours == nil && f.Theirs == nil {- return fmt.Errorf("conflicting path %q is on neither side of the merge, which is a file/directory conflict", f.Path)- }- if f.Base == nil && (f.Ours == nil || f.Theirs == nil) {- return fmt.Errorf("conflicting path %q has no base and a missing side, which is not resolved", f.Path)- }- return nil-}--// landReadSide reads the version of a conflicting file from its stage entry. It returns nil if the-// side is absent. Sides that are not files, or larger than maxBytes, are an error because they-// cannot be sent.-func landReadSide(ctx context.Context, repo *localrepo.Repo, blob *landBlob, p string, maxBytes int64) (*resolver.Side, error) {- if blob == nil {- return nil, nil- }-- switch blob.mode {- case resolver.ModeRegular, resolver.ModeExecutable, resolver.ModeSymlink:- default:- return nil, fmt.Errorf("path %q is not a file on one side of the conflict", p)- }-- info, err := repo.ReadObjectInfo(ctx, blob.oid.Revision())- if err != nil {- return nil, fmt.Errorf("reading size of %q: %w", p, err)- }- if info.Size > maxBytes {- return nil, fmt.Errorf("file %q is %d bytes, larger than max_file_bytes", p, info.Size)- }-- content, err := repo.ReadObject(ctx, blob.oid)- if err != nil {- return nil, fmt.Errorf("reading blob of %q: %w", p, err)- }-- return &resolver.Side{OID: blob.oid.String(), Mode: blob.mode, Content: content}, nil-}--// landConflictKind classifies a conflicting file from the presence of its versions.-func landConflictKind(f resolver.File) string {- switch {- case f.Ours == nil || f.Theirs == nil:- return resolver.KindModifyDelete- case f.Base == nil:- return resolver.KindAddAdd- case f.Ours.OID == f.Theirs.OID:- return resolver.KindMode- default:- return resolver.KindContent- }-}-// isLandMergeConflict reports whether a landing failed because the change does not apply cleanly// onto the tip.func isLandMergeConflict(err error) bool {diff --git a/internal/gitaly/service/operations/land_resolve_paths_test.go b/internal/gitaly/service/operations/land_resolve_paths_test.goindex 454f1b6..7b25bd3 100644--- a/internal/gitaly/service/operations/land_resolve_paths_test.go+++ b/internal/gitaly/service/operations/land_resolve_paths_test.go@@ -84,15 +84,20 @@ func TestUserLand_fileDirectoryConflictIsNotResolved(t *testing.T) {}}-// TestLandResolveFiles_absentFromBothSides checks the fail-closed rule directly: a conflicting path-// that is on neither side yields no request file, so no modify-delete without sides is sent.-func TestLandResolveFiles_absentFromBothSides(t *testing.T) {+// TestLandClassify_absentFromBothSides checks the fail-closed rule directly: a conflicting path+// that is on neither side is not sent, so no modify-delete without sides reaches the resolver.+func TestLandClassify_absentFromBothSides(t *testing.T) {t.Parallel()- fx := newResolveFixture(t, config.GraftResolver{})+ _, argv := resolverScript(t, "")+ rcfg := enabledResolver(argv)+ fx := newResolveFixture(t, rcfg)+ s := fx.server(t, rcfg)- _, err := landResolveFiles(fx.ctx, fx.repo, []landFileConflict{{path: "x~" + fx.tip.String()}}, 1048576)- require.ErrorContains(t, err, "neither side of the merge")+ f := &landFileState{conflict: landFileConflict{path: "x~" + fx.tip.String()}}+ require.NoError(t, s.landClassify(fx.ctx, fx.repo, []*landFileState{f}, fx.base, fx.tip, fx.commit))+ require.Equal(t, gitalypb.LandConflictFile_OUTCOME_NOT_SENT, f.outcome)+ require.Equal(t, landNotSentNoSide, f.reason)}// TestUserLand_pathStartingWithDashIsResolved covers a conflicting path that starts with a dash.diff --git a/internal/gitaly/service/operations/land_resolve_rename_test.go b/internal/gitaly/service/operations/land_resolve_rename_test.goindex 2b6f2a1..f5a71b1 100644--- a/internal/gitaly/service/operations/land_resolve_rename_test.go+++ b/internal/gitaly/service/operations/land_resolve_rename_test.go@@ -11,6 +11,7 @@ import ("github.com/feder-cr/git-ai/internal/git/gittest""github.com/feder-cr/git-ai/internal/gitaly/config""github.com/feder-cr/git-ai/internal/graft/resolver"+ "github.com/feder-cr/git-ai/proto/go/gitalypb")// renameFileContent returns a 12-line file whose line 6 is line6. A rename and an edit of the same@@ -181,9 +182,13 @@ func TestUserLand_renameFromDeniedPathIsNotResolved(t *testing.T) {tc.tip, tc.commit,)- // Directly, the reason is the source path of the side.+ // Directly, the file is not sent, and the package names the source path of the side._, err := fx.server(t, rcfg).resolveLandConflicts(fx.ctx, fx.request("Land rename"), fx.repo, fx.tip, fx.commit, fx.committer())- require.ErrorContains(t, err, `conflicting path "pub/k" comes from path "secrets/k"`)+ var unresolved *landUnresolvedError+ require.ErrorAs(t, err, &unresolved)+ k := packageFile(t, unresolved.pkg, "pub/k")+ require.Equal(t, gitalypb.LandConflictFile_OUTCOME_NOT_SENT, k.GetOutcome())+ require.Equal(t, `a side comes from path "secrets/k", which may not be sent to the resolver`, k.GetReason())require.Equal(t, 0, resolverCalls(t, dir))// Through the RPC, the landing keeps the merge conflict.@@ -271,37 +276,34 @@ func TestLandSourcePaths(t *testing.T) {require.Equal(t, []string{"u"}, got)require.Len(t, listings, 1)- _, err = landSourcePaths(fx.ctx, fx.repo, listings, fx.base, absent, "a")- require.ErrorContains(t, err, "is in no path of")+ // A blob in no path of the tree has no source: the classification does not send the file.+ got, err = landSourcePaths(fx.ctx, fx.repo, listings, fx.base, absent, "a")+ require.NoError(t, err)+ require.Empty(t, got)}// TestLandCheckSides covers the shapes of the sides that are not resolved.-func TestLandCheckSides(t *testing.T) {+func TestLandShapeReason(t *testing.T) {t.Parallel()- side := &resolver.Side{OID: "o", Mode: resolver.ModeRegular, Content: []byte("x")}+ side := &landBlob{mode: resolver.ModeRegular, oid: "o"}for _, tc := range []struct {- name string- file resolver.File- wantErr string+ name string+ c landFileConflict+ want string}{- {name: "content", file: resolver.File{Path: "a", Base: side, Ours: side, Theirs: side}},- {name: "add-add", file: resolver.File{Path: "a", Ours: side, Theirs: side}},- {name: "modify-delete with base", file: resolver.File{Path: "a", Base: side, Ours: side}},- {name: "modify-delete with base on theirs", file: resolver.File{Path: "a", Base: side, Theirs: side}},- {name: "neither side", file: resolver.File{Path: "a", Base: side}, wantErr: "neither side"},- {name: "no sides", file: resolver.File{Path: "a"}, wantErr: "neither side"},- {name: "no base, ours missing", file: resolver.File{Path: "a", Theirs: side}, wantErr: "no base and a missing side"},- {name: "no base, theirs missing", file: resolver.File{Path: "a", Ours: side}, wantErr: "no base and a missing side"},+ {name: "content", c: landFileConflict{path: "a", base: side, ours: side, theirs: side}},+ {name: "add-add", c: landFileConflict{path: "a", ours: side, theirs: side}},+ {name: "modify-delete with base", c: landFileConflict{path: "a", base: side, ours: side}},+ {name: "modify-delete with base on theirs", c: landFileConflict{path: "a", base: side, theirs: side}},+ {name: "neither side", c: landFileConflict{path: "a", base: side}, want: landNotSentNoSide},+ {name: "no sides", c: landFileConflict{path: "a"}, want: landNotSentNoSide},+ {name: "no base, ours missing", c: landFileConflict{path: "a", theirs: side}, want: landNotSentNoBaseOneSide},+ {name: "no base, theirs missing", c: landFileConflict{path: "a", ours: side}, want: landNotSentNoBaseOneSide},} {t.Run(tc.name, func(t *testing.T) {- err := landCheckSides(tc.file)- if tc.wantErr == "" {- require.NoError(t, err)- return- }- require.ErrorContains(t, err, tc.wantErr)+ require.Equal(t, tc.want, landShapeReason(tc.c))})}}diff --git a/internal/gitaly/service/operations/land_resolve_test.go b/internal/gitaly/service/operations/land_resolve_test.goindex f4ee945..6285d70 100644--- a/internal/gitaly/service/operations/land_resolve_test.go+++ b/internal/gitaly/service/operations/land_resolve_test.go@@ -491,30 +491,55 @@ func TestResolveLandConflicts_policy(t *testing.T) {fx := newResolveFixture(t, config.GraftResolver{})+ // A path the policy denies is not sent; the other conflicting file still is (PLAN10 3.4). The+ // land fails, since nothing lands partially, and the package names the denied path.for _, tc := range []struct {- desc string- rcfg func(config.GraftResolver) config.GraftResolver- errContains string+ desc string+ rcfg func(config.GraftResolver) config.GraftResolver+ }{+ {desc: "denied path", rcfg: func(r config.GraftResolver) config.GraftResolver { r.PathsDeny = []string{"a"}; return r }},+ {desc: "path outside the allow list", rcfg: func(r config.GraftResolver) config.GraftResolver { r.PathsAllow = []string{"b"}; return r }},+ } {+ t.Run(tc.desc, func(t *testing.T) {+ dir, argv := resolverScript(t, "")+ writeAnswer(t, dir, resolver.Response{+ Version: resolver.ProtocolVersion,+ Resolver: "graft-resolve/fake",+ Files: []resolver.ResponseFile{{Path: "b", Action: resolver.ActionWrite, Mode: resolver.ModeRegular, Content: []byte("merged-b\n")}},+ })+ s := fx.server(t, tc.rcfg(enabledResolver(argv)))++ _, err := s.resolveLandConflicts(fx.ctx, fx.request("Land"), fx.repo, fx.tip, fx.commit, fx.committer())+ var unresolved *landUnresolvedError+ require.ErrorAs(t, err, &unresolved)+ a := packageFile(t, unresolved.pkg, "a")+ require.Equal(t, gitalypb.LandConflictFile_OUTCOME_NOT_SENT, a.GetOutcome())+ require.Equal(t, landNotSentDenied, a.GetReason())+ require.Equal(t, gitalypb.LandConflictFile_OUTCOME_RESOLVED, packageFile(t, unresolved.pkg, "b").GetOutcome())++ require.Equal(t, 1, resolverCalls(t, dir))+ req := resolverRequest(t, dir, 1)+ require.Len(t, req.Files, 1, "the denied path never reaches the resolver")+ require.Equal(t, "b", req.Files[0].Path)+ })+ }++ // A refusal of the whole request is decided before the resolver is called, and every file is+ // not attempted.+ for _, tc := range []struct {+ desc string+ rcfg func(config.GraftResolver) config.GraftResolver+ reason string}{{- desc: "denied path",- rcfg: func(r config.GraftResolver) config.GraftResolver { r.PathsDeny = []string{"a"}; return r },- errContains: `path "a" may not be sent to the resolver`,- },- {- desc: "path outside the allow list",- rcfg: func(r config.GraftResolver) config.GraftResolver { r.PathsAllow = []string{"docs/**"}; return r },- errContains: "may not be sent to the resolver",- },- {- desc: "actor not allowed",- rcfg: func(r config.GraftResolver) config.GraftResolver { r.Actors = []string{"someone-else"}; return r },- errContains: "may not resolve conflicts",+ desc: "actor not allowed",+ rcfg: func(r config.GraftResolver) config.GraftResolver { r.Actors = []string{"someone-else"}; return r },+ reason: "may not resolve conflicts",},{- desc: "more conflicting files than max_files",- rcfg: func(r config.GraftResolver) config.GraftResolver { r.MaxFiles = 1; return r },- errContains: "exceed max_files",+ desc: "more conflicting files than max_files",+ rcfg: func(r config.GraftResolver) config.GraftResolver { r.MaxFiles = 1; return r },+ reason: "exceed max_files",},} {t.Run(tc.desc, func(t *testing.T) {@@ -523,8 +548,12 @@ func TestResolveLandConflicts_policy(t *testing.T) {s := fx.server(t, tc.rcfg(enabledResolver(argv)))_, err := s.resolveLandConflicts(fx.ctx, fx.request("Land"), fx.repo, fx.tip, fx.commit, fx.committer())- require.ErrorContains(t, err, tc.errContains)- // Policy is checked before the resolver is called.+ var unresolved *landUnresolvedError+ require.ErrorAs(t, err, &unresolved)+ require.Contains(t, unresolved.pkg.GetReason(), tc.reason)+ for _, f := range unresolved.pkg.GetFiles() {+ require.Equal(t, gitalypb.LandConflictFile_OUTCOME_NOT_ATTEMPTED, f.GetOutcome())+ }require.Equal(t, 0, resolverCalls(t, dir))})}@@ -676,7 +705,7 @@ func TestLandResolveCommitMessage(t *testing.T) {in := &gitalypb.UserLandRequest{Branch: []byte("main"), MergeMessage: []byte("Custom\n\n")}require.Equal(t,"Custom\n\nGraft-Resolved-By: graft-resolve/x\nGraft-Resolved-Path: a\nGraft-Resolved-Path: dir/b c\n",- landResolveCommitMessage(in, commit, "graft-resolve/x", []string{"a", "dir/b c"}),+ landResolveCommitMessage(in, commit, "graft-resolve/x", "", []string{"a", "dir/b c"}),)})@@ -684,29 +713,29 @@ func TestLandResolveCommitMessage(t *testing.T) {in := &gitalypb.UserLandRequest{Branch: []byte("main")}require.Equal(t,"Merge 1111111 into main\n\nGraft-Resolved-By: graft-resolve/x\nGraft-Resolved-Path: a\n",- landResolveCommitMessage(in, commit, "graft-resolve/x", []string{"a"}),+ landResolveCommitMessage(in, commit, "graft-resolve/x", "", []string{"a"}),)})}-func TestLandConflictKind(t *testing.T) {+func TestLandKindOf(t *testing.T) {t.Parallel()- side := func(oid string) *resolver.Side { return &resolver.Side{OID: oid, Mode: "100644"} }+ side := func(oid string) *landBlob { return &landBlob{mode: "100644", oid: git.ObjectID(oid)} }for _, tc := range []struct {desc string- file resolver.File+ c landFileConflictwant string}{- {desc: "content", file: resolver.File{Base: side("b"), Ours: side("o"), Theirs: side("t")}, want: resolver.KindContent},- {desc: "add-add", file: resolver.File{Ours: side("o"), Theirs: side("t")}, want: resolver.KindAddAdd},- {desc: "modify-delete, theirs deleted", file: resolver.File{Base: side("b"), Ours: side("o")}, want: resolver.KindModifyDelete},- {desc: "modify-delete, ours deleted", file: resolver.File{Base: side("b"), Theirs: side("t")}, want: resolver.KindModifyDelete},- {desc: "mode", file: resolver.File{Base: side("b"), Ours: side("o"), Theirs: side("o")}, want: resolver.KindMode},+ {desc: "content", c: landFileConflict{base: side("b"), ours: side("o"), theirs: side("t")}, want: resolver.KindContent},+ {desc: "add-add", c: landFileConflict{ours: side("o"), theirs: side("t")}, want: resolver.KindAddAdd},+ {desc: "modify-delete, theirs deleted", c: landFileConflict{base: side("b"), ours: side("o")}, want: resolver.KindModifyDelete},+ {desc: "modify-delete, ours deleted", c: landFileConflict{base: side("b"), theirs: side("t")}, want: resolver.KindModifyDelete},+ {desc: "mode", c: landFileConflict{base: side("b"), ours: side("o"), theirs: side("o")}, want: resolver.KindMode},} {t.Run(tc.desc, func(t *testing.T) {- require.Equal(t, tc.want, landConflictKind(tc.file))+ require.Equal(t, tc.want, landKindOf(tc.c))})}}diff --git a/internal/graft/resolver/check.go b/internal/graft/resolver/check.gonew file mode 100644index 0000000..3e3838b--- /dev/null+++ b/internal/graft/resolver/check.go@@ -0,0 +1,91 @@+package resolver++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+)++// ErrCheckUnsupported is returned by Check when the resolver answers a check request with+// something other than a check response, as a resolver that predates the check operation does.+var ErrCheckUnsupported = errors.New("the resolver does not support the check operation")++// Check asks the resolver to check an agent's resolution of the request's files with the checks+// of its own answers (OperationCheck). It returns the response, with one verdict per file of+// req.Resolution in its order. It fails closed: an error, a refusal, or an answer that is not a+// check response with one verdict per file in order is an error, and the caller must not land the+// resolution.+func (c *Client) Check(ctx context.Context, req Request) (*CheckResponse, error) {+ if c == nil {+ return nil, ErrDisabled+ }++ req.Version = ProtocolVersion+ req.Operation = OperationCheck+ req.Limits = Limits{MaxFileBytes: c.maxFileBytes}++ if err := c.checkRequest(req); err != nil {+ return nil, err+ }+ if len(req.Resolution) != len(req.Files) {+ return nil, fmt.Errorf("check request: %d resolved files for %d conflicting files", len(req.Resolution), len(req.Files))+ }+ for _, f := range req.Resolution {+ if int64(len(f.Content)) > c.maxFileBytes {+ return nil, fmt.Errorf("check request: resolved %q is %d bytes, limit is %d", f.Path, len(f.Content), c.maxFileBytes)+ }+ }++ body, err := json.Marshal(req)+ if err != nil {+ return nil, fmt.Errorf("encode check request: %w", err)+ }++ ctx, cancel := context.WithTimeout(ctx, c.timeout)+ defer cancel()++ // The answer is a verdict per file, without content.+ limit := int64(maxEnvelopeBytes) + int64(len(req.Resolution))*(maxCheckVerdictBytes)++ var raw []byte+ if c.url != "" {+ raw, err = c.callHTTP(ctx, body, limit)+ } else {+ raw, err = c.callCommand(ctx, body, limit)+ }+ if err != nil {+ if errors.Is(ctx.Err(), context.DeadlineExceeded) {+ return nil, fmt.Errorf("resolver check timed out after %s: %w", c.timeout, ctx.Err())+ }+ return nil, fmt.Errorf("resolver check: %w", err)+ }++ var resp CheckResponse+ if err := json.Unmarshal(raw, &resp); err != nil {+ return nil, fmt.Errorf("%w: %w", ErrInvalidResponse, err)+ }+ if resp.Operation != OperationCheck {+ return nil, ErrCheckUnsupported+ }+ if resp.Version != ProtocolVersion {+ return nil, fmt.Errorf("%w: check response version %d", ErrInvalidResponse, resp.Version)+ }+ if len(resp.Files) != len(req.Resolution) {+ return nil, fmt.Errorf("%w: %d verdicts for %d files", ErrInvalidResponse, len(resp.Files), len(req.Resolution))+ }+ for i, v := range resp.Files {+ if v.Path != req.Resolution[i].Path {+ return nil, fmt.Errorf("%w: verdict %d is for %q, not %q", ErrInvalidResponse, i, v.Path, req.Resolution[i].Path)+ }+ switch v.Syntax {+ case SyntaxChecked, SyntaxUnchecked, SyntaxNone:+ default:+ return nil, fmt.Errorf("%w: verdict for %q has syntax %q", ErrInvalidResponse, v.Path, v.Syntax)+ }+ }+ return &resp, nil+}++// maxCheckVerdictBytes bounds the answer of one file of a check: its path and a reason.+const maxCheckVerdictBytes = 8 << 10diff --git a/internal/graft/resolver/client.go b/internal/graft/resolver/client.goindex b0d6769..6ca2f4c 100644--- a/internal/graft/resolver/client.go+++ b/internal/graft/resolver/client.go@@ -32,6 +32,36 @@ var ErrInvalidResponse = errors.New("invalid resolver response")// stderr or the 422 error message).type UnresolvableError struct {Reason string+ // Files are the resolver's outcomes per requested file, when it gave them+ // (the "files" member of the refusal). Resolve keeps them only when there is+ // exactly one per requested path, each with a known outcome; otherwise Files+ // is nil and every file shares Reason.+ Files []FileOutcome+}++// validOutcomes returns files when it has exactly one entry per requested path+// with a known outcome, and nil otherwise: a malformed list is not trusted in+// part.+func validOutcomes(req Request, files []FileOutcome) []FileOutcome {+ if len(files) != len(req.Files) {+ return nil+ }+ want := make(map[string]bool, len(req.Files))+ for _, f := range req.Files {+ want[f.Path] = true+ }+ for _, f := range files {+ switch f.Outcome {+ case OutcomeResolved, OutcomeRejected, OutcomeFailed:+ default:+ return nil+ }+ if !want[f.Path] {+ return nil+ }+ delete(want, f.Path)+ }+ return files}// Error implements error.@@ -57,6 +87,13 @@ type Client struct {pathsDeny []stringactors []stringhttpClient *http.Client+ // sendRules decide the files that are never sent (SendRules).+ sendRules *SendRules+}++// SendRules returns the rules of the files that are never sent to this resolver.+func (c *Client) SendRules() *SendRules {+ return c.sendRules}// New builds the resolver client from the configuration. It returns a nil@@ -84,6 +121,10 @@ func New(cfg config.GraftResolver) (*Client, error) {return nil, errors.New("graft land resolver: max_files and max_file_bytes must not be negative")}+ rules, err := NewSendRules(cfg)+ if err != nil {+ return nil, err+ }c := &Client{command: slices.Clone(cfg.Command),timeout: timeout,@@ -92,6 +133,7 @@ func New(cfg config.GraftResolver) (*Client, error) {pathsAllow: slices.Clone(cfg.PathsAllow),pathsDeny: slices.Clone(cfg.PathsDeny),actors: slices.Clone(cfg.Actors),+ sendRules: rules,}if cfg.URL != "" {@@ -165,6 +207,10 @@ func (c *Client) Resolve(ctx context.Context, req Request) (*Response, error) {return nil, fmt.Errorf("resolver timed out after %s: %w", c.timeout, ctx.Err())}+ var refusal *UnresolvableError+ if errors.As(err, &refusal) {+ refusal.Files = validOutcomes(req, refusal.Files)+ }return nil, err}diff --git a/internal/graft/resolver/client_test.go b/internal/graft/resolver/client_test.goindex 63589df..a81f003 100644--- a/internal/graft/resolver/client_test.go+++ b/internal/graft/resolver/client_test.go@@ -534,10 +534,42 @@ func TestResolve_ConcurrentCalls(t *testing.T) {}}-func TestRefusalReason(t *testing.T) {+func TestParseRefusal(t *testing.T) {t.Parallel()- require.Equal(t, "no", refusalReason(strings.NewReader(`{"error":"no"}`)))- require.Equal(t, defaultRefusalReason, refusalReason(strings.NewReader(`not json`)))- require.Equal(t, defaultRefusalReason, refusalReason(strings.NewReader(`{"error":" "}`)))+ refusal, ok := parseRefusal([]byte(`{"error":"no"}`))+ require.True(t, ok)+ require.Equal(t, "no", refusal.Reason)+ require.Nil(t, refusal.Files)++ refusal, ok = parseRefusal([]byte(`{"error":"no","files":[{"path":"a","outcome":"rejected","reason":"syntax"}]}`))+ require.True(t, ok)+ require.Equal(t, []FileOutcome{{Path: "a", Outcome: OutcomeRejected, Reason: "syntax"}}, refusal.Files)++ refusal, ok = parseRefusal([]byte(`{"error":"` + strings.Repeat("x", maxErrorBodyBytes+10) + `"}`))+ require.True(t, ok)+ require.Len(t, refusal.Reason, maxErrorBodyBytes)++ for _, raw := range []string{`not json`, `{"error":" "}`, `{"version":1,"files":[]}`} {+ _, ok := parseRefusal([]byte(raw))+ require.False(t, ok, raw)+ }+}++func TestValidOutcomes(t *testing.T) {+ t.Parallel()++ req := Request{Files: []File{{Path: "a"}, {Path: "b"}}}+ good := []FileOutcome{{Path: "b", Outcome: OutcomeFailed}, {Path: "a", Outcome: OutcomeResolved}}+ require.Equal(t, good, validOutcomes(req, good), "any order")++ for name, files := range map[string][]FileOutcome{+ "missing": {{Path: "a", Outcome: OutcomeResolved}},+ "extra": {{Path: "a", Outcome: OutcomeResolved}, {Path: "b", Outcome: OutcomeFailed}, {Path: "c", Outcome: OutcomeFailed}},+ "duplicate": {{Path: "a", Outcome: OutcomeResolved}, {Path: "a", Outcome: OutcomeFailed}},+ "unknown path": {{Path: "a", Outcome: OutcomeResolved}, {Path: "z", Outcome: OutcomeFailed}},+ "unknown status": {{Path: "a", Outcome: OutcomeResolved}, {Path: "b", Outcome: "maybe"}},+ } {+ require.Nil(t, validOutcomes(req, files), name)+ }}diff --git a/internal/graft/resolver/command.go b/internal/graft/resolver/command.goindex ea513b5..47f5f15 100644--- a/internal/graft/resolver/command.go+++ b/internal/graft/resolver/command.go@@ -60,6 +60,11 @@ func (c *Client) callCommand(ctx context.Context, body []byte, limit int64) ([]bif err != nil {var exitErr *exec.ExitErrorif errors.As(err, &exitErr) {+ // A refusal may carry an ErrorResponse on stdout, with the outcome of+ // every file; otherwise the stderr is the reason.+ if refusal, ok := parseRefusal(stdout.Bytes()); ok {+ return nil, refusal+ }reason := strings.TrimSpace(stderr.String())if reason == "" {reason = fmt.Sprintf("resolver %s", exitErr.String())diff --git a/internal/graft/resolver/http.go b/internal/graft/resolver/http.goindex 5bd865b..2328940 100644--- a/internal/graft/resolver/http.go+++ b/internal/graft/resolver/http.go@@ -47,30 +47,34 @@ func (c *Client) callHTTP(ctx context.Context, body []byte, limit int64) ([]bytereturn raw, nilcase http.StatusUnprocessableEntity:- return nil, &UnresolvableError{Reason: refusalReason(resp.Body)}+ raw, err := io.ReadAll(io.LimitReader(resp.Body, limit))+ if err == nil {+ if refusal, ok := parseRefusal(raw); ok {+ return nil, refusal+ }+ }+ return nil, &UnresolvableError{Reason: defaultRefusalReason}default:return nil, fmt.Errorf("resolver answered HTTP %d", resp.StatusCode)}}-// refusalReason extracts the "error" member of a 422 answer, falling back to-// a generic reason when the body is not such an object.-func refusalReason(body io.Reader) string {- raw, err := io.ReadAll(io.LimitReader(body, maxErrorBodyBytes))- if err != nil {- return defaultRefusalReason- }-- var answer struct {- Error string `json:"error"`- }+// parseRefusal reads an ErrorResponse: the body of a 422, or the stdout of a+// command that exited non-zero. It reports false when raw is not such an+// object with a non-empty error. The reason is cut to maxErrorBodyBytes; the+// files are checked against the request by Resolve.+func parseRefusal(raw []byte) (*UnresolvableError, bool) {+ var answer ErrorResponseif err := json.Unmarshal(raw, &answer); err != nil {- return defaultRefusalReason+ return nil, false}- if reason := strings.TrimSpace(answer.Error); reason != "" {- return reason+ reason := strings.TrimSpace(answer.Error)+ if reason == "" {+ return nil, false}-- return defaultRefusalReason+ if len(reason) > maxErrorBodyBytes {+ reason = strings.ToValidUTF8(reason[:maxErrorBodyBytes], "")+ }+ return &UnresolvableError{Reason: reason, Files: answer.Files}, true}diff --git a/internal/graft/resolver/protocol.go b/internal/graft/resolver/protocol.goindex 809e93d..75a9311 100644--- a/internal/graft/resolver/protocol.go+++ b/internal/graft/resolver/protocol.go@@ -47,7 +47,9 @@ const (// Ours is the current branch tip side, Theirs the change being landed. Any// side may be nil (absent).type Request struct {- Version int `json:"version"`+ Version int `json:"version"`+ // Operation is OperationResolve (also when absent) or OperationCheck.+ Operation string `json:"operation,omitempty"`Repository Repository `json:"repository"`Branch string `json:"branch"`Tip string `json:"tip"`@@ -56,7 +58,73 @@ type Request struct {Messages Messages `json:"messages"`Actor string `json:"actor"`Files []File `json:"files"`- Limits Limits `json:"limits"`+ // Resolution is, for OperationCheck only, the agent's resolution of Files to check.+ Resolution []ResponseFile `json:"resolution,omitempty"`+ Limits Limits `json:"limits"`+}++// Operations of a request.+const (+ // OperationResolve asks the resolver to resolve Files; an absent operation means it.+ OperationResolve = "resolve"+ // OperationCheck asks the resolver to check an agent's Resolution of Files with the checks of+ // its own answers, and to answer a CheckResponse.+ OperationCheck = "check"+)++// CheckResponse is the answer to an OperationCheck request: one verdict per file of the+// resolution, in its order.+type CheckResponse struct {+ Version int `json:"version"`+ Operation string `json:"operation"`+ // Resolver names the checker, for the Graft-Checked-By trailer.+ Resolver string `json:"resolver"`+ Files []CheckFile `json:"files"`+}++// Syntax verdicts of a CheckFile.+const (+ // SyntaxChecked: both sides parse, and so does the resolution.+ SyntaxChecked = "checked"+ // SyntaxUnchecked: a side does not parse with the grammar, so the resolution got no syntax+ // verdict.+ SyntaxUnchecked = "unchecked"+ // SyntaxNone: the path has no grammar, or the file is deleted.+ SyntaxNone = "none"+)++// CheckFile is the verdict on one file of a resolution.+type CheckFile struct {+ Path string `json:"path"`+ OK bool `json:"ok"`+ Reason string `json:"reason,omitempty"`+ Syntax string `json:"syntax"`+}++// ErrorResponse is the body of a refusal: the HTTP 422 answer, or the stdout of+// a command that exits non-zero. Files is optional.+type ErrorResponse struct {+ Error string `json:"error"`+ Files []FileOutcome `json:"files,omitempty"`+}++// Outcomes of a file in a refusal.+const (+ // OutcomeResolved: the resolver resolved the file, but not every file of+ // the request.+ OutcomeResolved = "resolved"+ // OutcomeRejected: the resolver's result for the file failed a check.+ OutcomeRejected = "rejected"+ // OutcomeFailed: the resolver failed on the file (a model error, a spent+ // budget, no strategy applying).+ OutcomeFailed = "failed"+)++// FileOutcome is what the resolver did with one file of a refused request.+type FileOutcome struct {+ Path string `json:"path"`+ Outcome string `json:"outcome"`+ Reason string `json:"reason,omitempty"`}// Repository identifies the repository the conflict belongs to.diff --git a/internal/graft/resolver/protocol_fields_test.go b/internal/graft/resolver/protocol_fields_test.gonew file mode 100644index 0000000..d114462--- /dev/null+++ b/internal/graft/resolver/protocol_fields_test.go@@ -0,0 +1,64 @@+package resolver++import (+ "encoding/json"+ "os"+ "reflect"+ "sort"+ "strings"+ "testing"++ "github.com/stretchr/testify/require"+)++// jsonFields returns the sorted JSON field names of a struct type.+func jsonFields(t reflect.Type) []string {+ var names []string+ for i := 0; i < t.NumField(); i++ {+ tag := t.Field(i).Tag.Get("json")+ name, _, _ := strings.Cut(tag, ",")+ if name == "" || name == "-" {+ continue+ }+ names = append(names, name)+ }+ sort.Strings(names)+ return names+}++// TestProtocolFieldsMatchTheOtherCopy checks the wire fields of this copy of the protocol against+// testdata/protocol-fields.json, which tools/graft-agents/protocol is tested against too.+func TestProtocolFieldsMatchTheOtherCopy(t *testing.T) {+ t.Parallel()++ data, err := os.ReadFile("testdata/protocol-fields.json")+ require.NoError(t, err)+ var golden map[string]any+ require.NoError(t, json.Unmarshal(data, &golden))+ delete(golden, "comment")++ types := map[string]reflect.Type{+ "request": reflect.TypeOf(Request{}),+ "repository": reflect.TypeOf(Repository{}),+ "messages": reflect.TypeOf(Messages{}),+ "file": reflect.TypeOf(File{}),+ "side": reflect.TypeOf(sideJSON{}), // Side's wire form+ "limits": reflect.TypeOf(Limits{}),+ "response": reflect.TypeOf(Response{}),+ "response_file": reflect.TypeOf(ResponseFile{}),+ "error_response": reflect.TypeOf(ErrorResponse{}),+ "file_outcome": reflect.TypeOf(FileOutcome{}),+ "check_response": reflect.TypeOf(CheckResponse{}),+ "check_file": reflect.TypeOf(CheckFile{}),+ }+ require.Len(t, golden, len(types), "every message of the golden file has a type here")+ for name, typ := range types {+ raw, ok := golden[name].([]any)+ require.True(t, ok, "golden file lacks %q", name)+ var want []string+ for _, v := range raw {+ want = append(want, v.(string))+ }+ require.Equal(t, want, jsonFields(typ), name)+ }+}diff --git a/internal/graft/resolver/sendrules.go b/internal/graft/resolver/sendrules.gonew file mode 100644index 0000000..2750bdb--- /dev/null+++ b/internal/graft/resolver/sendrules.go@@ -0,0 +1,152 @@+package resolver++import (+ "bytes"+ "fmt"+ "path"+ "regexp"++ "github.com/feder-cr/git-ai/internal/gitaly/config"+)++// Reasons why a conflicting file is never sent to the resolver (PLAN10 3.4). Such a file goes to+// the agent, and the reason is in the conflict package.+const (+ NotSentLarge = "large"+ NotSentBinary = "binary"+ NotSentLockfile = "lockfile"+ NotSentGenerated = "generated"+ NotSentMinified = "minified"+)++// builtinLockfiles are the base names of the lockfiles that always go to the agent.+var builtinLockfiles = []string{"package-lock.json", "yarn.lock", "pnpm-lock.yaml", "poetry.lock", "Cargo.lock", "go.sum"}++// builtinGeneratedMarkers are searched in the first generatedMarkerLines lines of every side.+var builtinGeneratedMarkers = []string{`Code generated .* DO NOT EDIT\.`, `@generated`, `DO NOT EDIT`, `(?i)auto-generated`}++// generatedMarkerLines is the number of first lines searched for a generated marker.+const generatedMarkerLines = 10++// builtinMinifiedGlobs are base-name globs of minified files.+var builtinMinifiedGlobs = []string{"*.min.js", "*.min.mjs", "*.min.css", "*.bundle.js"}++// minifiedMinBytes is the size above which a side is judged by its line lengths.+const minifiedMinBytes = 2 << 10++// SendRules decide which conflicting files are never sent to the resolver: large, binary,+// lockfile, generated or minified. The bench of tools/graft-agents (resolve/bench) applies the+// same rules, and both are tested against testdata/never-send.json so that they cannot drift.+type SendRules struct {+ maxFileBytes int64+ lockfiles map[string]bool+ markers []*regexp.Regexp+ minifiedGlobs []string+ averageLineBytes int+ longestLineBytes int+}++// NewSendRules returns the built-in rules extended by the configuration.+func NewSendRules(cfg config.GraftResolver) (*SendRules, error) {+ r := &SendRules{+ maxFileBytes: cfg.MaxFileBytesOrDefault(),+ lockfiles: map[string]bool{},+ minifiedGlobs: append(append([]string(nil), builtinMinifiedGlobs...), cfg.Minified.Globs...),+ averageLineBytes: cfg.Minified.AverageLineBytesOrDefault(),+ longestLineBytes: cfg.Minified.LongestLineBytesOrDefault(),+ }+ for _, name := range append(append([]string(nil), builtinLockfiles...), cfg.Lockfiles...) {+ r.lockfiles[name] = true+ }+ for _, expr := range append(append([]string(nil), builtinGeneratedMarkers...), cfg.GeneratedMarkers...) {+ re, err := regexp.Compile(expr)+ if err != nil {+ return nil, fmt.Errorf("graft land resolver: generated marker %q: %w", expr, err)+ }+ r.markers = append(r.markers, re)+ }+ return r, nil+}++// TooLarge reports whether a side of size bytes is too large to be sent. It is checked before the+// content is read, so a large side is never read.+func (r *SendRules) TooLarge(size int64) bool {+ return size > r.maxFileBytes+}++// Reason returns why the conflicting file p with the given sides (nil for an absent side) is not+// sent, or "" when it is. generated reports linguist-generated for p in the tip's attributes.+// The rules apply in this order: large, binary, lockfile, generated (attribute, then markers),+// minified (glob, then line lengths); the first that matches is the reason.+func (r *SendRules) Reason(p string, generated bool, sides ...[]byte) string {+ for _, s := range sides {+ if r.TooLarge(int64(len(s))) {+ return NotSentLarge+ }+ }+ for _, s := range sides {+ if bytes.IndexByte(s, 0) >= 0 {+ return NotSentBinary+ }+ }+ base := path.Base(p)+ if r.lockfiles[base] {+ return NotSentLockfile+ }+ if generated {+ return NotSentGenerated+ }+ for _, s := range sides {+ head := firstLines(s, generatedMarkerLines)+ for _, m := range r.markers {+ if m.Match(head) {+ return NotSentGenerated+ }+ }+ }+ for _, g := range r.minifiedGlobs {+ if ok, _ := path.Match(g, base); ok {+ return NotSentMinified+ }+ }+ for _, s := range sides {+ if r.looksMinified(s) {+ return NotSentMinified+ }+ }+ return ""+}++// firstLines returns the first n lines of s.+func firstLines(s []byte, n int) []byte {+ end := 0+ for i := 0; i < n; i++ {+ j := bytes.IndexByte(s[end:], '\n')+ if j < 0 {+ return s+ }+ end += j + 1+ }+ return s[:end]+}++// looksMinified reports whether a side larger than minifiedMinBytes has an average line longer+// than averageLineBytes or a line longer than longestLineBytes.+func (r *SendRules) looksMinified(s []byte) bool {+ if len(s) <= minifiedMinBytes {+ return false+ }+ lines := bytes.Count(s, []byte{'\n'})+ if len(s) > 0 && s[len(s)-1] != '\n' {+ lines+++ }+ if lines > 0 && len(s)/lines > r.averageLineBytes {+ return true+ }+ for _, line := range bytes.Split(s, []byte{'\n'}) {+ if len(line) > r.longestLineBytes {+ return true+ }+ }+ return false+}diff --git a/internal/graft/resolver/sendrules_test.go b/internal/graft/resolver/sendrules_test.gonew file mode 100644index 0000000..f8870ab--- /dev/null+++ b/internal/graft/resolver/sendrules_test.go@@ -0,0 +1,81 @@+package resolver++import (+ "encoding/json"+ "os"+ "strings"+ "testing"++ "github.com/stretchr/testify/require"++ "github.com/feder-cr/git-ai/internal/gitaly/config"+)++// neverSendVectors are the test vectors of testdata/never-send.json, which the bench of+// tools/graft-agents checks too.+type neverSendVectors struct {+ MaxFileBytes int64 `json:"max_file_bytes"`+ Cases []struct {+ Name string `json:"name"`+ Path string `json:"path"`+ Generated bool `json:"generated"`+ Sides []*[]struct {+ Text string `json:"text"`+ Repeat int `json:"repeat"`+ } `json:"sides"`+ Want string `json:"want"`+ } `json:"cases"`+}++func TestSendRulesVectors(t *testing.T) {+ t.Parallel()++ data, err := os.ReadFile("testdata/never-send.json")+ require.NoError(t, err)+ var v neverSendVectors+ require.NoError(t, json.Unmarshal(data, &v))+ require.NotEmpty(t, v.Cases)++ rules, err := NewSendRules(config.GraftResolver{MaxFileBytes: v.MaxFileBytes})+ require.NoError(t, err)++ for _, c := range v.Cases {+ var sides [][]byte+ for _, side := range c.Sides {+ if side == nil {+ sides = append(sides, nil)+ continue+ }+ var b strings.Builder+ for _, part := range *side {+ b.WriteString(strings.Repeat(part.Text, max(1, part.Repeat)))+ }+ sides = append(sides, []byte(b.String()))+ }+ require.Equal(t, c.Want, rules.Reason(c.Path, c.Generated, sides...), c.Name)+ }+}++func TestSendRulesConfiguredExtensions(t *testing.T) {+ t.Parallel()++ rules, err := NewSendRules(config.GraftResolver{+ Lockfiles: []string{"Gemfile.lock"},+ GeneratedMarkers: []string{`^// Generated by mytool`},+ Minified: config.GraftResolverMinified{+ Globs: []string{"*.min.html"},+ AverageLineBytes: 50,+ LongestLineBytes: 100,+ },+ })+ require.NoError(t, err)++ require.Equal(t, NotSentLockfile, rules.Reason("Gemfile.lock", false, []byte("x\n")))+ require.Equal(t, NotSentLockfile, rules.Reason("go.sum", false, []byte("x\n")), "the built-in list stays")+ require.Equal(t, NotSentGenerated, rules.Reason("a.go", false, []byte("// Generated by mytool\npackage a\n")))+ require.Equal(t, NotSentMinified, rules.Reason("index.min.html", false, []byte("<p>\n")))+ require.Equal(t, NotSentMinified, rules.Reason("a.js", false, []byte(strings.Repeat(strings.Repeat("x", 60)+"\n", 40))), "average above 50")+ require.Equal(t, "", rules.Reason("a.js", false, []byte(strings.Repeat(strings.Repeat("x", 40)+"\n", 60))))+ require.True(t, rules.TooLarge(config.DefaultGraftResolverMaxFileBytes+1))+ require.False(t, rules.TooLarge(config.DefaultGraftResolverMaxFileBytes))+}diff --git a/internal/graft/resolver/testdata/never-send.json b/internal/graft/resolver/testdata/never-send.jsonnew file mode 100644index 0000000..57b4c33--- /dev/null+++ b/internal/graft/resolver/testdata/never-send.json@@ -0,0 +1,32 @@+{+ "comment": "Test vectors of the never-send rules (PLAN10 3.4), shared by internal/graft/resolver (SendRules.Reason) and tools/graft-agents/resolve/bench (notSentReason) so that the two copies cannot drift. A side is a list of parts, each part text repeated repeat times (default 1), or null when the side is absent.",+ "max_file_bytes": 1048576,+ "cases": [+ {"name": "plain source", "path": "a/b.go", "sides": [[{"text": "package b\n"}], [{"text": "package b\n\nvar x = 1\n"}]], "want": ""},+ {"name": "lockfile", "path": "web/package-lock.json", "sides": [[{"text": "{}\n"}]], "want": "lockfile"},+ {"name": "go.sum", "path": "go.sum", "sides": [[{"text": "a v1 h1:x\n"}]], "want": "lockfile"},+ {"name": "lockfile name elsewhere in the path", "path": "go.sum/notes.txt", "sides": [[{"text": "x\n"}]], "want": ""},+ {"name": "binary", "path": "img.go", "sides": [[{"text": "a\u0000b"}]], "want": "binary"},+ {"name": "large", "path": "big.go", "sides": [[{"text": "x", "repeat": 1048577}]], "want": "large"},+ {"name": "exactly max_file_bytes", "path": "edge.txt", "sides": [[{"text": "x\n", "repeat": 524288}]], "want": ""},+ {"name": "large wins over binary", "path": "big.bin", "sides": [[{"text": "\u0000"}, {"text": "x", "repeat": 1048577}]], "want": "large"},+ {"name": "binary wins over lockfile", "path": "yarn.lock", "sides": [[{"text": "\u0000"}]], "want": "binary"},+ {"name": "linguist-generated", "path": "api/client.go", "generated": true, "sides": [[{"text": "package api\n"}]], "want": "generated"},+ {"name": "lockfile wins over generated", "path": "Cargo.lock", "generated": true, "sides": [[{"text": "x\n"}]], "want": "lockfile"},+ {"name": "Go generated marker", "path": "x.pb.go", "sides": [[{"text": "// Code generated by protoc-gen-go. DO NOT EDIT.\npackage x\n"}]], "want": "generated"},+ {"name": "@generated in line 3", "path": "x.js", "sides": [[{"text": "/**\n * x\n * @generated\n */\n"}]], "want": "generated"},+ {"name": "marker in line 10", "path": "y.js", "sides": [[{"text": "l\n", "repeat": 9}, {"text": "// @generated\n"}]], "want": "generated"},+ {"name": "marker in line 11 is not looked at", "path": "z.js", "sides": [[{"text": "l\n", "repeat": 10}, {"text": "// @generated\n"}]], "want": ""},+ {"name": "auto-generated, any case", "path": "w.py", "sides": [[{"text": "# Auto-Generated file\nx = 1\n"}]], "want": "generated"},+ {"name": "marker on one side only", "path": "v.go", "sides": [[{"text": "package v\n"}], [{"text": "// DO NOT EDIT\npackage v\n"}]], "want": "generated"},+ {"name": "minified glob", "path": "static/app.min.js", "sides": [[{"text": "var a=1;\n"}]], "want": "minified"},+ {"name": "bundle glob", "path": "main.bundle.js", "sides": [[{"text": "x\n"}]], "want": "minified"},+ {"name": "longest line over 5000", "path": "long.js", "sides": [[{"text": "x", "repeat": 5001}, {"text": "\n"}]], "want": "minified"},+ {"name": "line of exactly 5000 among short ones", "path": "edge.js", "sides": [[{"text": "x", "repeat": 5000}, {"text": "\n"}, {"text": "y\n", "repeat": 20}]], "want": ""},+ {"name": "average line over 300", "path": "dense.js", "sides": [[{"text": "x", "repeat": 300}, {"text": "\n"}, {"text": "x", "repeat": 300}, {"text": "\n"}, {"text": "x", "repeat": 300}, {"text": "\n"}, {"text": "x", "repeat": 300}, {"text": "\n"}, {"text": "x", "repeat": 300}, {"text": "\n"}, {"text": "x", "repeat": 300}, {"text": "\n"}, {"text": "x", "repeat": 300}, {"text": "\n"}, {"text": "x", "repeat": 300}, {"text": "\n"}]], "want": "minified"},+ {"name": "average line of exactly 300 bytes", "path": "even.js", "sides": [[{"text": "x", "repeat": 299}, {"text": "\n"}, {"text": "x", "repeat": 299}, {"text": "\n"}, {"text": "x", "repeat": 299}, {"text": "\n"}, {"text": "x", "repeat": 299}, {"text": "\n"}, {"text": "x", "repeat": 299}, {"text": "\n"}, {"text": "x", "repeat": 299}, {"text": "\n"}, {"text": "x", "repeat": 299}, {"text": "\n"}, {"text": "x", "repeat": 299}, {"text": "\n"}, {"text": "x", "repeat": 299}, {"text": "\n"}, {"text": "x", "repeat": 299}, {"text": "\n"}]], "want": ""},+ {"name": "small file with long lines", "path": "small.js", "sides": [[{"text": "x", "repeat": 2000}, {"text": "\n"}]], "want": ""},+ {"name": "no final newline", "path": "nofinal.js", "sides": [[{"text": "x", "repeat": 2100}]], "want": "minified"},+ {"name": "absent side", "path": "gone.go", "sides": [null, [{"text": "package gone\n"}]], "want": ""}+ ]+}diff --git a/internal/graft/resolver/testdata/protocol-fields.json b/internal/graft/resolver/testdata/protocol-fields.jsonnew file mode 100644index 0000000..40cedcb--- /dev/null+++ b/internal/graft/resolver/testdata/protocol-fields.json@@ -0,0 +1,15 @@+{+ "comment": "The JSON fields of every message of the resolver protocol v1, by message. Both copies of the protocol (internal/graft/resolver and tools/graft-agents/protocol) are tested against this file, so they cannot drift: a field added to one copy fails the other's test until it is added there and here.",+ "request": ["actor", "branch", "commit", "files", "limits", "merge_base", "messages", "operation", "repository", "resolution", "tip", "version"],+ "repository": ["relative_path", "storage"],+ "messages": ["commit", "tip"],+ "file": ["base", "kind", "ours", "path", "theirs"],+ "side": ["content", "mode", "oid"],+ "limits": ["max_file_bytes"],+ "response": ["explanation", "files", "resolver", "version"],+ "response_file": ["action", "content", "mode", "path"],+ "error_response": ["error", "files"],+ "file_outcome": ["outcome", "path", "reason"],+ "check_response": ["files", "operation", "resolver", "version"],+ "check_file": ["ok", "path", "reason", "syntax"]+}diff --git a/internal/graft/resolver/validate.go b/internal/graft/resolver/validate.goindex ffd923e..65354b0 100644--- a/internal/graft/resolver/validate.go+++ b/internal/graft/resolver/validate.go@@ -64,6 +64,12 @@ func Validate(req *Request, resp *Response) error {return nil}+// ValidateFile applies the acceptance rules of Validate to one resolved file: the action, the+// mode, the size and the conflict markers. The server applies it to an agent's resolution too.+func ValidateFile(f ResponseFile, maxBytes int64) error {+ return validateFile(f, maxBytes)+}+// validateFile checks one answered file.func validateFile(f ResponseFile, maxBytes int64) error {switch f.Action {diff --git a/proto/go/gitalypb/operations.pb.go b/proto/go/gitalypb/operations.pb.goindex c76fea8..66b47a2 100644--- a/proto/go/gitalypb/operations.pb.go+++ b/proto/go/gitalypb/operations.pb.go@@ -197,6 +197,189 @@ func (UserLandRequest_Strategy) EnumDescriptor() ([]byte, []int) {return file_operations_proto_rawDescGZIP(), []int{49, 0}}+// Kind is the kind of the conflict.+type LandConflictFile_Kind int32++const (+ // KIND_UNSPECIFIED is never sent.+ LandConflictFile_KIND_UNSPECIFIED LandConflictFile_Kind = 0+ // KIND_CONTENT: both sides changed the content.+ LandConflictFile_KIND_CONTENT LandConflictFile_Kind = 1+ // KIND_MODIFY_DELETE: one side changed the file, the other deleted it.+ LandConflictFile_KIND_MODIFY_DELETE LandConflictFile_Kind = 2+ // KIND_ADD_ADD: both sides added the file.+ LandConflictFile_KIND_ADD_ADD LandConflictFile_Kind = 3+ // KIND_MODE: the sides differ in mode only.+ LandConflictFile_KIND_MODE LandConflictFile_Kind = 4+)++// Enum value maps for LandConflictFile_Kind.+var (+ LandConflictFile_Kind_name = map[int32]string{+ 0: "KIND_UNSPECIFIED",+ 1: "KIND_CONTENT",+ 2: "KIND_MODIFY_DELETE",+ 3: "KIND_ADD_ADD",+ 4: "KIND_MODE",+ }+ LandConflictFile_Kind_value = map[string]int32{+ "KIND_UNSPECIFIED": 0,+ "KIND_CONTENT": 1,+ "KIND_MODIFY_DELETE": 2,+ "KIND_ADD_ADD": 3,+ "KIND_MODE": 4,+ }+)++func (x LandConflictFile_Kind) Enum() *LandConflictFile_Kind {+ p := new(LandConflictFile_Kind)+ *p = x+ return p+}++func (x LandConflictFile_Kind) String() string {+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))+}++func (LandConflictFile_Kind) Descriptor() protoreflect.EnumDescriptor {+ return file_operations_proto_enumTypes[3].Descriptor()+}++func (LandConflictFile_Kind) Type() protoreflect.EnumType {+ return &file_operations_proto_enumTypes[3]+}++func (x LandConflictFile_Kind) Number() protoreflect.EnumNumber {+ return protoreflect.EnumNumber(x)+}++// Deprecated: Use LandConflictFile_Kind.Descriptor instead.+func (LandConflictFile_Kind) EnumDescriptor() ([]byte, []int) {+ return file_operations_proto_rawDescGZIP(), []int{51, 0}+}++// Outcome is what the server did with the file.+type LandConflictFile_Outcome int32++const (+ // OUTCOME_UNSPECIFIED is never sent.+ LandConflictFile_OUTCOME_UNSPECIFIED LandConflictFile_Outcome = 0+ // OUTCOME_NOT_SENT: the file was not sent to the resolver (reason: lockfile,+ // binary, large, generated, minified, denied path, invalid UTF-8 path).+ LandConflictFile_OUTCOME_NOT_SENT LandConflictFile_Outcome = 1+ // OUTCOME_REJECTED: the resolver's result failed a check (reason: the check).+ LandConflictFile_OUTCOME_REJECTED LandConflictFile_Outcome = 2+ // OUTCOME_FAILED: the resolver failed on the file (reason: the error, such as a+ // model error or "AI budget exhausted").+ LandConflictFile_OUTCOME_FAILED LandConflictFile_Outcome = 3+ // OUTCOME_RESOLVED: the file was resolved, but the land failed because another+ // file was not.+ LandConflictFile_OUTCOME_RESOLVED LandConflictFile_Outcome = 4+ // OUTCOME_NOT_ATTEMPTED: the request was not resolved at all (see+ // LandConflict.reason).+ LandConflictFile_OUTCOME_NOT_ATTEMPTED LandConflictFile_Outcome = 5+)++// Enum value maps for LandConflictFile_Outcome.+var (+ LandConflictFile_Outcome_name = map[int32]string{+ 0: "OUTCOME_UNSPECIFIED",+ 1: "OUTCOME_NOT_SENT",+ 2: "OUTCOME_REJECTED",+ 3: "OUTCOME_FAILED",+ 4: "OUTCOME_RESOLVED",+ 5: "OUTCOME_NOT_ATTEMPTED",+ }+ LandConflictFile_Outcome_value = map[string]int32{+ "OUTCOME_UNSPECIFIED": 0,+ "OUTCOME_NOT_SENT": 1,+ "OUTCOME_REJECTED": 2,+ "OUTCOME_FAILED": 3,+ "OUTCOME_RESOLVED": 4,+ "OUTCOME_NOT_ATTEMPTED": 5,+ }+)++func (x LandConflictFile_Outcome) Enum() *LandConflictFile_Outcome {+ p := new(LandConflictFile_Outcome)+ *p = x+ return p+}++func (x LandConflictFile_Outcome) String() string {+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))+}++func (LandConflictFile_Outcome) Descriptor() protoreflect.EnumDescriptor {+ return file_operations_proto_enumTypes[4].Descriptor()+}++func (LandConflictFile_Outcome) Type() protoreflect.EnumType {+ return &file_operations_proto_enumTypes[4]+}++func (x LandConflictFile_Outcome) Number() protoreflect.EnumNumber {+ return protoreflect.EnumNumber(x)+}++// Deprecated: Use LandConflictFile_Outcome.Descriptor instead.+func (LandConflictFile_Outcome) EnumDescriptor() ([]byte, []int) {+ return file_operations_proto_rawDescGZIP(), []int{51, 1}+}++// Action is what becomes of the path.+type LandResolvedFile_Action int32++const (+ // ACTION_UNSPECIFIED is rejected.+ LandResolvedFile_ACTION_UNSPECIFIED LandResolvedFile_Action = 0+ // ACTION_WRITE writes content with mode.+ LandResolvedFile_ACTION_WRITE LandResolvedFile_Action = 1+ // ACTION_DELETE deletes the path.+ LandResolvedFile_ACTION_DELETE LandResolvedFile_Action = 2+)++// Enum value maps for LandResolvedFile_Action.+var (+ LandResolvedFile_Action_name = map[int32]string{+ 0: "ACTION_UNSPECIFIED",+ 1: "ACTION_WRITE",+ 2: "ACTION_DELETE",+ }+ LandResolvedFile_Action_value = map[string]int32{+ "ACTION_UNSPECIFIED": 0,+ "ACTION_WRITE": 1,+ "ACTION_DELETE": 2,+ }+)++func (x LandResolvedFile_Action) Enum() *LandResolvedFile_Action {+ p := new(LandResolvedFile_Action)+ *p = x+ return p+}++func (x LandResolvedFile_Action) String() string {+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))+}++func (LandResolvedFile_Action) Descriptor() protoreflect.EnumDescriptor {+ return file_operations_proto_enumTypes[5].Descriptor()+}++func (LandResolvedFile_Action) Type() protoreflect.EnumType {+ return &file_operations_proto_enumTypes[5]+}++func (x LandResolvedFile_Action) Number() protoreflect.EnumNumber {+ return protoreflect.EnumNumber(x)+}++// Deprecated: Use LandResolvedFile_Action.Descriptor instead.+func (LandResolvedFile_Action) EnumDescriptor() ([]byte, []int) {+ return file_operations_proto_rawDescGZIP(), []int{56, 0}+}+// UserCreateBranchRequest is a request for the UserCreateBranch RPC.type UserCreateBranchRequest struct {state protoimpl.MessageState `protogen:"open.v1"`@@ -4543,8 +4726,19 @@ type UserLandRequest struct {// fails with merge_conflict as usual) when no resolver is configured or the// server policy does not allow it for the caller.ResolveConflicts bool `protobuf:"varint,10,opt,name=resolve_conflicts,json=resolveConflicts,proto3" json:"resolve_conflicts,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache+ // resolution lands commit_id with the caller's resolution of the conflicts that a+ // LandConflict described, instead of asking the server's resolver. The server+ // accepts it only when resolution.tip equals the current branch tip,+ // resolution.commit equals commit_id, and resolution.files resolve exactly the+ // paths that conflict at that tip, each once; otherwise the land fails with a+ // fresh LandConflict. It is validated like a resolver answer (no conflict+ // markers; modes 100644, 100755 or 120000; sizes; the syntax check when a+ // resolver is configured) and lands as a merge commit with a+ // Graft-Resolved-By: agent/<actor> trailer. The whole request is bounded by+ // the 4 MiB gRPC message limit.+ Resolution *LandResolution `protobuf:"bytes,11,opt,name=resolution,proto3" json:"resolution,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache}func (x *UserLandRequest) Reset() {@@ -4647,6 +4841,561 @@ func (x *UserLandRequest) GetResolveConflicts() bool {return false}+func (x *UserLandRequest) GetResolution() *LandResolution {+ if x != nil {+ return x.Resolution+ }+ return nil+}++// LandConflict describes the conflicts of a land that the server did not resolve, so+// that the caller can resolve them and land again with UserLandRequest.resolution. It+// is sent as an additional detail of the error, next to UserLandError, when the+// request set resolve_conflicts or resolution.+type LandConflict struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // tip is the branch tip that the change was merged with.+ Tip string `protobuf:"bytes,1,opt,name=tip,proto3" json:"tip,omitempty"`+ // commit is the landed commit.+ Commit string `protobuf:"bytes,2,opt,name=commit,proto3" json:"commit,omitempty"`+ // merge_base is the merge base of tip and commit, empty for unrelated histories.+ MergeBase string `protobuf:"bytes,3,opt,name=merge_base,json=mergeBase,proto3" json:"merge_base,omitempty"`+ // tip_message is the message of the tip, cut to 4 KiB.+ TipMessage []byte `protobuf:"bytes,4,opt,name=tip_message,json=tipMessage,proto3" json:"tip_message,omitempty"`+ // commit_message is the message of the landed commit, cut to 4 KiB.+ CommitMessage []byte `protobuf:"bytes,5,opt,name=commit_message,json=commitMessage,proto3" json:"commit_message,omitempty"`+ // messages_truncated is set when a message was cut.+ MessagesTruncated bool `protobuf:"varint,6,opt,name=messages_truncated,json=messagesTruncated,proto3" json:"messages_truncated,omitempty"`+ // files are the conflicting files, at most max_files of them.+ Files []*LandConflictFile `protobuf:"bytes,7,rep,name=files,proto3" json:"files,omitempty"`+ // reason is set when the server did not try to resolve the request at all, for+ // example because it has too many files or the actor may not resolve; it is cut to+ // 512 bytes.+ Reason string `protobuf:"bytes,8,opt,name=reason,proto3" json:"reason,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *LandConflict) Reset() {+ *x = LandConflict{}+ mi := &file_operations_proto_msgTypes[50]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *LandConflict) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*LandConflict) ProtoMessage() {}++func (x *LandConflict) ProtoReflect() protoreflect.Message {+ mi := &file_operations_proto_msgTypes[50]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use LandConflict.ProtoReflect.Descriptor instead.+func (*LandConflict) Descriptor() ([]byte, []int) {+ return file_operations_proto_rawDescGZIP(), []int{50}+}++func (x *LandConflict) GetTip() string {+ if x != nil {+ return x.Tip+ }+ return ""+}++func (x *LandConflict) GetCommit() string {+ if x != nil {+ return x.Commit+ }+ return ""+}++func (x *LandConflict) GetMergeBase() string {+ if x != nil {+ return x.MergeBase+ }+ return ""+}++func (x *LandConflict) GetTipMessage() []byte {+ if x != nil {+ return x.TipMessage+ }+ return nil+}++func (x *LandConflict) GetCommitMessage() []byte {+ if x != nil {+ return x.CommitMessage+ }+ return nil+}++func (x *LandConflict) GetMessagesTruncated() bool {+ if x != nil {+ return x.MessagesTruncated+ }+ return false+}++func (x *LandConflict) GetFiles() []*LandConflictFile {+ if x != nil {+ return x.Files+ }+ return nil+}++func (x *LandConflict) GetReason() string {+ if x != nil {+ return x.Reason+ }+ return ""+}++// LandConflictFile is one conflicting file of a LandConflict.+type LandConflictFile struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // path is the path of the conflict in the merged tree.+ Path []byte `protobuf:"bytes,1,opt,name=path,proto3" json:"path,omitempty"`+ // kind is the kind of the conflict.+ Kind LandConflictFile_Kind `protobuf:"varint,2,opt,name=kind,proto3,enum=gitaly.LandConflictFile_Kind" json:"kind,omitempty"`+ // base, ours and theirs are the sides; an absent side is unset. ours is the tip's+ // side, theirs the landed commit's.+ Base *LandConflictSide `protobuf:"bytes,3,opt,name=base,proto3" json:"base,omitempty"`+ // ours is the tip's side.+ Ours *LandConflictSide `protobuf:"bytes,4,opt,name=ours,proto3" json:"ours,omitempty"`+ // theirs is the landed commit's side.+ Theirs *LandConflictSide `protobuf:"bytes,5,opt,name=theirs,proto3" json:"theirs,omitempty"`+ // hunks are the conflicting regions, in order.+ Hunks []*LandConflictHunk `protobuf:"bytes,6,rep,name=hunks,proto3" json:"hunks,omitempty"`+ // outcome is what the server did with the file.+ Outcome LandConflictFile_Outcome `protobuf:"varint,7,opt,name=outcome,proto3,enum=gitaly.LandConflictFile_Outcome" json:"outcome,omitempty"`+ // reason explains the outcome, cut to 512 bytes.+ Reason string `protobuf:"bytes,8,opt,name=reason,proto3" json:"reason,omitempty"`+ // syntax_unchecked is set when a resolution of the file was accepted without a+ // syntax verdict, because a side does not parse with the grammar of its language.+ SyntaxUnchecked bool `protobuf:"varint,9,opt,name=syntax_unchecked,json=syntaxUnchecked,proto3" json:"syntax_unchecked,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *LandConflictFile) Reset() {+ *x = LandConflictFile{}+ mi := &file_operations_proto_msgTypes[51]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *LandConflictFile) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*LandConflictFile) ProtoMessage() {}++func (x *LandConflictFile) ProtoReflect() protoreflect.Message {+ mi := &file_operations_proto_msgTypes[51]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use LandConflictFile.ProtoReflect.Descriptor instead.+func (*LandConflictFile) Descriptor() ([]byte, []int) {+ return file_operations_proto_rawDescGZIP(), []int{51}+}++func (x *LandConflictFile) GetPath() []byte {+ if x != nil {+ return x.Path+ }+ return nil+}++func (x *LandConflictFile) GetKind() LandConflictFile_Kind {+ if x != nil {+ return x.Kind+ }+ return LandConflictFile_KIND_UNSPECIFIED+}++func (x *LandConflictFile) GetBase() *LandConflictSide {+ if x != nil {+ return x.Base+ }+ return nil+}++func (x *LandConflictFile) GetOurs() *LandConflictSide {+ if x != nil {+ return x.Ours+ }+ return nil+}++func (x *LandConflictFile) GetTheirs() *LandConflictSide {+ if x != nil {+ return x.Theirs+ }+ return nil+}++func (x *LandConflictFile) GetHunks() []*LandConflictHunk {+ if x != nil {+ return x.Hunks+ }+ return nil+}++func (x *LandConflictFile) GetOutcome() LandConflictFile_Outcome {+ if x != nil {+ return x.Outcome+ }+ return LandConflictFile_OUTCOME_UNSPECIFIED+}++func (x *LandConflictFile) GetReason() string {+ if x != nil {+ return x.Reason+ }+ return ""+}++func (x *LandConflictFile) GetSyntaxUnchecked() bool {+ if x != nil {+ return x.SyntaxUnchecked+ }+ return false+}++// LandConflictSide is one side of a conflicting file; its content is read by oid.+type LandConflictSide struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // oid is the object ID of the blob.+ Oid string `protobuf:"bytes,1,opt,name=oid,proto3" json:"oid,omitempty"`+ // mode is the file mode.+ Mode string `protobuf:"bytes,2,opt,name=mode,proto3" json:"mode,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *LandConflictSide) Reset() {+ *x = LandConflictSide{}+ mi := &file_operations_proto_msgTypes[52]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *LandConflictSide) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*LandConflictSide) ProtoMessage() {}++func (x *LandConflictSide) ProtoReflect() protoreflect.Message {+ mi := &file_operations_proto_msgTypes[52]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use LandConflictSide.ProtoReflect.Descriptor instead.+func (*LandConflictSide) Descriptor() ([]byte, []int) {+ return file_operations_proto_rawDescGZIP(), []int{52}+}++func (x *LandConflictSide) GetOid() string {+ if x != nil {+ return x.Oid+ }+ return ""+}++func (x *LandConflictSide) GetMode() string {+ if x != nil {+ return x.Mode+ }+ return ""+}++// LandConflictHunk is a conflicting region as line ranges of each side. Each range+// counts the lines of the side it names (base of the base side's file, ours of the+// tip's, theirs of the landed commit's), 1-based and half-open ([start, end)); an+// empty range (start == end) is an insertion point before line start.+type LandConflictHunk struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // base is the range in the base side.+ Base *LineRange `protobuf:"bytes,1,opt,name=base,proto3" json:"base,omitempty"`+ // ours is the range in the tip's side.+ Ours *LineRange `protobuf:"bytes,2,opt,name=ours,proto3" json:"ours,omitempty"`+ // theirs is the range in the landed commit's side.+ Theirs *LineRange `protobuf:"bytes,3,opt,name=theirs,proto3" json:"theirs,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *LandConflictHunk) Reset() {+ *x = LandConflictHunk{}+ mi := &file_operations_proto_msgTypes[53]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *LandConflictHunk) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*LandConflictHunk) ProtoMessage() {}++func (x *LandConflictHunk) ProtoReflect() protoreflect.Message {+ mi := &file_operations_proto_msgTypes[53]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use LandConflictHunk.ProtoReflect.Descriptor instead.+func (*LandConflictHunk) Descriptor() ([]byte, []int) {+ return file_operations_proto_rawDescGZIP(), []int{53}+}++func (x *LandConflictHunk) GetBase() *LineRange {+ if x != nil {+ return x.Base+ }+ return nil+}++func (x *LandConflictHunk) GetOurs() *LineRange {+ if x != nil {+ return x.Ours+ }+ return nil+}++func (x *LandConflictHunk) GetTheirs() *LineRange {+ if x != nil {+ return x.Theirs+ }+ return nil+}++// LineRange is a half-open range of 1-based lines.+type LineRange struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // start is the first line of the range.+ Start uint32 `protobuf:"varint,1,opt,name=start,proto3" json:"start,omitempty"`+ // end is the line after the last line of the range.+ End uint32 `protobuf:"varint,2,opt,name=end,proto3" json:"end,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *LineRange) Reset() {+ *x = LineRange{}+ mi := &file_operations_proto_msgTypes[54]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *LineRange) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*LineRange) ProtoMessage() {}++func (x *LineRange) ProtoReflect() protoreflect.Message {+ mi := &file_operations_proto_msgTypes[54]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use LineRange.ProtoReflect.Descriptor instead.+func (*LineRange) Descriptor() ([]byte, []int) {+ return file_operations_proto_rawDescGZIP(), []int{54}+}++func (x *LineRange) GetStart() uint32 {+ if x != nil {+ return x.Start+ }+ return 0+}++func (x *LineRange) GetEnd() uint32 {+ if x != nil {+ return x.End+ }+ return 0+}++// LandResolution is the caller's resolution of the conflicts of a LandConflict.+type LandResolution struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // tip is the tip that the resolution was made against, from LandConflict.tip.+ Tip string `protobuf:"bytes,1,opt,name=tip,proto3" json:"tip,omitempty"`+ // commit is the landed commit, LandConflict.commit; it must equal commit_id.+ Commit string `protobuf:"bytes,2,opt,name=commit,proto3" json:"commit,omitempty"`+ // files resolve every conflicting path exactly once.+ Files []*LandResolvedFile `protobuf:"bytes,3,rep,name=files,proto3" json:"files,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *LandResolution) Reset() {+ *x = LandResolution{}+ mi := &file_operations_proto_msgTypes[55]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *LandResolution) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*LandResolution) ProtoMessage() {}++func (x *LandResolution) ProtoReflect() protoreflect.Message {+ mi := &file_operations_proto_msgTypes[55]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use LandResolution.ProtoReflect.Descriptor instead.+func (*LandResolution) Descriptor() ([]byte, []int) {+ return file_operations_proto_rawDescGZIP(), []int{55}+}++func (x *LandResolution) GetTip() string {+ if x != nil {+ return x.Tip+ }+ return ""+}++func (x *LandResolution) GetCommit() string {+ if x != nil {+ return x.Commit+ }+ return ""+}++func (x *LandResolution) GetFiles() []*LandResolvedFile {+ if x != nil {+ return x.Files+ }+ return nil+}++// LandResolvedFile resolves one conflicting path.+type LandResolvedFile struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // path is the path of the conflict.+ Path []byte `protobuf:"bytes,1,opt,name=path,proto3" json:"path,omitempty"`+ // action is what becomes of the path.+ Action LandResolvedFile_Action `protobuf:"varint,2,opt,name=action,proto3,enum=gitaly.LandResolvedFile_Action" json:"action,omitempty"`+ // mode is 100644, 100755 or 120000 for ACTION_WRITE.+ Mode string `protobuf:"bytes,3,opt,name=mode,proto3" json:"mode,omitempty"`+ // content is the file's content for ACTION_WRITE.+ Content []byte `protobuf:"bytes,4,opt,name=content,proto3" json:"content,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *LandResolvedFile) Reset() {+ *x = LandResolvedFile{}+ mi := &file_operations_proto_msgTypes[56]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *LandResolvedFile) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*LandResolvedFile) ProtoMessage() {}++func (x *LandResolvedFile) ProtoReflect() protoreflect.Message {+ mi := &file_operations_proto_msgTypes[56]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use LandResolvedFile.ProtoReflect.Descriptor instead.+func (*LandResolvedFile) Descriptor() ([]byte, []int) {+ return file_operations_proto_rawDescGZIP(), []int{56}+}++func (x *LandResolvedFile) GetPath() []byte {+ if x != nil {+ return x.Path+ }+ return nil+}++func (x *LandResolvedFile) GetAction() LandResolvedFile_Action {+ if x != nil {+ return x.Action+ }+ return LandResolvedFile_ACTION_UNSPECIFIED+}++func (x *LandResolvedFile) GetMode() string {+ if x != nil {+ return x.Mode+ }+ return ""+}++func (x *LandResolvedFile) GetContent() []byte {+ if x != nil {+ return x.Content+ }+ return nil+}+// UserLandResponse is a response for the UserLand RPC.type UserLandResponse struct {state protoimpl.MessageState `protogen:"open.v1"`@@ -4683,7 +5432,7 @@ type UserLandResponse struct {func (x *UserLandResponse) Reset() {*x = UserLandResponse{}- mi := &file_operations_proto_msgTypes[50]+ mi := &file_operations_proto_msgTypes[57]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -4695,7 +5444,7 @@ func (x *UserLandResponse) String() string {func (*UserLandResponse) ProtoMessage() {}func (x *UserLandResponse) ProtoReflect() protoreflect.Message {- mi := &file_operations_proto_msgTypes[50]+ mi := &file_operations_proto_msgTypes[57]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -4708,7 +5457,7 @@ func (x *UserLandResponse) ProtoReflect() protoreflect.Message {// Deprecated: Use UserLandResponse.ProtoReflect.Descriptor instead.func (*UserLandResponse) Descriptor() ([]byte, []int) {- return file_operations_proto_rawDescGZIP(), []int{50}+ return file_operations_proto_rawDescGZIP(), []int{57}}func (x *UserLandResponse) GetBranchUpdate() *OperationBranchUpdate {@@ -4799,7 +5548,7 @@ type UserLandError struct {func (x *UserLandError) Reset() {*x = UserLandError{}- mi := &file_operations_proto_msgTypes[51]+ mi := &file_operations_proto_msgTypes[58]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -4811,7 +5560,7 @@ func (x *UserLandError) String() string {func (*UserLandError) ProtoMessage() {}func (x *UserLandError) ProtoReflect() protoreflect.Message {- mi := &file_operations_proto_msgTypes[51]+ mi := &file_operations_proto_msgTypes[58]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -4824,7 +5573,7 @@ func (x *UserLandError) ProtoReflect() protoreflect.Message {// Deprecated: Use UserLandError.ProtoReflect.Descriptor instead.func (*UserLandError) Descriptor() ([]byte, []int) {- return file_operations_proto_rawDescGZIP(), []int{51}+ return file_operations_proto_rawDescGZIP(), []int{58}}func (x *UserLandError) GetError() isUserLandError_Error {@@ -4959,7 +5708,7 @@ type UserRebaseConfirmableRequest_Header struct {func (x *UserRebaseConfirmableRequest_Header) Reset() {*x = UserRebaseConfirmableRequest_Header{}- mi := &file_operations_proto_msgTypes[52]+ mi := &file_operations_proto_msgTypes[59]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -4971,7 +5720,7 @@ func (x *UserRebaseConfirmableRequest_Header) String() string {func (*UserRebaseConfirmableRequest_Header) ProtoMessage() {}func (x *UserRebaseConfirmableRequest_Header) ProtoReflect() protoreflect.Message {- mi := &file_operations_proto_msgTypes[52]+ mi := &file_operations_proto_msgTypes[59]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -5079,7 +5828,7 @@ type UserApplyPatchRequest_Header struct {func (x *UserApplyPatchRequest_Header) Reset() {*x = UserApplyPatchRequest_Header{}- mi := &file_operations_proto_msgTypes[53]+ mi := &file_operations_proto_msgTypes[60]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -5091,7 +5840,7 @@ func (x *UserApplyPatchRequest_Header) String() string {func (*UserApplyPatchRequest_Header) ProtoMessage() {}func (x *UserApplyPatchRequest_Header) ProtoReflect() protoreflect.Message {- mi := &file_operations_proto_msgTypes[53]+ mi := &file_operations_proto_msgTypes[60]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -5497,7 +6246,7 @@ const file_operations_proto_rawDesc = "" +"\x10reference_update\x18\x02 \x01(\v2\x1c.gitaly.ReferenceUpdateErrorH\x00R\x0freferenceUpdate\x122\n" +"\n" +"path_error\x18\x03 \x01(\v2\x11.gitaly.PathErrorH\x00R\tpathErrorB\a\n" +- "\x05error\"\x8b\x04\n" ++ "\x05error\"\xc3\x04\n" +"\x0fUserLandRequest\x128\n" +"\n" +"repository\x18\x01 \x01(\v2\x12.gitaly.RepositoryB\x04\x98\xc6,\x01R\n" +@@ -5511,11 +6260,71 @@ const file_operations_proto_rawDesc = "" +"\ttimestamp\x18\b \x01(\v2\x1a.google.protobuf.TimestampR\ttimestamp\x12#\n" +"\rmerge_message\x18\t \x01(\fR\fmergeMessage\x12+\n" +"\x11resolve_conflicts\x18\n" +- " \x01(\bR\x10resolveConflicts\"U\n" ++ " \x01(\bR\x10resolveConflicts\x126\n" ++ "\n" ++ "resolution\x18\v \x01(\v2\x16.gitaly.LandResolutionR\n" ++ "resolution\"U\n" +"\bStrategy\x12\x1f\n" +"\x1bSTRATEGY_REBASE_UNSPECIFIED\x10\x00\x12\x12\n" +"\x0eSTRATEGY_MERGE\x10\x01\x12\x14\n" +- "\x10STRATEGY_FF_ONLY\x10\x02\"\x83\x03\n" ++ "\x10STRATEGY_FF_ONLY\x10\x02\"\x96\x02\n" ++ "\fLandConflict\x12\x10\n" ++ "\x03tip\x18\x01 \x01(\tR\x03tip\x12\x16\n" ++ "\x06commit\x18\x02 \x01(\tR\x06commit\x12\x1d\n" ++ "\n" ++ "merge_base\x18\x03 \x01(\tR\tmergeBase\x12\x1f\n" ++ "\vtip_message\x18\x04 \x01(\fR\n" ++ "tipMessage\x12%\n" ++ "\x0ecommit_message\x18\x05 \x01(\fR\rcommitMessage\x12-\n" ++ "\x12messages_truncated\x18\x06 \x01(\bR\x11messagesTruncated\x12.\n" ++ "\x05files\x18\a \x03(\v2\x18.gitaly.LandConflictFileR\x05files\x12\x16\n" ++ "\x06reason\x18\b \x01(\tR\x06reason\"\x95\x05\n" ++ "\x10LandConflictFile\x12\x12\n" ++ "\x04path\x18\x01 \x01(\fR\x04path\x121\n" ++ "\x04kind\x18\x02 \x01(\x0e2\x1d.gitaly.LandConflictFile.KindR\x04kind\x12,\n" ++ "\x04base\x18\x03 \x01(\v2\x18.gitaly.LandConflictSideR\x04base\x12,\n" ++ "\x04ours\x18\x04 \x01(\v2\x18.gitaly.LandConflictSideR\x04ours\x120\n" ++ "\x06theirs\x18\x05 \x01(\v2\x18.gitaly.LandConflictSideR\x06theirs\x12.\n" ++ "\x05hunks\x18\x06 \x03(\v2\x18.gitaly.LandConflictHunkR\x05hunks\x12:\n" ++ "\aoutcome\x18\a \x01(\x0e2 .gitaly.LandConflictFile.OutcomeR\aoutcome\x12\x16\n" ++ "\x06reason\x18\b \x01(\tR\x06reason\x12)\n" ++ "\x10syntax_unchecked\x18\t \x01(\bR\x0fsyntaxUnchecked\"g\n" ++ "\x04Kind\x12\x14\n" ++ "\x10KIND_UNSPECIFIED\x10\x00\x12\x10\n" ++ "\fKIND_CONTENT\x10\x01\x12\x16\n" ++ "\x12KIND_MODIFY_DELETE\x10\x02\x12\x10\n" ++ "\fKIND_ADD_ADD\x10\x03\x12\r\n" ++ "\tKIND_MODE\x10\x04\"\x93\x01\n" ++ "\aOutcome\x12\x17\n" ++ "\x13OUTCOME_UNSPECIFIED\x10\x00\x12\x14\n" ++ "\x10OUTCOME_NOT_SENT\x10\x01\x12\x14\n" ++ "\x10OUTCOME_REJECTED\x10\x02\x12\x12\n" ++ "\x0eOUTCOME_FAILED\x10\x03\x12\x14\n" ++ "\x10OUTCOME_RESOLVED\x10\x04\x12\x19\n" ++ "\x15OUTCOME_NOT_ATTEMPTED\x10\x05\"8\n" ++ "\x10LandConflictSide\x12\x10\n" ++ "\x03oid\x18\x01 \x01(\tR\x03oid\x12\x12\n" ++ "\x04mode\x18\x02 \x01(\tR\x04mode\"\x8b\x01\n" ++ "\x10LandConflictHunk\x12%\n" ++ "\x04base\x18\x01 \x01(\v2\x11.gitaly.LineRangeR\x04base\x12%\n" ++ "\x04ours\x18\x02 \x01(\v2\x11.gitaly.LineRangeR\x04ours\x12)\n" ++ "\x06theirs\x18\x03 \x01(\v2\x11.gitaly.LineRangeR\x06theirs\"3\n" ++ "\tLineRange\x12\x14\n" ++ "\x05start\x18\x01 \x01(\rR\x05start\x12\x10\n" ++ "\x03end\x18\x02 \x01(\rR\x03end\"j\n" ++ "\x0eLandResolution\x12\x10\n" ++ "\x03tip\x18\x01 \x01(\tR\x03tip\x12\x16\n" ++ "\x06commit\x18\x02 \x01(\tR\x06commit\x12.\n" ++ "\x05files\x18\x03 \x03(\v2\x18.gitaly.LandResolvedFileR\x05files\"\xd4\x01\n" ++ "\x10LandResolvedFile\x12\x12\n" ++ "\x04path\x18\x01 \x01(\fR\x04path\x127\n" ++ "\x06action\x18\x02 \x01(\x0e2\x1f.gitaly.LandResolvedFile.ActionR\x06action\x12\x12\n" ++ "\x04mode\x18\x03 \x01(\tR\x04mode\x12\x18\n" ++ "\acontent\x18\x04 \x01(\fR\acontent\"E\n" ++ "\x06Action\x12\x16\n" ++ "\x12ACTION_UNSPECIFIED\x10\x00\x12\x10\n" ++ "\fACTION_WRITE\x10\x01\x12\x11\n" ++ "\rACTION_DELETE\x10\x02\"\x83\x03\n" +"\x10UserLandResponse\x12B\n" +"\rbranch_update\x18\x01 \x01(\v2\x1d.gitaly.OperationBranchUpdateR\fbranchUpdate\x12(\n" +"\x10landed_commit_id\x18\x02 \x01(\tR\x0elandedCommitId\x12\x1c\n" +@@ -5570,233 +6379,256 @@ func file_operations_proto_rawDescGZIP() []byte {return file_operations_proto_rawDescData}-var file_operations_proto_enumTypes = make([]protoimpl.EnumInfo, 3)-var file_operations_proto_msgTypes = make([]protoimpl.MessageInfo, 54)+var file_operations_proto_enumTypes = make([]protoimpl.EnumInfo, 6)+var file_operations_proto_msgTypes = make([]protoimpl.MessageInfo, 61)var file_operations_proto_goTypes = []any{(UserRevertResponse_CreateTreeError)(0), // 0: gitaly.UserRevertResponse.CreateTreeError(UserCommitFilesActionHeader_ActionType)(0), // 1: gitaly.UserCommitFilesActionHeader.ActionType(UserLandRequest_Strategy)(0), // 2: gitaly.UserLandRequest.Strategy- (*UserCreateBranchRequest)(nil), // 3: gitaly.UserCreateBranchRequest- (*UserCreateBranchResponse)(nil), // 4: gitaly.UserCreateBranchResponse- (*UserCreateBranchError)(nil), // 5: gitaly.UserCreateBranchError- (*UserUpdateBranchRequest)(nil), // 6: gitaly.UserUpdateBranchRequest- (*UserUpdateBranchResponse)(nil), // 7: gitaly.UserUpdateBranchResponse- (*UserDeleteBranchRequest)(nil), // 8: gitaly.UserDeleteBranchRequest- (*UserDeleteBranchResponse)(nil), // 9: gitaly.UserDeleteBranchResponse- (*UserDeleteBranchError)(nil), // 10: gitaly.UserDeleteBranchError- (*UserDeleteTagRequest)(nil), // 11: gitaly.UserDeleteTagRequest- (*UserDeleteTagResponse)(nil), // 12: gitaly.UserDeleteTagResponse- (*UserCreateTagRequest)(nil), // 13: gitaly.UserCreateTagRequest- (*UserCreateTagResponse)(nil), // 14: gitaly.UserCreateTagResponse- (*UserCreateTagError)(nil), // 15: gitaly.UserCreateTagError- (*UserMergeBranchRequest)(nil), // 16: gitaly.UserMergeBranchRequest- (*UserMergeBranchResponse)(nil), // 17: gitaly.UserMergeBranchResponse- (*UserMergeBranchError)(nil), // 18: gitaly.UserMergeBranchError- (*UserMergeToRefRequest)(nil), // 19: gitaly.UserMergeToRefRequest- (*UserMergeToRefResponse)(nil), // 20: gitaly.UserMergeToRefResponse- (*UserMergeToRefError)(nil), // 21: gitaly.UserMergeToRefError- (*UserRebaseToRefRequest)(nil), // 22: gitaly.UserRebaseToRefRequest- (*UserRebaseToRefResponse)(nil), // 23: gitaly.UserRebaseToRefResponse- (*OperationBranchUpdate)(nil), // 24: gitaly.OperationBranchUpdate- (*UserFFBranchError)(nil), // 25: gitaly.UserFFBranchError- (*UserFFBranchRequest)(nil), // 26: gitaly.UserFFBranchRequest- (*UserFFBranchResponse)(nil), // 27: gitaly.UserFFBranchResponse- (*UserCherryPickRequest)(nil), // 28: gitaly.UserCherryPickRequest- (*UserCherryPickResponse)(nil), // 29: gitaly.UserCherryPickResponse- (*UserCherryPickError)(nil), // 30: gitaly.UserCherryPickError- (*UserRevertRequest)(nil), // 31: gitaly.UserRevertRequest- (*UserRevertResponse)(nil), // 32: gitaly.UserRevertResponse- (*UserRevertError)(nil), // 33: gitaly.UserRevertError- (*UserCommitFilesActionHeader)(nil), // 34: gitaly.UserCommitFilesActionHeader- (*UserCommitFilesAction)(nil), // 35: gitaly.UserCommitFilesAction- (*UserCommitFilesRequestHeader)(nil), // 36: gitaly.UserCommitFilesRequestHeader- (*UserCommitFilesRequest)(nil), // 37: gitaly.UserCommitFilesRequest- (*UserCommitFilesResponse)(nil), // 38: gitaly.UserCommitFilesResponse- (*UserCommitFilesError)(nil), // 39: gitaly.UserCommitFilesError- (*UserRebaseConfirmableRequest)(nil), // 40: gitaly.UserRebaseConfirmableRequest- (*UserRebaseConfirmableResponse)(nil), // 41: gitaly.UserRebaseConfirmableResponse- (*UserSquashRequest)(nil), // 42: gitaly.UserSquashRequest- (*UserSquashResponse)(nil), // 43: gitaly.UserSquashResponse- (*UserRebaseConfirmableError)(nil), // 44: gitaly.UserRebaseConfirmableError- (*UserSquashError)(nil), // 45: gitaly.UserSquashError- (*UserApplyPatchRequest)(nil), // 46: gitaly.UserApplyPatchRequest- (*UserApplyPatchError)(nil), // 47: gitaly.UserApplyPatchError- (*UserApplyPatchResponse)(nil), // 48: gitaly.UserApplyPatchResponse- (*UserUpdateSubmoduleRequest)(nil), // 49: gitaly.UserUpdateSubmoduleRequest- (*UserUpdateSubmoduleResponse)(nil), // 50: gitaly.UserUpdateSubmoduleResponse- (*UserUpdateSubmoduleError)(nil), // 51: gitaly.UserUpdateSubmoduleError- (*UserLandRequest)(nil), // 52: gitaly.UserLandRequest- (*UserLandResponse)(nil), // 53: gitaly.UserLandResponse- (*UserLandError)(nil), // 54: gitaly.UserLandError- (*UserRebaseConfirmableRequest_Header)(nil), // 55: gitaly.UserRebaseConfirmableRequest.Header- (*UserApplyPatchRequest_Header)(nil), // 56: gitaly.UserApplyPatchRequest.Header- (*Repository)(nil), // 57: gitaly.Repository- (*User)(nil), // 58: gitaly.User- (*Branch)(nil), // 59: gitaly.Branch- (*CustomHookError)(nil), // 60: gitaly.CustomHookError- (*AccessCheckError)(nil), // 61: gitaly.AccessCheckError- (*ReferenceUpdateError)(nil), // 62: gitaly.ReferenceUpdateError- (*timestamppb.Timestamp)(nil), // 63: google.protobuf.Timestamp- (*Tag)(nil), // 64: gitaly.Tag- (*ReferenceExistsError)(nil), // 65: gitaly.ReferenceExistsError- (*MergeConflictError)(nil), // 66: gitaly.MergeConflictError- (*GitCommit)(nil), // 67: gitaly.GitCommit- (*NotAncestorError)(nil), // 68: gitaly.NotAncestorError- (*ChangesAlreadyAppliedError)(nil), // 69: gitaly.ChangesAlreadyAppliedError- (*IndexError)(nil), // 70: gitaly.IndexError- (*ResolveRevisionError)(nil), // 71: gitaly.ResolveRevisionError- (*PathError)(nil), // 72: gitaly.PathError+ (LandConflictFile_Kind)(0), // 3: gitaly.LandConflictFile.Kind+ (LandConflictFile_Outcome)(0), // 4: gitaly.LandConflictFile.Outcome+ (LandResolvedFile_Action)(0), // 5: gitaly.LandResolvedFile.Action+ (*UserCreateBranchRequest)(nil), // 6: gitaly.UserCreateBranchRequest+ (*UserCreateBranchResponse)(nil), // 7: gitaly.UserCreateBranchResponse+ (*UserCreateBranchError)(nil), // 8: gitaly.UserCreateBranchError+ (*UserUpdateBranchRequest)(nil), // 9: gitaly.UserUpdateBranchRequest+ (*UserUpdateBranchResponse)(nil), // 10: gitaly.UserUpdateBranchResponse+ (*UserDeleteBranchRequest)(nil), // 11: gitaly.UserDeleteBranchRequest+ (*UserDeleteBranchResponse)(nil), // 12: gitaly.UserDeleteBranchResponse+ (*UserDeleteBranchError)(nil), // 13: gitaly.UserDeleteBranchError+ (*UserDeleteTagRequest)(nil), // 14: gitaly.UserDeleteTagRequest+ (*UserDeleteTagResponse)(nil), // 15: gitaly.UserDeleteTagResponse+ (*UserCreateTagRequest)(nil), // 16: gitaly.UserCreateTagRequest+ (*UserCreateTagResponse)(nil), // 17: gitaly.UserCreateTagResponse+ (*UserCreateTagError)(nil), // 18: gitaly.UserCreateTagError+ (*UserMergeBranchRequest)(nil), // 19: gitaly.UserMergeBranchRequest+ (*UserMergeBranchResponse)(nil), // 20: gitaly.UserMergeBranchResponse+ (*UserMergeBranchError)(nil), // 21: gitaly.UserMergeBranchError+ (*UserMergeToRefRequest)(nil), // 22: gitaly.UserMergeToRefRequest+ (*UserMergeToRefResponse)(nil), // 23: gitaly.UserMergeToRefResponse+ (*UserMergeToRefError)(nil), // 24: gitaly.UserMergeToRefError+ (*UserRebaseToRefRequest)(nil), // 25: gitaly.UserRebaseToRefRequest+ (*UserRebaseToRefResponse)(nil), // 26: gitaly.UserRebaseToRefResponse+ (*OperationBranchUpdate)(nil), // 27: gitaly.OperationBranchUpdate+ (*UserFFBranchError)(nil), // 28: gitaly.UserFFBranchError+ (*UserFFBranchRequest)(nil), // 29: gitaly.UserFFBranchRequest+ (*UserFFBranchResponse)(nil), // 30: gitaly.UserFFBranchResponse+ (*UserCherryPickRequest)(nil), // 31: gitaly.UserCherryPickRequest+ (*UserCherryPickResponse)(nil), // 32: gitaly.UserCherryPickResponse+ (*UserCherryPickError)(nil), // 33: gitaly.UserCherryPickError+ (*UserRevertRequest)(nil), // 34: gitaly.UserRevertRequest+ (*UserRevertResponse)(nil), // 35: gitaly.UserRevertResponse+ (*UserRevertError)(nil), // 36: gitaly.UserRevertError+ (*UserCommitFilesActionHeader)(nil), // 37: gitaly.UserCommitFilesActionHeader+ (*UserCommitFilesAction)(nil), // 38: gitaly.UserCommitFilesAction+ (*UserCommitFilesRequestHeader)(nil), // 39: gitaly.UserCommitFilesRequestHeader+ (*UserCommitFilesRequest)(nil), // 40: gitaly.UserCommitFilesRequest+ (*UserCommitFilesResponse)(nil), // 41: gitaly.UserCommitFilesResponse+ (*UserCommitFilesError)(nil), // 42: gitaly.UserCommitFilesError+ (*UserRebaseConfirmableRequest)(nil), // 43: gitaly.UserRebaseConfirmableRequest+ (*UserRebaseConfirmableResponse)(nil), // 44: gitaly.UserRebaseConfirmableResponse+ (*UserSquashRequest)(nil), // 45: gitaly.UserSquashRequest+ (*UserSquashResponse)(nil), // 46: gitaly.UserSquashResponse+ (*UserRebaseConfirmableError)(nil), // 47: gitaly.UserRebaseConfirmableError+ (*UserSquashError)(nil), // 48: gitaly.UserSquashError+ (*UserApplyPatchRequest)(nil), // 49: gitaly.UserApplyPatchRequest+ (*UserApplyPatchError)(nil), // 50: gitaly.UserApplyPatchError+ (*UserApplyPatchResponse)(nil), // 51: gitaly.UserApplyPatchResponse+ (*UserUpdateSubmoduleRequest)(nil), // 52: gitaly.UserUpdateSubmoduleRequest+ (*UserUpdateSubmoduleResponse)(nil), // 53: gitaly.UserUpdateSubmoduleResponse+ (*UserUpdateSubmoduleError)(nil), // 54: gitaly.UserUpdateSubmoduleError+ (*UserLandRequest)(nil), // 55: gitaly.UserLandRequest+ (*LandConflict)(nil), // 56: gitaly.LandConflict+ (*LandConflictFile)(nil), // 57: gitaly.LandConflictFile+ (*LandConflictSide)(nil), // 58: gitaly.LandConflictSide+ (*LandConflictHunk)(nil), // 59: gitaly.LandConflictHunk+ (*LineRange)(nil), // 60: gitaly.LineRange+ (*LandResolution)(nil), // 61: gitaly.LandResolution+ (*LandResolvedFile)(nil), // 62: gitaly.LandResolvedFile+ (*UserLandResponse)(nil), // 63: gitaly.UserLandResponse+ (*UserLandError)(nil), // 64: gitaly.UserLandError+ (*UserRebaseConfirmableRequest_Header)(nil), // 65: gitaly.UserRebaseConfirmableRequest.Header+ (*UserApplyPatchRequest_Header)(nil), // 66: gitaly.UserApplyPatchRequest.Header+ (*Repository)(nil), // 67: gitaly.Repository+ (*User)(nil), // 68: gitaly.User+ (*Branch)(nil), // 69: gitaly.Branch+ (*CustomHookError)(nil), // 70: gitaly.CustomHookError+ (*AccessCheckError)(nil), // 71: gitaly.AccessCheckError+ (*ReferenceUpdateError)(nil), // 72: gitaly.ReferenceUpdateError+ (*timestamppb.Timestamp)(nil), // 73: google.protobuf.Timestamp+ (*Tag)(nil), // 74: gitaly.Tag+ (*ReferenceExistsError)(nil), // 75: gitaly.ReferenceExistsError+ (*MergeConflictError)(nil), // 76: gitaly.MergeConflictError+ (*GitCommit)(nil), // 77: gitaly.GitCommit+ (*NotAncestorError)(nil), // 78: gitaly.NotAncestorError+ (*ChangesAlreadyAppliedError)(nil), // 79: gitaly.ChangesAlreadyAppliedError+ (*IndexError)(nil), // 80: gitaly.IndexError+ (*ResolveRevisionError)(nil), // 81: gitaly.ResolveRevisionError+ (*PathError)(nil), // 82: gitaly.PathError}var file_operations_proto_depIdxs = []int32{- 57, // 0: gitaly.UserCreateBranchRequest.repository:type_name -> gitaly.Repository- 58, // 1: gitaly.UserCreateBranchRequest.user:type_name -> gitaly.User- 59, // 2: gitaly.UserCreateBranchResponse.branch:type_name -> gitaly.Branch- 60, // 3: gitaly.UserCreateBranchError.custom_hook:type_name -> gitaly.CustomHookError- 57, // 4: gitaly.UserUpdateBranchRequest.repository:type_name -> gitaly.Repository- 58, // 5: gitaly.UserUpdateBranchRequest.user:type_name -> gitaly.User- 57, // 6: gitaly.UserDeleteBranchRequest.repository:type_name -> gitaly.Repository- 58, // 7: gitaly.UserDeleteBranchRequest.user:type_name -> gitaly.User- 61, // 8: gitaly.UserDeleteBranchError.access_check:type_name -> gitaly.AccessCheckError- 62, // 9: gitaly.UserDeleteBranchError.reference_update:type_name -> gitaly.ReferenceUpdateError- 60, // 10: gitaly.UserDeleteBranchError.custom_hook:type_name -> gitaly.CustomHookError- 57, // 11: gitaly.UserDeleteTagRequest.repository:type_name -> gitaly.Repository- 58, // 12: gitaly.UserDeleteTagRequest.user:type_name -> gitaly.User- 57, // 13: gitaly.UserCreateTagRequest.repository:type_name -> gitaly.Repository- 58, // 14: gitaly.UserCreateTagRequest.user:type_name -> gitaly.User- 63, // 15: gitaly.UserCreateTagRequest.timestamp:type_name -> google.protobuf.Timestamp- 64, // 16: gitaly.UserCreateTagResponse.tag:type_name -> gitaly.Tag- 61, // 17: gitaly.UserCreateTagError.access_check:type_name -> gitaly.AccessCheckError- 62, // 18: gitaly.UserCreateTagError.reference_update:type_name -> gitaly.ReferenceUpdateError- 60, // 19: gitaly.UserCreateTagError.custom_hook:type_name -> gitaly.CustomHookError- 65, // 20: gitaly.UserCreateTagError.reference_exists:type_name -> gitaly.ReferenceExistsError- 57, // 21: gitaly.UserMergeBranchRequest.repository:type_name -> gitaly.Repository- 58, // 22: gitaly.UserMergeBranchRequest.user:type_name -> gitaly.User- 63, // 23: gitaly.UserMergeBranchRequest.timestamp:type_name -> google.protobuf.Timestamp- 24, // 24: gitaly.UserMergeBranchResponse.branch_update:type_name -> gitaly.OperationBranchUpdate- 61, // 25: gitaly.UserMergeBranchError.access_check:type_name -> gitaly.AccessCheckError- 62, // 26: gitaly.UserMergeBranchError.reference_update:type_name -> gitaly.ReferenceUpdateError- 60, // 27: gitaly.UserMergeBranchError.custom_hook:type_name -> gitaly.CustomHookError- 66, // 28: gitaly.UserMergeBranchError.merge_conflict:type_name -> gitaly.MergeConflictError- 57, // 29: gitaly.UserMergeToRefRequest.repository:type_name -> gitaly.Repository- 58, // 30: gitaly.UserMergeToRefRequest.user:type_name -> gitaly.User- 63, // 31: gitaly.UserMergeToRefRequest.timestamp:type_name -> google.protobuf.Timestamp- 66, // 32: gitaly.UserMergeToRefError.merge_conflict:type_name -> gitaly.MergeConflictError- 57, // 33: gitaly.UserRebaseToRefRequest.repository:type_name -> gitaly.Repository- 58, // 34: gitaly.UserRebaseToRefRequest.user:type_name -> gitaly.User- 63, // 35: gitaly.UserRebaseToRefRequest.timestamp:type_name -> google.protobuf.Timestamp- 60, // 36: gitaly.UserFFBranchError.custom_hook:type_name -> gitaly.CustomHookError- 62, // 37: gitaly.UserFFBranchError.reference_update:type_name -> gitaly.ReferenceUpdateError- 57, // 38: gitaly.UserFFBranchRequest.repository:type_name -> gitaly.Repository- 58, // 39: gitaly.UserFFBranchRequest.user:type_name -> gitaly.User- 24, // 40: gitaly.UserFFBranchResponse.branch_update:type_name -> gitaly.OperationBranchUpdate- 57, // 41: gitaly.UserCherryPickRequest.repository:type_name -> gitaly.Repository- 58, // 42: gitaly.UserCherryPickRequest.user:type_name -> gitaly.User- 67, // 43: gitaly.UserCherryPickRequest.commit:type_name -> gitaly.GitCommit- 57, // 44: gitaly.UserCherryPickRequest.start_repository:type_name -> gitaly.Repository- 63, // 45: gitaly.UserCherryPickRequest.timestamp:type_name -> google.protobuf.Timestamp- 24, // 46: gitaly.UserCherryPickResponse.branch_update:type_name -> gitaly.OperationBranchUpdate- 66, // 47: gitaly.UserCherryPickError.cherry_pick_conflict:type_name -> gitaly.MergeConflictError- 68, // 48: gitaly.UserCherryPickError.target_branch_diverged:type_name -> gitaly.NotAncestorError- 69, // 49: gitaly.UserCherryPickError.changes_already_applied:type_name -> gitaly.ChangesAlreadyAppliedError- 61, // 50: gitaly.UserCherryPickError.access_check:type_name -> gitaly.AccessCheckError- 57, // 51: gitaly.UserRevertRequest.repository:type_name -> gitaly.Repository- 58, // 52: gitaly.UserRevertRequest.user:type_name -> gitaly.User- 67, // 53: gitaly.UserRevertRequest.commit:type_name -> gitaly.GitCommit- 57, // 54: gitaly.UserRevertRequest.start_repository:type_name -> gitaly.Repository- 63, // 55: gitaly.UserRevertRequest.timestamp:type_name -> google.protobuf.Timestamp- 24, // 56: gitaly.UserRevertResponse.branch_update:type_name -> gitaly.OperationBranchUpdate+ 67, // 0: gitaly.UserCreateBranchRequest.repository:type_name -> gitaly.Repository+ 68, // 1: gitaly.UserCreateBranchRequest.user:type_name -> gitaly.User+ 69, // 2: gitaly.UserCreateBranchResponse.branch:type_name -> gitaly.Branch+ 70, // 3: gitaly.UserCreateBranchError.custom_hook:type_name -> gitaly.CustomHookError+ 67, // 4: gitaly.UserUpdateBranchRequest.repository:type_name -> gitaly.Repository+ 68, // 5: gitaly.UserUpdateBranchRequest.user:type_name -> gitaly.User+ 67, // 6: gitaly.UserDeleteBranchRequest.repository:type_name -> gitaly.Repository+ 68, // 7: gitaly.UserDeleteBranchRequest.user:type_name -> gitaly.User+ 71, // 8: gitaly.UserDeleteBranchError.access_check:type_name -> gitaly.AccessCheckError+ 72, // 9: gitaly.UserDeleteBranchError.reference_update:type_name -> gitaly.ReferenceUpdateError+ 70, // 10: gitaly.UserDeleteBranchError.custom_hook:type_name -> gitaly.CustomHookError+ 67, // 11: gitaly.UserDeleteTagRequest.repository:type_name -> gitaly.Repository+ 68, // 12: gitaly.UserDeleteTagRequest.user:type_name -> gitaly.User+ 67, // 13: gitaly.UserCreateTagRequest.repository:type_name -> gitaly.Repository+ 68, // 14: gitaly.UserCreateTagRequest.user:type_name -> gitaly.User+ 73, // 15: gitaly.UserCreateTagRequest.timestamp:type_name -> google.protobuf.Timestamp+ 74, // 16: gitaly.UserCreateTagResponse.tag:type_name -> gitaly.Tag+ 71, // 17: gitaly.UserCreateTagError.access_check:type_name -> gitaly.AccessCheckError+ 72, // 18: gitaly.UserCreateTagError.reference_update:type_name -> gitaly.ReferenceUpdateError+ 70, // 19: gitaly.UserCreateTagError.custom_hook:type_name -> gitaly.CustomHookError+ 75, // 20: gitaly.UserCreateTagError.reference_exists:type_name -> gitaly.ReferenceExistsError+ 67, // 21: gitaly.UserMergeBranchRequest.repository:type_name -> gitaly.Repository+ 68, // 22: gitaly.UserMergeBranchRequest.user:type_name -> gitaly.User+ 73, // 23: gitaly.UserMergeBranchRequest.timestamp:type_name -> google.protobuf.Timestamp+ 27, // 24: gitaly.UserMergeBranchResponse.branch_update:type_name -> gitaly.OperationBranchUpdate+ 71, // 25: gitaly.UserMergeBranchError.access_check:type_name -> gitaly.AccessCheckError+ 72, // 26: gitaly.UserMergeBranchError.reference_update:type_name -> gitaly.ReferenceUpdateError+ 70, // 27: gitaly.UserMergeBranchError.custom_hook:type_name -> gitaly.CustomHookError+ 76, // 28: gitaly.UserMergeBranchError.merge_conflict:type_name -> gitaly.MergeConflictError+ 67, // 29: gitaly.UserMergeToRefRequest.repository:type_name -> gitaly.Repository+ 68, // 30: gitaly.UserMergeToRefRequest.user:type_name -> gitaly.User+ 73, // 31: gitaly.UserMergeToRefRequest.timestamp:type_name -> google.protobuf.Timestamp+ 76, // 32: gitaly.UserMergeToRefError.merge_conflict:type_name -> gitaly.MergeConflictError+ 67, // 33: gitaly.UserRebaseToRefRequest.repository:type_name -> gitaly.Repository+ 68, // 34: gitaly.UserRebaseToRefRequest.user:type_name -> gitaly.User+ 73, // 35: gitaly.UserRebaseToRefRequest.timestamp:type_name -> google.protobuf.Timestamp+ 70, // 36: gitaly.UserFFBranchError.custom_hook:type_name -> gitaly.CustomHookError+ 72, // 37: gitaly.UserFFBranchError.reference_update:type_name -> gitaly.ReferenceUpdateError+ 67, // 38: gitaly.UserFFBranchRequest.repository:type_name -> gitaly.Repository+ 68, // 39: gitaly.UserFFBranchRequest.user:type_name -> gitaly.User+ 27, // 40: gitaly.UserFFBranchResponse.branch_update:type_name -> gitaly.OperationBranchUpdate+ 67, // 41: gitaly.UserCherryPickRequest.repository:type_name -> gitaly.Repository+ 68, // 42: gitaly.UserCherryPickRequest.user:type_name -> gitaly.User+ 77, // 43: gitaly.UserCherryPickRequest.commit:type_name -> gitaly.GitCommit+ 67, // 44: gitaly.UserCherryPickRequest.start_repository:type_name -> gitaly.Repository+ 73, // 45: gitaly.UserCherryPickRequest.timestamp:type_name -> google.protobuf.Timestamp+ 27, // 46: gitaly.UserCherryPickResponse.branch_update:type_name -> gitaly.OperationBranchUpdate+ 76, // 47: gitaly.UserCherryPickError.cherry_pick_conflict:type_name -> gitaly.MergeConflictError+ 78, // 48: gitaly.UserCherryPickError.target_branch_diverged:type_name -> gitaly.NotAncestorError+ 79, // 49: gitaly.UserCherryPickError.changes_already_applied:type_name -> gitaly.ChangesAlreadyAppliedError+ 71, // 50: gitaly.UserCherryPickError.access_check:type_name -> gitaly.AccessCheckError+ 67, // 51: gitaly.UserRevertRequest.repository:type_name -> gitaly.Repository+ 68, // 52: gitaly.UserRevertRequest.user:type_name -> gitaly.User+ 77, // 53: gitaly.UserRevertRequest.commit:type_name -> gitaly.GitCommit+ 67, // 54: gitaly.UserRevertRequest.start_repository:type_name -> gitaly.Repository+ 73, // 55: gitaly.UserRevertRequest.timestamp:type_name -> google.protobuf.Timestamp+ 27, // 56: gitaly.UserRevertResponse.branch_update:type_name -> gitaly.OperationBranchUpdate0, // 57: gitaly.UserRevertResponse.create_tree_error_code:type_name -> gitaly.UserRevertResponse.CreateTreeError- 66, // 58: gitaly.UserRevertError.merge_conflict:type_name -> gitaly.MergeConflictError- 69, // 59: gitaly.UserRevertError.changes_already_applied:type_name -> gitaly.ChangesAlreadyAppliedError- 60, // 60: gitaly.UserRevertError.custom_hook:type_name -> gitaly.CustomHookError- 68, // 61: gitaly.UserRevertError.not_ancestor:type_name -> gitaly.NotAncestorError+ 76, // 58: gitaly.UserRevertError.merge_conflict:type_name -> gitaly.MergeConflictError+ 79, // 59: gitaly.UserRevertError.changes_already_applied:type_name -> gitaly.ChangesAlreadyAppliedError+ 70, // 60: gitaly.UserRevertError.custom_hook:type_name -> gitaly.CustomHookError+ 78, // 61: gitaly.UserRevertError.not_ancestor:type_name -> gitaly.NotAncestorError1, // 62: gitaly.UserCommitFilesActionHeader.action:type_name -> gitaly.UserCommitFilesActionHeader.ActionType- 34, // 63: gitaly.UserCommitFilesAction.header:type_name -> gitaly.UserCommitFilesActionHeader- 57, // 64: gitaly.UserCommitFilesRequestHeader.repository:type_name -> gitaly.Repository- 58, // 65: gitaly.UserCommitFilesRequestHeader.user:type_name -> gitaly.User- 57, // 66: gitaly.UserCommitFilesRequestHeader.start_repository:type_name -> gitaly.Repository- 63, // 67: gitaly.UserCommitFilesRequestHeader.timestamp:type_name -> google.protobuf.Timestamp- 36, // 68: gitaly.UserCommitFilesRequest.header:type_name -> gitaly.UserCommitFilesRequestHeader- 35, // 69: gitaly.UserCommitFilesRequest.action:type_name -> gitaly.UserCommitFilesAction- 24, // 70: gitaly.UserCommitFilesResponse.branch_update:type_name -> gitaly.OperationBranchUpdate- 61, // 71: gitaly.UserCommitFilesError.access_check:type_name -> gitaly.AccessCheckError- 70, // 72: gitaly.UserCommitFilesError.index_update:type_name -> gitaly.IndexError- 60, // 73: gitaly.UserCommitFilesError.custom_hook:type_name -> gitaly.CustomHookError- 55, // 74: gitaly.UserRebaseConfirmableRequest.header:type_name -> gitaly.UserRebaseConfirmableRequest.Header- 57, // 75: gitaly.UserSquashRequest.repository:type_name -> gitaly.Repository- 58, // 76: gitaly.UserSquashRequest.user:type_name -> gitaly.User- 58, // 77: gitaly.UserSquashRequest.author:type_name -> gitaly.User- 63, // 78: gitaly.UserSquashRequest.timestamp:type_name -> google.protobuf.Timestamp- 66, // 79: gitaly.UserRebaseConfirmableError.rebase_conflict:type_name -> gitaly.MergeConflictError- 61, // 80: gitaly.UserRebaseConfirmableError.access_check:type_name -> gitaly.AccessCheckError- 71, // 81: gitaly.UserSquashError.resolve_revision:type_name -> gitaly.ResolveRevisionError- 66, // 82: gitaly.UserSquashError.rebase_conflict:type_name -> gitaly.MergeConflictError- 56, // 83: gitaly.UserApplyPatchRequest.header:type_name -> gitaly.UserApplyPatchRequest.Header- 60, // 84: gitaly.UserApplyPatchError.custom_hook:type_name -> gitaly.CustomHookError- 24, // 85: gitaly.UserApplyPatchResponse.branch_update:type_name -> gitaly.OperationBranchUpdate- 57, // 86: gitaly.UserUpdateSubmoduleRequest.repository:type_name -> gitaly.Repository- 58, // 87: gitaly.UserUpdateSubmoduleRequest.user:type_name -> gitaly.User- 63, // 88: gitaly.UserUpdateSubmoduleRequest.timestamp:type_name -> google.protobuf.Timestamp- 24, // 89: gitaly.UserUpdateSubmoduleResponse.branch_update:type_name -> gitaly.OperationBranchUpdate- 60, // 90: gitaly.UserUpdateSubmoduleError.custom_hook:type_name -> gitaly.CustomHookError- 62, // 91: gitaly.UserUpdateSubmoduleError.reference_update:type_name -> gitaly.ReferenceUpdateError- 72, // 92: gitaly.UserUpdateSubmoduleError.path_error:type_name -> gitaly.PathError- 57, // 93: gitaly.UserLandRequest.repository:type_name -> gitaly.Repository- 58, // 94: gitaly.UserLandRequest.user:type_name -> gitaly.User+ 37, // 63: gitaly.UserCommitFilesAction.header:type_name -> gitaly.UserCommitFilesActionHeader+ 67, // 64: gitaly.UserCommitFilesRequestHeader.repository:type_name -> gitaly.Repository+ 68, // 65: gitaly.UserCommitFilesRequestHeader.user:type_name -> gitaly.User+ 67, // 66: gitaly.UserCommitFilesRequestHeader.start_repository:type_name -> gitaly.Repository+ 73, // 67: gitaly.UserCommitFilesRequestHeader.timestamp:type_name -> google.protobuf.Timestamp+ 39, // 68: gitaly.UserCommitFilesRequest.header:type_name -> gitaly.UserCommitFilesRequestHeader+ 38, // 69: gitaly.UserCommitFilesRequest.action:type_name -> gitaly.UserCommitFilesAction+ 27, // 70: gitaly.UserCommitFilesResponse.branch_update:type_name -> gitaly.OperationBranchUpdate+ 71, // 71: gitaly.UserCommitFilesError.access_check:type_name -> gitaly.AccessCheckError+ 80, // 72: gitaly.UserCommitFilesError.index_update:type_name -> gitaly.IndexError+ 70, // 73: gitaly.UserCommitFilesError.custom_hook:type_name -> gitaly.CustomHookError+ 65, // 74: gitaly.UserRebaseConfirmableRequest.header:type_name -> gitaly.UserRebaseConfirmableRequest.Header+ 67, // 75: gitaly.UserSquashRequest.repository:type_name -> gitaly.Repository+ 68, // 76: gitaly.UserSquashRequest.user:type_name -> gitaly.User+ 68, // 77: gitaly.UserSquashRequest.author:type_name -> gitaly.User+ 73, // 78: gitaly.UserSquashRequest.timestamp:type_name -> google.protobuf.Timestamp+ 76, // 79: gitaly.UserRebaseConfirmableError.rebase_conflict:type_name -> gitaly.MergeConflictError+ 71, // 80: gitaly.UserRebaseConfirmableError.access_check:type_name -> gitaly.AccessCheckError+ 81, // 81: gitaly.UserSquashError.resolve_revision:type_name -> gitaly.ResolveRevisionError+ 76, // 82: gitaly.UserSquashError.rebase_conflict:type_name -> gitaly.MergeConflictError+ 66, // 83: gitaly.UserApplyPatchRequest.header:type_name -> gitaly.UserApplyPatchRequest.Header+ 70, // 84: gitaly.UserApplyPatchError.custom_hook:type_name -> gitaly.CustomHookError+ 27, // 85: gitaly.UserApplyPatchResponse.branch_update:type_name -> gitaly.OperationBranchUpdate+ 67, // 86: gitaly.UserUpdateSubmoduleRequest.repository:type_name -> gitaly.Repository+ 68, // 87: gitaly.UserUpdateSubmoduleRequest.user:type_name -> gitaly.User+ 73, // 88: gitaly.UserUpdateSubmoduleRequest.timestamp:type_name -> google.protobuf.Timestamp+ 27, // 89: gitaly.UserUpdateSubmoduleResponse.branch_update:type_name -> gitaly.OperationBranchUpdate+ 70, // 90: gitaly.UserUpdateSubmoduleError.custom_hook:type_name -> gitaly.CustomHookError+ 72, // 91: gitaly.UserUpdateSubmoduleError.reference_update:type_name -> gitaly.ReferenceUpdateError+ 82, // 92: gitaly.UserUpdateSubmoduleError.path_error:type_name -> gitaly.PathError+ 67, // 93: gitaly.UserLandRequest.repository:type_name -> gitaly.Repository+ 68, // 94: gitaly.UserLandRequest.user:type_name -> gitaly.User2, // 95: gitaly.UserLandRequest.strategy:type_name -> gitaly.UserLandRequest.Strategy- 63, // 96: gitaly.UserLandRequest.timestamp:type_name -> google.protobuf.Timestamp- 24, // 97: gitaly.UserLandResponse.branch_update:type_name -> gitaly.OperationBranchUpdate- 66, // 98: gitaly.UserLandError.merge_conflict:type_name -> gitaly.MergeConflictError- 68, // 99: gitaly.UserLandError.not_ancestor:type_name -> gitaly.NotAncestorError- 62, // 100: gitaly.UserLandError.reference_update:type_name -> gitaly.ReferenceUpdateError- 60, // 101: gitaly.UserLandError.custom_hook:type_name -> gitaly.CustomHookError- 61, // 102: gitaly.UserLandError.access_check:type_name -> gitaly.AccessCheckError- 57, // 103: gitaly.UserRebaseConfirmableRequest.Header.repository:type_name -> gitaly.Repository- 58, // 104: gitaly.UserRebaseConfirmableRequest.Header.user:type_name -> gitaly.User- 57, // 105: gitaly.UserRebaseConfirmableRequest.Header.remote_repository:type_name -> gitaly.Repository- 63, // 106: gitaly.UserRebaseConfirmableRequest.Header.timestamp:type_name -> google.protobuf.Timestamp- 57, // 107: gitaly.UserApplyPatchRequest.Header.repository:type_name -> gitaly.Repository- 58, // 108: gitaly.UserApplyPatchRequest.Header.user:type_name -> gitaly.User- 63, // 109: gitaly.UserApplyPatchRequest.Header.timestamp:type_name -> google.protobuf.Timestamp- 3, // 110: gitaly.OperationService.UserCreateBranch:input_type -> gitaly.UserCreateBranchRequest- 6, // 111: gitaly.OperationService.UserUpdateBranch:input_type -> gitaly.UserUpdateBranchRequest- 8, // 112: gitaly.OperationService.UserDeleteBranch:input_type -> gitaly.UserDeleteBranchRequest- 13, // 113: gitaly.OperationService.UserCreateTag:input_type -> gitaly.UserCreateTagRequest- 11, // 114: gitaly.OperationService.UserDeleteTag:input_type -> gitaly.UserDeleteTagRequest- 19, // 115: gitaly.OperationService.UserMergeToRef:input_type -> gitaly.UserMergeToRefRequest- 22, // 116: gitaly.OperationService.UserRebaseToRef:input_type -> gitaly.UserRebaseToRefRequest- 16, // 117: gitaly.OperationService.UserMergeBranch:input_type -> gitaly.UserMergeBranchRequest- 26, // 118: gitaly.OperationService.UserFFBranch:input_type -> gitaly.UserFFBranchRequest- 28, // 119: gitaly.OperationService.UserCherryPick:input_type -> gitaly.UserCherryPickRequest- 37, // 120: gitaly.OperationService.UserCommitFiles:input_type -> gitaly.UserCommitFilesRequest- 40, // 121: gitaly.OperationService.UserRebaseConfirmable:input_type -> gitaly.UserRebaseConfirmableRequest- 31, // 122: gitaly.OperationService.UserRevert:input_type -> gitaly.UserRevertRequest- 42, // 123: gitaly.OperationService.UserSquash:input_type -> gitaly.UserSquashRequest- 46, // 124: gitaly.OperationService.UserApplyPatch:input_type -> gitaly.UserApplyPatchRequest- 49, // 125: gitaly.OperationService.UserUpdateSubmodule:input_type -> gitaly.UserUpdateSubmoduleRequest- 52, // 126: gitaly.OperationService.UserLand:input_type -> gitaly.UserLandRequest- 4, // 127: gitaly.OperationService.UserCreateBranch:output_type -> gitaly.UserCreateBranchResponse- 7, // 128: gitaly.OperationService.UserUpdateBranch:output_type -> gitaly.UserUpdateBranchResponse- 9, // 129: gitaly.OperationService.UserDeleteBranch:output_type -> gitaly.UserDeleteBranchResponse- 14, // 130: gitaly.OperationService.UserCreateTag:output_type -> gitaly.UserCreateTagResponse- 12, // 131: gitaly.OperationService.UserDeleteTag:output_type -> gitaly.UserDeleteTagResponse- 20, // 132: gitaly.OperationService.UserMergeToRef:output_type -> gitaly.UserMergeToRefResponse- 23, // 133: gitaly.OperationService.UserRebaseToRef:output_type -> gitaly.UserRebaseToRefResponse- 17, // 134: gitaly.OperationService.UserMergeBranch:output_type -> gitaly.UserMergeBranchResponse- 27, // 135: gitaly.OperationService.UserFFBranch:output_type -> gitaly.UserFFBranchResponse- 29, // 136: gitaly.OperationService.UserCherryPick:output_type -> gitaly.UserCherryPickResponse- 38, // 137: gitaly.OperationService.UserCommitFiles:output_type -> gitaly.UserCommitFilesResponse- 41, // 138: gitaly.OperationService.UserRebaseConfirmable:output_type -> gitaly.UserRebaseConfirmableResponse- 32, // 139: gitaly.OperationService.UserRevert:output_type -> gitaly.UserRevertResponse- 43, // 140: gitaly.OperationService.UserSquash:output_type -> gitaly.UserSquashResponse- 48, // 141: gitaly.OperationService.UserApplyPatch:output_type -> gitaly.UserApplyPatchResponse- 50, // 142: gitaly.OperationService.UserUpdateSubmodule:output_type -> gitaly.UserUpdateSubmoduleResponse- 53, // 143: gitaly.OperationService.UserLand:output_type -> gitaly.UserLandResponse- 127, // [127:144] is the sub-list for method output_type- 110, // [110:127] is the sub-list for method input_type- 110, // [110:110] is the sub-list for extension type_name- 110, // [110:110] is the sub-list for extension extendee- 0, // [0:110] is the sub-list for field type_name+ 73, // 96: gitaly.UserLandRequest.timestamp:type_name -> google.protobuf.Timestamp+ 61, // 97: gitaly.UserLandRequest.resolution:type_name -> gitaly.LandResolution+ 57, // 98: gitaly.LandConflict.files:type_name -> gitaly.LandConflictFile+ 3, // 99: gitaly.LandConflictFile.kind:type_name -> gitaly.LandConflictFile.Kind+ 58, // 100: gitaly.LandConflictFile.base:type_name -> gitaly.LandConflictSide+ 58, // 101: gitaly.LandConflictFile.ours:type_name -> gitaly.LandConflictSide+ 58, // 102: gitaly.LandConflictFile.theirs:type_name -> gitaly.LandConflictSide+ 59, // 103: gitaly.LandConflictFile.hunks:type_name -> gitaly.LandConflictHunk+ 4, // 104: gitaly.LandConflictFile.outcome:type_name -> gitaly.LandConflictFile.Outcome+ 60, // 105: gitaly.LandConflictHunk.base:type_name -> gitaly.LineRange+ 60, // 106: gitaly.LandConflictHunk.ours:type_name -> gitaly.LineRange+ 60, // 107: gitaly.LandConflictHunk.theirs:type_name -> gitaly.LineRange+ 62, // 108: gitaly.LandResolution.files:type_name -> gitaly.LandResolvedFile+ 5, // 109: gitaly.LandResolvedFile.action:type_name -> gitaly.LandResolvedFile.Action+ 27, // 110: gitaly.UserLandResponse.branch_update:type_name -> gitaly.OperationBranchUpdate+ 76, // 111: gitaly.UserLandError.merge_conflict:type_name -> gitaly.MergeConflictError+ 78, // 112: gitaly.UserLandError.not_ancestor:type_name -> gitaly.NotAncestorError+ 72, // 113: gitaly.UserLandError.reference_update:type_name -> gitaly.ReferenceUpdateError+ 70, // 114: gitaly.UserLandError.custom_hook:type_name -> gitaly.CustomHookError+ 71, // 115: gitaly.UserLandError.access_check:type_name -> gitaly.AccessCheckError+ 67, // 116: gitaly.UserRebaseConfirmableRequest.Header.repository:type_name -> gitaly.Repository+ 68, // 117: gitaly.UserRebaseConfirmableRequest.Header.user:type_name -> gitaly.User+ 67, // 118: gitaly.UserRebaseConfirmableRequest.Header.remote_repository:type_name -> gitaly.Repository+ 73, // 119: gitaly.UserRebaseConfirmableRequest.Header.timestamp:type_name -> google.protobuf.Timestamp+ 67, // 120: gitaly.UserApplyPatchRequest.Header.repository:type_name -> gitaly.Repository+ 68, // 121: gitaly.UserApplyPatchRequest.Header.user:type_name -> gitaly.User+ 73, // 122: gitaly.UserApplyPatchRequest.Header.timestamp:type_name -> google.protobuf.Timestamp+ 6, // 123: gitaly.OperationService.UserCreateBranch:input_type -> gitaly.UserCreateBranchRequest+ 9, // 124: gitaly.OperationService.UserUpdateBranch:input_type -> gitaly.UserUpdateBranchRequest+ 11, // 125: gitaly.OperationService.UserDeleteBranch:input_type -> gitaly.UserDeleteBranchRequest+ 16, // 126: gitaly.OperationService.UserCreateTag:input_type -> gitaly.UserCreateTagRequest+ 14, // 127: gitaly.OperationService.UserDeleteTag:input_type -> gitaly.UserDeleteTagRequest+ 22, // 128: gitaly.OperationService.UserMergeToRef:input_type -> gitaly.UserMergeToRefRequest+ 25, // 129: gitaly.OperationService.UserRebaseToRef:input_type -> gitaly.UserRebaseToRefRequest+ 19, // 130: gitaly.OperationService.UserMergeBranch:input_type -> gitaly.UserMergeBranchRequest+ 29, // 131: gitaly.OperationService.UserFFBranch:input_type -> gitaly.UserFFBranchRequest+ 31, // 132: gitaly.OperationService.UserCherryPick:input_type -> gitaly.UserCherryPickRequest+ 40, // 133: gitaly.OperationService.UserCommitFiles:input_type -> gitaly.UserCommitFilesRequest+ 43, // 134: gitaly.OperationService.UserRebaseConfirmable:input_type -> gitaly.UserRebaseConfirmableRequest+ 34, // 135: gitaly.OperationService.UserRevert:input_type -> gitaly.UserRevertRequest+ 45, // 136: gitaly.OperationService.UserSquash:input_type -> gitaly.UserSquashRequest+ 49, // 137: gitaly.OperationService.UserApplyPatch:input_type -> gitaly.UserApplyPatchRequest+ 52, // 138: gitaly.OperationService.UserUpdateSubmodule:input_type -> gitaly.UserUpdateSubmoduleRequest+ 55, // 139: gitaly.OperationService.UserLand:input_type -> gitaly.UserLandRequest+ 7, // 140: gitaly.OperationService.UserCreateBranch:output_type -> gitaly.UserCreateBranchResponse+ 10, // 141: gitaly.OperationService.UserUpdateBranch:output_type -> gitaly.UserUpdateBranchResponse+ 12, // 142: gitaly.OperationService.UserDeleteBranch:output_type -> gitaly.UserDeleteBranchResponse+ 17, // 143: gitaly.OperationService.UserCreateTag:output_type -> gitaly.UserCreateTagResponse+ 15, // 144: gitaly.OperationService.UserDeleteTag:output_type -> gitaly.UserDeleteTagResponse+ 23, // 145: gitaly.OperationService.UserMergeToRef:output_type -> gitaly.UserMergeToRefResponse+ 26, // 146: gitaly.OperationService.UserRebaseToRef:output_type -> gitaly.UserRebaseToRefResponse+ 20, // 147: gitaly.OperationService.UserMergeBranch:output_type -> gitaly.UserMergeBranchResponse+ 30, // 148: gitaly.OperationService.UserFFBranch:output_type -> gitaly.UserFFBranchResponse+ 32, // 149: gitaly.OperationService.UserCherryPick:output_type -> gitaly.UserCherryPickResponse+ 41, // 150: gitaly.OperationService.UserCommitFiles:output_type -> gitaly.UserCommitFilesResponse+ 44, // 151: gitaly.OperationService.UserRebaseConfirmable:output_type -> gitaly.UserRebaseConfirmableResponse+ 35, // 152: gitaly.OperationService.UserRevert:output_type -> gitaly.UserRevertResponse+ 46, // 153: gitaly.OperationService.UserSquash:output_type -> gitaly.UserSquashResponse+ 51, // 154: gitaly.OperationService.UserApplyPatch:output_type -> gitaly.UserApplyPatchResponse+ 53, // 155: gitaly.OperationService.UserUpdateSubmodule:output_type -> gitaly.UserUpdateSubmoduleResponse+ 63, // 156: gitaly.OperationService.UserLand:output_type -> gitaly.UserLandResponse+ 140, // [140:157] is the sub-list for method output_type+ 123, // [123:140] is the sub-list for method input_type+ 123, // [123:123] is the sub-list for extension type_name+ 123, // [123:123] is the sub-list for extension extendee+ 0, // [0:123] is the sub-list for field type_name}func init() { file_operations_proto_init() }@@ -5887,7 +6719,7 @@ func file_operations_proto_init() {(*UserUpdateSubmoduleError_ReferenceUpdate)(nil),(*UserUpdateSubmoduleError_PathError)(nil),}- file_operations_proto_msgTypes[51].OneofWrappers = []any{+ file_operations_proto_msgTypes[58].OneofWrappers = []any{(*UserLandError_MergeConflict)(nil),(*UserLandError_NotAncestor)(nil),(*UserLandError_ReferenceUpdate)(nil),@@ -5899,8 +6731,8 @@ func file_operations_proto_init() {File: protoimpl.DescBuilder{GoPackagePath: reflect.TypeOf(x{}).PkgPath(),RawDescriptor: unsafe.Slice(unsafe.StringData(file_operations_proto_rawDesc), len(file_operations_proto_rawDesc)),- NumEnums: 3,- NumMessages: 54,+ NumEnums: 6,+ NumMessages: 61,NumExtensions: 0,NumServices: 1,},diff --git a/proto/operations.proto b/proto/operations.protoindex d5a31f2..b549e27 100644--- a/proto/operations.proto+++ b/proto/operations.proto@@ -1270,6 +1270,158 @@ message UserLandRequest {// fails with merge_conflict as usual) when no resolver is configured or the// server policy does not allow it for the caller.bool resolve_conflicts = 10;+ // resolution lands commit_id with the caller's resolution of the conflicts that a+ // LandConflict described, instead of asking the server's resolver. The server+ // accepts it only when resolution.tip equals the current branch tip,+ // resolution.commit equals commit_id, and resolution.files resolve exactly the+ // paths that conflict at that tip, each once; otherwise the land fails with a+ // fresh LandConflict. It is validated like a resolver answer (no conflict+ // markers; modes 100644, 100755 or 120000; sizes; the syntax check when a+ // resolver is configured) and lands as a merge commit with a+ // Graft-Resolved-By: agent/<actor> trailer. The whole request is bounded by+ // the 4 MiB gRPC message limit.+ LandResolution resolution = 11;+}++// LandConflict describes the conflicts of a land that the server did not resolve, so+// that the caller can resolve them and land again with UserLandRequest.resolution. It+// is sent as an additional detail of the error, next to UserLandError, when the+// request set resolve_conflicts or resolution.+message LandConflict {+ // tip is the branch tip that the change was merged with.+ string tip = 1;+ // commit is the landed commit.+ string commit = 2;+ // merge_base is the merge base of tip and commit, empty for unrelated histories.+ string merge_base = 3;+ // tip_message is the message of the tip, cut to 4 KiB.+ bytes tip_message = 4;+ // commit_message is the message of the landed commit, cut to 4 KiB.+ bytes commit_message = 5;+ // messages_truncated is set when a message was cut.+ bool messages_truncated = 6;+ // files are the conflicting files, at most max_files of them.+ repeated LandConflictFile files = 7;+ // reason is set when the server did not try to resolve the request at all, for+ // example because it has too many files or the actor may not resolve; it is cut to+ // 512 bytes.+ string reason = 8;+}++// LandConflictFile is one conflicting file of a LandConflict.+message LandConflictFile {+ // Kind is the kind of the conflict.+ enum Kind {+ // KIND_UNSPECIFIED is never sent.+ KIND_UNSPECIFIED = 0;+ // KIND_CONTENT: both sides changed the content.+ KIND_CONTENT = 1;+ // KIND_MODIFY_DELETE: one side changed the file, the other deleted it.+ KIND_MODIFY_DELETE = 2;+ // KIND_ADD_ADD: both sides added the file.+ KIND_ADD_ADD = 3;+ // KIND_MODE: the sides differ in mode only.+ KIND_MODE = 4;+ }+ // Outcome is what the server did with the file.+ enum Outcome {+ // OUTCOME_UNSPECIFIED is never sent.+ OUTCOME_UNSPECIFIED = 0;+ // OUTCOME_NOT_SENT: the file was not sent to the resolver (reason: lockfile,+ // binary, large, generated, minified, denied path, invalid UTF-8 path).+ OUTCOME_NOT_SENT = 1;+ // OUTCOME_REJECTED: the resolver's result failed a check (reason: the check).+ OUTCOME_REJECTED = 2;+ // OUTCOME_FAILED: the resolver failed on the file (reason: the error, such as a+ // model error or "AI budget exhausted").+ OUTCOME_FAILED = 3;+ // OUTCOME_RESOLVED: the file was resolved, but the land failed because another+ // file was not.+ OUTCOME_RESOLVED = 4;+ // OUTCOME_NOT_ATTEMPTED: the request was not resolved at all (see+ // LandConflict.reason).+ OUTCOME_NOT_ATTEMPTED = 5;+ }+ // path is the path of the conflict in the merged tree.+ bytes path = 1;+ // kind is the kind of the conflict.+ Kind kind = 2;+ // base, ours and theirs are the sides; an absent side is unset. ours is the tip's+ // side, theirs the landed commit's.+ LandConflictSide base = 3;+ // ours is the tip's side.+ LandConflictSide ours = 4;+ // theirs is the landed commit's side.+ LandConflictSide theirs = 5;+ // hunks are the conflicting regions, in order.+ repeated LandConflictHunk hunks = 6;+ // outcome is what the server did with the file.+ Outcome outcome = 7;+ // reason explains the outcome, cut to 512 bytes.+ string reason = 8;+ // syntax_unchecked is set when a resolution of the file was accepted without a+ // syntax verdict, because a side does not parse with the grammar of its language.+ bool syntax_unchecked = 9;+}++// LandConflictSide is one side of a conflicting file; its content is read by oid.+message LandConflictSide {+ // oid is the object ID of the blob.+ string oid = 1;+ // mode is the file mode.+ string mode = 2;+}++// LandConflictHunk is a conflicting region as line ranges of each side. Each range+// counts the lines of the side it names (base of the base side's file, ours of the+// tip's, theirs of the landed commit's), 1-based and half-open ([start, end)); an+// empty range (start == end) is an insertion point before line start.+message LandConflictHunk {+ // base is the range in the base side.+ LineRange base = 1;+ // ours is the range in the tip's side.+ LineRange ours = 2;+ // theirs is the range in the landed commit's side.+ LineRange theirs = 3;+}++// LineRange is a half-open range of 1-based lines.+message LineRange {+ // start is the first line of the range.+ uint32 start = 1;+ // end is the line after the last line of the range.+ uint32 end = 2;+}++// LandResolution is the caller's resolution of the conflicts of a LandConflict.+message LandResolution {+ // tip is the tip that the resolution was made against, from LandConflict.tip.+ string tip = 1;+ // commit is the landed commit, LandConflict.commit; it must equal commit_id.+ string commit = 2;+ // files resolve every conflicting path exactly once.+ repeated LandResolvedFile files = 3;+}++// LandResolvedFile resolves one conflicting path.+message LandResolvedFile {+ // Action is what becomes of the path.+ enum Action {+ // ACTION_UNSPECIFIED is rejected.+ ACTION_UNSPECIFIED = 0;+ // ACTION_WRITE writes content with mode.+ ACTION_WRITE = 1;+ // ACTION_DELETE deletes the path.+ ACTION_DELETE = 2;+ }+ // path is the path of the conflict.+ bytes path = 1;+ // action is what becomes of the path.+ Action action = 2;+ // mode is 100644, 100755 or 120000 for ACTION_WRITE.+ string mode = 3;+ // content is the file's content for ACTION_WRITE.+ bytes content = 4;}// UserLandResponse is a response for the UserLand RPC.diff --git a/tools/graft-agents/cmd/graft-resolve/main.go b/tools/graft-agents/cmd/graft-resolve/main.goindex 785254c..eab7fc4 100644--- a/tools/graft-agents/cmd/graft-resolve/main.go+++ b/tools/graft-agents/cmd/graft-resolve/main.go@@ -127,12 +127,32 @@ func runCommand(args []string, stdin io.Reader, stdout, stderr io.Writer) int {ctx, cancel := context.WithTimeout(context.Background(), res.Timeout)defer cancel()+ if req.Operation == protocol.OperationCheck {+ verdicts, err := res.Check(ctx, req)+ if err != nil {+ fmt.Fprintln(stderr, err)+ return 1+ }+ return writeOut(stdout, stderr, verdicts)+ }resp, err := res.Resolve(ctx, req)if err != nil {fmt.Fprintln(stderr, err)+ // A refusal also goes to stdout as an ErrorResponse, with the outcome of every file.+ var unresolved *resolve.UnresolvedError+ if errors.As(err, &unresolved) {+ if out, jerr := json.Marshal(unresolved.Response()); jerr == nil {+ _, _ = stdout.Write(append(out, '\n'))+ }+ }return 1}- out, err := json.Marshal(resp)+ return writeOut(stdout, stderr, resp)+}++// writeOut writes the answer of command mode on stdout.+func writeOut(stdout, stderr io.Writer, answer any) int {+ out, err := json.Marshal(answer)if err != nil {fmt.Fprintf(stderr, "graft-resolve: encoding response: %v\n", err)return 1diff --git a/tools/graft-agents/cmd/graft-resolve/main_test.go b/tools/graft-agents/cmd/graft-resolve/main_test.goindex 800d767..880e229 100644--- a/tools/graft-agents/cmd/graft-resolve/main_test.go+++ b/tools/graft-agents/cmd/graft-resolve/main_test.go@@ -81,14 +81,48 @@ func TestCommandModeUnresolvableExitsOne(t *testing.T) {if code := run(nil, stdin, &stdout, &stderr); code != 1 {t.Fatalf("exit %d, want 1", code)}- if stdout.Len() != 0 {- t.Fatalf("stdout must be empty on failure: %q", stdout.String())+ // The refusal is on stdout as an ErrorResponse with the outcome of every file (the server reads+ // it), and its reason on stderr (for a server that predates the outcomes).+ var refusal protocol.ErrorResponse+ if err := json.Unmarshal(stdout.Bytes(), &refusal); err != nil {+ t.Fatalf("stdout is not an ErrorResponse: %v\n%s", err, stdout.String())+ }+ if !strings.Contains(refusal.Error, "hard.go") || len(refusal.Files) != 1 ||+ refusal.Files[0] != (protocol.FileOutcome{Path: "hard.go", Outcome: protocol.OutcomeFailed, Reason: "no strategy resolved this conflict"}) {+ t.Fatalf("refusal = %+v", refusal)}if !strings.Contains(stderr.String(), "hard.go") || !strings.Contains(stderr.String(), "unresolved") {t.Fatalf("stderr = %q", stderr.String())}}+func TestCommandModeCheck(t *testing.T) {+ req := protocol.Request{+ Version: protocol.Version, Operation: protocol.OperationCheck,+ Files: []protocol.FileConflict{fileConflict("a.txt", "base\n", "ours\n", "theirs\n")},+ Resolution: []protocol.ResolvedFile{+ {Path: "a.txt", Action: protocol.ActionWrite, Mode: protocol.ModeFile, Content: []byte("merged\n")},+ },+ Limits: protocol.Limits{MaxFileBytes: 1 << 20},+ }+ raw, err := json.Marshal(req)+ if err != nil {+ t.Fatal(err)+ }+ var stdout, stderr bytes.Buffer+ if code := run(nil, bytes.NewReader(raw), &stdout, &stderr); code != 0 {+ t.Fatalf("exit %d: %s", code, stderr.String())+ }+ var resp protocol.CheckResponse+ if err := json.Unmarshal(stdout.Bytes(), &resp); err != nil {+ t.Fatalf("stdout is not a CheckResponse: %v\n%s", err, stdout.String())+ }+ if resp.Operation != protocol.OperationCheck || resp.Resolver != "graft-resolve" || len(resp.Files) != 1 ||+ resp.Files[0] != (protocol.CheckFile{Path: "a.txt", OK: true, Syntax: protocol.SyntaxNone}) {+ t.Fatalf("check response %+v", resp)+ }+}+func TestCommandModeInvalidJSON(t *testing.T) {var stdout, stderr bytes.Bufferif code := run(nil, strings.NewReader("{not json"), &stdout, &stderr); code != 1 {diff --git a/tools/graft-agents/cmd/graft-resolve/serve.go b/tools/graft-agents/cmd/graft-resolve/serve.goindex 1a3de45..a8f1160 100644--- a/tools/graft-agents/cmd/graft-resolve/serve.go+++ b/tools/graft-agents/cmd/graft-resolve/serve.go@@ -81,12 +81,24 @@ func newHandler(res *resolve.Resolver, token string) http.Handler {ctx, cancel := context.WithTimeout(r.Context(), res.Timeout)defer cancel()+ if req.Operation == protocol.OperationCheck {+ verdicts, err := res.Check(ctx, req)+ switch {+ case errors.Is(err, resolve.ErrInvalidRequest):+ writeError(w, http.StatusBadRequest, err.Error())+ case err != nil:+ writeError(w, http.StatusInternalServerError, err.Error())+ default:+ writeJSON(w, http.StatusOK, verdicts)+ }+ return+ }resp, err := res.Resolve(ctx, req)if err != nil {var unresolved *resolve.UnresolvedErrorswitch {case errors.As(err, &unresolved):- writeError(w, http.StatusUnprocessableEntity, err.Error())+ writeJSON(w, http.StatusUnprocessableEntity, unresolved.Response())case errors.Is(err, resolve.ErrInvalidRequest):writeError(w, http.StatusBadRequest, err.Error())default:diff --git a/tools/graft-agents/cmd/graft-resolve/serve_test.go b/tools/graft-agents/cmd/graft-resolve/serve_test.goindex 8ca9127..d79951e 100644--- a/tools/graft-agents/cmd/graft-resolve/serve_test.go+++ b/tools/graft-agents/cmd/graft-resolve/serve_test.go@@ -168,6 +168,9 @@ func TestServeUnresolvedIs422WithError(t *testing.T) {if !strings.Contains(e.Error, "code.go") {t.Fatalf("error = %q", e.Error)}+ if len(e.Files) != 1 || e.Files[0].Path != "code.go" || e.Files[0].Outcome != protocol.OutcomeFailed {+ t.Fatalf("files = %+v, want the outcome of code.go", e.Files)+ }}func TestServeMalformedRequests(t *testing.T) {diff --git a/tools/graft-agents/protocol/fields_test.go b/tools/graft-agents/protocol/fields_test.gonew file mode 100644index 0000000..f4b5135--- /dev/null+++ b/tools/graft-agents/protocol/fields_test.go@@ -0,0 +1,64 @@+package protocol++import (+ "encoding/json"+ "os"+ "reflect"+ "sort"+ "strings"+ "testing"+)++// TestProtocolFieldsMatchTheServerCopy checks the wire fields of this copy of the protocol against+// the server's golden file (internal/graft/resolver/testdata/protocol-fields.json), which the+// server's copy is tested against too, so that the two copies cannot drift.+func TestProtocolFieldsMatchTheServerCopy(t *testing.T) {+ data, err := os.ReadFile("../../../internal/graft/resolver/testdata/protocol-fields.json")+ if err != nil {+ t.Fatal(err)+ }+ var golden map[string]any+ if err := json.Unmarshal(data, &golden); err != nil {+ t.Fatal(err)+ }+ delete(golden, "comment")++ types := map[string]reflect.Type{+ "request": reflect.TypeOf(Request{}),+ "repository": reflect.TypeOf(Repository{}),+ "messages": reflect.TypeOf(Messages{}),+ "file": reflect.TypeOf(FileConflict{}),+ "side": reflect.TypeOf(Side{}),+ "limits": reflect.TypeOf(Limits{}),+ "response": reflect.TypeOf(Response{}),+ "response_file": reflect.TypeOf(ResolvedFile{}),+ "error_response": reflect.TypeOf(ErrorResponse{}),+ "file_outcome": reflect.TypeOf(FileOutcome{}),+ "check_response": reflect.TypeOf(CheckResponse{}),+ "check_file": reflect.TypeOf(CheckFile{}),+ }+ if len(golden) != len(types) {+ t.Fatalf("golden file has %d messages, this copy %d", len(golden), len(types))+ }+ for name, typ := range types {+ raw, ok := golden[name].([]any)+ if !ok {+ t.Fatalf("golden file lacks %q", name)+ }+ var want []string+ for _, v := range raw {+ want = append(want, v.(string))+ }+ var got []string+ for i := 0; i < typ.NumField(); i++ {+ n, _, _ := strings.Cut(typ.Field(i).Tag.Get("json"), ",")+ if n != "" && n != "-" {+ got = append(got, n)+ }+ }+ sort.Strings(got)+ if !reflect.DeepEqual(got, want) {+ t.Errorf("%s: fields %v, golden %v", name, got, want)+ }+ }+}diff --git a/tools/graft-agents/protocol/protocol.go b/tools/graft-agents/protocol/protocol.goindex d708f73..20148d2 100644--- a/tools/graft-agents/protocol/protocol.go+++ b/tools/graft-agents/protocol/protocol.go@@ -49,7 +49,9 @@ const MaxResolverNameBytes = 128// Request is the server-to-resolver message.type Request struct {- Version int `json:"version"`+ Version int `json:"version"`+ // Operation is OperationResolve (also when absent) or OperationCheck.+ Operation string `json:"operation,omitempty"`Repository Repository `json:"repository"`Branch string `json:"branch"`Tip string `json:"tip"`@@ -58,9 +60,48 @@ type Request struct {Messages Messages `json:"messages"`Actor string `json:"actor"`Files []FileConflict `json:"files"`+ // Resolution is, for OperationCheck only, the agent's resolution of Files to check.+ Resolution []ResolvedFile `json:"resolution,omitempty"`Limits Limits `json:"limits"`}+// Operations of a request.+const (+ // OperationResolve asks for a resolution of Files; an absent operation means it.+ OperationResolve = "resolve"+ // OperationCheck asks to check an agent's Resolution of Files with the checks of the resolver's+ // own answers, answered with a CheckResponse.+ OperationCheck = "check"+)++// CheckResponse is the answer to an OperationCheck request: one verdict per file of the+// resolution, in its order.+type CheckResponse struct {+ Version int `json:"version"`+ Operation string `json:"operation"`+ // Resolver names the checker, for the Graft-Checked-By trailer of the server.+ Resolver string `json:"resolver"`+ Files []CheckFile `json:"files"`+}++// Syntax verdicts of a CheckFile.+const (+ // SyntaxChecked: both sides parse, and so does the resolution.+ SyntaxChecked = "checked"+ // SyntaxUnchecked: a side does not parse with the grammar, so there is no syntax verdict.+ SyntaxUnchecked = "unchecked"+ // SyntaxNone: the path has no grammar, or the file is deleted.+ SyntaxNone = "none"+)++// CheckFile is the verdict on one file of a resolution.+type CheckFile struct {+ Path string `json:"path"`+ OK bool `json:"ok"`+ Reason string `json:"reason,omitempty"`+ Syntax string `json:"syntax"`+}+// Repository identifies the repository the conflict belongs to.type Repository struct {Storage string `json:"storage"`@@ -115,6 +156,27 @@ type ResolvedFile struct {// ErrorResponse is the body of an HTTP 422 (unresolvable) or other error.type ErrorResponse struct {Error string `json:"error"`+ // Files is the outcome of every file of a refused request (optional). The server uses it only+ // when it has exactly one entry per requested path, each with a known outcome.+ Files []FileOutcome `json:"files,omitempty"`+}++// Outcomes of a file in a refusal.+const (+ // OutcomeResolved: the file was resolved, but not every file of the request.+ OutcomeResolved = "resolved"+ // OutcomeRejected: a strategy's result for the file failed a rule or a check.+ OutcomeRejected = "rejected"+ // OutcomeFailed: the file could not be resolved (no strategy applied, a model error, a spent+ // AI budget).+ OutcomeFailed = "failed"+)++// FileOutcome is what the resolver did with one file of a refused request.+type FileOutcome struct {+ Path string `json:"path"`+ Outcome string `json:"outcome"`+ Reason string `json:"reason,omitempty"`}// ValidMode reports whether mode is one of the modes the server accepts.diff --git a/tools/graft-agents/resolve/bench/judge.go b/tools/graft-agents/resolve/bench/judge.goindex 46aee9e..66b55ef 100644--- a/tools/graft-agents/resolve/bench/judge.go+++ b/tools/graft-agents/resolve/bench/judge.go@@ -84,16 +84,19 @@ const ()// notSentReason returns why the file at p with the given sides would not be sent to the resolver,-// or "" when it would be. generated reports linguist-generated for the path.+// or "" when it would be. generated reports linguist-generated for the path. It mirrors the+// server's SendRules.Reason (internal/graft/resolver/sendrules.go), rule for rule and in the same+// order (large first: the server decides it from the size, before reading); both are tested+// against internal/graft/resolver/testdata/never-send.json.func notSentReason(p string, sides [][]byte, maxBytes int64, generated bool) string {for _, s := range sides {- if bytes.IndexByte(s, 0) >= 0 {- return NotSentBinary+ if int64(len(s)) > maxBytes {+ return NotSentLarge}}for _, s := range sides {- if int64(len(s)) > maxBytes {- return NotSentLarge+ if bytes.IndexByte(s, 0) >= 0 {+ return NotSentBinary}}if lockfiles[path.Base(p)] {@@ -136,16 +139,24 @@ func firstLines(s []byte, n int) []byte {return s[:end]}+// looksMinified reports whether a side larger than minifiedMinBytes has an average line longer+// than minifiedAverageLine or a line longer than minifiedLongestLine. It is the server's rule+// (internal/graft/resolver/sendrules.go): a final newline does not start another line.func looksMinified(s []byte) bool {if len(s) <= minifiedMinBytes {return false}- lines := bytes.Split(s, []byte("\n"))- longest := 0- for _, l := range lines {- if len(l) > longest {- longest = len(l)+ lines := bytes.Count(s, []byte{'\n'})+ if len(s) > 0 && s[len(s)-1] != '\n' {+ lines+++ }+ if lines > 0 && len(s)/lines > minifiedAverageLine {+ return true+ }+ for _, line := range bytes.Split(s, []byte{'\n'}) {+ if len(line) > minifiedLongestLine {+ return true}}- return longest > minifiedLongestLine || len(s)/len(lines) > minifiedAverageLine+ return false}diff --git a/tools/graft-agents/resolve/bench/vectors_test.go b/tools/graft-agents/resolve/bench/vectors_test.gonew file mode 100644index 0000000..2e7c98a--- /dev/null+++ b/tools/graft-agents/resolve/bench/vectors_test.go@@ -0,0 +1,53 @@+package bench++import (+ "encoding/json"+ "os"+ "strings"+ "testing"+)++// TestNotSentReasonVectors checks notSentReason against the server's test vectors+// (internal/graft/resolver/testdata/never-send.json), so that the bench and the server apply the+// same never-send rules in the same order.+func TestNotSentReasonVectors(t *testing.T) {+ data, err := os.ReadFile("../../../../internal/graft/resolver/testdata/never-send.json")+ if err != nil {+ t.Fatal(err)+ }+ var v struct {+ MaxFileBytes int64 `json:"max_file_bytes"`+ Cases []struct {+ Name string `json:"name"`+ Path string `json:"path"`+ Generated bool `json:"generated"`+ Sides []*[]struct {+ Text string `json:"text"`+ Repeat int `json:"repeat"`+ } `json:"sides"`+ Want string `json:"want"`+ } `json:"cases"`+ }+ if err := json.Unmarshal(data, &v); err != nil {+ t.Fatal(err)+ }+ if len(v.Cases) == 0 {+ t.Fatal("no vectors")+ }+ for _, c := range v.Cases {+ var sides [][]byte+ for _, side := range c.Sides {+ if side == nil {+ continue // the bench passes present sides only+ }+ var b strings.Builder+ for _, part := range *side {+ b.WriteString(strings.Repeat(part.Text, max(1, part.Repeat)))+ }+ sides = append(sides, []byte(b.String()))+ }+ if got := notSentReason(c.Path, sides, v.MaxFileBytes, c.Generated); got != c.Want {+ t.Errorf("%s: notSentReason = %q, want %q", c.Name, got, c.Want)+ }+ }+}diff --git a/tools/graft-agents/resolve/check.go b/tools/graft-agents/resolve/check.gonew file mode 100644index 0000000..67d413a--- /dev/null+++ b/tools/graft-agents/resolve/check.go@@ -0,0 +1,100 @@+package resolve++import (+ "context"+ "errors"+ "fmt"++ "github.com/feder-cr/git-ai/tools/graft-agents/protocol"+ "github.com/feder-cr/git-ai/tools/graft-agents/resolve/syntax"+)++// checkResolverName names graft-resolve in a check response, for the server's Graft-Checked-By+// trailer.+const checkResolverName = "graft-resolve"++// Check answers an OperationCheck request: it checks an agent's resolution of the request's files+// with the checks that an llm answer gets, so that one validation path applies to AI answers and+// agent resolutions (PLAN10 12). For every written file: the answer rules (action, mode, size,+// conflict markers), the syntax check (syntax.CheckMerge with the request's sides), then the+// configured checks for the path. A deletion only needs a valid action.+//+// A file that fails is a verdict, not an error. An error means the request could not be checked+// (malformed, or the context ended); the server fails closed on it.+func (r *Resolver) Check(ctx context.Context, req protocol.Request) (protocol.CheckResponse, error) {+ if req.Operation != protocol.OperationCheck {+ return protocol.CheckResponse{}, fmt.Errorf("%w: operation %q is not %q", ErrInvalidRequest, req.Operation, protocol.OperationCheck)+ }+ if err := validateRequest(req); err != nil {+ return protocol.CheckResponse{}, err+ }+ files := make(map[string]protocol.FileConflict, len(req.Files))+ for _, f := range req.Files {+ files[f.Path] = f+ }+ if len(req.Resolution) != len(req.Files) {+ return protocol.CheckResponse{}, fmt.Errorf("%w: the resolution has %d files, the request %d", ErrInvalidRequest, len(req.Resolution), len(req.Files))+ }+ seen := make(map[string]bool, len(req.Resolution))+ for _, res := range req.Resolution {+ if _, ok := files[res.Path]; !ok || seen[res.Path] {+ return protocol.CheckResponse{}, fmt.Errorf("%w: the resolution names %q, which is not a conflicting file or is named twice", ErrInvalidRequest, res.Path)+ }+ seen[res.Path] = true+ }+ maxBytes := req.Limits.MaxFileBytes+ if maxBytes <= 0 {+ maxBytes = protocol.DefaultMaxFileBytes+ }++ out := protocol.CheckResponse{Version: protocol.Version, Operation: protocol.OperationCheck, Resolver: checkResolverName}+ for _, res := range req.Resolution {+ verdict, err := r.checkFile(ctx, files[res.Path], Resolution{Action: res.Action, Mode: res.Mode, Content: res.Content}, maxBytes)+ if err != nil {+ return protocol.CheckResponse{}, err+ }+ out.Files = append(out.Files, verdict)+ }+ return out, nil+}++func (r *Resolver) checkFile(ctx context.Context, f protocol.FileConflict, res Resolution, maxBytes int64) (protocol.CheckFile, error) {+ verdict := protocol.CheckFile{Path: f.Path, Syntax: protocol.SyntaxNone}+ if err := checkResolution(res, maxBytes); err != nil {+ verdict.Reason = err.Error()+ return verdict, nil+ }+ if res.Action == protocol.ActionDelete {+ verdict.OK = true+ return verdict, nil+ }++ if res.Mode != protocol.ModeSymlink {+ if _, ok := syntax.LanguageOf(f.Path); ok {+ checked, err := syntax.CheckMerge(ctx, f.Path, res.Content, sideContent(f.Ours), sideContent(f.Theirs))+ var se *syntax.Error+ switch {+ case errors.As(err, &se):+ verdict.Syntax = protocol.SyntaxChecked+ verdict.Reason = se.Error()+ return verdict, nil+ case err != nil:+ return protocol.CheckFile{}, fmt.Errorf("checking the syntax of %q: %w", f.Path, err)+ case checked:+ verdict.Syntax = protocol.SyntaxChecked+ default:+ verdict.Syntax = protocol.SyntaxUnchecked+ }+ }+ }++ if err := r.runChecks(ctx, f.Path, res); err != nil {+ if ctxErr := ctx.Err(); ctxErr != nil {+ return protocol.CheckFile{}, ctxErr+ }+ verdict.Reason = "check failed: " + err.Error()+ return verdict, nil+ }+ verdict.OK = true+ return verdict, nil+}diff --git a/tools/graft-agents/resolve/check_test.go b/tools/graft-agents/resolve/check_test.gonew file mode 100644index 0000000..91590e5--- /dev/null+++ b/tools/graft-agents/resolve/check_test.go@@ -0,0 +1,121 @@+//go:build cgo++package resolve++import (+ "context"+ "errors"+ "strings"+ "testing"++ "github.com/feder-cr/git-ai/tools/graft-agents/protocol"+)++func checkSide(content string) *protocol.Side {+ return &protocol.Side{OID: "0123", Mode: protocol.ModeFile, Content: []byte(content)}+}++func checkRequest(resolution ...protocol.ResolvedFile) protocol.Request {+ files := []protocol.FileConflict{+ {Path: "a.go", Kind: protocol.KindContent, Base: checkSide("package a\n\nvar x = 1\n"), Ours: checkSide("package a\n\nvar x = 2\n"), Theirs: checkSide("package a\n\nvar x = 3\n")},+ {Path: "b.js", Kind: protocol.KindContent, Base: checkSide("// @flow\nconst x: ?number = 1;\n"), Ours: checkSide("// @flow\nconst x: ?number = 2;\n"), Theirs: checkSide("// @flow\nconst x: ?number = 3;\n")},+ {Path: "c.txt", Kind: protocol.KindContent, Base: checkSide("1\n"), Ours: checkSide("2\n"), Theirs: checkSide("3\n")},+ }+ return protocol.Request{+ Version: protocol.Version, Operation: protocol.OperationCheck,+ Repository: protocol.Repository{Storage: "default", RelativePath: "x.git"},+ Branch: "main", Tip: "tip", Commit: "commit", Actor: "agent-1",+ Files: files, Resolution: resolution,+ Limits: protocol.Limits{MaxFileBytes: 1 << 20},+ }+}++func write(p, content string) protocol.ResolvedFile {+ return protocol.ResolvedFile{Path: p, Action: protocol.ActionWrite, Mode: protocol.ModeFile, Content: []byte(content)}+}++func newCheckResolver(t *testing.T) *Resolver {+ t.Helper()+ cfg, err := ParseConfig([]byte("[[strategy]]\ntype = \"trivial\"\n"))+ if err != nil {+ t.Fatal(err)+ }+ r, err := cfg.Build()+ if err != nil {+ t.Fatal(err)+ }+ return r+}++func TestCheckGivesAVerdictPerFile(t *testing.T) {+ r := newCheckResolver(t)+ resp, err := r.Check(context.Background(), checkRequest(+ write("a.go", "package a\n\nvar x = 2 + 3\n"),+ write("b.js", "// @flow\nconst x: ?number = 5;\n"),+ protocol.ResolvedFile{Path: "c.txt", Action: protocol.ActionDelete},+ ))+ if err != nil {+ t.Fatal(err)+ }+ if resp.Operation != protocol.OperationCheck || resp.Version != protocol.Version || len(resp.Files) != 3 {+ t.Fatalf("response %+v", resp)+ }+ want := []protocol.CheckFile{+ {Path: "a.go", OK: true, Syntax: protocol.SyntaxChecked},+ {Path: "b.js", OK: true, Syntax: protocol.SyntaxUnchecked}, // Flow: the sides do not parse+ {Path: "c.txt", OK: true, Syntax: protocol.SyntaxNone},+ }+ for i, w := range want {+ if resp.Files[i] != w {+ t.Errorf("file %d: %+v, want %+v", i, resp.Files[i], w)+ }+ }+}++func TestCheckRejectsWhatAnLLMAnswerWouldFail(t *testing.T) {+ r := newCheckResolver(t)+ for name, tc := range map[string]struct {+ file protocol.ResolvedFile+ want string+ }{+ "syntax": {write("a.go", "package a\n\nvar x = \n"), "does not parse as go"},+ "markers": {write("a.go", "package a\n<<<<<<< ours\nvar x = 2\n=======\nvar x = 3\n>>>>>>> theirs\n"), "conflict markers"},+ "mode": {protocol.ResolvedFile{Path: "a.go", Action: protocol.ActionWrite, Mode: "160000", Content: []byte("x")}, "invalid mode"},+ "action": {protocol.ResolvedFile{Path: "a.go", Action: "rename"}, "unknown action"},+ } {+ t.Run(name, func(t *testing.T) {+ resp, err := r.Check(context.Background(), checkRequest(tc.file, write("b.js", "x\n"), write("c.txt", "x\n")))+ if err != nil {+ t.Fatal(err)+ }+ if f := resp.Files[0]; f.OK || !strings.Contains(f.Reason, tc.want) {+ t.Fatalf("verdict %+v, want a rejection mentioning %q", f, tc.want)+ }+ })+ }+}++func TestCheckRefusesMalformedRequests(t *testing.T) {+ r := newCheckResolver(t)+ ok := []protocol.ResolvedFile{write("a.go", "package a\n"), write("b.js", "x\n"), write("c.txt", "x\n")}+ for name, req := range map[string]protocol.Request{+ "missing file": checkRequest(ok[:2]...),+ "unknown path": checkRequest(ok[0], ok[1], write("d.txt", "x\n")),+ "named twice": checkRequest(ok[0], ok[0], ok[2]),+ "not a check": func() protocol.Request { q := checkRequest(ok...); q.Operation = "resolve"; return q }(),+ "wrong version": func() protocol.Request { q := checkRequest(ok...); q.Version = 9; return q }(),+ } {+ if _, err := r.Check(context.Background(), req); !errors.Is(err, ErrInvalidRequest) {+ t.Errorf("%s: err = %v, want ErrInvalidRequest", name, err)+ }+ }+ // A resolve request must not carry a check operation or a resolution.+ q := checkRequest(ok...)+ if _, err := r.Resolve(context.Background(), q); !errors.Is(err, ErrInvalidRequest) {+ t.Errorf("resolve of a check request: err = %v", err)+ }+ q.Operation = ""+ if _, err := r.Resolve(context.Background(), q); !errors.Is(err, ErrInvalidRequest) {+ t.Errorf("resolve with a resolution: err = %v", err)+ }+}diff --git a/tools/graft-agents/resolve/outcomes_test.go b/tools/graft-agents/resolve/outcomes_test.gonew file mode 100644index 0000000..cb24923--- /dev/null+++ b/tools/graft-agents/resolve/outcomes_test.go@@ -0,0 +1,66 @@+package resolve++import (+ "context"+ "errors"+ "strings"+ "testing"++ "github.com/feder-cr/git-ai/tools/graft-agents/protocol"+)++// TestUnresolvedErrorResponseHasEveryFile: a refused request answers the outcome of every file:+// resolved, rejected (an answer failed a rule or a check) or failed (no strategy applied).+func TestUnresolvedErrorResponseHasEveryFile(t *testing.T) {+ cfg, err := ParseConfig([]byte("[[strategy]]\ntype = \"trivial\"\n"))+ if err != nil {+ t.Fatal(err)+ }+ r, err := cfg.Build()+ if err != nil {+ t.Fatal(err)+ }+ side := func(c string) *protocol.Side {+ return &protocol.Side{OID: "1", Mode: protocol.ModeFile, Content: []byte(c)}+ }+ req := protocol.Request{+ Version: protocol.Version,+ Files: []protocol.FileConflict{+ // trivial resolves a file that only one side changed.+ {Path: "one-side.txt", Kind: protocol.KindContent, Base: side("1\n"), Ours: side("1\n"), Theirs: side("2\n")},+ {Path: "both.txt", Kind: protocol.KindContent, Base: side("1\n"), Ours: side("2\n"), Theirs: side("3\n")},+ },+ Limits: protocol.Limits{MaxFileBytes: 1 << 20},+ }+ _, err = r.Resolve(context.Background(), req)+ var unresolved *UnresolvedError+ if !errors.As(err, &unresolved) {+ t.Fatalf("err = %v", err)+ }+ resp := unresolved.Response()+ if resp.Error == "" || len(resp.Files) != 2 {+ t.Fatalf("response %+v", resp)+ }+ got := map[string]protocol.FileOutcome{}+ for _, f := range resp.Files {+ got[f.Path] = f+ }+ if got["one-side.txt"].Outcome != protocol.OutcomeResolved {+ t.Errorf("one-side.txt: %+v, want resolved", got["one-side.txt"])+ }+ if f := got["both.txt"]; f.Outcome != protocol.OutcomeFailed || !strings.Contains(f.Reason, "no strategy") {+ t.Errorf("both.txt: %+v, want failed with the reason", f)+ }+}++func TestUnresolvedErrorResponseRejectedAndCut(t *testing.T) {+ e := &UnresolvedError{Failures: []Failure{{+ Path: "a.go",+ Reasons: []string{strings.Repeat("x", 600)},+ Attempts: []Attempt{{Strategy: "llm", Kind: AttemptCheckFailed, Err: errors.New("syntax")}},+ }}}+ f := e.Response().Files[0]+ if f.Outcome != protocol.OutcomeRejected || len(f.Reason) != maxOutcomeReasonBytes {+ t.Fatalf("outcome %+v (reason %d bytes)", f, len(f.Reason))+ }+}diff --git a/tools/graft-agents/resolve/resolve.go b/tools/graft-agents/resolve/resolve.goindex 127ff8e..750a74b 100644--- a/tools/graft-agents/resolve/resolve.go+++ b/tools/graft-agents/resolve/resolve.go@@ -245,6 +245,36 @@ var ErrBudgetExhausted = errors.New("AI budget exhausted")// UnresolvedError reports files that stayed unresolved.type UnresolvedError struct {Failures []Failure+ // Resolved are the paths of the request that were resolved; nothing lands, since the request+ // is answered as a whole.+ Resolved []string+}++// maxOutcomeReasonBytes bounds the reason of one file in an ErrorResponse, as the server's+// conflict package does.+const maxOutcomeReasonBytes = 512++// Response returns the refusal as the protocol's ErrorResponse, with the outcome of every file of+// the request: resolved, rejected (a strategy's answer failed a rule or a check) or failed.+func (e *UnresolvedError) Response() protocol.ErrorResponse {+ out := protocol.ErrorResponse{Error: e.Error()}+ for _, p := range e.Resolved {+ out.Files = append(out.Files, protocol.FileOutcome{Path: p, Outcome: protocol.OutcomeResolved})+ }+ for _, f := range e.Failures {+ outcome := protocol.OutcomeFailed+ for _, a := range f.Attempts {+ if a.Kind == AttemptRejected || a.Kind == AttemptCheckFailed {+ outcome = protocol.OutcomeRejected+ }+ }+ reason := strings.Join(f.Reasons, "; ")+ if len(reason) > maxOutcomeReasonBytes {+ reason = strings.ToValidUTF8(reason[:maxOutcomeReasonBytes], "")+ }+ out.Files = append(out.Files, protocol.FileOutcome{Path: f.Path, Outcome: outcome, Reason: reason})+ }+ return out}func (e *UnresolvedError) Error() string {@@ -259,6 +289,12 @@ func (e *UnresolvedError) Error() string {// file stays unresolved, and an error wrapping ErrInvalidRequest for a// malformed request. Nothing is returned partially.func (r *Resolver) Resolve(ctx context.Context, req protocol.Request) (protocol.Response, error) {+ if req.Operation != "" && req.Operation != protocol.OperationResolve {+ return protocol.Response{}, fmt.Errorf("%w: operation %q is not %q", ErrInvalidRequest, req.Operation, protocol.OperationResolve)+ }+ if len(req.Resolution) > 0 {+ return protocol.Response{}, fmt.Errorf("%w: a resolve request carries no resolution", ErrInvalidRequest)+ }if err := validateRequest(req); err != nil {return protocol.Response{}, err}@@ -293,7 +329,11 @@ func (r *Resolver) Resolve(ctx context.Context, req protocol.Request) (protocol.resp.Files = append(resp.Files, out)}if len(failures) > 0 {- return protocol.Response{}, &UnresolvedError{Failures: failures}+ resolved := make([]string, 0, len(resp.Files))+ for _, f := range resp.Files {+ resolved = append(resolved, f.Path)+ }+ return protocol.Response{}, &UnresolvedError{Failures: failures, Resolved: resolved}}resp.Resolver = resolverName(used)