# GitHub

`gvn_tools.github` gives a model GitHub issues and pull requests (REST API version
2022-11-28), confined to a set of repositories: two tools that read and three that comment,
create an issue or open a pull request.

- **You will learn:** how to build the GitHub tools, how they stay inside the allowed
  repositories, and how a repeated create is recognised.
- **Read first:** [Tools](index.md) for the safety model, and [Web](web.md) for the `Http`
  port.
- **Time:** about 10 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 five tools and the policy fulfiller one policy for them,
`github.rules(github_tools)`: the two reads are cleared, and the three writes need a person. It sits on the `Http` port, as the
[web tools](web.md) do, but a model never writes a URL or a query here: the tools build every
request themselves, with your token, inside the repositories you list.

## A first example

You build the tools with an `Http` port, a token and the `owner/name` repositories they may
touch. Here `FakeHttp` answers every request with an empty list, and records each request so
you can see what the tool sent:

```python
import asyncio

from gvn.harness.tools import Invocation
from gvn_tools import github
from gvn_tools.fakes import FakeHttp
from gvn_tools.transport import Response

empty_list = Response(status=200, headers={"content-type": "application/json"}, text="[]")
http = FakeHttp(default=empty_list)
github_tools = github.tools(http=http, token="s3cret", repositories=["acme/shop"])
invocation = Invocation(key="run/2#c1", origin="agent")

list_issues = github_tools.github_list_issues
listing = {"repository": "acme/shop", "state": "open"}
print(asyncio.run(list_issues.run(arguments=listing, invocation=invocation)))
# {'repository': 'acme/shop', 'issues': [], 'more': False}
print(http.requests()[0]["url"])
# https://api.github.com/repos/acme/shop/issues?state=open&per_page=20&sort=updated&direction=desc
```

`github.tools(...)` returns a `GithubTools`, a named tuple of the five tools:
`github_tools.github_list_issues` is one, with the identity
`gvn_tools.github.github_list_issues` (see
[Tools](index.md#step-1-a-tool-is-built-with-its-limits)). The tool built the whole URL; the
model gave only the repository and the state.

## Trying to reach another repository

A repository that is not on the list is refused before any request is sent:

```python
async def try_payroll() -> None:
    try:
        await github_tools.github_get_issue.run(
            arguments={"repository": "acme/payroll", "number": 1}, invocation=invocation
        )
    except Exception as error:
        print(type(error).__name__, error)


asyncio.run(try_payroll())
# ToolFailure repository 'acme/payroll' is not one of the allowed ['acme/shop']
print(len(http.requests()))  # 1: only the listing above was sent
```

## What it refuses

- **Repositories outside `repositories`** (compared case-insensitively, as GitHub does),
  and, when the run context carries `"repository"`, any but that one.
- **Branches that are not plain names of the same repository** for a pull request, and the
  same branch as head and base.
- **A model choosing a host or a credential.** The API root and the token come from the
  constructor only, and every path and query is built by the tool.

## When a call fails

Every failure the tools understand is a `ToolFailure`, which an agent's tools report as a failed
result, and whether the call is tried again depends on which kind it is:

- **Not retryable** (`{"error": "tool_rejected", "detail": ...}`): a refusal before any request
  (a repository, number, branch, label or body outside what the tools may touch), any other error
  answer from GitHub (any status outside 2xx, a redirect included, with GitHub's message), and
  a GraphQL answer that carries errors.
- **Retryable** (`{"error": "tool_unavailable", "detail": ...}`): GitHub could not be reached,
  or it answered `429` or a `5xx`, or any error answer with a `Retry-After` in seconds. That
  wait comes back as `retry_after`.

A retryable failure is tried again only by a tool built with a retry: `github.tools(...,
retry=Retry(...))` gives it to the two reads, which have no effect to repeat. The three
writes are tried once whatever you pass: a retry would follow a lost answer within seconds,
before the write's repeat check can count on seeing what the first attempt created, so a
write reported unavailable is left to the model or to you.

`GithubError` is left for a `2xx` answer that is not what the tool expected (over `limit`, not
JSON, not the right shape). It is a fault the model cannot act on, so it is not a `ToolFailure`.

## How repeats are harmless

gvn delivers work at least once: if the process stops after GitHub created an issue but
before the result was saved, the same call runs again, with the same call key (the
`key` of its `Invocation`). Without care, that second run opens a second issue.

So each create puts a hidden marker at the end of the body it sends, an HTML comment that
GitHub does not display: `<!-- gvn:<hash of the tool's short name and the call key> -->`. Before creating, the tool
looks for that marker:

- `github_comment` reads the issue's comments (up to 10 pages of 100).
- `github_create_issue` reads the repository's 100 most recently created issues, in any
  state, through GitHub's GraphQL API (newest first).
- `github_open_pull_request` first looks for an open pull request from `head` into `base`.
  GitHub allows only one, so that pull request is the effect, keyed by what it is, whichever
  call made it.

Here is a redelivery as `github_create_issue` sees it. The fake now answers the GraphQL read
with an issue whose body carries the marker of call `run/2#c3`, as if the first delivery had
created issue 41 and then crashed:

```python
import json

marker = github.marker(github_tools.github_create_issue, "run/2#c3")
issue_41 = {
    "number": 41,
    "url": "https://github.com/acme/shop/issues/41",
    "body": f"Checkout fails on Safari\n\n{marker}",
    "repository": {"nameWithOwner": "acme/shop"},
}
recent_issues = {"data": {"repository": {"issues": {"nodes": [issue_41]}}}}
http.script(
    "POST",
    "https://api.github.com/graphql",
    Response(
        status=200, headers={"content-type": "application/json"}, text=json.dumps(recent_issues)
    ),
)
```

`FakeHttp.script` takes the method, the URL and then the answers, in turn. Now the same
call runs again, with the same key:

```python
redelivered = Invocation(key="run/2#c3", origin="agent")
new_issue = {
    "repository": "acme/shop",
    "title": "Checkout fails",
    "body": "Checkout fails on Safari",
}
create_issue = github_tools.github_create_issue
print(asyncio.run(create_issue.run(arguments=new_issue, invocation=redelivered)))
# {'repository': 'acme/shop', 'number': 41, 'url': 'https://github.com/acme/shop/issues/41', 'created': False}
print([request["method"] for request in http.requests()[1:]])
# ['POST']
```

The tool found issue 41 and returned it with `"created": False`. The only request it sent
was the GraphQL read (a `POST` to `/graphql`); it never sent the create.

### Why the check reads GraphQL

The repeat check exists for a crash and a redelivery a few seconds after the create, so it
must see an issue made a moment ago. Measured against github.com, GraphQL's
`repository.issues`, ordered by creation date, showed the new issue on the first read every
time, where the REST issue list and the search API did not yet. So the check reads GraphQL.
The live test `test_the_repeat_check_sees_an_issue_made_a_moment_ago` repeats a create at
once, from a new transport, and expects no second issue.

### The model never sees the marker

The marker stays on GitHub, where the next repeat check needs it, but `github_get_issue`
removes it from the bodies and comments it returns: the model reads what people wrote.
`github.unmarked` is the function it uses:

```python
print(repr(github.unmarked(text=issue_41["body"])))
# 'Checkout fails on Safari'
```

## The tools, for lookup

Each row gives a tool's arguments (`?` marks an optional one), its **default verdict** (what
`github.rules(github_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 |
|---|---|---|---|
| `github_get_issue` | `repository`, `number` | `cleared` | yes |
| `github_list_issues` | `repository`, `state?`, `labels?`, `query?`, `max_results?` | `cleared` | yes |
| `github_comment` | `repository`, `number`, `body` | `needs_approval` | no |
| `github_create_issue` | `repository`, `title`, `body?`, `labels?` | `needs_approval` | no |
| `github_open_pull_request` | `repository`, `title`, `head`, `base`, `body?`, `draft?` | `needs_approval` | 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)).

- `github_get_issue` returns the title, state, author, labels, assignees, dates, body (capped)
  and the first 30 comments (each capped). It works for pull requests too. A redirect (the
  issue was transferred) is an error, never followed. The hidden markers described in
  [How repeats are harmless](#how-repeats-are-harmless) are removed from the body and the
  comments it returns.
- `github_list_issues` without `query` reads the repository's issue list. With it, it uses
  the search API with `q = repo:<owner/name> is:issue "<query>"`: the model's words are one
  quoted phrase (quotes and backslashes removed), so a qualifier in them (`repo:`, `org:`,
  `OR`) is searched as text, never applied, and every result outside the repository is
  dropped too.
- `github_open_pull_request` takes `head` and `base` as branches of the same repository: no
  forks, no `owner:` prefix.

## Configuration

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

```python
# not runnable: the signatures.
github.tools(http, token, repositories, base_url="https://api.github.com", limit=2_000_000,
             timeout=30, retry=None)
# -> GithubTools(github_get_issue, github_list_issues, github_comment, github_create_issue,
#                github_open_pull_request)
github.rules(github_tools)
github.marker(tool, key)  # the hidden marker a call of one of these tools leaves
```

Each argument of `github.tools`:

| Argument | Default | Meaning |
|---|---|---|
| `http` | | the `Http` port: `LocalHttp()` (the `http` extra) or `FakeHttp` |
| `token` | | a GitHub token, sent as `Authorization: Bearer` |
| `repositories` | | the `owner/name` repositories the tools may touch |
| `base_url` | `https://api.github.com` | the API root; GitHub Enterprise Server: `https://<host>/api/v3` (see below for GraphQL) |
| `limit`, `timeout` | 2,000,000, 30 | characters of response read; seconds per request |
| `retry` | `None` | a `gvn.harness.ports.Retry` that `github_get_issue` and `github_list_issues` declare (`Tool.retry()`); the writes never retry |

The repeat check of `github_create_issue` reads GraphQL at `<base_url>/graphql`; for a root
ending in `/api/v3` (GitHub Enterprise Server), at `https://<host>/api/graphql` instead.

The token is redacted as `[REDACTED]` from every result and every error, transport errors
included. Results are untrusted text, bounded in size.

Every tool declares its results untrusted (`untrusted()` is `True`): GitHub's answers carry
issue, comment and pull-request text other people wrote. An agent or a conversation that
hands such a result to its model records the tool in its exposure, and its policy and its
approver see that record with every later call, so a policy can ask a person before an
effect once the model has read an issue ([Trust](../concepts/trust.md), and `exposed=` in
[Rules](rules.md#a-rule-that-reads-the-exposure)).

One `LocalHttp()` can serve many `asyncio.run` calls: it makes one client per event loop
and reuses it within that loop. A client you pass in, `LocalHttp(client=...)`, stays with
the event loop of its first request; using it from another loop raises `RuntimeError`.

## Running them safely

The tools confine every request to the listed repositories and recognise a repeat by its
marker. What to know when you deploy them:

- **A repeat is recognised when it follows the first attempt.** The check and the create are
  two requests, so two deliveries of one call running at the same moment can both create
  (pull requests excepted: GitHub refuses the second). An issue is looked for among the 100
  most recently created.
- **A repeated pull request is never a second one.** When GitHub answers the create with
  `422` ("a pull request already exists"), the call fails with that message.
- **Treat what GitHub returns as untrusted.** Issue bodies and comments are written by
  people, possibly to steer the model reading them.

## Recap

- `github.tools(http=..., token=..., repositories=[...])` reaches only the listed
  repositories, with your token; every path and query is built by the tool.
- Reads are cleared; comments, issues and pull requests need a person.
- A repeated create looks for a hidden marker first (for issues, through GraphQL, which sees
  a new issue at once); the model never sees the marker.

**Next:** [Rules](rules.md), to write a policy of your own.
