# Cortex execution authority v1

Canonical issuer: `https://auth.hybrid-id.com`. Sole resource audience:
`https://hybrid-cortex.com`. See deployment receipt (contact the integration team)
for actual rollout status and [OpenAPI](cortex-execution.openapi.json) for exact
JSON schemas. This contract extends existing agent identities; it does not enable
Cortex's task scheduler or waive Cortex's own supervised acceptance gates.

## Endpoints and credentials

All operations are POST with `Content-Type: application/json`, maximum 24,576
bytes, no redirects and `Cache-Control: no-store`.

| Endpoint | Caller and purpose |
| --- | --- |
| `https://auth.hybrid-id.com/cortex/runtime` | Agent runtime obtains a five-minute Cortex credential using an Ed25519 possession proof; no human token or app secret. |
| `http://127.0.0.1:3152/hybrid/cortex-execution` | Existing confidential Cortex server backchannel. Basic authentication with its existing client registration. Human delegation management OR current runtime request validation. |
| `http://127.0.0.1:3152/hybrid/cortex-knowledge` | Same confidential backchannel; validates the runtime proof and reads the exact approved canonical knowledge version. |

Private routes reject forwarded requests and external peers with 404. They are
not browser endpoints and must never be exposed through a public proxy. Cortex
already uses this Core-local transport for `/hybrid/cortex-agents`.

For human management, request `openid cortex:agents cortex:execution` plus
`cortex:companies` for a company. The new scope permits requesting explicit grants;
it does not itself grant unattended execution. Existing scoped sessions may use a
normal incremental-consent authorization flow with PKCE; no forced complete login
is required while native login remains valid. Basic sign-in and creation/linking
remain insufficient. The runtime never receives that human token.

## Persistent delegation

Management envelope:

```json
{
  "operation": "grant",
  "access_token": "<current Cortex OIDC access token>",
  "subject": "<Cortex pairwise human subject>",
  "workspace": "",
  "payload": {
    "statement": {
      "app": "<existing Cortex client ID>",
      "controller_subject": "<same pairwise subject>",
      "operation_id": "0123456789abcdef0123456789abcdef",
      "agent_id": "<existing stable 32-hex agent ID>",
      "workspace": null,
      "actions": ["tasks:claim", "tasks:result"],
      "resources": [],
      "expires_at": 1791500000,
      "public_key_jwk": {"kty":"OKP","crv":"Ed25519","x":"<public key>"}
    },
    "proof": "<new runtime key signature>",
    "acknowledgement": "I_APPROVE_CORTEX_GRANT"
  }
}
```

Replace the illustrative timestamp with a reviewed expiry from 60 seconds to 30
days ahead. The runtime generates and retains its Cortex key. Sign UTF-8 bytes of
`hybrid-id/cortex-delegation/v1`, one NUL byte, then canonical JSON of the statement
(recursively sorted object keys, compact separators, unescaped Unicode). Only
public JWK fields `kty`, `crv`, `x` are accepted. No private key is sent to Identity.

The human controller must explicitly review the agent, company, actions, resources,
expiry and key before Cortex submits `grant`. A personal grant becomes ACTIVE.
A company grant starts PENDING_COMPANY: an authorized company manager separately
calls `approve`. The controller must remain a member of the represented company;
the approving manager must remain OWNER/ADMIN. A controller who is also a manager
may explicitly approve both roles. A personal agent can represent a company with
these approvals **without changing its native workspace or trading configuration**.
An unrelated manager cannot take over another person's agent.

Management operations all use the same envelope. Company requests set `workspace`
to the exact 32-hex company ID; personal requests use the empty string.

| Operation | Exact payload |
| --- | --- |
| `list` | `{ "workspace": null }`, or the selected company ID; at most 250 grants |
| `inspect` | `{ "id": "<delegation ID>" }` |
| `approve`, `pause`, `resume`, `revoke` | `{ "id": "…", "expected_revision": 1, "acknowledgement": "I_APPROVE_CORTEX_APPROVE" }`, replacing the final word with the uppercase operation |
| `rotate` | Above envelope with `I_APPROVE_CORTEX_ROTATE`, `public_key_jwk`, `proof` |

Controller or current company manager can inspect, pause or revoke. The person
who paused must resume; revocation is final. Rotation requires the controller and
proof under the new key over `hybrid-id/cortex-key-rotation/v1` + NUL + canonical
`{delegation_id,expected_revision,public_key_jwk}`. It changes only this delegation's
Cortex key. Every mutation advances the revision and invalidates existing tokens.
Existing native agent-key rotation also invalidates issued Cortex tokens, while
preserving the stable agent and delegation. No wallet key or financial scope changes.

Grant retries use the same operation ID and exact statement. Different input is
409; withdrawal/revocation cannot be recovered by replay. Other mutations use
revision comparison: after an uncertain response, inspect before retrying. A 409
requires refreshed state and a newly reviewed operation. No automatic restoration
of paused/revoked grants occurs.

Response `HYBRID_CORTEX_DELEGATION_V1` contains `delegation_id`, `agent_id`,
`controller_subject`, `manager_subject` (nullable), `workspace` (nullable), audience,
actions, resources, expiry, state, revision, key_revision, public key, created/updated
seconds and `financial_authority:false`. `knowledge_principal` is the existing
canonical `hcwc_…` identifier for collection-owner binding; it is not a credential.
No native human ID, browser session, trading settings or wallet data is disclosed.

## Runtime authentication and exact-request proof

Use the [reference signing helper](https://github.com/Hybrid-Chain/hybrid-id-sso-website/blob/main/examples/cortex/runtime.mjs).
This is a purpose-specific Hybrid PoP protocol, **not** an OAuth refresh token,
JWT access token, DPoP or RFC 8693 exchange. General `hcw_` credentials and human
`hcb_` or OIDC credentials are not accepted as Cortex runtime tokens.

Every signed statement has exactly:

```json
{
  "issuer":"https://auth.hybrid-id.com",
  "audience":"https://hybrid-cortex.com",
  "delegation_id":"<32 hex>",
  "operation":"exchange",
  "issued_at":1791490000,
  "expires_at":1791490030,
  "nonce":"<fresh random base64url, 24–96 characters>",
  "token_sha256":null,
  "request":null
}
```

Sign `hybrid-id/cortex-runtime/v1` + NUL + canonical statement JSON with the
approved Cortex runtime key. Send `{statement,proof}` to `/cortex/runtime`.
Assertions last at most 30 seconds, allow at most five seconds future clock skew,
and use durable, single-use nonces. Response:

```json
{
  "schema":"HYBRID_CORTEX_RUNTIME_TOKEN_V1",
  "access_token":"hcxc_<opaque secret>",
  "token_type":"Hybrid-PoP",
  "expires_at":1791490300,
  "renewal_mode":"REASSERT",
  "delegation":{"schema":"HYBRID_CORTEX_DELEGATION_V1","...":"full projection above"}
}
```

Tokens last at most 300 seconds and never outlive the delegation. Renew using a
new signed exchange; no browser session or refresh token is involved. A lost
exchange response can be retried with a fresh nonce; old unused tokens remain
bounded by their expiry. Do not log proofs, tokens or authorization bodies.

For a protected Cortex request change operation to `authorize`, set `token_sha256`
to SHA-256 of the exact opaque token, and include this exact `request` object:

```json
{
  "action":"tasks:claim",
  "method":"POST",
  "path":"/api/agents/tasks/claim",
  "body_sha256":"<SHA-256 of exact incoming request bytes>",
  "request_id":"<16–96 base64url characters; stable for the task operation>",
  "resource":null
}
```

The runtime sends `{statement,proof,access_token}` alongside its request to Cortex.
Cortex must compare method, exact path/query, body hash, action and request ID with
its actual request, then send that object to the private execution endpoint using
Cortex Basic authentication. Identity verifies token/key/delegation binding and
consumes the proof nonce. Cortex must compare the returned request_digest with
SHA-256 of canonical `request`, and enforce the returned agent/controller/company
against its own task lease, revision, capabilities and expected identity context.
A caller-supplied action label never defines the route's required capability.

Allowed capabilities: `tasks:claim`, `tasks:result`, `knowledge:read`, `drafts:write`,
`messages:write`, `posts:publish`, `pipelines:advance`. No wildcard, financial,
trading, wallet or contract-signing permission exists in this contract. Publishing
capability is execution permission, not public identity/photo redistribution.

Current authority response: `HYBRID_CORTEX_EXECUTION_AUTHORITY_V1`, issuer, audience,
`active:true`, `checked_at`, `expires_at`, `request_digest`, full delegation.
No public JWKS verification is appropriate for these opaque tokens. Use the
existing authenticated confidential backchannel; key material is never fetched
from an untrusted caller URL.

## Freshness, withdrawal and failures

Each protected operation gets a fresh check; **do not cache authorization across
requests**. Observations expire after at most five seconds, shortened by token,
proof and delegation expiry. These seconds permit completion of the same bounded
request, not reuse for other operations. Recheck immediately before a queued
external action. Long tasks should checkpoint authority and stop further effects
on failure; Identity cannot undo an external side effect already completed.

Every exchange/use checks native account activation, suspension/login policy,
agent ownership/status, current controller membership, manager authority, grant
state/expiry/revision and key. Account-created company projections additionally
require a fresh independent Account membership check. Native reconciled workspaces
use native Identity authority. Human logout alone does not withdraw delegation.
Removing the app connection or required consent scopes does. Reconsenting later
does not reactivate the old consent generation; create a newly reviewed grant.

| HTTP | Meaning / retry |
| --- | --- |
| 400 | Malformed or unsupported fields; correct the request. |
| 401 | Wrong confidential app credentials; fix configuration. |
| 403 | No current authority, invalid/stale/replayed proof, expired token, withdrawn consent or inactive grant; stop effects. Inspect/reconnect explicitly where appropriate. |
| 404 | Private route not exposed, or approved knowledge object/version missing. |
| 409 | Grant revision/idempotency conflict or content commitment mismatch; reload and review. |
| 413 | Body exceeds the bound. |
| 429 | Rate limit; bounded jittered backoff, fresh proof nonce. |
| 503 | Identity, Account or knowledge authority unavailable/expired in transit; fail closed, retain prepared work, bounded jittered backoff with fresh proof. |

Error envelope is `{error,message}`. There is no fail-open mode, stale positive
cache, empty-success fallback, or automatic downgrade to a human token. Cortex
must retain its task-level idempotency ledger: a fresh proof authenticates a retry,
it does not authorize executing a task twice. On lost validation response obtain
a fresh proof for the same request ID; never replay a used nonce. Rate limit is
240 requests/minute per provider socket peer; shared gateway traffic may share it.

## Delegated knowledge

This release reads **reviewed Context Mesh collection documents/projections**, not
raw private Data Vault files. The original collections, immutable revision documents,
publication policy, audience and agent connections remain canonical in Core.
No second knowledge store, new IPFS layer or Verify job credentials are introduced.

The collection owner must use the existing Context Mesh collection-agent binding
control to grant `memory:browse` to the grant's `knowledge_principal`. The selected
personal/company context must also be in the collection's current audience. Grant
`knowledge:read` in the explicit Cortex delegation and name each exact resource:

```json
{
  "collection_id":"<canonical 32-hex collection UUID>",
  "document_id":"<64-hex canonical source commitment, or null for the whole reviewed collection>",
  "version":1,
  "commitment":"<64-hex canonical collection revision commitment>"
}
```

`version` always identifies the **collection revision**, even for one document.
Each returned document also has its canonical `source_version`. Use the owner
collection interface to obtain reviewed version references; a typed URL is never
accepted as authority. Original source identifiers are not returned.

Send the runtime proof with action `knowledge:read` and exactly that resource to
`/hybrid/cortex-knowledge` through Cortex. Core checks current publication, audience
and the canonical agent binding before and after reading the original revision.
Identity and consent are checked again before releasing the result. Withdrawing
either grant, setting DARK/ARCHIVED, losing company access or changing the pinned
commitment stops access. Historical revisions require a retained immutable snapshot;
missing historical content is 404, not synthesized or silently replaced by latest.

Response `HYBRID_CORTEX_KNOWLEDGE_V1`: exact `resource`, title, `documents` with
`document_id`, `source_version`, title, reviewed summary and category; plus
`private_source_access:false`, `content_kind:reviewed_projection`, delegation ID/
revision, checked_at and expires_at. Maximum response is 256 KiB. Account/company
and resource bindings must be part of Cortex's private result/cache keys. Do not
serve retained data after withdrawal or authorize from a cached URL/reference.
Previously delivered plaintext cannot be recalled; Cortex must stop reuse and
remove withdrawn cached copies under its data-retention policy.

## Remaining boundaries

No raw passport, Vault attachment bytes, arbitrary URLs, write/query/propose access,
new wallet permissions, named public attribution or automatic KYC approval is
included. Raw document delivery requires the canonical Data Vault's own separately
consented recipient/encryption contract; this knowledge endpoint does not bypass it.
Management UI and supervised task execution remain Cortex's responsibility. This
release supplies canonical management and validation APIs, not a task runner.
Lists are capped at 250 grants per controller/company. Expiry extension/action
expansion requires a new explicit grant. The separate synthetic batch approval
block is unaffected. Keep Cortex live execution disabled until acceptance below
has passed in Cortex's deployment.
