# The contract language

Every key a contract file can have, what it means and how the fold uses it.
Read this to write or change a contract. To learn what the team's contracts
say, read [contracts.md](contracts.md) instead.

The parser is `crates/gromit-core/src/contract.rs`, the expression language is
`expr.rs`, and the rules run in `fold.rs`. `gromit contract lint` checks every
key below.

## A whole contract, annotated

```yaml
contract: work-item            # name. Events name it as work-item@1.1.0, rules and refs as work-item@1
version: 1.1.0                 # semver string. The major is part of the key: a breaking change is a new file, work-item@2.yaml
status: draft                  # draft | stable (informational)
steward: tom                   # who looks after it (informational)
description: >                 # free text; say what changed in each minor version
  A piece of shared work with one holder.

entities:                      # one or more entity types. Most contracts have one
  work_item:
    default_profile: stream
    fields:
      title:   { type: string, maxLength: 200, required: true }
      state:   { enum: [open, active, done], default: open }
      holder:  { type: person, nullable: true, managed_by: transfer }
      creator: { type: person, managed_by: runtime }
      tags:    { type: set, items: string }
      links:   { type: set, items: link }      # a named type from types:
      comments: { type: log, items: comment }

types:                          # reusable object shapes for set/log items
  link:    { rel: { enum: [blocks, relates] }, ref: { type: ref, contracts: [work-item@1] } }
  comment: { body: { type: string, format: markdown } }

roles: { lead: { granted_by: grouping } }      # members get roles in grouping.yaml

states:                         # the allowed transitions of the `state` field
  open:   { to: [active] }
  active: { to: [done, open] }
  done:   { to: [active] }

rights:                         # who may change each field through a `who: per_field` verb
  title: [creator, holder, bridge]
  tags:  [member]

verbs:
  created: { kind: fact, weight: routine, who: [member, bridge],
             sets: { $payload, creator: $person, state: open, holder: null } }
  edited:  { kind: fact, weight: routine, who: per_field }
  claimed: { kind: transfer, weight: commitment, who: member, when: holder == null,
             sets: { holder: $person, state: active }, concurrent: lowest_hash_wins }

extensions: { allowed: true, default_rights: [holder, bridge] }

clock: relay_received_at        # the only clock; time rules use the relay's stamp

tests:                          # run by gromit contract test
  - name: Create, then claim
    events:
      - { id: c, by: sam, verb: created, payload: { title: Fix login } }
      - { id: k, by: tom, verb: claimed, entity: c }
    expect:
      { entity: c, state: { state: active, holder: tom, creator: sam } }
```

## Top-level keys

| Key | Required | Meaning |
|---|---|---|
| `contract` | yes | Name, kebab-case |
| `version` | yes | Semver string, quoted if YAML would read it as a number. A minor bump must be additive: old events still fold the same |
| `status`, `steward`, `description` | no | Informational |
| `core` | no | `true` for contracts the runtime itself relies on (`mandate@0`) |
| `entities` | yes | At least one entity type |
| `types` | no | Named shapes for `set`/`log` items, or aliases of a primitive with constraints |
| `roles` | no | Role names a member can hold, e.g. `role:lead` |
| `states` | no | Transition graph for the `state` field. With several entities, key it by entity: `states: { week: {…}, meal: {…} }` |
| `rights` | no | Field → who may change it, for `who: per_field` verbs |
| `verbs` | yes | What actors can do |
| `holder`, `parties` | no | Entity-level expressions, e.g. `holder: $subject.holder`: a decision is held by whoever holds its subject |
| `extensions` | no | `{ allowed, default_rights, default_profile }`. With `allowed: true`, any `ext.*` key is carried and folded |
| `clock` | no | `relay_received_at`, the only clock |
| `tests` | no, but write them | Test table, below |
| `enforcement`, `enforcer_tests` | no | Parsed, not run in v0 |

## Fields

A field is `name: { type: …, … }`, or `name: { enum: [...] }` for an enum.

### Types

| Type | JSON | Use |
|---|---|---|
| `string` | string | add `format: markdown`, `maxLength`, `minLength`, `pattern` |
| `int`, `bool` | number, boolean | `int` takes `min`, `max` |
| `date` | `"2026-11-18"` | |
| `datetime` | string | |
| `duration` | `"24h"`, `"7d"`: `\d+[smhd]` | |
| `enum` | one of the listed strings | |
| `set` | array, no duplicates, order not meaningful | `items: <type>`, `minItems` |
| `log` | array, append-only | `items: <type>` |
| `person` | a member's name, `"sam"` | |
| `actor` | `"sam"`, `"sam/claude"` or `"system:asana-bridge"` | |
| `ref` | an entity id | `contracts: [decision@0]` or `["*"]` limits what it may point at |
| `external_ref` | a string naming something off the bus | `git:platform`, a URL |
| `hash` | string | a commit sha, a content hash |
| `grouping`, `blob`, `scope`, `condition` | string | specialised: a grouping name, an attachment, a mandate scope, an expression |

### Field attributes

| Attribute | Meaning |
|---|---|
| `required: true` | must be in the creating event's payload |
| `nullable: true` | may be `null` |
| `default: x` | value when the entity is created without it |
| `managed_by: runtime` / `transfer` | can't be set from a payload, only by a verb's `sets:` (`creator: $person`, `holder: $payload.to`). The two are enforced the same way; the name says which kind of verb is meant to change it. A verb that declares `payload:` can carry such a field and set it, as `assigned` does for `holder` |
| `authority: bridge` | only a bridge may set it. Anyone else gets `rejected:authority_bridge` |
| `redactable: true` | a `redacted` event may blank it |
| `profile` | `stream` `reviewed` `collab` `blob` `presence` `private`. Linted, no effect in v0 |

## Verbs

```yaml
verbs:
  <name>: { kind, weight, who, …effects and conditions… }
```

### Every verb has

| Key | Values |
|---|---|
| `kind` | `fact` `transfer` `handshake` `response` `attestation` `proposal` `redaction`, below |
| `weight` | `routine` `commitment` `protected`. What an agent may do: routine at once; commitment waits for its person to ratify; protected never |
| `who` | one expression, a list (any may match), or `per_field` (each payload field checked against `rights:`) |
| `entity` | which entity type, when the contract has several |

### Kinds

| Kind | What it is | Example |
|---|---|---|
| `fact` | something that happened. Applies its effects | `created`, `edited`, `commented` |
| `transfer` | changes who holds something | `claimed`, `released` |
| `handshake` | opens an agreement that completes when enough `parties` respond | `offered`, `review_requested` |
| `response` | answers a handshake or an attestation. Names it in `responds_to` | `approved`, `confirmed`, built-in `accept` |
| `attestation` | a claim about someone else's thing, held in the `claim` layer until its holder confirms | `decision@0.inferred` |
| `proposal`, `redaction` | reserved / built-in `redacted` |

### Effects

| Key | Does |
|---|---|
| `sets: { $payload }` | merge the payload into the entity |
| `sets: { field: literal }` | `state: open`, `holder: null` |
| `sets: { field: $expr }` | `holder: $person`, `state: $payload.to` |
| `adds: field` / `removes: field` | add / remove the payload's `item` (or the whole payload) in a set |
| `appends: field` | append to a log |
| `creates: entity` | make a child entity (`mandate@0.delegated`) |
| `cascades: children` | apply to children too (`revoked`) |

A `fact` with a `payload:` and no effect sets its payload. A verb can make a
new entity, sent with no `entity`, when it sets `$payload` or is a
handshake or an attestation.

`sets: { $payload }` merges every key the payload has, known or not, so a
typo (`titel`) on `created` is stored silently. Unknown keys are only refused
on `who: per_field` verbs, where nothing grants a right to them. When a verb
declares `payload:`, only that shape is checked, not the entity's field types.

### Conditions

| Key | Rejects with | Meaning |
|---|---|---|
| `when: <expr>` | `precondition` | must hold first, e.g. `holder == null` |
| `requires: <expr>` or a list of `{ check, reason }` | the `reason`; else `illegal_transition` for `transition_allowed`, `not_attenuating` for `attenuates`, `precondition` for the rest | must hold |
| `requires_party: human` | `requires_human` | no agent, whatever its weight |
| `payload: { to!: person, reason: string }` | `invalid_payload` | the payload's shape. `!` = required. Field types, or `state` for the entity's state enum |
| `budget_per_subject: { max: 8, per: at_sha }` | `budget_exceeded` | at most N per subject per value of a field |
| `concurrent: lowest_hash_wins` | `fork` | two concurrent uses: the lower event hash wins |
| `audience: grouping` | n/a | who sees it. Must be `grouping` until seed:861 |

### Handshake keys

| Key | Meaning |
|---|---|
| `parties` | who must respond: `$payload.to`, `$entity.reviewers` |
| `quorum` | `1` (default), `all`, or an expression such as `$entity.quorum` |
| `party_rule` | which responses count, e.g. `human and not party_to($entity.holder)` |
| `binds_to: head_sha` | a change to that field reopens a met handshake |
| `on_open`, `on_complete`, `on_reset` | effects when it opens, completes, and is reopened by `binds_to` |
| `auto_complete_if` | completes with no responses when true |

Responses: `accept` and `reject` from a party, `withdraw` from the proposer,
or a contract's own `kind: response` verbs with `responds_to: <handshake verb>`.
`counts: reject` makes a response count against quorum (`changes_requested`).
A handshake also lapses when its precondition stops holding: an offer lapses
if the offerer releases the item.

### Built-in verbs

Every contract has `accept`, `reject`, `withdraw` and `redacted`. Don't define
them. `redacted` takes `{event, field, reason}`, where `reason` is `secret`,
`personal` or `mistake`, and works only on a field marked `redactable: true`.

## Expressions

Used in `who`, `rights`, `when`, `requires`, `party_rule`, `parties`,
`quorum` and `sets`. Deliberately tiny: no loops, no functions of your own.

| Form | Meaning |
|---|---|
| `member`, `holder`, `creator`, `bridge`, `human`, `agent`, `party`, `guardian` | actor tests, where a truth value is wanted |
| `role:lead` | the actor holds the role |
| `party_to(x)` | the actor is person `x` or one of their agents |
| `transition_allowed` | the target state (`$payload.to`, else the literal `state` the verb sets, else the verb's own name) is reachable from the current one in `states:` |
| `attenuates($entity)` | the payload only narrows the mandate |
| `holder == null`, `state == approved` | inside a comparison a bare name reads the entity's field, or else is an enum symbol |
| `$payload.x`, `$entity.x`, `$person`, `$proposal.person`, `$on_behalf_or_person` | variables. `$actor` is an object, `{id, person}` |
| `person`, `proposer`, `actor`, `clock` (or `clock()`) | bare values: the acting person, a handshake's proposer, the actor, the relay time of the event. Use `clock`, not `$clock`, which reads a field named `clock` |
| `'sam'`, `3` | string and number literals |
| `$subject.holder`, `$week.state` | `$<field>` reads a field of this entity; if it's a ref, `.x` reads the entity it points at |
| `==` `!=` `<` `>` `<=` `>=` `contains` | comparisons. `$entity.eaters contains $person` |
| `and` `or` `not`, `( )` | logic |
| `a + b` | set union: `$subject.holder + $subject.reviewers` |
| `.count` | size of a set |

## The rights check, in order

Every event goes through these steps (`fold.rs`, lines 464 to 684). The
first failure decides the outcome.

0. **Basics**, before any rights: the rules it names exist and aren't stale
   (`unknown_rules`, `stale_rules`); the contract and verb exist; the
   envelope's `kind` is the verb's; the actor matches its person and only a
   bridge sets `on_behalf`; the person is a member and on the bus; the
   target exists and fits (`unknown_entity`, `cannot_create`,
   `wrong_contract`, `unknown_target`…); the payload's shape
   (`invalid_payload`, `managed_field`).
1. **Bridge.** It's in `grouping.yaml`, has this contract and the entity's
   `repo`, and the verb's `who` names `bridge`. `on_behalf` only on facts and
   responses.
2. **Mandate**, for agents. A grant covers this verb (`no_mandate`), its
   `when` holds (`grant_condition`).
3. **Budget**, for agents.
4. **Floor.** A protected verb, or `requires_party: human`, by an agent, or
   by a bridge not mirroring a human approval, is `requires_human`.
5. **Authority.** `authority: bridge` fields only from a bridge.
6. **Contract right.** `who`, or `rights:` per field. A person who fails
   becomes a `suggestion` to the first person who has the right, the holder
   first.
7. **Preconditions.** `when`, `requires`, and the handshake still open.
8. **Outcome.** An agent's commitment is `pending` until ratified. Otherwise
   the effects apply.

Rejections are listed in [outcomes.md](outcomes.md).

## Tests

A contract's `tests:` table is event scripts plus expectations:

```yaml
tests:
  - name: Offer, then accept; the holder changes only on accept
    events:
      - { id: c, by: sam, verb: created, payload: { title: Fix login } }
      - { id: k, by: sam, verb: claimed, entity: c }
      - { id: o, by: sam, verb: offered, entity: c, payload: { to: tom } }
      - { id: a, by: tom, verb: accept, responds_to: o }
    expect:
      - { after: o, entity: c, state: { holder: sam }, outcomes: { o: pending } }
      - { entity: c, state: { holder: tom }, handshakes: { o: met } }
```

- `id` names the event so later ones can refer to it: `entity: c`,
  `responds_to: o`, or `"@c"` inside a payload.
- `by` is the actor. Each is signed with a test key and chained into its
  own feed. `contract:` on an event uses another contract (a `mandate@0`
  grant before an agent acts).
- `seen` defaults to every earlier event. List them to make two events
  concurrent: `seen: [c]` on both claims.
- `on_behalf: priya` for a bridge's event. `at: 25h` moves the relay clock.
- `expect` checks `state`, `outcomes` (`rejected` matches any reason,
  `rejected:no_mandate` exactly), `handshakes` (`open` `met` `lapsed`
  `withdrawn`), `counts`, `suggested_to`, `visible_to`, `layer` and `purged`.
  `after: <id>` checks the state at that point.

Every test also folds in 12 shuffled orders and must reach the same state.

### Running them without this repo

The tests name fixture people (`tom`, `sam`, `alex`, off-bus `priya`) and
fixture bridges, so they fold against a fixture grouping rather than the
team's. Save this as `fixtures/grouping.yaml` next to your contracts. It's
`contracts/fixtures/grouping.yaml` in this repo:

```yaml
grouping: conformance
steward: tom
relay: wss://relay.conformance.invalid
members:
  - { person: tom, roles: [lead] }
  - { person: sam }
  - { person: alex }
  - { person: priya, on_bus: false }
bridges:
  - actor: system:gitlab-bridge
    mirrors: gitlab.example.invalid
    repos: [platform, web]
    contracts: [change-set@0, decision@0]
  - actor: system:asana-bridge
    mirrors: app.asana.com
    repos: [tooling]
    contracts: [work-item@1]
contracts: [mandate@0, work-item@1, change-set@0, decision@0]   # plus yours
```

```sh
gromit contract lint my-contracts/*.yaml
gromit contract test --dir my-contracts --grouping fixtures/grouping.yaml   # every contract
gromit contract test thing@0 --dir my-contracts --grouping fixtures/grouping.yaml
```

Without `--grouping`, the test uses a `grouping.yaml` next to the contracts.
In a governance clone that is the team's, whose members aren't the
fixtures, so most tests fail with `unknown_bridge` or `not_member`. A test
that uses another contract (`mandate@0`'s red-list test) needs that contract
in `--dir` too.

## Changing a contract the team uses

1. Copy the governance repo's contract, change it, bump `version`, and add a
   test for the new behaviour. Lint and test it as above.
2. Additive (new optional field, new verb, wider `who`): bump the minor and
   keep the file name. Old events fold the same.
3. Breaking (removed field, narrower `who`, new required field): a new major,
   a new file `thing@1.yaml`, both listed in `contracts:` while tools move.
4. Commit it to the governance repo's `main` and ask for approvals
   (`contracts/**` needs the steward and a majority). Sidecars and the relay
   switch to it within about 15 seconds of the last approval.
5. Adding a contract is the same: a new file under `contracts/`. Every
   contract file in the active commit is in force. `grouping.yaml`'s
   `contracts:` list only names what the default agent mandate covers.
   Editing it touches a path no governance rule names, so it needs
   everyone's approval: make it a separate commit if you want it.
6. A new major doesn't move anything. Entities created under `thing@0` only
   take `thing@0` events (`wrong_contract` otherwise), so the tools that
   publish them need a plan to switch: keep both files in force, create new
   entities under the new major, and finish old ones under the old.
