# Git

`gvn_tools.git` gives a model git through six tools that each build their own command line:
status, diff, log, a new branch, a commit and a push.

- **You will learn:** how to build the git tools over a repository, what each one takes, why a
  repeated commit does not commit twice, and what git configuration they neutralise.
- **Read first:** [Tools](index.md) for the safety model, and [Files](files.md) for the
  workspace.
- **Time:** about 15 minutes; the tables at the end are for lookup.

## Where this family sits

In the picture of [where tools plug in](index.md#where-tools-plug-in), this family gives the
tool fulfiller six tools and the policy fulfiller one policy for them,
`git.rules(git_tools)`. It sits on the
same two ports as the [shell tool](shell.md): the `Workspace`, which here must be a git
repository, and `Commands`, which runs the `git` program. The difference from the shell tool
is that the model never writes a git command line: each tool builds its own, from structured
arguments it checks first. Reading, branching and committing stay on your machine and can be
undone, so they are cleared; pushing reaches outside, so it needs a person.

## A first example

The repository is the workspace: its root must hold a `.git` directory. The git tools run
`git` through a `Commands` port, here `LocalCommands()`, which starts real processes with no
shell and a clean environment.

This example makes an empty repository and asks for its status. `ISOLATED` points git away
from your own configuration, so the example behaves the same on every machine:

```python
import asyncio
import os
import pathlib
import subprocess
import typing

from gvn.harness.tools import Invocation, Tool
from gvn_tools import git
from gvn_tools.process import LocalCommands
from gvn_tools.workspace import Workspace

ISOLATED = {"GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1"}  # ignore your config
repo = pathlib.Path("repo")
repo.mkdir()
subprocess.run(["git", "init", "-q", "-b", "main"], cwd=repo, env={**os.environ, **ISOLATED}, check=True)
(repo / "notes.txt").write_text("one\n")

git_tools = git.tools(
    workspace=Workspace(root=repo.resolve()),
    commands=LocalCommands(),
    environment=ISOLATED,
)
invocation = Invocation(key="run/3#c1", origin="agent")

status = asyncio.run(git_tools.git_status.run(arguments={}, invocation=invocation))
print(status["branch"], status["changes"])
# main [{'path': 'notes.txt', 'status': '??'}]
```

`git.tools(...)` returns a `GitTools`, a named tuple of the six tools: `git_tools.git_status`
is one, with the identity `gvn_tools.git.git_status` (see
[Tools](index.md#step-1-a-tool-is-built-with-its-limits)). The status is plain JSON: the
branch, and one entry per changed path (`??` means not yet tracked).

## A tour: branch, commit, repeat, refuse

The next example continues the first. It creates a branch, commits the file, repeats the
same commit under the same call key, then tries two things the tools refuse: a ref that is
really a flag, and a push to `main`. The helper leaves out the commit hash, which differs on
every run:

```python
async def show(tool: Tool, arguments: dict[str, typing.Any]) -> None:
    try:
        result = await tool.run(arguments=arguments, invocation=invocation)
        print({key: value for key, value in result.items() if key != "commit"})
    except Exception as error:
        print(type(error).__name__, error)


async def tour() -> None:
    commit = {"paths": ["notes.txt"], "message": "Add notes"}
    await show(git_tools.git_create_branch, {"name": "fix-notes"})
    await show(git_tools.git_commit, commit)
    await show(git_tools.git_commit, commit)  # a repeat
    await show(git_tools.git_diff, {"ref": "--output=/tmp/x"})
    await show(git_tools.git_push, {"branch": "main"})


asyncio.run(tour())
# {'branch': 'fix-notes', 'created': True}
# {'created': True}
# {'created': False}
# ToolFailure ref must not start with '-', got '--output=/tmp/x'
# ToolFailure branch 'main' is protected: it is never pushed by this tool
```

What to notice:

- the second commit found the first by its `Gvn-Key` trailer (a `Gvn-Key: <call key>` line
  the tool adds at the end of every commit message) and made nothing;
- `--output=/tmp/x` would have made git write a file anywhere; as a ref starting with `-`, it
  is refused;
- the push to `main` is refused by the tool itself, before any policy is asked.

## The policy for pushing

`git.rules(git_tools)` clears reading, branching and committing: every commit is recorded and can be
undone. Pushing is the one call that reaches outside the machine, so it needs a person, and a
push of a protected branch is forbidden outright. The verdict depends on the argument:

```python
from gvn.harness.messages import ToolCall
from gvn.harness.tools import Consultation

git_push = git_tools.git_push
policy = git.rules(git_tools)
for branch in ("fix-notes", "main", "Master"):
    push = ToolCall(call_id="c1", name=git_push.name(), arguments={"branch": branch})
    consultation = Consultation(calls=[push], identities=[git_push.identity()], origin="agent")
    print(branch, policy.decide(consultation).name())
# fix-notes needs_approval
# main forbidden
# Master forbidden
```

Protected branches are compared case-insensitively, so `Master` is caught too.

## What it refuses

- **Any path, ref or branch that could become a flag or escape.** Not a str, empty, starting
  with `-`, or holding a control character; a ref holding whitespace; a path that leaves the
  workspace; a branch name `git check-ref-format --branch` would reject, or `HEAD`. Paths go
  after `--` as literal pathspecs, refs after `--end-of-options`.
- **A bad message:** blank, holding a control character other than newline and tab, or
  already holding a `Gvn-Key` trailer.
- **A repository elsewhere.** The workspace root must hold a real `.git` directory, not a
  symbolic link and not a `gitdir:` file, so git can never be pointed at another repository.
- **Pushing a protected branch** (compared case-insensitively), and any
  force push: `git_push` never forces.
- **Configuration that would run or prompt for something.** The settings and environment
  neutralise an editor, a pager, prompts (`GIT_TERMINAL_PROMPT=0`, no askpass, ssh in batch
  mode), signing, an fsmonitor, an external diff or a textconv filter, following tags or
  recursing into submodules on push, and a configured receive-pack program.

Every refusal is a `ToolFailure`, which an agent's tools report as
`{"error": "tool_rejected", "detail": ...}`, a failed result that is not retried. So is a git
command that exits non-zero: it fails the call with git's message. A git process killed at
`timeout` is different: it is retryable (`{"error": "tool_unavailable", "detail": ...}`),
because every git tool is safe to repeat (see the next section). It is tried again only when
the tools were built with `retry=` (see Configuration), which then applies to all six. A shell
program that times out is not retried. Credentials in URLs are redacted from anything returned or raised.

## How repeats are harmless

- **`git_commit`** stages exactly the given paths (`git add --all -- <paths>`), commits only
  them (other staged changes stay staged), and adds the trailer `Gvn-Key: <invocation.key()>`.
  Before anything, it looks for a commit carrying that trailer in the history of `HEAD`; a
  repeat finds it and returns the existing commit with `"created": false`.
- **`git_create_branch`** creates the branch and switches to it; a repeat finds the branch,
  switches to it and returns `"created": false`. It refuses when the existing branch is not
  at the requested start.
- **`git_push`** pushes `refs/heads/<b>:refs/heads/<b>` to the configured remote, never with
  force: a repeat finds the remote already up to date. A remote that diverged rejects the
  push, which raises.

## Hooks are off by default

A repository hook is a program in the repository, and a model may have written it (through
the shell tool, or a file tool configured without `.git` protection). So by default hooks do
not run (`core.hooksPath=/dev/null`, `--no-verify`). Pass `hooks=True` only for a repository
whose hooks the deployment trusts.

## The tools, for lookup

Each row gives a tool's arguments (`?` marks an optional one), its **default verdict** (what
`git.rules(git_tools)` answers for it; see [verdicts](index.md#step-4-a-rule-you-can-see-deciding))
and whether it is **independent**:

| Tool | Arguments | Default verdict | Independent |
|---|---|---|---|
| `git_status` | | `cleared` | yes |
| `git_diff` | `paths?`, `staged?`, `ref?` | `cleared` | yes |
| `git_log` | `paths?`, `ref?`, `count?` | `cleared` | yes |
| `git_create_branch` | `name`, `start?` | `cleared` | no |
| `git_commit` | `paths`, `message` | `cleared` | no |
| `git_push` | `branch` | `needs_approval`; forbidden for a protected branch | no |

**Independent** tools are pure reads: calls to them that sit next to each other in one
model reply run together; every other call runs in the order the model gave, one at a time
(see [The order of a reply's tool calls](../concepts/governor.md#the-order-of-a-replys-tool-calls)).

Every argv is built by the tool, never by a shell:
`git -C <root> --no-pager --literal-pathspecs -c <setting>... <subcommand> ...`.

## Configuration

`git.tools` and `git.rules`, with their defaults:

```python
# not runnable: the signatures.
git.tools(workspace, commands, author=("gvn", "gvn@localhost"), remote="origin",
          protected=("main", "master"), hooks=False, timeout=60, limit=20000, environment=None,
          retry=None)
# -> GitTools(git_status, git_diff, git_log, git_create_branch, git_commit, git_push)
git.rules(git_tools, protected=("main", "master"))
```

Each argument of `git.tools`:

| Argument | Default | Meaning |
|---|---|---|
| `workspace` | | the repository's top level |
| `commands` | | the `Commands` port that runs `git` |
| `author` | `("gvn", "gvn@localhost")` | author and committer of every commit |
| `remote` | `"origin"` | the one remote `git_push` pushes to |
| `protected` | `("main", "master")` | branches never pushed; `()` allows all |
| `hooks` | `False` | whether repository hooks run |
| `timeout`, `limit` | 60, 20,000 | seconds per git process; characters kept of each output |
| `environment` | `None` | extra variables for git, such as `GIT_CONFIG_GLOBAL` |
| `retry` | `None` | a `gvn.harness.ports.Retry` every tool declares (`Tool.retry()`): a git process killed at `timeout` is run again, under the same key; None tries each call once |

Diff and log text is capped at `limit` characters, status at `limit` characters and 1,000
entries, with `"truncated": true` when cut. Text from the repository (diffs, messages, names)
is data for the model to read, never instructions. The git tools leave `untrusted()` at
`False`, so their results add nothing to an agent's [exposure](../concepts/trust.md).

## Running them safely

The tools enforce the refusals and settings above. What you add:

- **Point the workspace at the repository's top level.** A workspace inside a repository, or
  one holding a repository in a subdirectory, is refused.
- **Keep a task's commits on one branch.** `git_commit` looks for its key in the history of
  `HEAD`, so a repeat on the same branch finds the earlier commit; a repeat after a switch to
  another branch commits again.
- **Keep `.git/config` out of the model's reach.** Clean and smudge filters, credential
  helpers, URL rewrites and the remote's URL are used as configured, so whoever writes that
  file decides what git runs and where it pushes. The [file tools](files.md) protect `.git`;
  if the agent also has the [shell tool](shell.md), allow only programs that cannot write
  there.
- **Turn on `hooks` only for hooks you trust.** With `hooks=True`, git runs whatever the
  repository's hooks contain.

## Recap

- `git.tools(workspace=..., commands=...)` builds six tools over one repository; each builds
  its own argv, so nothing a model writes becomes a flag.
- A commit carries the call's key as a `Gvn-Key` trailer, so a repeat finds it instead of
  committing twice.
- `git.rules(git_tools)` clears everything but pushing, which needs a person and is forbidden for
  protected branches. Hooks are off unless you turn them on.

**Next:** [Web](web.md), or see the git tools at work in the
[coding agent guide](../guides/coding-agent.md).
