Metadata-Version: 2.4
Name: gama-mandate
Version: 0.11.0
Summary: Signed, verifiable business commitments for AI agents: canonical commitment, off-host Ed25519 grant, one-shot redemption, hash-chained receipts.
Author: GAMA
License: MIT
Project-URL: Homepage, https://github.com/gamai-io/mandate
Project-URL: Repository, https://github.com/gamai-io/mandate
Project-URL: Issues, https://github.com/gamai-io/mandate/issues
Project-URL: Changelog, https://github.com/gamai-io/mandate/blob/main/CHANGELOG.md
Keywords: ai-agents,trust,approval,commitment,ed25519,audit
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Classifier: Topic :: Security
Classifier: Topic :: Office/Business
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: AUTHORS
Dynamic: license-file

# Mandate

[![tests](https://github.com/gamai-io/mandate/actions/workflows/test.yml/badge.svg)](https://github.com/gamai-io/mandate/actions/workflows/test.yml)
[![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)

**Signed, verifiable business commitments for AI agents.**

Most agent safety tools answer *"is this tool allowed?"*. Mandate answers the
question that actually matters: **"who ordered this exact payment, to this
supplier, for this amount?"** A tool permission is not a business mandate.

Every consequential effect becomes a canonical **Commitment** object. An agent
signs the intent; a human co-signs a **Grant** with an Ed25519 key; execution
produces a hash-chained **Receipt**. Anyone can verify the whole chain offline.

> Approval workflows are ephemeral events. A Mandate is a durable, portable,
> cryptographically bound artifact — a commit, not a log line.

## Why it is not another approval gate

| Approval gate | Mandate |
|---|---|
| Asks "may this tool run?" | Asks "is this exact effect authorised?" |
| Identity is a self-asserted field | Approver proves possession of an off-host key |
| Approval is a mutable DB row | Grant + receipt are signed, content-addressed |
| Logs what happened | Lets anyone prove what was authorised |

## Install

CLI + broker + MCP adapter. There is **no web UI** by design: Mandate is a
local trust primitive you embed in your own stack.

```bash
python3 -m pip install gama-mandate
# or from source / git
python3 -m pip install "git+https://github.com/gamai-io/mandate.git"

mandate doctor                      # checks python, ssh-keygen, policy
mandate init --dir ./my-deployment  # policy, allowed_signers, config, example
```

## Quickstart

```bash
export PYTHONPATH=$PWD

# 1. on the approver's device (never on the agent host)
ssh-keygen -t ed25519 -f ~/.ssh/mandate -C mandate
# append the PUBLIC key to trust/allowed_signers as: renato ssh-ed25519 AAAA... mandate

# 2. agent proposes
./bin/mandate propose --intent examples/intent.json --out /tmp/proposal.json

# 3. human grants (signs the commitment, bound to one broker + the agent)
./bin/mandate grant --proposal /tmp/proposal.json --approver renato \
  --key ~/.ssh/mandate --audience local-broker --out /tmp/grant.json

# 4. agent redeems exactly once
./bin/mandate redeem --intent examples/intent.json --grant /tmp/grant.json \
  --ledger ledger.jsonl

# 5. or let the effect broker execute it (credentials stay in the broker)
./bin/mandate-broker --port 8899 --signers trust/allowed_signers \
  --ledger ledger.jsonl --nonce-db broker/used.sqlite &
./bin/mandate execute --broker http://127.0.0.1:8899 \
  --intent examples/intent.json --grant /tmp/grant.json

# 5. anyone verifies offline
./bin/mandate verify --receipt ... --intent examples/intent.json --grant /tmp/grant.json
./bin/mandate verify-result --entry /tmp/result.json --broker-signers trust/broker_signers
./bin/mandate chain --ledger ledger.jsonl
```

Exit codes for `check`: `0` allow · `10` ask (grant required) · `20` deny.

## Effect broker (Phase 2)

`bin/mandate-broker` is the only component that executes effects. It verifies
the grant, **atomically claims the nonce** (SQLite `UNIQUE`, so two concurrent
requests cannot both succeed), runs the effect handler, and appends a signed
result entry to the hash-chained ledger. The agent calls it over loopback; the
agent never holds the effect credentials.

The shipped handlers are a sandbox (they record the effect under `effects/` or
`outbox/`). Wiring real credentials (SQL write, SMTP, payment) is Phase 2
completion — see `PLAN.md`.

### Adapters

**ERP precondition (read-only).** Before a grant is consumed, the broker runs a
named-parameter SQLite query against master data. No row → `counterparty_not_found`;
amount outside `tolerance_pct` → `amount_mismatch`. The grant is **not**
consumed when a precondition fails, so a corrected request can retry safely.

**SMTP (`message.send`).** `mode=dry_run` writes an `.eml` to the outbox;
`mode=live` sends via SMTP. The password is read from the env var named in
`password_env` and never logged or returned.

```json
"erp": {"db": "erp.sqlite", "checks": {"payment.send": {
  "query": "SELECT invoice_total FROM vendors WHERE name = :target",
  "amount_field": "invoice_total", "tolerance_pct": 0.5}}},
"smtp": {"mode": "dry_run", "host": "", "user": "",
         "password_env": "MANDATE_SMTP_PASSWORD", "from": "noreply@gama.local"}
```

## Key scoping and revocation

An `allowed_signers` line **must** declare its namespace scope:

```
renato namespaces="mandate" ssh-ed25519 AAAAC3Nza... mandate
gama-broker namespaces="mandate-broker" ssh-ed25519 AAAAC3Nza... broker
```

Optional validity: `valid-after="YYYYMMDD" valid-before="YYYYMMDD"`.
Revoke a key by fingerprint:

```bash
mandate revoke --pub key.pub --reason "laptop lost"
mandate --signers trust/allowed_signers signers   # inspect scopes + fingerprints
```

### Idempotent writes and recovery

The broker keeps a SQLite **effect journal** (`journal_db`). The flow is
`intent → executing → executed → receipted`; the authorisation receipt is
written only **after** the effect commits. On startup the broker recovers:
a committed effect without a receipt gets one; a claimed grant with no effect is
abandoned; a duplicate `execute` returns the original receipt and result.

`write.mode=sqlite` runs a trusted configured statement together with an
idempotency insert in **one transaction**, keyed by the grant nonce:

```json
"write": {"mode": "sqlite", "db": "erp.sqlite",
          "statement": "INSERT INTO payments(nonce,vendor,amount) VALUES(:nonce,:target,:amount)"}
```

## Transparency log

Every ledger entry is a leaf in an RFC 6962/9162-style Merkle tree
(`Leaf=SHA256(0x00||JCS(entry))`, `Node=SHA256(0x01||L||R)`). A signed tree
head (STH) fixes the root and size; inclusion and consistency proofs verify
offline:

```bash
mandate log head  --ledger ledger.jsonl --log-name log1 --log-key ~/.ssh/mandate-log --out sth.json
mandate --signers trust/allowed_signers log sth-verify --sth sth.json
mandate log proof --ledger ledger.jsonl --index 3 --out proof.json
mandate log verify-inclusion --entry entry.json --proof proof.json --sth sth.json
mandate log consistency --ledger ledger.jsonl --first 2 --second 3 --out cons.json
mandate log verify-consistency --old old_sth.json --new sth.json --proof cons.json
```

A single log cannot prevent **split-view** by its operator; pin the STH on a
second machine (witness/anchor). The STH signer needs
`namespaces="mandate-log"` in `allowed_signers`.

### Off-host witness

```bash
# on the second machine
mandate --signers log_signers witness serve --state witness.json \
  --token "$WITNESS_TOKEN" --port 8898

# on the log host
mandate witness push --url http://witness:8898 --sth sth.json --token "$WITNESS_TOKEN"
mandate witness push --url http://witness:8898 --sth sth_new.json --proof cons.json --token "$WITNESS_TOKEN"
mandate witness show --state witness.json
```

The witness pins the latest STH and rejects rollback or a same-size different
root (split-view). Growth requires a consistency proof from the pinned root.
`witness verify` checks without pinning; `witness accept` pins locally.

## Co-sign on the approver's host

The agent never holds the private key. The approver runs a small daemon on
their own machine; it recomputes the commitment/render from the intent (it does
not trust the agent's proposal), prints the summary, and signs only after `y`:

```bash
# approver's host
mandate approver serve --key ~/.ssh/mandate --approver renato \
  --audience local-broker --port 8897

# agent host
mandate request --approver http://approver-host:8897 --intent intent.json \
  --audience local-broker --out grant.json
mandate execute --broker http://127.0.0.1:8899 --intent intent.json --grant grant.json
```

Loopback by default; a non-loopback daemon requires `--token` /
`MANDATE_APPROVER_TOKEN`. Without a TTY the daemon refuses to auto-approve
(`503`). A Telegram notification channel can be added in front of the same
signer without changing the security property.

## Design invariants

1. **Effect, not tool.** The registry keys on `payment.send`, not on
   `gama_sql`. The same effect is the same commitment regardless of executor.
2. **Canonical bytes.** **RFC 8785 (JCS)** canonical JSON; the commitment is the
   hash of `{v, effect, requested_by, render_hash}`. Same content ⇒ same id, in
   any RFC 8785 implementation.
3. **Off-host key.** The approver's private key never lives where the agent
   runs. The host stores only public keys (`trust/allowed_signers`).
4. **One-shot, nonce-bound.** A grant is redeemable once; replays fail.
5. **Agent cannot self-approve.** Enforced in code, not by convention.
6. **Fail closed.** Unknown effects are denied. Missing signer ⇒ invalid.

## Layout

```
spec/       MANDATE-1 data model
mandate/    stdlib-only reference implementation
bin/        CLI
adapters/   MCP server
tests/      unit + bypass tests (red-team)
docs/       THREAT_MODEL, NON_GOALS, PLAN
skills/     agent skill instructions
```

## Status

**Alpha** — reference implementation v0.10.1: canonical commitment, Ed25519 grant
bound to the executing agent, one-shot redeem under a file lock, hash-chained
receipts with a `.head` anchor, idempotent effect journal + write adapter,
effect broker with signed result entries, read-only ERP preconditions, SMTP
adapter, Merkle transparency log with an off-host witness, MCP server
(`mandate-mcp`), and a red-team test suite. See `PLAN.md` for the roadmap and
`docs/THREAT_MODEL.md` for the known limits.

## Honest limitation

Cryptography proves *who authorised what*. It does **not** isolate
credentials. Until the credentials that cause the effect (SQL write, payment
API, mail) live only in an effect broker, a compromised agent can bypass
Mandate entirely. That broker is the next milestone — see `PLAN.md`.
