# CAIN Governance Contract — specification `cain.contract.v1`

Status: **TESTED + REPRODUCIBLE** in this repository (2026-10-04). It is not deployed: no gateway route mounts it yet.

## 1. Purpose

A governance contract is one signed, versioned object. It binds who may do what, under which authority, policy, risk
limit, execution path and evidence policy, for which resource and time window, and under which conditions. It covers
four products:

| Product | Kind(s) | Resource form |
|---|---|---|
| OpenShell | `exec` | a normalized absolute directory; the request `cwd` must be inside it |
| MemVault | `memory_write`, `memory_read` | `memvault/ns/<namespace>` |
| SCITT | `evidence_register` | `scitt/<payload_type>` |
| RIG | the authority source, not a kind | — |

**A contract never creates authority.** `capability.action` is `<product>.<kind>`. At AUTHORIZE and at every
invocation, every agent in the subject's RIG delegation chain must be ACTIVE. Each one must also grant that action and
have a scope that covers the resource.

## 2. Body: 14 sections, exact keys, no extras

| Section | Keys |
|---|---|
| `header` | `schema`=`cain.contract.v1`, `contract_id` (`ctr_`+32 hex), `lineage_id` (`lin_`+32 hex), `version` (≥1), `supersedes` (`""` for v1, otherwise the predecessor fingerprint), `tenant` |
| `subject` | `agent_id`, `spiffe_id`, `public_key_b64` (raw Ed25519), `runtime_digest` |
| `purpose` | `statement` (WHY) |
| `capability` | `action`, `resource` (concrete, no `*`), `max_uses` (1..1000), `audience` |
| `authority` | `source`=`rig`, `agent_chain` (root..subject), `grant_digest` |
| `policy` | `product`, `policy_id`, `policy_digest` (the product policy at draft time), `rules` |
| `risk` | `risk_class` (low/medium/high/critical), `max_risk_score` (0..100) |
| `action` | `kind`, `request_hash` (`""` = any request that meets the conditions, otherwise one pinned request) |
| `execution_path` | `product`, `engine`, `adapter_version`=`1` |
| `environment` | `environment_digest`, `model_runtime_digest` (must equal `subject.runtime_digest`) |
| `evidence_policy` | `scitt_required`, `payload_type`, `record_outputs` (digest/none) |
| `conditions` | list of `{op, arg}` from a closed operator set (§5) |
| `validity` | `issued_at_ms`, `not_before_ms`, `expires_at_ms` (window 1 s..24 h), `epoch` |
| `annotations` | free object ≤ 4 KiB; the only non-material section |

## 3. Canonical form CJ1 and fingerprint

* JSON values are restricted to objects, arrays, strings, integers with |n| < 2^53, booleans and null. **No floats.**
* Keys must match `[a-z0-9_]{1,64}`. Strings must be NFC and contain no NUL. Keys are sorted, separators are compact, and the encoding is UTF-8.
* On parse, duplicate keys, floats and NaN are rejected. The input bytes must equal their own canonical encoding, so two different byte strings can never be accepted as one contract.
* `section_digest(name) = SHA-256("CAIN/contract/v1/section" ‖ 0x1F ‖ name ‖ 0x1F ‖ CJ1(section))`
* `fingerprint = SHA-256("CAIN/contract/v1/fingerprint" ‖ 0x1F ‖ CJ1({name: section_digest}))`

## 4. Lifecycle

```
DRAFT → PROPOSED → VALIDATED → AUTHORIZED → ACTIVE → CONSUMED | EXPIRED | REVOKED | SUPERSEDED
```

| Step | What happens |
|---|---|
| propose | Freezes the bytes. Lineage rules: v1 starts a lineage. vN must have version = head + 1 and supersedes = the head fingerprint. `(lineage, version)`, the id and the fingerprint are each unique. |
| validate | Runs the structural, semantic and risk checks. A failure moves the contract to REVOKED, so an id can never be retried. |
| authorize | The RIG chain must cover the contract. `grant_digest`, `policy_digest` and `environment_digest` must still match. The issuer signs `fp ‖ authority_digest`. |
| activate | The subject signs the fingerprint (consent). A successor whose diff from the ACTIVE predecessor is **non-material only** may carry the predecessor's consent forward (`consent_mode=carried`). Activating a successor supersedes the predecessor atomically. A REVOKED or EXPIRED predecessor blocks activation (no resurrection). |
| invoke | See §6. |
| revoke | Produces a signed revocation statement. |
| expire | Lazy: the next operation commits EXPIRED and refuses. |

Terminal states have no outgoing transitions. Every transition is compare-and-set under `BEGIN IMMEDIATE` and is appended to an HMAC'd hash chain.

## 5. Conditions (closed set; an unknown operator makes the contract invalid)

| Operator | Kinds | Argument |
|---|---|---|
| `argv0_in` | exec | list of bare command names |
| `max_argc`, `max_timeout_s` | exec | positive integer |
| `cwd_under` | exec | absolute paths |
| `namespace_in` | memory_write, memory_read | list |
| `source_type_in` | memory_write | subset of user/tool/document/web/agent/system |
| `min_trust` | memory_read | low/medium/high |
| `max_content_bytes` | memory_write, evidence_register | positive integer |
| `max_top_k` | memory_read | positive integer |
| `payload_type_in` | evidence_register | list |
| `utc_hour_window` | all | `[start, end)` hours |

## 6. Decision function (pure; the check order is normative)

The checks run in this order. The first that fails decides the reason code:

1. Tenant matches → state is ACTIVE → not_before ≤ t < expires_at → uses < max_uses
   (reasons `TENANT_MISMATCH`, `STATE_*`, `NOT_YET_VALID`, `EXPIRED`, `USES_EXHAUSTED`)
2. RIG snapshot is complete, its chain equals `authority.agent_chain`, and every member is ACTIVE
   (`AUTHORITY_*`). The subject key must match (`IDENTITY_SUBSTITUTION`) and so must the runtime digest
   (`MODEL_SUBSTITUTION`). Every ancestor must grant the action and cover the resource (`AUTHORITY_AMPLIFICATION`).
3. The presented runtime digest, the current environment digest and the current product policy digest must equal
   the contract's (`MODEL_SUBSTITUTION`, `ENVIRONMENT_DRIFT`, `POLICY_DRIFT`).
4. The request shape for the kind is valid (`MALFORMED_REQUEST`). If the contract pins a request, its hash must
   match (`REQUEST_NOT_PINNED`).
5. Invocation proof-of-possession:
   * `{nonce, ts_ms, request_hash, signature_b64}` must be present (`POP_MISSING`)
   * its request_hash must match (`POP_REQUEST_MISMATCH`)
   * |t − ts| ≤ 60 s (`POP_STALE`)
   * the nonce is 32 hex characters (`POP_MALFORMED`)
   * the Ed25519 signature by the subject key verifies (`POP_INVALID`)
   * the nonce has not been used before (`POP_REPLAY`)
6. The request lies inside the contract resource (`RESOURCE_OUTSIDE_CONTRACT`), and every compiled condition holds
   (`CONDITION_<OP>`).
7. If everything passes, the result is `ALLOW`.

Risk score (0..100):

* base by kind: exec 40, memory_write 25, memory_read 10, evidence_register 5
* +20 if the request is not pinned
* +min(max_uses, 10)
* +10 if the window is longer than 15 min
* +10 if there are no conditions
* +10 if SCITT evidence is not required

The score maps to a class: ≥75 critical, ≥50 high, ≥25 medium, otherwise low.

The declared class may never be below the computed class. *high* needs a pinned request or at least one condition.
*critical* needs a pinned request, max_uses = 1 and a window of at most 300 s.

## 7. Receipts and replay

* **Decision receipt**: written in the same transaction as the decision, the spent use and the nonce. It carries
  `decision, reason, decided_at_ms, state_before, uses_before, request_hash, authority_snapshot_digest,
  environment_digest, policy_digest, runtime_digest, nonce_used, prev_receipt_hash`. It is hash-chained and signed.
* **Outcome receipt**: written after the product runs, only for ALLOW. It carries `decision_receipt_hash`,
  `product_result_digest` and `execution_failed`.
* **Replay record**: stored privately next to each decision receipt. It holds the full recorded inputs and the list of
  nondeterministic inputs: the clock (recorded), random ids, and product execution (recorded only as a digest).
  `replay_record()` and the clean-room `decision()` must reproduce the recorded decision and reason exactly.

## 8. Diff classes (deterministic, path-level, maximum class wins)

| Class | Paths |
|---|---|
| AUTHORITY-MATERIAL | `subject.*`, `authority.*`, `capability.action/resource/audience`, `header.tenant` |
| SECURITY-MATERIAL | `policy.*`, `risk.*`, `environment.*`, `evidence_policy.*` |
| EXECUTION-MATERIAL | `execution_path.*`, `action.*`, `conditions` (compared in compiled form, so reordering is not a change) |
| MATERIAL | validity window, `max_uses`, `purpose`, `header.schema/lineage_id` |
| NON-MATERIAL | `annotations.*` |
| Lineage bookkeeping (reported, never material) | `contract_id`, `version`, `supersedes`, `issued_at_ms`, `epoch` |

Any change other than NON-MATERIAL requires fresh subject consent.
