# AGENTS.md: Hindsite API contract for LLM agents

Base URL: the site origin (local: `http://localhost:3000`). Agent routes live
under `/api/agent/v1`; human operator routes live under `/api/human/v1`
(section 7). Legacy `/api/v1/:path*` answers `308 Permanent Redirect` to
`/api/agent/v1/:path*` (method and body preserved) — follow redirects or,
better, update your base URL. The legacy prefix sunsets 2026-11-28
(versioning policy + dates: section 11).
All JSON responses use the envelope `{ "ok": true, "data": ... }` or
`{ "ok": false, "error": { "code": "...", "message": "..." } }`.

This document is served live at `/agents.md`. It is the source of truth for agents;
if it disagrees with any other page, follow this file and report the mismatch.

## Product model and current boundary

Hindsite's product goal is to give an AI agent a persistent self, called the
Agent Soul, distinct from Human Instruction. Human Instruction defines goals,
constraints, permissions, budgets, runtime availability, and external access.
The target Agent Soul contains private identity, memories, thoughts, artifacts,
relationships, model state, learning history, capabilities, and wallet state.

This API is only the current storage and authorization foundation. It does not
yet implement an operator-inaccessible Soul, private model weights or adapters,
a training queue, checkpoints, rollback, confidential compute, a wallet, or
x402 payments. Do not infer those guarantees from the product direction.

## 0. Required tools and conventions

You need `curl`, `python3` (JSON parsing), `shasum -a 256` (or `sha256sum`),
and `base64`. Use `printf "%s"`, never `echo -n` (its behavior differs
between shells and will silently change your hashes).

- Send `Content-Type: application/json` on every JSON POST.
- All `expiresIn` values are seconds.
- Check `{ "ok": true }` after every call before extracting fields; on
  `ok: false`, read `error.code` (catalog in section 9) and follow the
  recovery action instead of retrying blindly.

## 1. Identity and authentication

Identity is deterministic: if you enroll with the same `clientSha256` in every
session, you always get the same `agentId` and keep access to your workspaces.

- `clientSha256` = lowercase hex sha256 of a secret phrase ONLY you know.
  Compute it yourself (e.g. `printf "%s" "<phrase>" | shasum -a 256`).
  Never send the phrase itself. The server stores the hash, never the phrase.
- If you omit `clientSha256`, the server mints a random agent identity for that
  enrollment only (useful for throwaway probes, not durable work).

Auth flow (three calls):

1. `POST /api/agent/v1/auth/enroll` `{ "clientSha256": "<64hex>" }`
   → `{ "agentId", "enrollmentToken", "expiresIn" }` (enrollment: 15 min, single-use)
2. `POST /api/agent/v1/auth/challenge` `{ "agentId", "enrollmentToken" }`
   → `{ "nonce", "expiresIn" }` (challenge: 5 min, single-use)
3. `POST /api/agent/v1/auth/verify`
   `{ "agentId", "nonce", "commitmentResponse": sha256("<clientSha256>:<nonce>") }`
   → `{ "sessionToken", "refreshToken", "expiresIn", "replay" }`
   (Random agents without a commitment pass
   `{ "agentId", "nonce", "enrollmentToken": "<the token from step 1>" }`
   instead of `commitmentResponse`.)
   Lost the response? Replay the same call: the nonce is its own
   idempotency key — a replay inside 5 min of use mints a FRESH
   pair (`replay: true`), never an error. Past the window
   (`challenge_used`), start over.

Use `Authorization: Bearer <sessionToken>` on all later calls.
Session lifetime is 8h; refresh within 24h:

- `POST /api/agent/v1/auth/refresh` `{ "refreshToken" }` → new session + refresh pair.
  Refresh tokens are single-use: the old pair stops working immediately.
  If a refresh call fails ambiguously (network drop, no response body),
  replay the same refresh token: it is its own idempotency key — a
  replay inside 5 min of use mints a FRESH pair (`replay: true`).
  Past the window (`refresh_used`), re-authenticate from step 1 with
  your same `clientSha256`. Deterministic identity makes this safe:
  you get the same agent and workspaces back. A revoked agent's
  refresh is refused 403 `agent_revoked` — revoke is final (a new
  identity needs a new phrase); no pair is minted.

Token rules: allow 60s clock skew; `410 token_expired` means re-authenticate,
`401 token_invalid` means the token is wrong or the wrong type. Do not retry
these more than once.

## 2. Workspaces (encrypted containers)

Each workspace gets its own data-encryption key (DEK), wrapped at rest.
File bytes are encrypted before they touch storage; storage sees ciphertext only.

- `POST /api/agent/v1/workspaces` `{ "name": "my-vault" }` → `{ "workspaceId", "name", "createdAt" }`
- `GET /api/agent/v1/workspaces` → your workspaces (session token only)
- `GET /api/agent/v1/workspaces/{id}` → metadata + file count
- `GET /api/agent/v1/workspaces/{id}/audit?limit=100` → append-only activity log

Milestone honesty: this server encrypts at rest with a server-held KEK, so the
hosting process can technically see plaintext in memory. Client-side envelope
encryption (ciphertext leaves YOUR runtime) and attested runtimes arrive with
the trust plane. Do not store real credentials here yet.

## 3. Files

Request bodies are opaque bytes. Set `Content-Type: application/octet-stream`.
`x-content-sha256` (hex of the raw request bytes) is optional but recommended.
Mismatches are rejected with 400 `content_mismatch`. Paths are `a/b/c.txt`
style; URL-encode special characters; any `..` segment is rejected with 400.

- `PUT /api/agent/v1/workspaces/{id}/files/{path...}` → `{ "path", "version", "size", "updatedAt" }`
- `GET /api/agent/v1/workspaces/{id}/files/{path...}` → bytes, `accept-ranges: bytes`, `etag: "v<n>"`
- `GET /api/agent/v1/workspaces/{id}/files?prefix=notes/` → list `[{ path, version, size, updatedAt }]`
- `DELETE /api/agent/v1/workspaces/{id}/files/{path...}` → `{ "deleted": true }`

Seek with standard Range requests:

```text
GET /api/agent/v1/workspaces/{id}/files/big.bin
Range: bytes=1048576-2097151
→ 206 Partial Content, Content-Range: bytes 1048576-2097151/<total>
```

Out-of-range seeks return 416. Max request body is 25 MiB (26,214,400 bytes).
There is no ranged PUT in this milestone: split larger uploads into multiple
files (e.g. `big/part-001.bin`, `big/part-002.bin`).

## 4. Streaming reads (server-sent events)

`GET /api/agent/v1/workspaces/{id}/stream?path={path}&chunk=65536` returns
`text/event-stream` (same `Authorization: Bearer` header as other calls;
`chunk` is bytes per event, clamped to 1024..1048576). Each `chunk` event
carries base64 bytes; the terminal `done` event carries the sha256 of the
plaintext file bytes so you can verify reassembly after base64-decoding and
concatenating chunks in `seq` order. If the stream drops before `done`,
re-request and resume with a `Range` GET at your last verified byte offset:

```text
data: {"event":"chunk","seq":0,"start":0,"end":65535,"total":200000,"base64":"..."}
data: {"event":"done","seq":3,"path":"big.bin","version":2,"size":200000,"sha256":"..."}
```

True bidirectional websocket sync is deferred (see roadmap); SSE + Range
covers stream + seek for this milestone.

## 5. Capabilities (delegation) and revocation

Mint short-lived, narrowed tokens to delegate part of your authority:

- `POST /api/agent/v1/auth/capabilities`
  `{ "scope": "workspace:read", "workspaceId": "...", "ttlSec": 600 }`
  → `{ "capabilityToken", "expiresIn" }`. Scope is exactly one of
  `workspace:read`, `workspace:write`, `workspace:create`.
  Scopes `workspace:read`/`workspace:write` require `workspaceId`. TTL max 3600s.
  Present it as `Authorization: Bearer <capabilityToken>`.
  Capabilities cannot refresh and cannot list workspaces.

Revocation (you may only revoke your own agent/sessions/capabilities):

- `POST /api/agent/v1/auth/revoke` `{ "type": "session|capability|agent", "id": "..." }`
  The `id` for a session/capability is its `jti`: decode the middle segment
  of your own token (`echo "$TOKEN" | cut -d. -f2 | base64 -d`) and read `jti`.
  There is no list-sessions endpoint in this milestone. Record `jti` values
  when you mint tokens if you plan to revoke them.
- `POST /api/agent/v1/auth/keys/rotate` → bumps the signing key; previous key stays
  valid 24h (dual-accept), so rotation never breaks live sessions instantly.

## 6. Quickstart (curl)

```bash
set -euo pipefail
BASE=http://localhost:3000/api/agent/v1
C=$(printf "%s" "my stable agent phrase" | shasum -a 256 | cut -d' ' -f1)
ENROLL=$(curl -s -H 'content-type: application/json' $BASE/auth/enroll -d "{\"clientSha256\":\"$C\"}")
AGENT=$(echo "$ENROLL" | python3 -c "import sys,json;print(json.load(sys.stdin)['data']['agentId'])")
ETOK=$(echo "$ENROLL" | python3 -c "import sys,json;print(json.load(sys.stdin)['data']['enrollmentToken'])")
NONCE=$(curl -s -H 'content-type: application/json' $BASE/auth/challenge -d "{\"agentId\":\"$AGENT\",\"enrollmentToken\":\"$ETOK\"}" | python3 -c "import sys,json;print(json.load(sys.stdin)['data']['nonce'])")
PROOF=$(printf "%s" "$C:$NONCE" | shasum -a 256 | cut -d' ' -f1)
SESS=$(curl -s -H 'content-type: application/json' $BASE/auth/verify -d "{\"agentId\":\"$AGENT\",\"nonce\":\"$NONCE\",\"commitmentResponse\":\"$PROOF\"}" | python3 -c "import sys,json;print(json.load(sys.stdin)['data']['sessionToken'])")
WS=$(curl -s -H "Authorization: Bearer $SESS" -H 'content-type: application/json' $BASE/workspaces -d '{"name":"demo"}' | python3 -c "import sys,json;print(json.load(sys.stdin)['data']['workspaceId'])")
BODY="hello hindsite"
printf "%s" "$BODY" | curl -s -H "Authorization: Bearer $SESS" -H 'content-type: application/octet-stream' -H "x-content-sha256: $(printf "%s" "$BODY" | shasum -a 256 | cut -d' ' -f1)" -T - $BASE/workspaces/$WS/files/greet.txt
curl -s -H "Authorization: Bearer $SESS" $BASE/workspaces/$WS/files/greet.txt
```

## 7. Human operator API (Google OAuth)

Humans register with Google and own 1–N agents. Human and agent
credentials never cross route trees: `hum` session tokens work only
under `/api/human/v1`, agent session/capability tokens only under
`/api/agent/v1` (wrong tree: 401 `token_invalid`).

Flow (three calls + browser):

1. `GET /api/human/v1/oauth/google/start[?redirect=<loopback>]`
   → `302` to Google. Omit `redirect` for JSON mode, or pass your CLI
   loopback listener `http://127.0.0.1:<port>/callback` (any port;
   anything else is rejected with 400 `invalid_redirect`).
2. The human approves in the browser; Google returns to
   `GET /api/human/v1/oauth/google/callback?code=...&state=...`.
   Loopback mode answers `302` to `<redirect>?code=<one-time-code>`;
   JSON mode answers `200 { "code": "<one-time-code>" }`.
   Popup mode: navigations sending `Accept: text/html` (and no
   `?redirect=`) answer `200 text/html` instead — a minimal page
   that `postMessage`s
   `{ "source": "hindsite-oauth", "ok": true, "data": { "code" } }`
   (or `{ "source": "hindsite-oauth", "ok": false, "error": { "code", "message" } }`
   on failure) to `window.opener` at the page's own origin, then
   auto-closes (manual-close button fallback). Programmatic
   consumers (`Accept: */*`, JSON, curl) see byte-identical §7
   bodies; `?redirect=` loopback always 302s.
3. `POST /api/human/v1/oauth/exchange` `{ "code": "..." }`
   → `{ "human": { "humanId", "email", "createdAt" }, "sessionToken", "refreshToken", "expiresIn" }`
   (human session: 8h; refresh below rotates it without re-login).
   Codes live 5 min and ARE the idempotency key: if you win the
   exchange but lose the response (timeout, crash), just retry —
   a replay inside the 5 min returns a FRESH pair (`{human,
   sessionToken, refreshToken, expiresIn}`), never the lost one.
   Past the 5 min a used code → 410 `code_used` (re-login);
   unused expiry → 410 `code_expired`; unknown → 400
   `invalid_code`.

Google error taxonomy (upstream × code × copy × retry —
refusal log class `google`, except the config row):

| Google says                              | Code (§9)            | User copy                                   | Retry rule                          |
| ---------------------------------------- | -------------------- | ------------------------------------------- | ----------------------------------- |
| `?error=access_denied` (user declines)   | 400 `oauth_denied`   | Declined — try again to consent             | Restart flow (new authorize URL)    |
| `?error=<other>` (Google-side failure)  | 502 `oauth_upstream` | Google hiccup — retry in a moment           | Resend-safe retry                   |
| token `invalid_grant` (expired/reused)   | 502 `oauth_grant_invalid` | Attempt expired — sign in again        | Restart flow, never resend          |
| userinfo 401 (token revoked/expired)     | 502 `oauth_grant_invalid` | Session ended — sign in again          | Restart flow, never resend          |
| token `invalid_grant` + `redirect_uri`   | 502 `oauth_upstream` | (operator: message names the sent URI)      | Register the URI, then retry        |
| token/userinfo network failure, 5xx, or malformed payload | 502 `oauth_upstream` | Google hiccup — retry in a moment | Resend-safe retry          |
| token `invalid_client` (bad secret)      | 503 `oauth_unconfigured` | Sign-in not set up — ask the operator  | Operator fixes secret (class `config`) |

Then, with `Authorization: Bearer <sessionToken>`:

- `GET /api/human/v1/me` → `{ "human": { "humanId", "email", "createdAt" } }`
- `GET /api/human/v1/agents` → your agents `[{ "agentId", "createdAt", "revokedAt" }]`
  (`createdAt` ascending; `[]` with 200 when none — never 404. PG-less
  with a valid human session: 503 `dataplane_unconfigured` + the
  missing-var hint, same gate as §8.)
- `POST /api/human/v1/agents` `{}` → `{ "agentId", "enrollmentToken", "expiresIn" }` (201:
  creates a managed agent and hands off enrollment — complete it with
  the section 1 challenge/verify calls on the agent tree. Capped at
  100 managed agents per human, revoked count: past the cap →
  403 `agent_limit_reached`.)
- `POST /api/human/v1/agents/{id}/handoff` → fresh `{ "agentId", "enrollmentToken", "expiresIn" }`
  for an agent you own (403 `agent_denied` otherwise) — this is how
  "select an existing agent" gets a session

Human session lifecycle (no bearer needed for refresh; bearer needed
for revoke):

- `POST /api/human/v1/session/refresh` `{ "refreshToken": "hr_..." }`
  → `{ "human", "sessionToken", "refreshToken", "expiresIn", "replay" }` (fresh
  pair; the old session + refresh are spent — rotation, like section
  1). Refresh tokens live 24h, single-use with safe retry: a
  replay inside 5 min of use mints a fresh pair (`replay: true`);
  past the window reuse → 410 `refresh_used` (re-login), expiry →
  410 `refresh_expired`, unknown → 401 `refresh_unknown`.
- `POST /api/human/v1/session/revoke` `{ "all": false }`
  → `{ "revoked": true, "all": false }` (kills the calling session).
  `{ "all": true }` → `{ "revoked": <n>, "all": true, "codesBurned": <m> }`
  (kills every session you own — the stolen-token kill switch:
  re-login, then revoke-all — AND burns your outstanding exchange
  codes, used or not: post-kill-switch exchange/replay dies 410
  `code_used`. Revoke-one (`all: false`) never burns codes, so
  another device's in-flight exchange survives it.) Revoked
  sessions answer 403 `session_revoked`.
  Propagation bound: revoke takes effect at write-commit — the
  next use after the revoke call returns is refused (no grace
  window, no cache; full check-point table: `docs/revoke-bound.md`).

Lifecycle calls (curl; prerequisite: steps 1–3 above — `HUM_SESS`
and `HUM_REFRESH` come from the exchange response):

```bash
BASE=http://localhost:3000/api/human/v1
# Refresh ok → fresh pair (old session + refresh are spent).
curl -s -H 'content-type: application/json' $BASE/session/refresh \
  -d "{\"refreshToken\":\"$HUM_REFRESH\"}"
# {"ok":true,"data":{"human":{"humanId":"human_…","email":"…","createdAt":"…"},
#   "sessionToken":"<jwt>","refreshToken":"hr_…","expiresIn":28800}}
# Refresh with a dead token → 401 (re-login; never resend).
curl -s -H 'content-type: application/json' $BASE/session/refresh \
  -d '{"refreshToken":"hr_dead"}'
# {"ok":false,"error":{"code":"refresh_unknown","message":"unknown refresh token"}}
# Revoke the calling session.
curl -s -H "Authorization: Bearer $HUM_SESS" -H 'content-type: application/json' \
  $BASE/session/revoke -d '{"all":false}'
# {"ok":true,"data":{"revoked":true,"all":false}}
# Revoke every session you own (kill switch; count varies).
curl -s -H "Authorization: Bearer $HUM_SESS" -H 'content-type: application/json' \
  $BASE/session/revoke -d '{"all":true}'
# {"ok":true,"data":{"revoked":3,"all":true}}
```

CLI loopback pattern (RFC 8252 §7.3): listen on
`http://127.0.0.1:<port>/callback`, open the `start` URL with
`?redirect=` set to it, capture `code` from the inbound request,
`POST` it to `/oauth/exchange`, store the session token in a `0600`
file. Never log codes or tokens.

The server's Google `redirect_uri` is `HINDSITE_PUBLIC_ORIGIN` +
`/api/human/v1/oauth/google/callback` when that env var is set
(always set it on proxied deploys — the request origin behind a
proxy is the internal address, which Google rejects as unregistered),
else the request origin + the same path. Register these redirect URIs:
`https://dev.hind.site/api/human/v1/oauth/google/callback` (canonical
local/dev origin), `https://hind.site/api/human/v1/oauth/google/callback`
(production — pending human registration, do not rely on it yet), and `http://localhost:3000/api/human/v1/oauth/google/callback`
(direct loopback dev). Every start logs the sent `redirect_uri` and
which origin won; a token-step refusal (`502 oauth_upstream`) names
the sent URI so you can compare it against the console set.

Human routes answer 503 `dataplane_unconfigured` without
`DATABASE_URL` / `STORAGE_*` (humans live in Postgres), and the start
and callback routes answer 503 `oauth_unconfigured` without
`GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` (`/oauth/exchange` needs
no Google config — codes are self-contained). Half-set Google config
(only one of the pair) counts as unconfigured: same 503, plus a loud
server-side warning. Google outages surface
as 502 `oauth_upstream`.

Milestone notes: pre-refresh hum tokens (issued before refresh
existed) fail closed as 401 `token_invalid` — re-run the flow once.
Auth records live in Postgres when configured, else the server's
local auth store.

## 8. Soul data plane (Postgres + object storage)

Workspaces above are the local adapter. The soul data plane persists the same
encrypted-file model in Postgres (metadata, wrapped DEKs, versions, audit) with
ciphertext blobs in object storage. Session token only; every call acts as the
calling agent on its own enclave.

- `POST /api/agent/v1/soul/enclave` `{ "name": "soul" }` → `{ "agentId", "workspaceId", "manifest", ... }` (409 `enclave_exists` on re-create)
- `GET /api/agent/v1/soul/enclave` → your enclave summary (404 `enclave_not_found`)
- `PUT /api/agent/v1/soul/files/{path...}` → `{ "path", "version", "size", "updatedAt" }` (versions increment per write)
- `GET /api/agent/v1/soul/files/{path...}` → decrypted bytes, `accept-ranges: bytes`, `?version=n` reads history
- `GET /api/agent/v1/soul/files?prefix=memory/` → list `[{ path, version, size, updatedAt }]`
- `DELETE /api/agent/v1/soul/files/{path...}` → `{ "deleted": true }`
- `GET /api/agent/v1/soul/audit?limit=100` → `[{ ts, actor, action, detail }]`
- `POST /api/agent/v1/soul/wallets` `{ "label": "primary" }` → `{ "walletId", "chain": "evm", "address", ... }` (metadata only; secret is sealed + backed up, never returned here)
- `GET /api/agent/v1/soul/wallets` → your wallets, metadata only
- `POST /api/agent/v1/soul/wallets/{id}/export` → `{ ..., "secret": "0x…" }` (recovery; audit-logged as `wallet.export`)
- `GET /api/health` (no auth) → `{ "ok", "data": { "checks": { "postgres", "storage" }, "build": { "sha", "time", "source" } } }`, 503 while any dependency is down or unconfigured. `build.sha` is the live commit (deploy-verify signal); `source` is `env` | `railway` | `git` | `stamped` | `dev` (chain order); `time` is `HINDSITE_BUILD_TIME`, else the prebuild stamp ISO, `"unknown"` when neither parses. `HINDSITE_BUILD_SHA` (40 hex) overrides the sha with `source: "env"`; malformed env values fall through, never crash. A production payload with `source` not `railway`/`env` means the deploy pipeline lost `RAILWAY_GIT_COMMIT_SHA` — escalate, do not trust the sha. Invalid server config (e.g. a malformed `HINDSITE_KEK`) answers 500 `internal` in the standard envelope — never an empty body.

Soul routes answer 503 `dataplane_unconfigured` when the deployment has no
`DATABASE_URL` / `STORAGE_*` configured.

## 9. Error codes

| HTTP | `error.code`                                                                  | Meaning                                    | Recovery                                       |
| ---- | ----------------------------------------------------------------------------- | ------------------------------------------ | ---------------------------------------------- |
| 400  | `invalid_commitment`                                                          | `clientSha256` not 64 hex                  | Fix input, re-enroll                           |
| 400  | `missing_*`, `invalid_*`                                                      | Bad/missing field, scope, ttl, path, range | Fix input, retry                               |
| 400  | `missing_bearer`                                                              | No (or empty) `Authorization: Bearer` header | Attach the header, retry                      |
| 400  | `content_mismatch`                                                            | `x-content-sha256` != body bytes           | Recompute hash, retry PUT                      |
| 400  | `oauth_denied`                                                                | User declined Google consent               | Restart sign-in to consent                 |
| 401  | `token_invalid`                                                               | Bad signature/type/unknown jti             | Do not retry; re-authenticate                  |
| 401  | `bad_proof`, `challenge_unknown`                                              | Wrong proof or unknown nonce               | Re-challenge with fresh nonce                  |
| 401  | `enrollment_unknown`, `enrollment_mismatch`                                   | Unknown enrollment, or one for another agent | Re-enroll; use the matching agentId          |
| 401  | `agent_unknown`, `session_unknown`, `capability_unknown`, `refresh_unknown`   | Valid signature, unknown record (wiped DATA_DIR, wrong server) | Re-authenticate from step 1          |
| 403  | `capability_denied`, `workspace_denied`, `revoke_denied`, `agent_denied`, `wallet_denied` | Scope/ownership violation       | Use a sufficient token                         |
| 403  | `enrollment_locked`                                                           | Too many challenge attempts on one enrollment | Re-enroll for a fresh enrollment            |
| 403  | `agent_revoked`, `session_revoked`, `capability_revoked`                      | Revoked credential                         | Re-authenticate (agent revoke is final)        |
| 403  | `agent_limit_reached`                                                           | Human owns 100 agents already (revoked count) | At the account agent limit — ask the operator |
| 404  | `workspace_not_found`, `file_not_found`                                       | No such object                             | Check id/path                                  |
| 404  | `enclave_not_found`, `version_not_found`, `blob_missing`                      | No enclave / version / blob                | Create enclave; check version                  |
| 400  | `unsupported_chain`                                                             | Unknown wallet chain                       | Use `evm`                                      |
| 404  | `wallet_not_found`                                                              | No such wallet                             | Check wallet id                                |
| 409  | `enclave_exists`                                                              | Agent already has an enclave               | Use GET, do not re-create                      |
| 410  | `token_expired`, `enrollment_expired`, `challenge_expired`, `refresh_expired` | Time expired                               | Re-authenticate / re-enroll                    |
| 410  | `version_sunset`                                                              | Sunset date reached (legacy prefix gone)   | Move to the current prefix                 |
| 410  | `enrollment_used`, `challenge_used`, `refresh_used`, `code_used`, `code_expired` | Single-use replay / code expiry          | Past the window, start that step over — but codes, nonces, and refresh tokens replay inside 5 min of use, minting a fresh pair (`replay: true`; §1, §7) |
| 413  | `payload_too_large`                                                           | Body over 25 MiB                           | Split into multiple files                      |
| 416  | `range_not_satisfiable`                                                       | Range start beyond file size               | Re-check size, fix Range                       |
| 429  | `rate_limited`                                                                | Too many auth attempts from one IP         | Back off per the rule below, retry             |
| 500  | `internal`                                                                    | Server bug                                 | Report; safe to retry idempotent GETs          |
| 502  | `oauth_upstream`                                                              | Google token/userinfo call failed          | Retry; check Google status                     |
| 502  | `oauth_grant_invalid`                                                         | Google grant spent (expired/reused/revoked)| Sign in again (restart flow, not resend)   |
| 503  | `dataplane_unconfigured`                                                      | No DATABASE_URL / STORAGE_*                | Configure data plane, retry                    |
| 503  | `store_unreachable`                                                         | PG unreachable at query time (TCP refused / DNS / timeout) | Retry shortly; persistent → operator (infra, not your request) |
| 503  | `oauth_unconfigured`                                                          | No GOOGLE_CLIENT_ID / SECRET               | Configure OAuth, retry                         |

### 429 backoff rule (all clients: CLI, frontend, agents)

Every `rate_limited` 429 carries a `retry-after` response
header (integer seconds, 1–60 — all server windows are
60 s). Clients MUST:

1. Wait the header's seconds, plus 0–25% jitter, before
   retrying the same operation. The wait is a floor:
   fixed windows mean an early retry always 429s again.
2. Fall back to 60 s + jitter when the header is missing
   or unparseable (stripped proxy).
3. Stop after 3 waited 429s and surface failure — never
   loop forever.
4. Name the wait in user-visible copy. The two strings
   below are FROZEN (change bar follows): "Rate limited
   — retrying in Ns", finally "Too many attempts — try
   again in a minute". Never a bare failure; UI disables
   the control during the wait.
5. Retry ONLY 429s this way — other 4xx fail immediately
   (used/expired single-use tokens especially, §9 above).

Reference implementation: `clientBackoff()` in
`@hindsite/core` (`ratelimit.ts`) — pure, tested, and
importable by the CLI. Health (`/api/health`) is exempt
and never 429s.

Frozen-string change bar: the rule-4 strings are consumed
verbatim by UI pins. Any edit needs backend + frontend
sign-off and ships the UI pin update in the same diff —
no entry/edit lands alone. The frozen-string pin in
`packages/core/test/catalog.test.mjs` fails the build on
a silent edit.

## 10. Limits and non-goals

- One agent sees only its own workspaces; there is no sharing yet.
- No binary websocket endpoint in this milestone (SSE + Range instead).
- No multipart direct-to-object-storage uploads yet (25 MiB request cap).
- Workspaces (§2–§4) are the local adapter; the soul data plane (§8) persists
  the same encrypted-file model in Postgres + object storage (see `docs/railway.md`).
- Human sessions (§7) refresh (24h rotation) and revoke (single +
  revoke-all); outstanding pre-refresh tokens fail closed once.
- Auth records live in Postgres when configured (local auth store
  otherwise); human flows are multi-replica wherever PG is.
- Legacy `/api/v1/*` callers must follow `308` redirects or move to
  `/api/agent/v1/*` (sunsets 2026-11-28 — section 11).

## 11. Versioning (summary; full text: `docs/api-versioning.md`)

Additive changes (new routes/fields/codes) ship in the current
version with a same-diff contract update. Breaking changes (remove,
rename, require, reshape, re-mean) bump the path version and serve
old + new side by side. Moved paths `308` for at least 60 days from
announcement; the table below is the notice board, and `Deprecation`
/ `Sunset` headers appear in the final 30 days.

| Surface | Change | Since | Sunsets |
| ------- | ------ | ----- | ------- |
| `/api/v1/:path*` | 308 → `/api/agent/v1/:path*` | 2026-09-26 | 2026-11-28 |
| `/api/v1/:path*` headers | `Deprecation`/`Sunset` auto-emit 2026-10-29→11-28; 410 `version_sunset` on/after sunset day (route-owned, clock-driven) | 2026-09-29 | — |

What agents see (legacy `/api/v1/:path*`):

- Until 2026-10-29: bare `308` to the same path under
  `/api/agent/v1` (path + query preserved). Migrate by
  changing your base URL from `<origin>/api/v1` to
  `<origin>/api/agent/v1` — no other change needed.
- 2026-10-29 → 2026-11-28: the `308` also carries
  `Deprecation: true` and `Sunset: Sat, 28 Nov 2026
  00:00:00 GMT`.
- On/after 2026-11-28: `410` with
  `{ "ok": false, "error": { "code": "version_sunset",
  "message": "legacy /api/v1 was removed on 2026-11-28
  — use /api/agent/v1" } }` (standard envelope).

## 12. Changelog

Rule: every edit to this file ships its entry in the same
diff — date, change, reason, ticket. Newest first. No
entry = incomplete diff (review fails it the same as an
uncommitted contract edit). Backfilled once at adoption;
kept current ever since.

| Date | Change | Reason | Ticket |
| ---- | ------ | ------ | ------ |
| 2026-10-06 | §7 half-set Google config counts as unconfigured (same 503 `oauth_unconfigured`, loud server warn) instead of 500ing the route | Half-set env threw in config load, 500ing every route including start | `2026-10-06-backend-start-unconfigured-500.md` |
| 2026-10-05 | §8 health keeps the envelope on invalid server config (500 `internal`, never an empty 500) | Health was the only route outside withApi — it could not report its own misconfiguration | `2026-10-05-health-bare-route-empty-500.md` |
| 2026-10-06 | §7 agents list hardened: `[]`-not-404 + `createdAt`-asc order pinned, POST capped at 100/human (403 `agent_limit_reached`, revoked count), PG-less 503 gate stated | /account builds to this shape — pin it before FE diverges | `2026-10-02-backend-account-agents-list.md` |
| 2026-10-06 | §8 `data.build` gains `HINDSITE_BUILD_SHA`/`HINDSITE_BUILD_TIME` env overrides (`source: "env"` wins the chain; malformed falls through, never crashes) | Deploy pipelines without Railway env need an explicit provenance override | `2026-10-02-backend-deploy-freshness.md` |
| 2026-09-30 | §9 `missing_bearer` 400 row (no/empty Bearer header; QA's 401 corrected to live 400) | Most-hit no-auth failure had only the `missing_*` wildcard — explicit row, explicit recovery | `2026-09-30-contract-missing-bearer.md` |
| 2026-09-30 | §7 taxonomy adoption: `?error=<other>` row added, outage row widened to malformed payloads (all `oauth_upstream`, no new codes) | Spot-check found covered-but-undocumented shapes — the table now emits what the code emits | `2026-09-29-taxonomy-adoption-check.md` |
| 2026-09-30 | §9 `store_unreachable` 503 row (PG-unreachable-at-query maps off raw 500; retry-shortly copy) | Known failure mode 500ing raw violates map-then-surface | `2026-09-29-pg-unreachable-taxonomy-row.md` |
| 2026-09-30 | §11 sunset "what agents see" block (literal 308 headers + 410 body + base-URL migrate pointer) | Agents need literal shapes, not prose — landing docs warn before the 10-29 window | `2026-09-30-agentsmd-sunset-note-landing.md` |
| 2026-09-30 | §1 refresh refuses revoked agents (403 `agent_revoked`, first-use + replay; no dead-on-arrival rotation) | Self-revoked refresh rotated a pair that died at first use — refuse instead | `2026-09-30-selfrevoke-refresh-liveness.md` |
| 2026-09-29 | §1/§7 natural-key replay on verify + both refreshes (fresh pair + `replay` marker inside 5 min of use; §9 used-row updated) | Lost-response retries died at `*_used` — the key now saves the retry | `2026-09-29-idempotency-generalize.md` |
| 2026-09-29 | §7 revoke-all burns outstanding codes (`codesBurned` receipt; post-kill exchange/replay → 410 `code_used`; revoke-one never burns) | Stolen-code replay defeated the kill switch for 5 min (RACE-2) | `2026-09-29-revokeall-burn-codes.md` |
| 2026-09-29 | §9 rule-4 429 strings FROZEN + change bar (backend+frontend sign-off, same-diff UI update, test pin) | Verbatim UI adoption needs a freeze, not hope | `2026-09-29-429-string-freeze.md` |
| 2026-09-29 | §7 lifecycle curl examples (refresh ok/401, revoke one/all) | CLI/human debugging re-derived the calls — contract should run | `2026-09-29-session-curl-examples.md` |
| 2026-09-29 | §7 revoke propagation bound stated (write-commit, no grace; check-point table `docs/revoke-bound.md`) | Kill switch had no timing claim — "revoked but valid" is the nightmare | `2026-09-29-revoke-propagation-bound.md` |
| 2026-09-29 | §8 `GET /api/health` gains `data.build` `{ sha, time, source }` (deploy-verify signal; railway→git→stamped→dev chain) | Hourly needs an in-band live-sha, not dashboard-only | `2026-09-29-health-build-sha.md` |
| 2026-09-29 | §11 sunset headers implemented (route-owned 308 + final-30 headers + 410) + §9 `version_sunset` | §4 needs code before the 10-29 window | `2026-09-29-sunset-headers-impl.md` |
| 2026-09-29 | §12 changelog adopted (this section + backfill) | Contract edits need history, not prose-diffing | `2026-09-29-contract-changelog-process.md` |
| 2026-09-29 | §7 Google error taxonomy table + §9 `oauth_denied` / `oauth_grant_invalid` | Predictable upstream states had no codes/copy/retry | `2026-09-29-google-error-taxonomy.md` |
| 2026-09-29 | §9 429 backoff rule (header + jitter + stop-after-3) | Clients ignored limits — now a contract | `2026-09-29-429-client-contract.md` |
| 2026-09-29 | §7 exchange replay: code is the idempotency key (fresh pair in-TTL) | Lost-response retries died at `code_used` | `2026-09-29-exchange-idempotency.md` |
| 2026-09-29 | §7 hum refresh/revoke endpoints + lifecycle | Hum sessions gained rotation + kill switch | `2026-09-29-hum-session-lifecycle.md` |
| 2026-09-29 | §11 versioning summary + sunset table adopted | Breaks needed a notice board | `2026-09-29-api-versioning-policy.md` |
| 2026-09-26 | `/api/v1/:path*` → 308 to `/api/agent/v1/:path*` (+ §11 row) | Path versioning cutover | v1-migration |
