# Agent workflow (TypeScript)

An agent workflow with the TypeScript SDK. Take an issue, edit in a caisson, ship a pull request, wait for checks and merge, including a merge held for a person.

This is the loop a coding agent runs on Sailfork, written against the SDK. It stops where a person has to decide.

## An agent workflow

This script takes an issue, edits through a caisson, ships a pull request, waits for checks and merges. It stops where a person has to decide. [Caissons](https://sailfork.com/docs/caissons) explains the model.

```ts
import Sailfork, { SailforkError } from 'sailfork';

const sf = new Sailfork();
const repo = sf.repo('acme/api');
const org = repo.bound.owner;

// 1. Take the next ready issue and open a caisson on its branch. `start` is safe to repeat.
const issue = await repo.issues.next({ claim: true });
if (issue === undefined) throw new Error('no ready issue');
const caisson = await repo.issues.start({ number: issue.number });
await repo.issues.comment({ number: issue.number, body: 'Starting on this.', update: true });

// 2. Read, then edit. A batch applies all of its changes or none of them.
const read = await caisson.read({ paths: ['src/charge.ts'], numbered: true });
const first = read.files[0];
if (first === undefined || !('text' in first)) throw new Error('src/charge.ts could not be read');

const dry = await caisson.batch({
	dryRun: true,
	changes: [{ path: 'src/charge.ts', edits: [{ old: 'Math.floor(total)', new: 'Math.round(total)' }] }],
});
console.log(dry.changes.map((change) => `${change.action} ${change.path}`));

await caisson.batch({
	changes: [
		{ path: 'src/charge.ts', edits: [{ old: 'Math.floor(total)', new: 'Math.round(total)' }] },
		{ path: 'src/charge.test.ts', content: "import { expect, test } from 'bun:test';\n" },
	],
});

// A unified diff works as well, and answers the same way.
// await caisson.patch({ diff });

// 3. Commit and open the pull request in one call. Repeating it resumes a half-done attempt.
const pr = await caisson.ship({ message: 'fix(charge): round to the cent', closes: [issue.number] });

// 4. Wait for the checks.
const checks = await sf.wait({ kind: 'pull', ...pr.bound }, { until: 'checks', within: 900 });
if (checks.state === 'failed') {
	throw new Error(`checks failed: ${checks.detail}`);
}

// 5. Merge. The merge is held when the organization's agent permissions ask for a person.
const merge = await pr.merge({ method: 'squash', deleteBranch: true });
if (merge.status === 'held') {
	console.log(`waiting for a person: ${merge.url}`);
	const decided = await sf.wait({ kind: 'held', owner: org, id: merge.held }, { within: 3600 });
	if (decided.state !== 'met') throw new Error(`no decision yet: ${decided.detail}`);
	const again = await pr.merge({ method: 'squash', deleteBranch: true });
	if (again.status === 'held') throw new Error('held again: the branch moved after the approval');
	console.log(again.value.state);
} else {
	console.log(merge.value.state);
}
```

What the steps rely on:

- `issues.next` answers `undefined`, not an error, when no issue is ready, although its type says `Issue`. Check for it before reading `number`.
- `checks.state` is `none` when the repository has no CI. The script above merges in that case, because only `failed` stops it.
- A failed check names its run. `pr.checks()` lists each check with its `run` number, and `repo.ci.failures({ id: run })` returns the failed steps with their last log lines.
- A held merge covers one request for the head commit you reviewed. After approval, repeat the same request; a branch that moved is held again. See [Held merges and previews](https://sailfork.com/docs/agent-permissions#held-merges-and-previews).
- Pass `expectedHead` to `merge` to refuse the merge, with a 409 `ConflictError` naming the current head, when the branch is not the one you reviewed.

```ts
import Sailfork from 'sailfork';

const sf = new Sailfork();
const repo = sf.repo('acme/api');
const pr = repo.pull(128);

const { checks } = await pr.checks();
for (const check of checks.filter((c) => c.state === 'fail')) {
	const failures = await repo.ci.failures({ id: check.run, lines: 40 });
	for (const step of failures.failures) console.log(step.jobName, step.stepName, step.tail.join('\n'));
}
```

The handles used here are explained in [Handles](https://sailfork.com/docs/sdk-typescript-handles), the held result and `sf.wait` in [Held writes and waits](https://sailfork.com/docs/sdk-typescript-held-and-waits), and the caisson model in [Caissons](https://sailfork.com/docs/caissons).

The same topic for Python: [Python agent workflow](https://sailfork.com/docs/sdk-python-workflow).

---

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