Git designed for AI agents.
Code review
Graft has a small code review system built into the server, designed for agents as much as for people. A review is a change (a head commit) that targets a branch. The server classifies every changed file (code, comment-only, docs, tests, generated, config), and approval rules say how many approvals each class needs. A fix to a comment does not need a new approval; a logic change does.
Code: internal/gitaly/service/review (server), internal/graft/review/store
(storage), internal/graft/review/classify (classifier),
internal/graft/review/rules (rules engine), sdk/review.go (SDK),
cmd/graft/review.go (CLI). Protocol: proto/review.proto.
Phase 5a stops at review state: landing does not check reviews yet. The "approved review required to land" gate and per-directory write permissions are phase 5b.
Concepts
- Review:
id(a decimal counter per repository),target_branch(a branch name withoutrefs/heads/),base_commit_id,head_commit_id,author(the identity that created it),title,description,state(open, landed, closed),files,verdicts,comments,created_at,updated_at, plus the computedrequirementsandapproved. - Files: every path changed between the base and the head
(
git diff-tree -r -z --no-renames base head), each with a class and a human-readablereason. A rename shows as a deletion and an addition. - Verdict: an approval or a change request by one identity on one head
commit. A verdict is
currentwhile it counts for the current head. Every verdict is kept, oldest first. - Comment: a message by one identity, optionally anchored to a file of the review and a 1-based line, recorded with the head it was written on. Comment ids are their 1-based position in the review.
- Identity: the actor of a request is the identity of its token
(
identity.Actor), oranonymouswithout one. Rules and author checks only mean something when every user and agent has its own token.
RPCs: ReviewService
| RPC | Type | What it does |
|---|---|---|
CreateReview |
mutator | Opens a review of head_commit_id against target_branch. |
GetReview |
accessor | Returns one review with its requirements evaluated. |
ListReviews |
accessor, stream | Lists reviews, newest first. |
UpdateReview |
mutator | Moves the review to a new head and decides which verdicts stay current. |
AddReviewComment |
mutator | Adds a comment. |
SubmitReviewVerdict |
mutator | Records an approval or a change request on the current head. |
CloseReview |
mutator | Marks the review closed, or landed with landed. |
Every read (GetReview, ListReviews, and every mutator's response)
recomputes requirements and approved from the configured rules, so a change
of the rules applies to existing reviews at once.
CreateReview
target_branchmust be a valid branch name and must exist (NotFound).head_commit_idmust resolve to a commit (NotFoundwhen missing,InvalidArgumentfor another object type).base_commit_idis optional. Empty meansgit merge-base head <branch tip>(FailedPreconditionwhen they have no common ancestor). An explicit base must be one ofgit merge-base --all head <branch tip>, otherwiseFailedPrecondition: any other base would misstate the change (the head itself, or a commit with the head's tree, would hide every change, and an older common ancestor hides a change that reverts what the branch gained since).- The author is the caller. The review starts open, with no verdicts.
GetReview and ListReviews
GetReview takes an id (InvalidArgument when empty, NotFound when
unknown). ListReviews filters by target_branch (empty: all), lists only
open reviews unless include_closed is set, and returns at most limit
reviews (0 means 100), 50 per message. Listings carry neither comments nor
verdict bodies.
UpdateReview
- Only the author may move the head (
PermissionDeniedotherwise). The rules exclude the author from approving their own change; that would mean nothing if another identity could put its own code under the author's name. - The review must be open (
FailedPrecondition). expected_head_commit_id, when set, must equal the current head (compare-and-swap,FailedPrecondition).- The new head must descend from the review's base (
FailedPrecondition): otherwise the files computed against the base would not be the change of the head. - The same head as the current one is a no-op.
- The files are recomputed as base..new head, and each current verdict is re-evaluated by the carry-over rule below.
AddReviewComment
Anyone may comment on an open review. The body must be non-empty and at most
64 KiB, line must not be negative, and path, when set, must be one of the
files of the review (InvalidArgument). The line is not checked against the
length of the file.
SubmitReviewVerdict
Anyone may give a verdict on an open review, the author included (the author's
approval is recorded but only counts under a rule with allow_author).
head_commit_id is required and must equal the review's current head
(FailedPrecondition otherwise), so a verdict never lands on code the reviewer
did not see. The body is at most 64 KiB. Earlier verdicts are not rewritten: a
later verdict by the same identity supersedes the earlier one for counting.
CloseReview
Only the author may close a review, as closed or with landed as landed
(PermissionDenied otherwise). A closed or landed review rejects every
further mutation with FailedPrecondition. landed is a label set by the
tool that landed the change; the server does not check that the head landed.
The classifier
classify.File(path, old, new) returns one class and a reason. old or new
is nil for an added or deleted file. The checks run in this order and the
first match wins:
- generated: the file name ends in
.pb.go,_pb2.py,.min.jsor_generated.go; or one of the first 20 lines of the old version contains@generated, orCode generatedtogether withDO NOT EDIT; or the file is added with such a marker. A marker that a change adds to an existing file does not count, otherwise adding one would turn any logic change into a generated change. - tests: the name ends in
_test.go,_test.py,.spec.{js,ts,jsx,tsx}or.test.{js,ts,jsx,tsx}, matchestest_*.py, or a directory component istest,tests,testdataor__tests__. - docs: the extension is
.md,.rst,.adocor.txt, or a directory component isdocordocs. Build and dependency manifests with a.txtextension are never docs:CMakeLists.txt, any*requirements*.txtor*constraints*.txt, and any.txtunder arequirements/directory. - config:
.toml,.yaml,.yml,.json,.ini,.cfg,.editorconfig,.gitignore,.gitattributes. - comment_only: both versions exist, the language is supported, both versions lex with certainty, and their token streams with comments and blanks removed are identical.
- code: everything else, including every uncertainty.
COMMENT_ONLY is only decided for four languages, and only when the lexer is certain:
- Go (
.go). Line breaks are tokens (automatic semicolons). Directive comments (//go:,//export,//line,//+build,extern) are code. A file that imports"C"(in any quoting) or has a#cgoline is code. - Python (
.py). Only#comments are dropped; docstrings and all strings are code. Indentation and line structure are tokens, and a line continuation backslash is a token. A#!comment, or any comment containingcoding(an encoding declaration), makes the file code. So does an f-string or t-string with a replacement field, and a name directly followed by a quote that is not a string prefix. - Rust (
.rs).//and nested/* */comments are dropped, but doc comments (///,//!,/** */,/*! */) are code. Literal prefixes and raw strings are handled;stringify!, literal suffixes and a shebang line make the file code. - Java (
.java).//and/* */comments are dropped, but Javadoc/** */and///comments are code. Text blocks are strings. Any\uescape makes the file code.
Each language splits runs of operator characters with its own operator set, the way its compiler does. Any other extension (C, C++, JavaScript, TypeScript, Ruby, shell, ...) is code unless a path rule matches. Binary content, invalid UTF-8, a lone carriage return, an unterminated string or comment, or a source over 1 MiB is code.
The server adds three rules before the classifier runs: a change of the file mode, a symlink and a submodule are code (their content does not show what the change does), and a version larger than 1 MiB is not read and is code. A blob that is missing from the object database is treated as an absent side (as if the file were added or deleted), so such a file can only get a class from a path rule or from a generated marker of the side that is present.
The rules engine
rules.Evaluate(rules, files, author, verdicts) returns one requirement per
rule that applies to at least one file, in rule order, and approved.
- A rule applies to a file when the path matches one of its
paths(orpathsis empty) and the file's class is in itsclasses(orclassesis empty). - Only the latest verdict of each identity counts, and only when it is current. The latest verdict is chosen among all verdicts before currency is checked, so an approval superseded by a later change request never counts again, even if the change request later becomes non-current.
- An approval counts for a rule when its identity matches one of the rule's
approvers(orapproversis empty) and it is not the author, unless the rule setsallow_author. Each identity counts once. - A requirement is satisfied when its approvals reach
approvals. - The review is approved when every requirement is satisfied and no identity's latest current verdict is a change request. A review that no rule applies to (for example docs only, under the default rules) is approved without any approval.
Globs (for paths and approvers) have the syntax of the standalone policy:
path.Match patterns, where a trailing /** matches anything below that
directory at any depth, any other trailing ** matches any remainder
including /, and a bare ** matches everything. * alone does not cross a
/.
The carry-over rule
When UpdateReview moves the head, each verdict that is still current is
checked against the change from the commit that verdict was given on to
the new head (not from the previous head, so several small updates are judged
as a whole). The verdict stays current only when every file in that change is:
- comment_only, or
- docs and documentation by its own name (
.md,.rst,.adoc,.txt, not a build manifest). A file that is docs only because it sits under adoc/ordocs/directory (internal/doc/handler.go) does not qualify.
An empty change qualifies. Otherwise the verdict becomes non-current, and it never becomes current again. When the verdict's commit is no longer in the object database (pruned after a force push), the change cannot be compared and the verdict becomes non-current.
Since the files of the review are always base..head, a comment-only update of
a code file keeps the file's class as code (the review still changes code)
while the approvals given before the update stay current.
Configuration: [[graft.review.rule]]
[[graft.review.rule]]
name = "code" # required; shown in requirements
classes = ["code", "config"] # empty: every class
paths = ["internal/**", "cmd/**"] # empty: every file
approvals = 1 # current approvals needed (>= 0)
approvers = ["team-*"] # identity globs; empty: anyone
allow_author = false # the author's approval counts
[[graft.review.rule]]
name = "security"
paths = ["internal/gitaly/server/auth/**"]
approvals = 2
approvers = ["security-*"]
Class names: code, comment_only, docs, tests, generated, config.
The configuration is rejected at load time when a rule has no name, a negative
approvals, an unknown class, or an empty or malformed glob. An absurd
approvals above 2147483647 is not rejected: the requirement then shows a
wrapped required_approvals, but it can never be satisfied (it fails closed).
Without any rule, the default applies:
[[graft.review.rule]]
name = "code"
classes = ["code", "config"]
approvals = 1
That is, code and configuration changes need one approval by someone other than the author; comment-only, docs, tests and generated changes need none.
Configuration: [graft.review] max_open_reviews
[graft.review]
max_open_reviews = 1000 # default when unset or 0; negative is rejected
Every open review keeps its head and base commits by hidden references
(refs/keep-around/review/<commit>, see STORAGE.md), in every
mode, storage core on or off. max_open_reviews bounds the open reviews of one
repository, and so those references and the objects they keep. CreateReview
refuses a review beyond it with ResourceExhausted ("the repository has N
open reviews, the limit is N; close or land an open review first, or raise
[graft.review] max_open_reviews") and writes nothing. The bound holds against
concurrent creates, on one node and, in authoritative mode, across nodes: the
store counts the open reviews and records the review under one lock (the file
lock, or the repository row in the database). Landed and closed reviews do not
count; closing one makes room. Reviews brought in by graft storage import
are not bounded: they exist already. Counting reads every review of the
repository in the files store (it has no index of the open ones), as listing
does.
Storage
Reviews live in the repository's git directory, under graft/reviews/:
<id>.json holds one review as protojson (without requirements and
approved, which are recomputed on read), next_id holds the next id, and
.lock is the file lock. Every mutation holds a per-directory in-process
mutex and an flock on .lock, and every write goes through a temporary
file, an fsync, a rename and an fsync of the directory. The id counter is
advanced before the review is written, so a crash leaves a gap, never a reused
id.
SDK
On *sdk.Repo, with the proto messages as aliases (sdk.Review,
sdk.ReviewFile, sdk.ReviewVerdict, sdk.ReviewComment,
sdk.ReviewRequirement, sdk.ReviewState):
func (r *Repo) CreateReview(ctx, CreateReviewOptions{TargetBranch, Head, Base, Title, Description}) (*Review, error)
func (r *Repo) GetReview(ctx, id string) (*Review, error)
func (r *Repo) ListReviews(ctx, ListReviewsOptions{TargetBranch, IncludeClosed, Limit}) ([]*Review, error)
func (r *Repo) UpdateReview(ctx, UpdateReviewOptions{ID, Head, ExpectedHead}) (*Review, error)
func (r *Repo) CommentReview(ctx, CommentReviewOptions{ID, Body, Path, Line}) (*ReviewComment, error)
func (r *Repo) ApproveReview(ctx, id, body string) (*Review, error)
func (r *Repo) ApproveReviewAt(ctx, VerdictOptions{ID, Head, Body}) (*Review, error)
func (r *Repo) RequestChanges(ctx, id, body string) (*Review, error)
func (r *Repo) RequestChangesAt(ctx, VerdictOptions{ID, Head, Body}) (*Review, error)
func (r *Repo) CloseReview(ctx, id string, landed bool) (*Review, error)
TargetBranch may be given with or without refs/heads/. ApproveReview
and RequestChanges read the review and give the verdict on its head at that
moment; prefer the ...At forms with the head that was actually reviewed, so
that a head moved in between makes the call fail instead of approving unseen
code.
CLI: graft review
graft review create --branch B --title T [--base C] [--head H] [--description D]
graft review show ID [--json]
graft review list [--branch B] [--all] [--json]
graft review comment ID --body B [--path P [--line N]]
graft review approve ID [--head H] [--body B]
graft review request-changes ID [--head H] [--body B]
graft review update ID [--head H]
graft review close ID [--landed]
- Inside a workspace, the server and repository come from the workspace.
Without a workspace, pass
-address,-storageand-repo; thencreateandupdateneed--head. createandupdatedefault the head to the workspace's pending commit (made bygraft commitand not landed yet).approveandrequest-changesgive the verdict on--head(a full ID, or a prefix of the review's current head asshowprints it), or on the current head when--headis not set.showprints the header, the class of every file, the requirements, the verdicts (non-current ones markedsuperseded) and the comments.listprints one tab-separated line per review: id, state, branch, head, title. Text from other clients goes through the same escaping as other graft output, so a title with a tab or a newline cannot forge a row.--jsonprints each review as one protojson object per line; bytes fields (title, description, paths, bodies) are base64, as protojson encodes them.
Deployment notes
- Agents may call every ReviewService RPC: the mutators only write the review store, never refs or objects.
- In Praefect, the review mutators are registered with transactions disabled. The review files are not part of what Praefect replicates (see the limitations).
Limitations
- Advisory only in phase 5a.
approvedis not checked byUserLandor any other write; the land gate is phase 5b. - Path-only classes. The path rules win over content. A source file under
test/,tests/,testdata/,doc/ordocs/, and a file named*_generated.go,*.pb.go,*_pb2.pyor*.min.jswithout a generated marker, are classified tests, docs or generated by name. Under the default rules such files need no approval, even if they are compiled into the product. Approvals of such a file do not carry over an update (the carry-over rule only accepts documentation by name and comment-only changes), but the first approval is not required. Configure rules that cover these classes, or paths, where that matters. - Rebasing can hide a revert. The files are always base..head. An author who updates the review to a head rebased onto a newer branch tip, and in the same head reverts a change that the newer tip brought, can make that revert invisible in the file list, because base..head then includes the tip's change and its revert. The land gate of phase 5b must compute the change against the real landing base.
- The landed state is a label.
CloseReviewwithlandeddoes not check that the head landed. - Not replicated, not backed up. The review store is a directory in the
git directory. Praefect replication and
gitaly-backupcopy refs and objects, not this directory, so reviews exist only on the node that handled the mutators; a Praefect read routed to a secondary may not see them. Reviews are intended for standalone Graft servers. - No authorization beyond authorship. Anyone who can reach the repository
can comment and give verdicts; the rules decide which verdicts count. Only
the author may update or close a review. Without per-identity tokens every
caller is
anonymous, and then the author exclusion makes every approval byanonymousthe author's own. - Lexers without an oracle. The Go lexer is fuzzed against
go/scanner(FuzzGoMatchesGoScanner). The Java, Rust and Python lexers are covered by table tests and by fuzzing for determinism and termination only; they have no reference implementation to compare with. - Scale.
ListReviewsreads review files one by one, newest first, until the limit is reached; a repository with many closed reviews pays for reading them when filtering by branch or state. A review file that cannot be read or decoded makes the wholeListReviewscall fail withInternal. Classification reads every changed blob (up to 1 MiB each) on create and on update.