# Python agent workflow

Take an issue to a merged pull request from Python with a caisson, a batch of edits, a ship, a wait for checks and a merge, in sync and async code, including a merge a person must approve.

This page walks one change from an issue to a merge: start a caisson on the issue, read and change files, ship a pull request, wait for its checks and merge. The merge may be held for a person, and the code handles that.

The steps use [handles](https://sailfork.com/docs/sdk-python-handles): `issues.start` returns the caisson and `ship` returns the pull request. Two of the calls are safe to repeat, which is what lets a script that crashed run again from the top: `issues.start` returns the caisson already working on the issue, and `caissons.ship` skips the commit when nothing is pending and reuses an open pull request.

## Sync

```python
from sailfork import Done, Held, HeldDeclinedError, Sailfork

OWNER, NAME = "acme", "api"

with Sailfork() as sf:
    repo = sf.repo(f"{OWNER}/{NAME}")

    issue = repo.issues.create("Charges round to the cent", body="Totals drop the half cent.")
    caisson = repo.issues.start(issue.number)

    source = caisson.read(paths=["src/charge.py"]).files[0]
    if "error" in source:
        raise RuntimeError(source["error"])
    print(source["text"])

    caisson.batch(
        changes=[
            {"path": "src/charge.py", "edits": [{"old": "int(total)", "new": "round(total)"}]},
            {"path": "docs/charges.md", "content": "Totals round to the cent.\n"},
        ],
    )
    print(*(file.path for file in caisson.diff()))

    pr = caisson.ship(message="fix(charge): round to the cent", closes=[issue.number])
    number = pr.get().number

    checks = sf.wait({"kind": "pull", "owner": OWNER, "repo": NAME, "number": number}, until="checks", timeout=900)
    if checks.failed:
        raise SystemExit(f"checks failed: {checks.detail}")

    merge = pr.merge(method="squash", delete_branch=True)
    if isinstance(merge, Held):
        print(f"waiting for a person: {merge.url}")
        decided = sf.wait({"kind": "held", "owner": OWNER, "id": merge.held}, timeout=3600)
        if not decided.met:
            raise SystemExit(f"not decided: {decided.detail}")
        try:
            merge = pr.merge(method="squash", delete_branch=True)
        except HeldDeclinedError as err:
            raise SystemExit(f"declined: {err}")
    if isinstance(merge, Done):
        print(merge.value.state)
```

What each step does:

| Step | Call | Notes |
| --- | --- | --- |
| File the issue | `repo.issues.create(title, body=)` | Skip it when the issue exists; `issues.start(number)` takes any open issue. |
| Open a caisson | `repo.issues.start(number)` | Claims the issue and opens a caisson on its branch. Returns a `Caisson`. |
| Read | `caisson.read(paths=)` | Entries are dicts: `text`, or `error` for a file that could not be read. |
| Change | `caisson.batch(changes=)` | All of the changes or none. Add `dry_run=True` to look first. |
| Look | `caisson.diff()` | A list of file diffs. |
| Ship | `caisson.ship(message=, closes=)` | Commits and opens the pull request. Returns a `PullRequest`. |
| Wait | `sf.wait({...}, until="checks")` | See [Held writes and waits](https://sailfork.com/docs/sdk-python-held-and-waits#wait-for-a-change). |
| Merge | `pr.merge(...)` | Returns `Done` or `Held`. |

`checks.state` is `none` when the repository has no CI. The script above goes on to merge in that case, since `failed` is the only thing it stops for. Add `if checks.pending: ...` to stop when the timeout passes first.

### Edit with a patch or a read-then-edit

`batch` takes `edits` that replace exact text. A batch is all or nothing: when one change cannot apply, none of them are saved. A unified diff goes through `patch`, which has the same all-or-nothing rule:

```python
caisson.patch(
    diff="""--- a/src/charge.py
+++ b/src/charge.py
@@ -10,3 +10,3 @@
-    return int(total)
+    return round(total)
""",
    dry_run=True,
)
```

A change to a path an organization's rules hold for a person raises `UnexpectedHeldError` with `code == "held"`; see [Held writes and waits](https://sailfork.com/docs/sdk-python-held-and-waits#caisson-writes).

## Async

The async client has the same shape. Everything that talks to the server is awaited, and `pr.get()` becomes `(await pr.get())`.

```python
import asyncio

from sailfork import AsyncSailfork, Done, Held, HeldDeclinedError

OWNER, NAME = "acme", "api"


async def main() -> None:
    async with AsyncSailfork() as sf:
        repo = sf.repo(f"{OWNER}/{NAME}")

        issue = await repo.issues.create("Charges round to the cent", body="Totals drop the half cent.")
        caisson = await repo.issues.start(issue.number)

        await caisson.batch(
            changes=[{"path": "src/charge.py", "edits": [{"old": "int(total)", "new": "round(total)"}]}],
        )

        pr = await caisson.ship(message="fix(charge): round to the cent", closes=[issue.number])
        number = (await pr.get()).number

        target = {"kind": "pull", "owner": OWNER, "repo": NAME, "number": number}
        checks = await sf.wait(target, until="checks", timeout=900)
        if checks.failed:
            raise SystemExit(f"checks failed: {checks.detail}")

        merge = await pr.merge(method="squash", delete_branch=True)
        if isinstance(merge, Held):
            print(f"waiting for a person: {merge.url}")
            decided = await sf.wait({"kind": "held", "owner": OWNER, "id": merge.held}, timeout=3600)
            if not decided.met:
                raise SystemExit(f"not decided: {decided.detail}")
            try:
                merge = await pr.merge(method="squash", delete_branch=True)
            except HeldDeclinedError as err:
                raise SystemExit(f"declined: {err}")
        if isinstance(merge, Done):
            print(merge.value.state)


asyncio.run(main())
```

To run independent calls at once, use `asyncio.gather`:

```python
pulls = [sf.repo("acme/api").pull(n) for n in (126, 127, 128)]
details = await asyncio.gather(*(pull.get() for pull in pulls))
```

## Resume after a crash

Without a key of your own, a restarted script makes new calls with new keys, so it resumes by repeating the calls that are safe to repeat. The workflow is written that way: run it again from the top and `issues.start` returns the live caisson, `batch` with the same `content` writes the same files, `ship` reuses the open pull request, and a `pulls.merge` of a pull request that is already merged answers with it while its branch has not moved.

For a write that is not safe to repeat, give the call an `idempotency_key` through `options` and derive it from the job, not from a random value. The server runs the write once per key and answers a repeat with the first result, so a script that crashed after the call can send it again:

```python
from sailfork import RequestOptions

key = f"charge-fix-{issue.number}"
caisson.bash(script="./gen.sh", options=RequestOptions(idempotency_key=key))
```

Use a different key for each distinct write. See [Per-call options](https://sailfork.com/docs/sdk-python-errors#per-call-options).

Next to the TypeScript version of this page: [TypeScript agent workflow](https://sailfork.com/docs/sdk-typescript-workflow).

---

Every docs page: https://sailfork.com/llms.txt
