# The sidecar API

How a program talks to its person's sidecar: the socket, every route, the
JSON it sends and gets back, the event stream, and the CLI and MCP that wrap
them. Read this to write an adapter or a script. Everything below was
captured from a running sidecar (gromit 0.2.0).

The routes are in `crates/gromit/src/sidecar.rs` (around line 630). The
request body type is `DoRequest` in `crates/gromit-core/src/api.rs`.

## Connecting

- **HTTP/1.1 over a unix socket**, with no TCP port:
  `~/.local/share/gromit/<grouping>/sidecar.sock`, so
  `~/.local/share/gromit/tally/sidecar.sock` for the team. (If that path
  were 100 bytes or longer, the sidecar would use
  `$TMPDIR/gromit-<hash>.sock` and print it in its log's first line.)
- **No auth beyond the file system.** The socket is mode 0600 in a 0700
  directory, so only your own user can open it. The sidecar signs with your
  device key. Callers never see a key.
- **Same machine, same user, sidecar running.** `gromit local status` says
  whether it is.

```sh
S=~/.local/share/gromit/tally/sidecar.sock
curl -s --unix-socket $S http://x/status          # the host name is ignored
```

Python's standard library (see the example adapter for the whole client):

```python
class Sidecar(http.client.HTTPConnection):
    def __init__(self, path): super().__init__("sidecar"); self.path = path
    def connect(self):
        self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM); self.sock.connect(self.path)
```

Node: `http.request({ socketPath: S, path: "/status" })`. Go: an
`http.Transport` whose `DialContext` dials `"unix", S`. Or shell out to the
`gromit` CLI, which wraps the same routes.

## Routes

| Route | Does | CLI |
|---|---|---|
| `GET /status` | who you are, relay connection, rules, queue | `gromit local status` |
| `GET /state?entity=<prefix\|all>` | folded state | `gromit fold all --json` |
| `POST /do` | publish one event | `gromit do` |
| `GET /events?since=N[&once=true]` | the event stream (SSE) | `gromit tail --json` |
| `GET /inbox[?mark=true]` | what's waiting on you | `gromit inbox --json` |
| `GET /mandate?agent=sam/todo` | `{"active": "<mandate id>"}` or `{"active": null}` | |
| `POST /default-mandate` | grant `<you>/claude` the default mandate from `<data>/default-mandate.json`; `{"said": null}` if that file isn't there | `gromit agent setup claude --write` |
| `POST /poll` | bridges only: poll now | `gromit bridge poll` |

### GET /status

```json
{
  "grouping": "tally", "person": "tom", "version": "0.2.0+e08556a5e479",
  "key": "ed25519:0dbf10ca54c0…",
  "relay": { "url": "wss://relay.example.com/", "connected": true,
             "last_heard": "2026-11-18T15:27:27.007Z", "last_error": null },
  "cursor": 1398,                 // newest local event position
  "queued": 0,                    // signed, not yet acked by the relay
  "refused": [],                  // events the relay refused
  "rules": { "active": "b54051189428…", "hash": "12200d654b0f…", "pending": [] }
}
```

Read `person` from here rather than configuring it. `rules.pending` lists
governance commits waiting for approvals.

### GET /state

`?entity=all` (or no parameter) returns everything; `?entity=12207ada`
returns entities whose id starts with that prefix.

```json
{
  "entities": {
    "12207adaede540…": {
      "type": "work-item@1#work_item",     // contract@major#entity
      "layer": "state",                    // "claim" for an unconfirmed attestation
      "audience": "grouping",
      "fields": { "title": "Ticket from the board", "repo": "git:platform",
                  "state": "active", "holder": "sam", "creator": "sam",
                  "comments": [], "links": [], "tags": [], "attachments": [], "viewing": [] }
    }
  },
  "handshakes": {
    "1220e1cc066a…": { "entity": "12204672a8df…", "verb": "agent_commitment", "state": "open",
                       "parties": ["sam"], "quorum": 1, "responses": 0 }
  },
  "outcomes": [
    { "event": "12204839004f…", "actor": "sam", "verb": "claimed", "outcome": "applied",
      "to": null, "received_at": "2026-11-18T15:30:09.896Z" }
  ]
}
```

- Extension fields are flat keys in `fields`: `"ext.asana": {…}`.
- There's no filter by contract or field. Fetch all and filter in your code.
  The team's bus is about 700 entities. A full `/state` takes well under a
  second.
- `/state` is folded on every call. It's the truth. Don't cache it across
  passes.

### POST /do

Publish one event. The body:

```json
{
  "contract": "work-item@1",        // required: name@major
  "verb": "created",                // required
  "entity": "12207adaede540",       // id or unique prefix; omit to create
  "responds_to": null,              // a handshake's id or prefix, for responses
  "payload": { "title": "Write the adapter guide", "repo": "git:platform",
               "ext.todo": "t3" },
  "actor": null,                    // omit for you; "sam/todo" for one of your agents
  "audience": null                  // omit. Anything narrower than the grouping is refused
}
```

The answer is always HTTP 200 when the request was well formed, **including
when the event was rejected**:

```json
{"id":"1220a13196865c…","outcome":"applied","to":null}
{"id":"122037f7c7fd…","outcome":"rejected:illegal_transition","to":null}
{"id":"1220e1cc066a…","outcome":"pending","to":null}
{"id":"…","outcome":"suggestion","to":"tom"}
```

So **check `outcome` every time**. A rejected event is not stored or sent.
Nobody else sees it, and publishing it again gets the same answer. Outcomes
are in [outcomes.md](outcomes.md).

A request the sidecar can't act on is HTTP 400 with a JSON sentence:

```json
{"error":"work-item@1 has no verb finished"}
{"error":" matches 7 events; give more of the id"}
{"error":"refused: audience [...]: … seed 861"}
```

A request it can't even parse gets a plain-text body, not JSON: 400 for bad
JSON, 415 without `Content-Type: application/json`, 422 when `contract` or
`verb` is missing. So check the status before parsing the body.

The sidecar fills in everything else in the envelope: `seq`, `prev`, `seen`,
`rules`, `ts` and the signature. Offline, the event is queued and sent when
the relay is back. `/status` `queued` counts it.

`actor` can only be you (`sam`) or one of your agents (`sam/<name>`).
Anything else is refused. An agent needs a mandate (`rejected:no_mandate`
otherwise). A normal sidecar can't publish as a bridge.

### GET /events: the event stream

Server-sent events. Every event the sidecar stores, yours and everyone
else's, in order:

```
id: 17
event: event
data: {"pos":17,"event":"122060bf50a6…","actor":"sam","verb":"commented","outcome":"applied","mine":true,
       "envelope":{ …the whole signed event, as in concepts.md… }}

event: status
data: {"acked":"122060bf50a6…","received_at":"2026-11-18T15:34:46.384Z"}
```

- `since=N` replays every event after local position N, then follows live.
  No `since` starts from now. `Last-Event-ID: N` works too.
- `once=true` stops after the replay. That's the easy way to poll with a
  cursor: keep the last `pos` you processed and ask for `since=<pos>&once=true`
  on each pass.
- `pos` is this sidecar's own position, not the relay's sequence. Keep your
  cursor per machine.
- `event: status` notes carry no `pos`: `acked` (the relay has your event),
  `refused` (it didn't, with `reason` and any events re-signed after it),
  rules changes, and `lagged` with `resync_from` if you fell behind.
- `outcome` is how this sidecar's fold judged the event **when the note was
  sent**. It can change afterwards: a `pending` offer becomes met, an agent's
  `pending` claim is ratified, an `applied` claim turns into `fork` when an
  earlier concurrent claim arrives. A live note isn't re-sent when that
  happens; a replay re-folds. So use the stream to learn *that* something
  happened, and `/state` for where things stand.
- Ignore `rejected:*` events. Trust `on_behalf` only from a bridge.

`gromit tail --since N --json` prints the same notes one JSON object per
line, if spawning a process is easier than reading SSE.

### GET /inbox

```json
{ "person": "sam",
  "waiting_on_you": [ { "verb": "agent_commitment", "title": "By the todo agent",
                        "handshake": "1220e1cc066a…", "entity": "12204672a8df…",
                        "answer_with": ["mandate@0 ratified"], "deadline": "2026-11-19T15:33:03.301Z",
                        "parties": ["sam"], "proposer": "sam", "quorum": 1, "responses": 0 } ],
  "waiting_on_others": [], "claims_about_you": [], "recent": [] }
```

Answer an item with its `answer_with` verb and the handshake as
`responds_to`:
`gromit do mandate@0 ratified --responds-to 1220e1cc066a`.
`?mark=true` marks `recent` as read.

## The CLI

Commands that talk to the sidecar take `--in <grouping>` (or `--data
<dir>`). Without them they find your only grouping. `gromit contract …`
works on files and takes neither.

```sh
gromit do work-item@1 created -s title="Rotate the API keys" -s repo=git:platform
gromit do work-item@1 claimed --entity 7adaede540
gromit do work-item@1 edited --entity 7adaede540 -s 'ext.todo="t3"'
gromit do work-item@1 state_changed --entity 7adaede540 --payload '{"to":"done"}'
gromit do work-item@1 created -s title="By my agent" --actor sam/todo
gromit fold all --json                  # /state
gromit fold 7adaede540                  # one entity, as YAML
gromit tail --since 0 --json            # /events
gromit inbox
```

- `-s key=value` parses the value as JSON, and as a plain string if it
  isn't JSON. Quote a string that would parse as JSON: `-s title='"42"'`.
  `--payload '{…}'` takes the whole payload at once.
- `gromit do` prints `<short id> <outcome>` and exits 1 when rejected. Use the
  socket if you need the full id.
- Relative `--data` paths can miss the socket; pass an absolute path.

## MCP, for agents

`gromit mcp --actor sam/claude` speaks MCP over stdio. `gromit local install`
registers it in Claude Code. The actor must be `person/agent`, so agents are
always under a mandate. Tools:

| Tool | Params | Route |
|---|---|---|
| `tally_status` | none | `GET /status` |
| `tally_state` | `entity?` | `GET /state` |
| `tally_inbox` | none | `GET /inbox` |
| `tally_do` | `contract`, `verb`, `entity?`, `responds_to?`, `payload?` | `POST /do`, with `actor` forced to the server's |

There's no stream over MCP. Agents poll `tally_state` or `tally_inbox`.
