# Writing an adapter

How to connect your own tool to the bus, in any language, with only the
released `gromit` binary. No access to this repo needed. Read
[concepts.md](concepts.md) first. The worked example is
[examples/todo-adapter/](examples/todo-adapter/).

## First: do you need one?

| You want | Do this instead of an adapter |
|---|---|
| Your GitLab MRs on the bus | Ask the steward to add your GitLab username (`add-member --existing --gitlab`). The GitLab bridge does it |
| Your Asana tasks on the bus | The same with `--asana <user gid>`, on a board the Asana bridge maps |
| Claude Code to see and act on team work | Already there: the `gromit` MCP server `local install` added |
| An occasional manual update | `gromit do work-item@1 …` |
| A tool with no API, or one-off syncing | Ask Claude Code to do it through MCP, as a recurring task |

Write an adapter when **your own tool**, the one only you use, should keep
the bus up to date and take things back from it: a personal task manager, a
notes app, a planning tool like Argonauts.

## What an adapter is

A small program on your machine that:

1. reads your tool;
2. reads the folded state from your sidecar (`GET /state`);
3. publishes the difference (`POST /do`), checking each outcome;
4. brings back what teammates did that concerns you (`GET /state` or
   `GET /events`), into your tool;
5. sleeps, and does it again.

It talks only to your sidecar's unix socket. The sidecar signs, queues while
offline and judges every event. The adapter holds no key and no relay
address. See [sidecar-api.md](sidecar-api.md) for every route.

```
your tool ──read──▶ adapter ──POST /do──▶ sidecar ──▶ relay ──▶ team
          ◀─write──         ◀─GET /state, /events──
```

## Step 1: map your tool onto a contract

Pick the contract whose meaning matches. For tasks, tickets and to-dos that's
`work-item@1`. Then write down, for each thing your tool has:

- **which field** it becomes. Check [contracts.md](contracts.md) for who may
  set it;
- **which states** map to which. Your tool's states must walk the contract's
  graph. `work-item@1` can't go from `open` straight to `done`: claim it
  first (`active`), then `done`;
- **what's lossy.** Things your tool can't represent, which you mustn't
  write back. Tiphys has no `blocked`, so it never publishes one;
- **what's unsupported.** Fields you ignore.

That list becomes your manifest (Step 6). If no contract fits, see "A new
contract" at the end.

## Step 2: decide who it publishes as

| As | Payload `actor` | When |
|---|---|---|
| You | omit | the adapter only mirrors what you did in your tool. Simplest |
| Your agent, `sam/<tool>` | `"sam/<tool>"` | you want its events marked as automated, limited and revocable. Grant a mandate first |

```sh
gromit do mandate@0 granted --payload '{"agent":"sam/todo","grants":[{"scope":"work-item@1:routine"},{"scope":"work-item@1:claimed","ratify":"none"}]}'
```

`:routine` doesn't cover commitments like `claimed`. Without the second grant
a claim by `sam/todo` is `rejected:no_mandate`. With it but no
`"ratify":"none"`, it's `pending` until you ratify. To change the grants
later, send `mandate@0 widened` or `narrowed` with the **whole** new
`grants` list: it replaces the old one. Protected verbs, such as
approving a change set, are never possible for an agent.

## Step 3: give your tool's items an `ext.<tool>` key

Put your tool's own id on every entity you create, under one key named after
your tool, **on the creating event**:

```json
{"contract": "work-item@1", "verb": "created",
 "payload": {"title": "Rotate the Snowflake key", "repo": "git:platform", "ext.todo": "t1"}}
```

Next pass, find your items by that key in `/state`. Putting it on `created`,
not a later `edited`, means a crash between two calls can never leave an
item you won't recognise, which would be published twice. Any value works: a
string, or an object like the Asana bridge's
`{"gid": …, "url": …}`. Never write another tool's `ext.` key.

`ext.*` is only allowed where the contract says `extensions: { allowed: true }`.
`work-item@1` does. On someone else's item you may set your key only if you
hold it.

## Step 4: the pass

```python
me     = GET /status            ["person"]
state  = GET /state?entity=all  ["entities"]
mine   = { f["ext.todo"]: id for id, e in state if e.type == "work-item@1#work_item" and "ext.todo" in e.fields }

for item in my_tool:
    if item.id not in mine:   do("created", payload={…, "ext.todo": item.id}); do("claimed", entity=new_id)
    elif item changed:        do the verb that moves it: edited / state_changed / commented

for id, e in state where e.holder == me and "ext.todo" not in e.fields:
    bring it into my tool, once
```

The rules that keep a pass safe:

- **Idempotent.** A second pass with nothing new publishes nothing. Compare
  with the folded state every time. Don't keep your own memory of what you
  sent and trust it over `/state`.
- **Check every outcome.** `/do` answers HTTP 200 even for
  `rejected:<reason>`. Log rejections. Don't retry them: the same event gets
  the same answer. Record the key and skip it, as the Tiphys adapter does in
  its ledger.
- **Check the HTTP status before parsing.** A request the sidecar can't
  parse gets plain text with 400, 415 or 422, not JSON.
- **Spell fields exactly.** `created` stores any key it's given, so a typo
  like `titel` is kept silently and `title` stays missing.
- **Change state with its own verb.** `edited {state: done}` is rejected;
  use `state_changed {to: done}`. Holders change by `claimed`, `offered`
  and `released`.
- **`suggestion`, `pending` and `fork` are not errors.** `pending` is an
  offer waiting for an answer, or your agent's commitment waiting for you. You didn't have the right, or
  someone else got there first. Re-read the state next pass.
- **Walk state graphs.** To get from `open` to `done`, claim first. To leave
  `done` for `open`, go through `active`.
- **Respect the holder.** Don't change items a teammate holds. The contract
  turns most such edits into suggestions anyway.
- **Everything is public to the team.** Every event goes to the whole
  grouping. Only publish what your tool marks as shared, as the example
  does with `repo`.
- **Don't open change sets.** The GitLab bridge owns them, one per MR.
  Link your planning to one with `change-set@0 linked`
  (`{"item": "mytool:thing:42"}`) and add `evidence_added` if you have
  test results.

## Step 5: bring things back

Two ways to see what changed:

- **The state.** Each pass, look for entities that concern you: held by you
  (`holder == me`), offered to you (`GET /inbox` `waiting_on_you`), claims
  about your work. Simple, and enough for most tools. The example does this.
- **The stream.** `GET /events?since=<cursor>&once=true` returns every event
  since your cursor, with its outcome and full envelope. Keep the last `pos`
  in a file. Use it when you need what happened, not just where things ended
  up: "Alex requested changes on my MR", "a comment was added". Skip
  `rejected:*` events. An outcome can change after the note was sent (an
  open offer is `pending` until accepted; a claim can later `fork`), and the
  stream doesn't resend it, so check `/state` before acting on one.

Bring each thing in once. Remember the entity id you imported it from (the
example stores it as `tally`) so you don't import it again.

## Step 6: test it in a sandbox, then with the conformance kit

Never test against the team's grouping. Everything you publish there stays.

```sh
PERSON=sam docs/sandbox.sh start     # a one-person grouping with the team's contracts
export GROMIT_KEYS=… GROMIT_DATA=… TALLY_SOCKET=…   # the line it prints
python3 my_adapter.py --once
gromit fold all --in sandbox
```

Not in this repo? `sandbox.sh` is standalone: save it anywhere and run it.

Then write a manifest and run the conformance kit, which ships in the
binary:

```yaml
adapter: todo
person: sam
speaks:
  work-item@1:
    produce: [created, claimed, state_changed]   # every verb you may publish
    consume: [created, claimed, offered]
    map:
      fields: { title: title, repo: repo, ext.todo: id }
      states: { active: "not done", done: done }
    lossy: []                    # fields you must never write back
    unsupported: [due, tags]
test:
  run: python3 my_adapter.py --todos todos.json --once     # one pass; $GROMIT_DATA is set
```

```sh
cd <the manifest's directory>      # test.run runs in your current directory
gromit conformance todo.adapter.yaml --in sandbox
```

It checks:

- the contracts' own tests, in shuffled orders;
- **round trip**: an `ext.` field the kit adds to one of your entities
  survives a pass of your adapter;
- **no lossy write-back**: no pass sets a `lossy` field, and a second pass
  publishes nothing;
- your adapter publishes only verbs in `produce`.

`compliant` means it's ready. Only `adapter`, `person`, `speaks.*.produce`,
`speaks.*.lossy` and `test.run` are read by the kit. The rest documents the
mapping for people. A `lossy` entry is a field (`due`) or one value of it
(`state.blocked`). The kit sets `GROMIT_DATA` for the run; everything else
comes from your shell.

## Step 7: run it

- Start with `--dry-run` against your real grouping and read every line.
- Then one `--once` pass, and check `gromit fold all` and the board.
- Then keep it running at login, like the sidecar. Copy
  `~/Library/LaunchAgents/com.gromit.sidecar.plist` to
  `com.<you>.<tool>-adapter.plist`, change `Label` and `ProgramArguments`,
  and `launchctl load` it. Poll every 30 seconds or more.

## Step 8: share it

Adapters live in their own repos, not in Gromit, because they belong to the
tool. Put yours where the team can see it, with its manifest, so the next
person with the same tool can use it.

## A new contract

If no contract fits (time off, on-call, meal plans), write one. See
[contract-language.md](contract-language.md):

1. Copy the closest contract from the governance repo as a start.
2. Write tests for the behaviour you want, then make them pass with
   `gromit contract test --dir <dir> --grouping fixtures/grouping.yaml`.
3. Try it with your adapter in a sandbox: `docs/sandbox.sh start --contracts <dir>`.
   That directory replaces the team's contracts, so put `mandate@0.yaml`
   (and any contract yours refers to) in it too.
4. Propose it as a commit to the governance repo, adding the file and
   listing it in `grouping.yaml` `contracts:`. The team approves it with
   `gromit approve`.

Ask the steward before step 4. A contract is the team agreeing what the
words mean, so it's worth a conversation first.

## Reference adapters

- **todo** ([examples/todo-adapter](examples/todo-adapter/)): Python,
  standard library, about 150 lines. The pattern to copy.
- **Tiphys** (`crates/gromit-tiphys`, binary `gromit-tiphys`): Rust, the
  full version. Batches become work items, decisions, links and evidence go
  out, and requested changes and tickets come back as seeds. Its manifest is
  `crates/gromit-tiphys/tiphys.adapter.yaml`. It uses only the routes above.
