# Jira Cloud

`gvn_tools.jira_cloud` gives a model Jira Cloud (REST API v3), confined to a set of
projects: two tools that read issues and three that comment on, create and move them. The
family is for Jira Cloud, and signs in with an Atlassian account's email and an API token.

- **You will learn:** how to build the Jira Cloud tools, how a search stays inside the
  allowed projects, and how a repeated create or comment 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,
`jira_cloud.rules(jira_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, for one site, with your credentials, inside the projects you list.

## A first example

You build the tools with an `Http` port, your site's address, an API token, the email of
the account it belongs to, and the project keys they may touch. The site and the
credentials are yours: a model never chooses them. Here `FakeHttp` answers every request
with an empty search result, so you can see the query the tool builds:

```python
import asyncio
import json
import typing

from gvn.harness.tools import Invocation, Tool
from gvn_tools import jira_cloud
from gvn_tools.fakes import FakeHttp
from gvn_tools.transport import Response

no_issues = Response(
    status=200,
    headers={"content-type": "application/json"},
    text=json.dumps({"issues": [], "isLast": True}),
)
http = FakeHttp(default=no_issues)
jira_tools = jira_cloud.tools(
    http=http,
    base_url="https://acme.atlassian.net",
    token="s3cret",
    projects=["OPS"],
    email="bot@acme.com",
)
invocation = Invocation(key="run/2#c1", origin="agent")

search = jira_tools.jira_search
found = asyncio.run(search.run(arguments={"status": "Open"}, invocation=invocation))
print(found)
# {'issues': [], 'more': False, 'jql': 'project in ("OPS") AND status = "Open" ORDER BY updated
#  DESC'}
```

`jira_cloud.tools(...)` returns a `JiraCloudTools`, a named tuple of the five tools:
`jira_tools.jira_search` is one, with the identity `gvn_tools.jira_cloud.jira_search` (see
[Tools](index.md#step-1-a-tool-is-built-with-its-limits)). The tool wrote the JQL (Jira's
query language) itself, and it always starts with the allowed projects.

## Trying to reach another project

A model, perhaps steered by text it read, may try to widen a search or read an issue in a
project it should not see. The next example tries both:

```python
async def show(tool: Tool, arguments: dict[str, typing.Any]) -> None:
    try:
        print(await tool.run(arguments=arguments, invocation=invocation))
    except Exception as error:
        print(type(error).__name__, error)


async def tour() -> None:
    await show(jira_tools.jira_search, {"text": 'disk full" OR project = HR', "status": "Open"})
    await show(jira_tools.jira_get_issue, {"key": "HR-12"})


asyncio.run(tour())
# {'issues': [], 'more': False, 'jql': 'project in ("OPS") AND text ~ "disk full\\" OR project =
#  HR" AND status = "Open" ORDER BY updated DESC'}
# ToolFailure project 'HR' is not one of the allowed projects ('OPS',)
```

The attempt to widen the search stayed inside one quoted string, and the issue in `HR` was
refused before any request was sent.

## What it refuses

- **Projects outside `projects`,** and, when the run's [context](../concepts/run-context.md)
  carries `"project"`, any but that one (it must be one of `projects`). The run context can only narrow.
- **Malformed keys.** An issue key must match `[A-Z][A-Z0-9_]+-[0-9]+` and its project must be
  allowed; such a key cannot change the path it is placed in. An issue that turns out to be in
  another project (it was moved) is refused.
- **A label shaped like a gvn marker** (`gvn-` and 24 hexadecimal digits): only the tool sets
  those (see the next section).
- **A model choosing a host or a credential.** The site and the credentials come from the
  constructor only, and every path and query is built by the tool.

## How repeats are harmless

gvn delivers work at least once: if the process stops after Jira 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 creates a second issue.

So each write leaves a marker derived from the call key, `gvn-<hash of the tool's short name
and the call key>`, and looks for it before acting:

- `jira_create_issue` adds the marker as a label of the issue. Before creating, it looks
  for an issue with that label in two places: the search, and a direct read of the newest
  issues, the 100 keys from 20 below to 79 above the newest key the search returns. Keys
  are numbered in order within a project (`OPS-40`, `OPS-41`, ...), so an issue the first
  delivery created a moment ago is among them.
- `jira_comment` stores the marker as a property of the comment (an entity property named
  `gvn`, kept with the comment and not displayed), and first looks for it among the issue's
  100 latest comments.
- `jira_transition` does nothing when the issue already has the transition's target
  status.

The check and the write are two requests, so two deliveries of the same call running at
the same instant can both find nothing and both write.

Here is a redelivery as `jira_create_issue` sees it. The fake answers the label search with
nothing and says the newest key is `OPS-40`; the direct read then returns `OPS-41`,
labelled with the marker of call `run/2#c3`, as if the first delivery had created it and
then crashed:

```python
marker = jira_cloud.marker(jira_tools.jira_create_issue, "run/2#c3")


def answer(body: dict[str, typing.Any]) -> Response:
    return Response(status=200, headers={"content-type": "application/json"}, text=json.dumps(body))


search_url = "https://acme.atlassian.net/rest/api/3/search/jql"
bulkfetch_url = "https://acme.atlassian.net/rest/api/3/issue/bulkfetch"
http.script(
    "POST",
    search_url,
    answer({"issues": []}),  # the label search
    answer({"issues": [{"key": "OPS-40"}]}),  # the newest key
)
issue_41 = {"key": "OPS-41", "fields": {"labels": ["checkout", marker]}}
http.script("POST", bulkfetch_url, answer({"issues": [issue_41]}))
```

`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 = {"project": "OPS", "summary": "Checkout fails on Safari", "labels": ["checkout"]}
already = len(http.requests())
create = jira_tools.jira_create_issue
print(asyncio.run(create.run(arguments=new_issue, invocation=redelivered)))
# {'key': 'OPS-41', 'url': 'https://acme.atlassian.net/browse/OPS-41', 'created': False}
print([request["url"].rsplit("/", 2)[-1] for request in http.requests()[already:]])
# ['jql', 'jql', 'bulkfetch']
fetched = json.loads(http.requests()[-1]["body"])["issueIdsOrKeys"]
print(fetched[0], fetched[-1], len(fetched))
# OPS-20 OPS-119 100
```

The tool found `OPS-41` and returned it with `"created": False`; it sent two searches and
one direct read (`POST /rest/api/3/issue/bulkfetch`), and never the create.

### The model never sees the marker

The marker label stays on the issue, where the next repeat check needs it, but
`jira_get_issue` leaves it out of the labels it returns: the model reads the labels people
gave. `jira_cloud.unmarked` is the function it uses:

```python
print(jira_cloud.unmarked(labels=issue_41["fields"]["labels"]))
# ['checkout']
```

Comment properties are never returned at all. The [GitHub](github.md) tools do the same
with their marker: it is bookkeeping, not something people wrote.

## The tools, for lookup

The tools' short names say `jira`: that is what the model works with. The Python module,
and so each tool's identity (`gvn_tools.jira_cloud.jira_search`), says which product the
family is for.

Each row gives a tool's arguments (`?` marks an optional one), its **default verdict** (what
`jira_cloud.rules(jira_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 |
|---|---|---|---|
| `jira_search` | `project?`, `text?`, `status?`, `type?`, `assignee?`, `labels?`, `max_results?` | `cleared` | yes |
| `jira_get_issue` | `key` | `cleared` | yes |
| `jira_comment` | `key`, `text` | `needs_approval` | no |
| `jira_create_issue` | `project`, `summary`, `description?`, `type?`, `labels?` | `needs_approval` | no |
| `jira_transition` | `key`, `transition` | `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)).

- `jira_search` composes the JQL itself, every value a quoted, escaped string, always as
  `project in (<allowed>) AND ...`, so no argument can widen the search. It returns
  `{"issues": [{"key", "summary", "status", "type", "assignee", "updated"}], "more", "jql"}`,
  most recently updated first. `more` is true when at least one more issue matches than
  `max_results` (20 unless given, at most 50). `assignee` matches a display name, an email
  address or an account ID.
- `jira_get_issue` returns the summary, status, type, priority, assignee, reporter, labels,
  dates, the description as plain text, the number of comments and the 10 latest comments
  (the oldest of those first), every text capped.
- `jira_comment` and `jira_create_issue` take plain text and send each line as one
  paragraph of Atlassian Document Format (ADF), the JSON tree Jira stores. What the tools
  read back is turned into plain text: line breaks, list items as `- `, and the visible text
  of links, mentions, emoji, status lozenges and dates. `jira_create_issue` makes a `Task`
  unless `type` says otherwise.
- `jira_transition` takes the transition's name, or the name of the status it leads to, in
  any case. An unknown one is an error that lists the transitions there are.

## Errors

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

- **Not retryable** (`{"error": "tool_rejected", "detail": ...}`): a project, key or label
  outside what the tools may touch (refused before any request), an issue Jira answers with
  from outside the allowed projects, an unknown transition, any other error answer, with its status and
  Jira's message, and any answer whose `X-Seraph-LoginReason` header says the credentials were
  refused, whatever its status:

```python
refused = Response(
    status=200,
    headers={"x-seraph-loginreason": "AUTHENTICATED_FAILED"},
    text=json.dumps({"issues": [], "isLast": True}),
)
http.script("POST", search_url, refused)
asyncio.run(show(jira_tools.jira_search, {"status": "Open"}))
# ToolFailure Jira refused the credentials (X-Seraph-LoginReason: AUTHENTICATED_FAILED) and
#  answered 200 to POST /rest/api/3/search/jql as to an anonymous caller: check the email and
#  the token
```

- **Retryable** (`{"error": "tool_unavailable", "detail": ...}`): no answer at all, an answer of
  `429` or a `5xx`, or any error answer with a `Retry-After` in seconds, which comes back as
  `retry_after`.

A retryable failure is tried again only by a tool built with a retry: `jira_cloud.tools(...,
retry=Retry(...))` gives it to `jira_search` and `jira_get_issue`, which have no effect to
repeat. The three writes are tried once whatever you pass: a retry follows a lost answer
within seconds, the moment a write's repeat check leans hardest on Jira's search and recent
keys, so a write reported unavailable is left to the model or to you.

`jira_cloud.JiraCloudError` is left for a `2xx` answer that is not what the tool expected (larger
than `limit`, not JSON, not of the expected shape). It is a fault the model cannot act on, so it
is not a `ToolFailure`.

## Configuration

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

```python
# not runnable: the signatures.
jira_cloud.tools(http, base_url, token, projects, email, limit=1_000_000, timeout=30,
                 retry=None)
# -> JiraCloudTools(jira_search, jira_get_issue, jira_comment, jira_create_issue,
#                   jira_transition)
jira_cloud.rules(jira_tools)
jira_cloud.marker(tool, key)  # the marker a call of one of these tools leaves
```

Every request signs in with HTTP Basic authentication, as `email:token`.

Each argument of `jira_cloud.tools`:

| Argument | Default | Meaning |
|---|---|---|
| `http` | | the `Http` port: `LocalHttp()` (the `http` extra) or `FakeHttp` |
| `base_url` | | the site, `https://<site>.atlassian.net` (https, no user information, query or fragment) |
| `token` | | an Atlassian API token |
| `projects` | | the project keys the tools may touch |
| `email` | | the email of the Atlassian account the token belongs to |
| `limit`, `timeout` | 1,000,000, 30 | characters of response read; seconds per request |

The token, and the Basic credential made from it, is redacted as `[REDACTED]` from every
result and every error, transport errors included. Results are untrusted text from Jira,
bounded in size: issue text and comments are written by people, possibly to manipulate the
model reading them.

So every tool declares its results untrusted (`untrusted()` is `True`). 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)).

## Recap

- `jira_cloud.tools(http=..., base_url=..., token=..., projects=[...], email=...)` reaches one
  Jira Cloud site, with your credentials, inside the listed projects; every query and path
  is built by the tool.
- Reads are cleared; comments, creates and transitions need a person.
- A repeat looks for a marker derived from the call's key (for issues, through the search
  and a direct read of the newest keys); the model never sees the marker.

**Next:** [GitHub](github.md).
