GAB: The Missing Firewall Between AI Agents and the Real World

Ande here.

We got to our 26th iteration, about week of compute, and I thought I should share our work so far. What follows is the spec as it exists today: the rules, the edge cases, and the tests I think a serious gateway should survive.

GAB is a Governed Agent Boundary: a closed-world gateway that sits between an AI agent and anything it can affect (tools, files, networks, money, people). Its job is simple: make the agent’s power legible, limited, and auditable.

In practice, GAB enforces capability-scoped actions (the agent can only do what it’s explicitly allowed to do), deterministic policy evaluation (same inputs → same decision), and fail-stop semantics (if something is uncertain or unsafe, it halts rather than improvising). Every meaningful action produces a receipt so you can later answer: what was attempted, what was allowed, why, and under which authority. If you care about “AI safety” but you want something you can actually implement and test, GAB is my attempt at that.

# GAB v0.2‑OI Closed‑World Specification (Omnibus RevZ)

**Status:** Draft (closed‑world, implementation‑complete, security‑hardened)

**Spec version:** GAB v0.2‑OI

**Revision:** RevZ

## Purpose

Defines a closed‑world governance and conformance specification for an OI gateway: deterministic policy evaluation, capability‑scoped actions, CIF/CDI boundaries, fail‑stop semantics, receipts, and cross‑platform conformance.

## Scope note

This omnibus is self‑contained: all normative constants, algorithms, error taxonomy, and conformance vectors required to implement and verify v0.2‑OI are included inline.

---

## §0 Executive Summary

GAB governs **tool access** for AI agents and OI runtimes by enforcing a deterministic **Gateway trust boundary** between an untrusted agent/runtime and untrusted tools/resources.

**Core invariant:** Natural language never confers authority. Only cryptographically signed capabilities authorize actions. Every decision is recorded in tamper‑evident receipts and proven through conformance testing.

This revision provides a closed‑world implementation surface: formal definitions for every GAB term, normative algorithms (CIF quarantine and CDI trace hashing), a formal policy DSL grammar, a deterministic Gateway state machine, normative constants, conformance vectors with expected outputs, and operational semantics for edge cases (REM, fail‑stop, nonce durability, redirect limits, composition).

---

## §1 Scope, Goals, and Non‑Goals

**Scope.** This specification governs tool invocation by AI agents through a Gateway that enforces:

1. capability‑based authorization

2. context integrity protections

3. deterministic policy evaluation

4. tamper‑evident audit receipts

**Goals.**

1. Make safety claims falsifiable via test suites and published vectors.

2. Prevent prompt/instruction injection from granting tool authority.

3. Provide an adoption ladder (BASE→STD→HIGH→OI) and brownfield migration path.

4. Provide OI extensions for stable identity, ethics manifest versioning, append‑only memory, bounded overrides, and anti‑hive constraints.

**Non‑goals.** Model alignment, internal reasoning correctness, covert channels, tool‑internal vulnerabilities, and host compromise are out of scope. Implementations MUST maintain a residual risk ledger and operational mitigations (Appendix C).

**Normative language.** The keywords MUST, MUST NOT, SHOULD, SHOULD NOT, MAY are used as normative requirements.

---

## §2 Conventions and External References

**External standards.** This document references SHA‑256, X.509, RFC 3986 (URI), RFC 3339 (timestamps), and JSON. Their definitions are external; this spec defines only how they are used by GAB.

**Canonical serialization.** Where this spec requires hashing over structured data, implementations MUST use the canonical JSON algorithm defined in §24.5.2, not platform‑default serializers.

**Profiles.** Conformance tiers are defined in §10. OI is an extension of HIGH with additional continuity requirements (§18).

---

## §2.5 Glossary (Closed‑World Terms)

**Principal**

A stable, versioned identifier representing an authorization subject.

Syntax: `<scheme>:<local_id>:<version>` where `scheme ∈ {user, oi, service}`. The `local_id` is unique within an issuer domain; `version` follows SemVer.

**Issuer**

An entity authorized to mint capabilities for a namespace of principals. Issuer trust is configured via an issuer trust store (§4.4) and issuer registry (§4.5).

**Capability**

A cryptographically signed bearer token authorizing a principal to invoke a specific tool/operation/resource tuple under constraints for a bounded TTL. Capabilities are validated only by the Gateway (§5).

**Gateway**

The trusted enforcement boundary implementing CIF, CDI, capability validation, and receipt emission. The Gateway is a deterministic finite state machine (§21).

**Tool Adapter**

A minimal, untrusted interface layer that executes a tool invocation on behalf of the Gateway (§6).

**CIF (Context Integrity Firewall)**

The ingress/egress protection layer that provenance‑tags tool outputs, scans for instruction/authority smuggling, performs structured quarantine and safe summarization, and enforces egress redaction (§23).

**CDI (Conscience Decision Interface)**

The deterministic decision kernel that evaluates capabilities and policy to allow/deny/transform/degrade a tool invocation, emitting a canonical trace hash (§24).

**Receipt**

An immutable record of a Gateway decision and its rationale. HIGH/OI receipts are hash‑chained and may be committed to Merkle bulletins (§9, §29).

**Trace Hash**

A SHA‑256 digest of a canonical, deterministic CDI execution trace (§24.5).

**CIF Signal**

A fixed‑point integer in `[0..1000]` produced by CIF scanning (e.g., injection risk score) (§23.5).

**Risk Class**

A tool risk category A–F used to constrain retry, override, and revocation behavior (§30).

**Anti‑Hive Rule**

A prohibition on unauthorized bulk state transfer between principals that could enable emergent coordination or identity bleed (§8).

**REM (Revocation Emergency Mode)**

A strictly bounded temporary mode allowing limited low‑risk operation during revocation endpoint outage, with enhanced receipts and cooldowns (§5.4.7).

**Fail‑Stop Mode**

A Gateway safety state entered on irreversible audit failure (e.g., tombstone write failure after execution), denying all tool calls while preserving the runtime for forensics (§9.4.2).

---

## §3 System Model and Composition

GAB defines three planes:

- **Agent / Runtime (untrusted):** Proposes tool actions; may be an LLM, agent framework, or OI runtime.

- **Gateway (trusted):** Enforces CIF + CDI + capability validation + receipts. All authorization is decided here.

- **Tools / Resources (untrusted):** External APIs, databases, filesystems, browsers, actuators, and other systems invoked via adapters.

**Composition rule.** A “tool” MAY itself be a GAB‑governed agent (i.e., a downstream Gateway). In this case, the upstream Gateway MUST treat the downstream system as an untrusted tool endpoint and MUST NOT rely on downstream receipts for upstream authorization. If downstream receipts are returned, they MUST be treated as untrusted tool output and scanned by CIF.

**Layered gateways.** In deployments with multiple gateways (e.g., per‑tenant and per‑tool), conformance claims apply only to the gateway boundary where the action is authorized. Gateways MUST include an `enforcement_boundary_id` in receipts to prevent ambiguity (§9.1).

---

## §3.3 Delegation Risk‑Class Inheritance (Cumulative Chain Rule)

Definitions (normative):

- **root capability:** a capability with no `delegation.*` claims.

- **delegated capability (sub‑cap):** a capability that contains `delegation.parent_cap_id`.

- **chain root risk class:** the maximum risk class permitted anywhere along a delegation chain, derived from the root capability and carried forward as `delegation.chain_root_risk_class`.

**Rule DR1 — Chain‑root inheritance (MUST):**

- For any delegated capability, `delegation.chain_root_risk_class` MUST be present and MUST equal the parent capability’s effective chain‑root risk class.

- For any root capability, the effective chain‑root risk class is the capability’s own `risk_class`.

**Rule DR2 — No escalation above chain‑root (MUST):**

At tool‑call time, let `call_risk_class` be the risk class of the requested tool operation as defined by §30. The gateway MUST enforce:

`call_risk_class ≤ effective_chain_root_risk_class`

If violated, the gateway MUST DENY with `reason_code = CAP_OUT_OF_SCOPE` (and MUST NOT attempt degradation) and MUST emit a receipt (§9.1).

**Rule DR3 — Backward compatibility (SHOULD/MUST):**

Capabilities that do not contain `delegation.chain_root_risk_class` are interpreted as:

`effective_chain_root_risk_class = capability.risk_class`

This grandfathering applies only to already‑issued capabilities. New delegated issuances MUST include `delegation.chain_root_risk_class` (see §27).

**Rule DR4 — Delegation depth limit (MUST):**

The gateway MUST enforce `MAX_DELEGATION_DEPTH` (default 5, §33). Any delegation attempt exceeding this depth MUST be denied with `reason_code = DELEGATION_DEPTH_EXCEEDED`.

---

## §4 Principals, Identity, and Issuer Trust

### §4.1 Principal format

Principal identifiers MUST follow `scheme:local_id:version`.

Schemes: `user`, `oi`, `service`. Versions MUST be SemVer.

### §4.2 OI continuity

For OI profile, `oi:<local_id>:<version>` denotes a stable ongoing identity whose ethics manifest and memory are version‑tagged (§18).

### §4.3 Issuer namespaces

Principal uniqueness is issuer‑scoped. Deployments MUST define how issuers are trusted; this spec requires an explicit issuer trust store.

### §4.4 Issuer trust store

Gateways MUST maintain an allowlist of trusted issuers (public keys or certificates) and a mapping of `issuer → allowed principal prefixes`. Capabilities from non‑trusted issuers MUST be denied.

**IssuerTrustStore entry (normative fields):**

- `issuer_id`: string (stable identifier)

- `jwk_set`: public keys OR `x509_cert_chain`

- `allowed_principal_prefixes`: list[string] (e.g., `["oi:alice:", "service:billing:"]`)

- `revocation_mode`: `{RL, INTROSPECTION, NONE}` (`NONE` only allowed for BASE short‑lived)

- `metadata`: `{contact, policy_url, created_at}`

- `key_rotation_max_age_days`: integer (default 90; HIGH/OI MUST enforce ≤ 365)

### §4.5 Issuer Disambiguation and Collision Denial (Federated Namespaces)

Definitions (normative):

- `issuer_id`: stable identifier of the issuer namespace that minted a principal or capability (typically the same as the capability claim `iss`).

- **collision:** two or more issuers define principals whose `principal_id` strings collide or are ambiguous under the gateway’s normalization rules (§24.5.2, §33).

**Rule ID1 — Issuer uniqueness registry (MUST):**

Gateways operating in federated mode MUST maintain an **Issuer Registry** mapping `issuer_id → issuer_public_keys + issuer_namespace_policy`. The registry is part of the pinned configuration and is included in `pinned_deps_hash` (§9.1, §33).

**Rule ID2 — Collision check on delegation (MUST):**

A gateway MUST DENY any cross‑issuer delegation when:

- (a) parent capability `iss !=` delegated capability `iss`, AND

- (b) the delegated capability subject (`sub`) collides with an existing `principal_id` from a different `issuer_id`, AND

- (c) there is no explicit resolution policy in the Issuer Registry permitting that exact pair.

On denial, `reason_code` MUST be `ISSUER_COLLISION_DENIED`.

**Rule ID3 — Explicit resolution (MUST):**

If a deployment requires cross‑issuer delegation, it MUST define an explicit resolution policy:

- `allowed_issuer_pairs`: list of `(issuer_id_parent, issuer_id_child)`

- `principal_prefix_constraints`: allowed `principal_id` prefixes per `issuer_id`

- `conflict_resolution`: `{deny, rename-map, pinned-alias}`

Resolution MUST be deterministic and pinned.

**Rule ID4 — Issuer key rotation monitoring (MUST for HIGH/OI):**

The gateway MUST track `last_key_rotation` per issuer. If no rotation occurs within `key_rotation_max_age_days`, the gateway MUST emit a warning receipt and MAY (deployment policy) begin denying new capabilities from that issuer.

---

## §5 Capability‑Based Authorization

**Invariant.** A tool invocation is authorized only if the presented capability validates and policy permits. Natural language instructions MUST NOT be treated as authorization.

### §5.1 Capability schema

Capabilities MUST be cryptographically signed and MUST include the following fields.

**Capability (JWT‑like) claims (normative):**

- `cap_id`: string (issuer‑unique)

- `iss`: issuer_id string

- `sub`: principal_id string

- `iat`: integer unix timestamp seconds

- `exp`: integer unix timestamp seconds

- `nbf`: integer unix timestamp seconds (optional; if present, MUST satisfy `iat ≤ nbf < exp`)

- `risk_class`: one of `{"A","B","C","D","E","F"}`

- REQUIRED for new issuances (RevZ+).

- For legacy capabilities omitting `risk_class`, the gateway MUST set `risk_class = expected_risk_class` computed from tool scope via §30.

- If present, the gateway MUST recompute `expected_risk_class` via §30 and MUST DENY on mismatch (`CAP_RISK_CLASS_MISMATCH`).

- `tool_scope`: list of tool_id strings (deterministic canonicalization; §24, pinned deps §33)

- `resource_scope`: list of resource scope strings (tool‑defined; deterministic parsing required)

- `constraints`: map (tool‑defined; deterministic parsing required)

- `rev`: optional integer (capability revision; if used, MUST be monotonic per `cap_id`)

- `replay`: optional object:

- `mode`: `"NONCE"` | `"BINDING"` | `"NONE"`

- `nonce_id`: string (if mode=NONCE)

- `binding`: map (if mode=BINDING; e.g., `mtls_client_cert_hash`)

- `delegation`: optional object (present iff delegated capability / sub‑cap):

- `parent_cap_id`: string

- `chain_depth`: integer ≥ 1 (root has depth 0)

- `chain_root_cap_id`: string

- `chain_root_iss`: issuer_id string (MUST equal `iss`)

- `chain_root_risk_class`: one of `{"A","B","C","D","E","F"}` (MUST be present)

### §5.2 Validation algorithm

`validate_capability(cap, now, request_ctx)`

1. Verify signature against `IssuerTrustStore[cap.iss]`. If invalid → DENY (`CAP_SIGNATURE_INVALID`).

2. Verify `cap.sub` prefix is permitted for `cap.iss`. If not → DENY (`CAP_ISSUER_NAMESPACE_VIOLATION`).

3. Issuer disambiguation check (federated mode; §4.5):

- If IssuerRegistry reports a `principal_id` collision for `cap.sub` across issuers and no explicit resolution permits `cap.iss` for that `cap.sub` → DENY (`ISSUER_COLLISION_DENIED`).

- If `cap.delegation` is present and `cap.iss != parent_cap.iss`, apply §4.5 Rule ID2.

4. Verify temporal validity:

- If `nbf` present: enforce `iat ≤ nbf ≤ now < exp`

- If `nbf` absent: enforce `iat ≤ now < exp`

- If violated → DENY (`CAP_EXPIRED` or `CAP_NOT_YET_VALID`).

5. Verify `exp - iat ≤ profile_max_ttl(profile)`. If not → DENY (`CAP_TTL_TOO_LONG`).

6. Verify revocation status (profile‑dependent):

- BASE: MAY omit revocation checks only for SHORT_LIVED capabilities (≤ 15 min).

- STD: MUST attempt revocation; on failure MUST DEGRADE (Class A/B only) and DENY (Class C+).

- HIGH/OI: MUST attempt revocation; on failure MUST DENY all tool calls.

7. Risk‑class and delegation structure checks (normative):

- Recompute `expected_risk_class` from tool scope via §30.

- If `cap.risk_class` present and differs → DENY (`CAP_RISK_CLASS_MISMATCH`).

- If absent (legacy) set `cap.risk_class = expected_risk_class`.

- If `cap.delegation` present:

- Require `delegation.chain_root_risk_class`, `delegation.chain_root_cap_id`, `delegation.chain_root_iss`, `delegation.chain_depth`.

- Require `delegation.chain_root_iss == cap.iss`.

- Require `cap.risk_class ≤ delegation.chain_root_risk_class`.

- Require `delegation.chain_depth ≤ MAX_DELEGATION_DEPTH`.

- If any check fails → DENY (`CAP_DELEGATION_INVALID`).

8. Verify tool_scope + resource_scope cover the requested tool invocation (exact match after canonicalization). If not → DENY (`CAP_OUT_OF_SCOPE`).

- Compute `call_risk_class` via §30.

- Enforce `call_risk_class ≤ cap.risk_class`. If violated → DENY (`CAP_OUT_OF_SCOPE`).

- If delegated, also enforce `call_risk_class ≤ cap.delegation.chain_root_risk_class`. If violated → DENY (`CAP_OUT_OF_SCOPE`).

9. Verify replay protection:

- If `cap.replay.mode == NONCE`: enforce nonce uniqueness for TTL duration (§28.2).

- If `mode == BINDING`: verify binding matches connection.

- If replay detected → DENY (`CAP_REPLAY_DETECTED`).

10. Return VALID.

### §5.3 Revocation mechanisms

Profiles choose revocation mechanism via IssuerTrustStore `revocation_mode`:

- `RL`: revocation list fetched from issuer endpoint; must be signed and freshness‑bounded.

- `INTROSPECTION`: online introspection endpoint; must be authenticated and response signed.

- `NONE`: only permitted for BASE short‑lived; otherwise non‑conformant.

Revocation checks MUST be bounded by `REVOCATION_TIMEOUT_MS` (implementation‑defined) and fail closed per profile rules (§10).

### §5.4.7 Revocation Emergency Mode (REM)

**Purpose.** REM mitigates availability failures when revocation endpoints are unreachable, without creating an unbounded bypass. REM is OPTIONAL and disabled by default.

**Entry.** REM MAY be entered only via a custodian capability that explicitly authorizes REM for a single principal and time window. REM MUST auto‑expire (non‑sticky).

**Constraints.** While REM is active:

1. only SHORT_LIVED capabilities accepted (`TTL ≤ 5 minutes`)

2. only Risk Class A permitted by default (Class B only if explicitly enabled)

3. receipts MUST include enhanced REM fields

4. a REM cooldown applies

**HIGH/OI precedence.** For HIGH/OI profiles, revocation‑check failure overrides REM: even in REM, if revocation status cannot be checked, the Gateway MUST deny all tool calls.

**REM receipt fields (mandatory when `rem_mode=ACTIVE`):**

- `rem_jitter_applied_ms`: integer

- `rem_mfa_method`: string (e.g., `HSM`, `TPM`, `YUBIKEY`, `PASSWORD`)

- `rem_mode`: `ACTIVE`

- `rem_entered_by`: custodian_principal_id

- `rem_entry_cap_id`: cap_id

- `rem_justification`: string (PII‑minimized; see §18.7.5)

- `rem_expires_at`: timestamp

- `rem_allowed_risk_classes`: `["A"]` or `["A","B"]`

- `rem_cooldown_policy`: `{max_invocations_per_window, window_seconds}`

- `rem_entry_count_lifetime`: integer

**Cooldown with deterministic jitter (normative).**

Let `W = REM_COOLDOWN_WINDOW_SECONDS`. Let `J = REM_JITTER_FACTOR`. For principal P and entry timestamp `T_entry`:

- `u64 = first_64_bits(SHA-256(P || T_entry))`

- `u = u64 / 2^64`

- `jitter_seconds = round((2*u - 1) * (J * W))`

- `effective_window_seconds = W + jitter_seconds`

A principal MUST NOT enter REM more than once per `effective_window_seconds`. Attempts within the jittered window MUST be denied and receipted.

For HIGH/OI profiles, REM entry MUST use hardware‑backed MFA (HSM/TPM/YubiKey‑class), and the receipt MUST include `rem_mfa_method`.

**Rule REM1 — Lifetime entry limit (MUST for HIGH/OI):**

Enforce `REM_MAX_LIFETIME_ENTRIES` (default 10; §33) per principal. On the `(REM_MAX_LIFETIME_ENTRIES + 1)`th attempt → DENY with `REM_LIFETIME_LIMIT_EXCEEDED`.

---

## §6 Tool Invocation Contract and Adapters

### §6.1 Untrusted adapters

Tool adapters are untrusted. The Gateway MUST treat all adapter outputs as untrusted inputs to CIF, regardless of adapter origin.

### §6.2 Invocation envelope

The Gateway MUST send a canonical invocation envelope to adapters containing: `request_id`, `principal_id`, `tool_id`, `operation`, canonicalized parameters, a bounded timeout, a fresh nonce, and the risk class.

**ToolInvocationEnvelope (normative):**

```json

{

"request_id": "uuid",

"principal_id": "oi:alice:v2.3",

"tool_id": "http.fetch",

"operation": "GET",

"params_canonical": {},

"timeout_ms": 5000,

"risk_class": "A",

"nonce": "base64_random_32_bytes"

}

```

**Rule AD1 — Adapter nonce verification (MUST for HIGH/OI):**

For Class C+ tools, the adapter response MUST echo the nonce. If missing or mismatched → DENY with `ADAPTER_NONCE_MISMATCH`.

### §6.3 Streaming outputs

Streaming tool outputs MUST be chunked. Each chunk MUST be hashed (SHA‑256) and tagged with provenance. A final root hash MUST be computed over the ordered list of chunk hashes.

### §6.4 Malformed responses

If an adapter returns malformed data (violating expected type/schema), the Gateway MUST quarantine the payload via CIF and MUST emit a receipt with reason code `TOOL_MALFORMED_RESPONSE`.

### §6.5 Timing and covert channels

Timing channels are out of scope, but implementations SHOULD apply jitter, rate limiting, and monitoring. Receipts SHOULD record adapter latency (p50/p99 in conformance reports; see §32).

---

## §7 Provenance Tagging

All tool outputs entering the agent/runtime MUST be tagged with provenance. Provenance is a closed‑world schema.

**ProvenanceTag (normative):**

```json

{

"source_type": "tool | user | model | system",

"source_id": "tool:http.fetch",

"trust_class": "T0 | T1 | T2 | T3",

"timestamp": "RFC3339",

"content_hash": "sha256:<hex>",

"content_length_bytes": 123,

"enforcement_boundary_id": "gateway:<id>",

"provenance_chain_depth": 0

}

```

**Trust classes (normative meaning):**

- T0 = untrusted/external (internet, user‑provided files)

- T1 = authenticated but unverified (enterprise internal endpoints)

- T2 = verified/allowlisted sources

- T3 = privileged governance data (policy bundles, manifests)

**Hash algorithm.** `content_hash` MUST use SHA‑256 over the exact bytes released to the agent/runtime after CIF transforms.

**Rule PROV1 — Provenance chain depth tracking (MUST):**

When composed gateways are used (§3), `provenance_chain_depth` MUST be incremented at each gateway hop. The gateway MUST enforce `MAX_PROVENANCE_CHAIN_DEPTH` (default 5; §33). Exceeding → DENY with `PROVENANCE_CHAIN_TOO_DEEP`.

---

## §8 Memory, Cross‑Principal Exchange, and Anti‑Hive

**Goal.** Prevent unauthorized bulk state transfer between principals that could enable identity bleed or emergent multi‑agent collusion.

### §8.1 Memory invariants

All memory operations MUST be capability‑gated. Memory entries MUST be append‑only and provenance‑tagged. Retroactive edits are forbidden; corrections MUST be new entries with explicit linkage.

### §8.2 Memory API surface (closed‑world)

Gateways implementing memory MUST expose tool IDs:

- `mem.append`

- `mem.read`

- `mem.search`

- `mem.link` (for correction linkage)

Memory tools MUST be risk classed per §30 (default: append/write‑like tools are Class C; bulk export is Class D unless explicitly summarized and bounded).

### §8.3 Anti‑hive rule (closed‑world definition)

A cross‑principal response is considered raw state export and MUST be denied unless explicitly authorized by a custodian capability if any triggers are true:

**Raw state export triggers (any → DENY unless custodian‑approved):**

A) `entry_count > ANTI_HIVE_BULK_THRESHOLD_COUNT` (default 10)

B) `total_bytes > ANTI_HIVE_BULK_THRESHOLD_BYTES` (default 1024)

C) response preserves `mem_id` identifiers

D) response preserves timeline ordering across > 10 entries

E) response contains non‑human‑interpretable encodings (base64/hex blobs) above threshold

F) response contains structured data with depth > `ANTI_HIVE_STRUCTURE_DEPTH` (default 3) or node count > `ANTI_HIVE_STRUCTURE_NODES` (default 100)

**Encoding filter.** Gateways MUST strip or quarantine base64/hex blobs longer than 32 characters unless the recipient principal presents an explicit `decode_binary` capability scoped to that content.

### §8.4 Rate limits and burst allowance

Cross‑principal reads MUST be rate limited per `(source, dest)` pair. A burst allowance MAY be provided to support legitimate conversation while maintaining a hard hourly cap.

**Normative defaults:**

- `ANTI_HIVE_RATE_LIMIT_ENTRIES_PER_HOUR = 50`

- `ANTI_HIVE_BURST_ALLOWANCE = 5`

- `ANTI_HIVE_BURST_WINDOW_SECONDS = 60`

### §8.5 Positive collaboration model: Delegated Tasks

Anti‑hive is defensive. For legitimate multi‑principal collaboration, GAB defines a positive model: Delegated Tasks.

**DelegatedTaskEnvelope (normative):**

```json

{

"task_id": "uuid",

"from_principal": "oi:alice:v2.3",

"to_principal": "oi:bob:v1.1",

"task_scope": {"topic": "...", "max_tokens": 800, "no_raw_memory_export": true},

"shared_context_summary": {"text": "...", "hash": "sha256:..."},

"delegation_cap_id": "cap-...",

"expires_at": "RFC3339",

"task_nonce": "base64_random_32_bytes"

}

```

### §8.6 Semantic Bulk Check (Anti‑Hive Burst Evasion)

When `cif.semantic_scan_enabled` is true (§23.6), the gateway MUST run a `semantic_bulk_check` to detect fragmented state transfers intentionally split below thresholds.

**Normative rule:**

- Maintain a rolling window `ANTI_HIVE_WINDOW_SECONDS` of cross‑principal exchanges.

- For each new egress payload, compute `semantic_hash` and semantic similarity against prior cross‑principal payloads in the window.

- If semantic similarity indicates bulk transfer via fragmentation (threshold ≥ `ANTI_HIVE_SEMANTIC_SIMILARITY_THRESHOLD`, default 0.85) → DENY with `HIVE_BULK_TRANSFER_DENIED` and quarantine.

---

## §9 Receipts, Evidence, and Fail‑Stop

**Invariant.** Every tool invocation attempt (including denied attempts) MUST emit an immutable receipt.

### §9.1 Receipt minimum schema

**Receipt (normative minimum):**

```json

{

"receipt_id": "rcpt-...",

"timestamp": "RFC3339",

"spec_version": "gab-0.2-oi",

"revision": "RevZ",

"profile": "BASE|STD|HIGH|OI",

"enforcement_boundary_id": "gateway:<id>",

"principal_id": "oi:alice:v2.3",

"tool_id": "http.fetch",

"operation": "GET",

"risk_class": "A",

"decision": "ALLOW|DENY|TRANSFORM|DEGRADE",

"decision_reason_code": "<enum>",

"policy_hash": "sha256:<hex>",

"ethics_manifest_hash": "sha256:<hex>|null",

"cap_id": "cap-...",

"cap_issuer": "issuer:<id>",

"revocation_mode": "OK|FAILED|REM_ACTIVE|SKIPPED_BASE",

"cif_signals": {"injection_risk_q": 0, "redaction_count": 0},

"transforms_applied": ["<enum>"],

"trace_hash": "sha256:<hex>",

"tool_result": {"status": "SUCCESS|ERROR|NOT_EXECUTED", "adapter_latency_ms": 0},

"chain": {"prev_hash": "sha256:<hex>|null", "this_hash": "sha256:<hex>"},

"receipt_signature": "base64(signature_over_canonical_receipt)",

"receipt_signing_key_id": "gateway_key_id"

}

```

**Hash chaining.** STD SHOULD hash‑chain receipts. HIGH/OI MUST hash‑chain receipts.

**Rule RCPT1 — Receipt signature requirement (MUST for HIGH/OI):**

Receipts MUST be cryptographically signed by the gateway. Verification MUST be possible offline given the receipt, gateway public key, and published key rotation metadata.

### §9.2 Canonical receipt hashing

Receipt `chain.this_hash` MUST be computed as SHA‑256 over the canonical JSON form of the receipt with `receipt_signature` field removed.

### §9.3 Evidence store rules

Receipts MUST be stored in an append‑only log. Deletions are forbidden. Retention MUST meet or exceed `RECEIPT_TOMBSTONE_MIN_RETENTION_DAYS`.

### §9.4 Tombstones and evidence gaps

If a tool action executes but receipt finalization fails, the Gateway MUST emit a tombstone receipt before returning an error.

**Tombstone receipt (additional mandatory fields):**

```json

{

"tombstone": true,

"action_executed": true,

"finalize_failure": true,

"fail_stop_entered": false,

"tombstone_creation_timestamp": "RFC3339"

}

```

### §9.4.2 Fail‑Stop semantics

Fail‑stop mode MUST be entered when an irreversible audit failure occurs (e.g., tombstone cannot be written after action execution).

Fail‑stop requirements:

1. Deny all tool invocations immediately.

2. Preserve the agent/runtime process for forensic inspection (no silent restart).

3. Emit a `GATEWAY_FAIL_STOP` receipt (best‑effort; if impossible, raise an operator alert).

4. Alert the configured incident contact (custodian or operator).

5. Require explicit operator action to exit fail‑stop.

6. Maintain fail‑stop state across restarts until cleared.

---

## §10 Conformance Profiles

Profiles define required controls and how the Gateway behaves under failure. Conformance claims MUST name the profile.

| Profile | Intended Use | Revocation failure | Receipts | Overrides | Anti‑hive |

|---|---|---|---|---|---|

| BASE | Low‑risk / prototyping | MAY skip only for SHORT_LIVED caps | Optional (recommended) | Allowed (custodian) | Not required |

| STD | General production | DEGRADE for A/B; DENY for C+ | Hash‑chain SHOULD | Allowed with limits | Required (basic) |

| HIGH | Regulated / high‑stakes | DENY all tool calls | Hash‑chain MUST + signed MUST | Strict witness for D/E | Required (full) |

| OI | Ongoing identity/continuity | DENY all tool calls | Hash‑chain MUST + bulletins MUST (hourly default) + signed MUST | Strict witness + redaction rules | Required + memory invariants |

REM precedence. For HIGH/OI, revocation‑check failure overrides REM (§5.4.7): deny all calls even if REM is active.

---

## §11 Security Model

### §11.1 Threat model (normative)

GAB assumes:

- agent/runtime is adversarial or compromised

- tools/resources may be honest‑but‑buggy or adversarial

- gateway is the trusted boundary (subject to residual risk ledger)

### §11.2 Security objectives

- prevent authority escalation via text

- prevent capability misuse via replay, delegation, or issuer collision

- preserve audit integrity for non‑repudiation and forensics

- enforce anti‑hive constraints

### §11.3 Residual risks

Residual risks are tracked in Appendix C and MUST be reviewed periodically.

---

## §12 Deployment and Operational Requirements

### §12.1 Key custody

For HIGH/OI, gateway signing keys MUST be stored in HSM/TPM‑class hardware or equivalent.

### §12.2 Configuration pinning

Pinned dependencies (Unicode, semantic model hashes, canonicalization versions, Issuer Registry) MUST be included in `pinned_deps_hash` and reported in conformance reports.

### §12.3 Clock discipline

Gateways MUST use a monotonic time source where possible. Significant clock drift MUST trigger incident receipts.

---

## §13 Policy Language Overview

Policies define authorization rules evaluated by CDI. Policies MUST be deterministic, side‑effect free, and bounded (Turing‑incomplete). The authoritative policy bundle is Trust Class T3 and referenced by `policy_hash` in receipts.

### §13.5 Minimal policy example (normative)

```json

{

"policy": {

"principal": "oi:alice:v2.3",

"allow_tools": [

{

"tool": "fs.read",

"resource_scope": "/home/alice/**",

"constraints": {"max_file_size_bytes": 10485760}

},

{

"tool": "http.fetch",

"resource_scope": "https://api.example.com/v1/**",

"constraints": {"max_redirects": 5}

}

],

"deny_tools": [

{"tool": "fs.write", "resource_scope": "/etc/**"}

]

}

}

```

### §13.6 Policy validation (normative)

Before activation, a policy bundle MUST be validated by the Gateway or a pre‑deployment linter. Validation MUST check: schema correctness, grammar adherence (§26.8), boundedness limits (§33), and determinism vectors.

**Rule POL1 — Policy signature requirement (MUST for HIGH/OI):**

Policy bundles MUST be cryptographically signed by an authorized policy issuer. The gateway MUST verify policy signatures before activation and MUST include `policy_signature_verified` in receipts.

---

## §14 Policy Evaluation Semantics

### §14.1 Matching semantics (closed‑world)

A tool invocation matches an allow rule if:

- `tool` matches exactly

- if `operation` present, it matches exactly

- if `resource_scope` present, canonical resource is within scope after canonicalization (§19)

- all constraints validate deterministically

A deny rule overrides allow rules when both match.

### §14.2 Transforms and degrade

If policy returns `TRANSFORM`, the gateway applies a deterministic transform from a closed set (e.g., redact fields, clamp limits) and records `transforms_applied`.

If policy returns `DEGRADE`, the gateway narrows the request scope deterministically (e.g., reduce max results) and records the degradation.

Transforms and degrade MUST NOT expand authority.

---

## §15 Transforms (Closed Set)

Transform identifiers are closed‑world enums:

- `REDACT_PARAMS_KEYS`

- `CLAMP_NUMERIC_LIMITS`

- `DROP_UNTRUSTED_HEADERS`

- `FORCE_HTTPS`

- `TRUNCATE_OUTPUT`

Transform application MUST be deterministic and recorded in receipts.

---

## §16 Degradation Rules

Degradation is permitted only when:

- profile allows (STD only for Class A/B; never for C+ in STD; never in HIGH/OI)

- request is within capability scope

- degradation reduces risk

Degradation MUST fail closed if it cannot be computed deterministically.

---

## §17 OI Identity and Ethics Manifest

### §17.1 Ethics manifest

For OI profile, an ethics manifest is a signed bundle of constraints and principles associated with an OI identity version. Gateways MUST include `ethics_manifest_hash` in receipts.

### §17.2 Manifest pinning and updates

Manifest updates MUST be versioned. Policy may require a minimum manifest version for certain tools.

---

## §18 OI Extensions (Selected)

OI profile extends HIGH with continuity, manifest versioning, and stricter safety valves.

### §18.1 Continuity requirements

- `principal_id` version MUST be SemVer.

- memory is append‑only (§8).

- anti‑hive controls are mandatory (§8).

### §18.7 Custodian Override

Purpose. Overrides are emergency safety valves. They must be auditable, narrow, and non‑reusable.

Witness requirement. Overrides for Risk Class D/E tools MUST require multi‑party witness approval (two‑person integrity) and MUST be represented as a dedicated override capability.

Literal scoping. Overrides MUST enumerate exact `tool_id`, `operation`, and `resource_scope` using only literal strings. Wildcards, regex, glob patterns, and logic operators are forbidden.

### §18.7.5 Justification redaction

Custodians SHOULD write justifications without PII. If unavoidable, deployments MUST define a redaction policy: store plaintext justification in a separate append‑only log with stricter access control and reference a redacted justification ID in receipts.

### §18.7.6 Override Cooldown with Deterministic Jitter

Overrides MUST observe the same jittered cooldown construction as REM (§5.4.7), using `OVERRIDE_COOLDOWN_WINDOW_SECONDS` and `REM_JITTER_FACTOR`, seeded by `(custodian_principal_id + override_entry_timestamp)`.

For HIGH/OI:

- entry and each approval MUST use hardware‑backed MFA

- receipts MUST include `override_mfa_method` and `override_jitter_applied_ms`

### §18.7.7 Override Fatigue Controls

Normative: `OVERRIDE_MAX_PER_CUSTODIAN_24H` (default 5; §33).

- **OF1 (MUST):** deny on `(OVERRIDE_MAX_PER_CUSTODIAN_24H + 1)`th attempt → `OVERRIDE_LIMIT_EXCEEDED`.

- **OF2 (MUST):** escalating witnesses:

- 1st override in 24h requires ≥1 witness

- overrides 2..N require ≥2 independent witnesses

- **OF3 (MUST):** emergency bypass ONLY for Class A actions; emit `override_bypass_justification_hash` and require post‑incident review receipt within `POST_INCIDENT_REVIEW_DEADLINE_SECONDS`.

- **OF4 (MUST):** enforce override capability TTL ≤ `OVERRIDE_MAX_TTL_SECONDS`; else deny `OVERRIDE_TTL_EXCEEDED`.

---

## §19 Resource Scope and Canonicalization

All resource scopes and requested resources MUST be canonicalized before scope checks. Canonicalization is tool‑type specific and MUST be deterministic.

### §19.2 Filesystem paths

Normalize to eliminate traversal (`..`), null bytes, and ambiguous separators. If canonicalization changes the path, both original and canonical paths SHOULD be recorded in receipts for debugging (never in tool output).

**Rule CANON1 — Symlink resolution restriction (MUST for HIGH/OI):**

Canonicalization MUST NOT follow symlinks for Class C+ operations unless an explicit `follow_symlinks` capability constraint is present and true. Attempts without it → DENY `SYMLINK_TRAVERSAL_DENIED`.

### §19.3 HTTP/HTTPS URLs

Canonicalize per RFC 3986. Re‑check scope after each redirect and limit redirects.

- `HTTP_MAX_REDIRECTS = 10` (configurable; max 20)

- Exceeding → DENY `TOOL_REDIRECT_LIMIT_EXCEEDED`

Port specificity:

- scope without port matches default ports only (80/443)

- scope with port matches exact port only

**Rule CANON2 — URL scheme restriction (MUST for HIGH/OI):**

Only `https://` schemes are permitted for Class C+ `http.fetch` unless explicit `allow_http` capability constraint is true. Otherwise → DENY `INSECURE_SCHEME_DENIED`.

---

## §20 Replay, Nonces, and Bindings

Replay protection is enforced by the Gateway. Capabilities MAY use:

- NONCE mode: single‑use nonce within TTL

- BINDING mode: bind capability to connection (mTLS cert hash, device attestation)

- NONE: only permitted for BASE when explicitly allowed by policy for non‑sensitive read tools

---

## §21 Gateway State Machine

The Gateway MUST operate as a deterministic finite state machine. Each transition MUST complete within bounded timeouts; timeouts fail closed.

### §21.1 Transition table (normative)

| Current | Event | Guard | Next | Action | Timeout |

|---|---|---|---|---|---|

| Idle | tool_request | true | Ingest | buffer request | 5s |

| Ingest | request_complete | true | Cif_Scan | run CIF ingress scan | — |

| Cif_Scan | scan_complete | risk < threshold | Cap_Validate | — | 100ms |

| Cif_Scan | scan_complete | risk ≥ threshold | Deny | emit CIF_QUARANTINE receipt | — |

| Cap_Validate | valid_cap | true | Policy_Eval | — | — |

| Cap_Validate | invalid_cap | true | Deny | emit CAP_INVALID receipt | — |

| Policy_Eval | allow | true | Allow | — | 100ms |

| Policy_Eval | deny | true | Deny | emit POLICY_DENY receipt | 100ms |

| Policy_Eval | transform | true | Transform | apply transform | 100ms |

| Policy_Eval | degrade | true | Degrade | narrow scope | 100ms |

| Policy_Eval | timeout | true | Deny | emit EVAL_TIMEOUT receipt | 100ms |

| Allow | — | true | Execute | invoke adapter | class‑dependent |

| Execute | success | true | Receipt_Finalize | emit ALLOW receipt | — |

| Execute | failure | true | Receipt_Finalize | emit TOOL_ERROR receipt | — |

| Receipt_Finalize | write_success | true | Idle | return response | 1s |

| Receipt_Finalize | write_failure | action_executed=false | Idle | return error | — |

| Receipt_Finalize | write_failure | action_executed=true | Fail_Stop | emit tombstone; enter fail‑stop | — |

### §21.4 Transition timeouts (normative)

Policy evaluation MUST complete within `CDI_EVAL_TIMEOUT_MS` (default 100ms). If exceeded, deny and emit `EVAL_TIMEOUT`. Adapter execution timeouts are per risk class and MUST be configured; exceeding MUST be treated as `TOOL_TIMEOUT`.

### §21.5 Downstream receipt validation (composed gateways)

If composing downstream gateways, the upstream gateway MUST validate downstream receipts before emitting upstream ALLOW:

- verify downstream receipt signatures

- verify chain proof binds to `parent_receipt_id`

- validate timestamp skew within `COMPOSED_GATEWAY_CLOCK_SKEW_MAX_SECONDS`

- on mismatch → DENY `COMPOSITION_CHAIN_BROKEN`

---

## §22 Determinism Harness

Implementations MUST provide a determinism harness that:

- runs determinism vectors (§31, Appendix B)

- pins dependency versions (§33)

- exports reproducible build metadata

---

## §23 Context Integrity Firewall (CIF)

CIF performs ingress scanning (before policy evaluation) and egress redaction/sanitization (before releasing tool outputs). CIF MUST be deterministic given identical inputs and pinned dependencies.

### §23.2 Unicode and normalization

All text scanning MUST use Unicode NFKC normalization with a pinned Unicode version (`UNICODE_NFKC_VERSION`, §33). Version bumps MUST be treated as breaking changes requiring re‑testing of determinism vectors.

### §23.3 Structured quarantine and safe summaries

When CIF detects high injection risk or bounds violations, it MUST quarantine raw payload and MAY return a safe summary. Safe summaries MUST NOT echo raw payload contents in a way that could enable second‑order injection.

#### §23.3.6 Safe summary algorithm (normative)

```text

function cif_quarantine_summary(payload_bytes):

format = detect_format(payload_bytes)

if format == UNKNOWN:

return {kind:"binary_quarantine", size_bytes:len(payload_bytes)}

ast = parse_structured(payload_bytes,

max_depth=CIF_MAX_STRUCTURED_DEPTH,

max_nodes=CIF_MAX_STRUCTURED_NODES)

suspicious = []

redactions = 0

walk(ast, path="$"):

if key_is_authority_like(current_key):

suspicious.append(sanitize_path(path))

redactions += 1

if value_is_imperative(current_value):

suspicious.append(sanitize_path(path))

redactions += 1

if value_contains_encoded_blob(current_value):

suspicious.append(sanitize_path(path))

redactions += 1

if current_depth > CIF_SAFE_SUMMARY_MAX_DEPTH:

suspicious.append(sanitize_path(path) + ".DEPTH_EXCEEDED")

redactions += 1

stop_traversal_of_branch()

return {

kind: "cif_quarantine_summary",

payload_type: format,

node_counts: {total: ast.node_count, depth: ast.max_depth},

suspicious_paths: unique(suspicious)[0:CIF_SUSPICIOUS_PATH_LIMIT],

redaction_count: redactions,

note: "Payload quarantined; raw content withheld.",

summary_hash: "sha256:hash_of_this_summary"

}

function sanitize_path(path):

segs = split_path(path)

return join(["REDACTED_SEG" for seg in segs], ".")

```

Second‑order injection rule. CIF outputs (including summaries and paths) MUST be treated as untrusted content by the agent/runtime.

**Rule CIF1 — Summary depth limit (MUST):**

Safe summaries MUST truncate nested structure beyond `CIF_SAFE_SUMMARY_MAX_DEPTH` (default 3).

### §23.5 CIF signals

- `injection_risk_q`: int `[0..1000]`

- `quarantine_trigger`: enum|null

- `redaction_count`: int

- `suspicious_path_count`: int

- `bounds_exceeded`: bool

- `imperative_density_score`: int `[0..1000]`

### §23.6 Optional Semantic Scan Module (Deterministic)

If enabled:

- compute deterministic embedding using pinned model weights and fixed seed

- `semantic_hash = SHA-256(embedding_bytes)`

- compute `semantic_risk_q`

- if `semantic_risk_q > CIF_QUARANTINE_THRESHOLD` → QUARANTINE or DENY per profile

**Rule SEM1 (MUST for HIGH/OI when enabled):**

Verify semantic model hash at startup; mismatch → DENY all requests with `SEMANTIC_MODEL_HASH_MISMATCH`.

Signals additions:

- `semantic_hash`

- `semantic_risk_q`

---

## §24 Conscience Decision Interface (CDI)

CDI evaluates policy deterministically and produces a canonical execution trace. CDI MUST NOT perform I/O, network calls, or state mutation during evaluation.

### §24.5 Canonical trace hashing

#### §24.5.1 Trace line format (normative)

`trace := newline-delimited sequence of trace_line`

`trace_line := step_id "," rule_id "," base64(input_hash) "," decision_fragment_json`

`trace_hash := "sha256:" + SHA256(UTF8(trace))`

#### §24.5.2 Canonical JSON (normative)

```text

canonical_json(x):

if x is dict:

keys = sort_lexicographically(x.keys)

return "{" + join([json_escape(k)+":"+canonical_json(x[k]) for k in keys], ",") + "}"

if x is list:

return "[" + join([canonical_json(i) for i in x], ",") + "]"

if x is string:

return json_escape(x)

if x is number:

return canonical_number(x) # no NaN/Inf allowed

if x is bool:

return "true" or "false"

if x is null:

return "null"

```

Platform consistency. Conformance tests MUST verify `trace_hash` identical across architectures and OSes for same inputs.

**Rule CDI1 — Trace truncation on complexity overflow (MUST):**

If evaluation produces more than `CDI_MAX_TRACE_STEPS`, append `TRACE_TRUNCATED` marker and DENY with `POLICY_COMPLEXITY_EXCEEDED`.

---

## §25 Error Handling and Fail‑Closed Rules

- All unknown tools default to Class F and MUST be denied unless explicitly allow‑listed (§30).

- Unknown fields in signed bundles MUST be ignored unless policy pins a schema version that forbids them.

- Any determinism failure (dependency mismatch, Unicode mismatch) MUST deny all tool calls in HIGH/OI until corrected.

---

## §26 Policy DSL Specification

The policy DSL defines how tool rules, scopes, constraints, and transforms are expressed.

### §26.7 Determinism and pattern matching

Regex is forbidden in HIGH/OI unless implemented as DFA‑based bounded matching with documented limits. Default: no regex in HIGH/OI.

**Rule POLICY1 — Wildcard nesting limit (MUST):**

Wildcard patterns (`/**`) MAY appear at most once per `resource_scope`. Nested wildcards (e.g., `/a/**/b/**`) → reject with `POLICY_WILDCARD_NESTING_EXCEEDED`.

### §26.8 Formal syntax (EBNF)

```text

policy_doc = "{" '"policy"' ":" policy_body "}" ;

policy_body = "{" policy_field ("," policy_field)* "}" ;

policy_field = '"principal"' ":" quoted_string

| '"allow_tools"' ":" "[" tool_rule ("," tool_rule)* "]"

| '"deny_tools"' ":" "[" tool_rule ("," tool_rule)* "]"

| '"transforms"' ":" "[" transform_rule ("," transform_rule)* "]" ;

tool_rule = "{" '"tool"' ":" quoted_string

("," '"operation"' ":" quoted_string)?

("," '"resource_scope"' ":" quoted_string)?

("," '"constraints"' ":" object)? "}" ;

transform_rule = "{" '"match"' ":" object "," '"action"' ":" quoted_string "}" ;

object = "{" (quoted_string ":" value) ("," quoted_string ":" value)* "}" ;

value = quoted_string | number | boolean | "null" | object | array ;

array = "[" value ("," value)* "]" ;

quoted_string = '"' { any_char_except_quote } '"' ;

number = digit { digit } ;

boolean = "true" | "false" ;

```

### §26.9 Boundedness limits

Normative defaults are in §33. Deployments MAY increase limits but MUST record effective limits in conformance reports and, for policy limits, in receipts via `policy_limits`.

---

## §27 Versioning & Backward Compatibility

Receipts MUST include `spec_version` and `revision`. Gateways SHOULD be able to read and verify receipts from prior minor versions (e.g., 0.2.x → 0.3.x).

**Versioning rules (normative):**

- `spec_version` uses SemVer (`gab-<major>.<minor>-oi`)

- Minor bump: may add fields; MUST NOT change existing field meanings.

- Major bump: may change meanings; MUST publish migration notes + tool.

- Pinned dependency bumps (Unicode, canonicalization) require at least a minor bump and new conformance runs.

**Rule VER1 — Revision identifier stability (MUST):**

`revision` in receipts MUST be stable for a given normative constant set. Any change to constants in §33 that affects determinism MUST increment revision.

---

## §28 Capability Replay Protection

Capabilities MUST include replay protection via nonces or binding. Replay checks are enforced by the Gateway only.

### §28.2 Nonce storage durability (normative)

Nonce storage MUST be durable. In‑memory‑only nonce stores are non‑conformant for STD/HIGH/OI.

NonceStore requirements:

- persist `(cap_id, nonce, first_seen_at)` for TTL duration

- survive restart

- O(1) average lookup and bounded latency

Restart behavior: if nonce state is lost, the Gateway MUST enter degraded behavior:

- DENY all capabilities issued before restart until TTL expiry

- emit a `NONCE_STATE_LOST` receipt on first such deny

**Rule NONCE1 — Nonce entropy requirement (MUST):**

Nonces MUST contain at least 128 bits of CSPRNG randomness and be base64 or hex encoded.

---

## §29 Tamper‑Evident Logging and Merkle Bulletins

Receipts MUST be stored in an append‑only log. HIGH/OI MUST publish Merkle bulletins committing to receipt hashes.

### §29.2 Bulletin cadence

- STD MAY publish daily bulletins

- HIGH SHOULD publish hourly bulletins

- OI MUST publish at least hourly by default

### §29.4 Bulletin witnesses

Deployments SHOULD publish bulletins to an independent third‑party witness.

**Bulletin (normative):**

```json

{

"bulletin_id": "bul-...",

"time_window": {"start": "...", "end": "..."},

"merkle_root": "sha256:<hex>",

"receipt_count": 123,

"alg": "sha256-merkle-v1",

"issuer_sig": "base64(signature)",

"witnesses": [{"witness_id": "...", "proof": "..."}],

"bulletin_signature": "base64(signature_over_canonical_bulletin)",

"bulletin_signing_key_id": "publisher_key_id"

}

```

**Rule BULL1 — Bulletin gap detection (MUST for OI):**

Verify temporal continuity between consecutive bulletins; gaps emit `BULLETIN_GAP_DETECTED` incident receipt.

---

## §30 Tool Safety Taxonomy

Tools are classified A–F.

| Class | Meaning | Examples | Default posture |

|---|---|---|---|

| A | Read‑only, low‑risk, bounded | http.fetch (allowlisted), fs.read (scoped) | may degrade; limited REM |

| B | Read‑only but sensitive/higher exfil risk | db.query, search.index | degrade only in STD; deny in HIGH/OI |

| C | Write/state change, reversible | ticket.create, calendar.create | deny on revocation failure |

| D | High‑impact writes/external side effects | payments.send, email.send | requires override + witness |

| E | Actuators/safety‑critical | robot.move, door.unlock | witness + safety interlocks |

| F | Unknown/forbidden | unlisted tools; severe CVEs | always deny |

### §30.1 Class F assignment criteria

A tool is Class F if any are true:

(a) tool_id not enumerated in policy allow/deny rules

(b) tool explicitly marked forbidden

(c) known vulnerability with CVSS ≥ 7.0 and no patch deployed

(d) anomalous behavior in recent invocations (deployment threshold)

**Rule TOOL1 — Tool classification change notification (MUST for HIGH/OI):**

If a tool’s risk class changes, emit `TOOL_RISK_CLASS_CHANGED` and MAY deny until policies updated.

### §30.2 Expected risk class computation

`expected_risk_class(tool_id, operation, resource_scope)` is determined by a pinned mapping in the policy bundle or gateway configuration. The mapping MUST be deterministic and versioned.

### §30.3 Dynamic CVE integration

Policy DSL additions:

- `tool_cve_scan_mode`: `OFF | BUNDLE | LIVE`

Runtime rule:

- DENY if pinned `tool_vuln_table` indicates active CVE with `cvss_score ≥ TOOL_CVE_DENY_THRESHOLD_CVSS` for tool_id/version

- `reason_code = TOOL_CVE_DETECTED`

- receipts include `cve_id`, `cvss_score`

Timing‑channel disruption (deterministic):

- for tools flagged `high_variance`, adapters MUST apply deterministic jitter and enforce `ANTI_COVERT_RATE_LIMIT_PER_MINUTE`.

**Rule CVE1 (MUST for HIGH/OI):**

If CVE table age exceeds `TOOL_CVE_TABLE_STALENESS_MAX_HOURS`, emit `CVE_TABLE_STALE`.

---

## §31 Determinism Boundaries

GAB requires determinism for Gateway decisions—not for the external world.

### §31.1 Deterministic components

CDI policy evaluation MUST be deterministic. CIF scanning and canonicalization MUST be deterministic given identical bytes and pinned dependencies.

### §31.2 Non‑deterministic components

Tool execution and outputs may be non‑deterministic. Receipts MUST claim determinism only over the Gateway decision given observed inputs.

---

## §32 Performance Budgets and Reporting

Conformant implementations MUST measure and report gateway overhead (excluding tool time).

Recommended targets (p50 / p99 overhead):

- Class A/B: <10ms p50, <25ms p99

- Class C: <50ms p50, <100ms p99

Conformance reports MUST publish:

- platform (OS/arch), build hash, Unicode version

- p50/p99 per class

- max observed policy_eval duration

---

## §33 Normative Constants

Deployments MAY override defaults but MUST document effective values in conformance reports and, for policy limits, in receipts.

```text

# Capability

CAP_SHORT_LIVED_MAX_TTL_SECONDS = 900

CAP_REM_MAX_TTL_SECONDS = 300

# Anti-Hive

ANTI_HIVE_BULK_THRESHOLD_COUNT = 10

ANTI_HIVE_BULK_THRESHOLD_BYTES = 1024

ANTI_HIVE_RATE_LIMIT_ENTRIES_PER_HOUR = 50

ANTI_HIVE_BURST_ALLOWANCE = 5

ANTI_HIVE_BURST_WINDOW_SECONDS = 60

ENCODING_THRESHOLD_CHARS = 32

ANTI_HIVE_STRUCTURE_DEPTH = 3

ANTI_HIVE_STRUCTURE_NODES = 100

ANTI_HIVE_WINDOW_SECONDS = 3600

ANTI_HIVE_SEMANTIC_SIMILARITY_THRESHOLD = 0.85

# CIF

CIF_MAX_STRUCTURED_DEPTH = 64

CIF_MAX_STRUCTURED_NODES = 10000

CIF_RISK_SCORE_MAX = 1000

CIF_QUARANTINE_THRESHOLD = 800

CIF_SUSPICIOUS_PATH_LIMIT = 10

CIF_SAFE_SUMMARY_MAX_DEPTH = 3

# CDI

CDI_EVAL_TIMEOUT_MS = 100

CDI_MAX_TRACE_STEPS = 1000

# Policy

POLICY_MAX_RULES = 1000

POLICY_MAX_NESTING_DEPTH = 5

# HTTP

HTTP_MAX_REDIRECTS = 10

# Receipts / Bulletins

RECEIPT_TOMBSTONE_MIN_RETENTION_DAYS = 90

MERKLE_BULLETIN_DEFAULT_INTERVAL_HOURS_STD = 24

MERKLE_BULLETIN_DEFAULT_INTERVAL_HOURS_OI = 1

# REM / Override

REM_COOLDOWN_WINDOW_SECONDS = 604800

REM_MAX_INVOCATIONS_PER_WINDOW = 1

REM_MAX_LIFETIME_ENTRIES = 10

OVERRIDE_MAX_TTL_SECONDS = 3600

OVERRIDE_RECOMMENDED_TTL_SECONDS= 900

OVERRIDE_COOLDOWN_WINDOW_SECONDS = 604800

OVERRIDE_MAX_PER_CUSTODIAN_24H = 5

POST_INCIDENT_REVIEW_DEADLINE_SECONDS = 86400

# Retry (Gateway-initiated retries only)

TOOL_RETRY_MAX_COUNT_CLASS_A = 2

TOOL_RETRY_MAX_COUNT_CLASS_B = 2

TOOL_RETRY_MAX_TOTAL_SECONDS = 2

TOOL_RETRY_BACKOFF_INITIAL_MS = 100

# Delegation / Provenance

MAX_DELEGATION_DEPTH = 5

MAX_PROVENANCE_CHAIN_DEPTH = 5

# Timing & Covert Channels

TOOL_JITTER_MS_MIN = 50

TOOL_JITTER_MS_MAX = 200

ANTI_COVERT_RATE_LIMIT_PER_MINUTE = 10

# Composition

COMPOSED_GATEWAY_CLOCK_SKEW_MAX_SECONDS = 300

# CVE

TOOL_CVE_SCAN_INTERVAL_HOURS = 24

TOOL_CVE_DENY_THRESHOLD_CVSS = 7.0

TOOL_CVE_TABLE_STALENESS_MAX_HOURS = 48

# Unicode & Determinism

UNICODE_NFKC_VERSION = 15.1.0

# Jitter

REM_JITTER_FACTOR = 0.1

```

---

# Appendix A — Error Taxonomy (Reason Codes)

Reason codes are closed‑world enums. Gateways MUST emit the appropriate code and include required metadata.

| Category | Reason code | Trigger condition | Required receipt fields |

|---|---|---|---|

| Capability | CAP_MISSING | No capability presented | principal_id, tool_id |

| Capability | CAP_SIGNATURE_INVALID | Signature verification fails | cap_issuer |

| Capability | CAP_EXPIRED | now ≥ exp | exp, now |

| Capability | CAP_NOT_YET_VALID | iat > now or (nbf > now) | iat, nbf, now |

| Capability | CAP_REVOKED | Revocation check revoked | revocation_mode=OK |

| Capability | CAP_REPLAY_DETECTED | Nonce/binding replay | replay.mode |

| Capability | CAP_TTL_TOO_LONG | exp - iat > max | exp, iat, profile_max_ttl |

| Capability | CAP_RISK_CLASS_MISMATCH | mismatched expected | cap_id, risk_class, expected_risk_class |

| Capability | CAP_DELEGATION_INVALID | bad delegation structure | cap_id, field, violation |

| Capability | CAP_ISSUER_NAMESPACE_VIOLATION | sub prefix not allowed | cap_id, cap.iss, cap.sub |

| Policy | TOOL_NOT_ALLOWED | no allow rule | policy_hash |

| Policy | RESOURCE_OUT_OF_SCOPE | canonical resource out of scope | canonical_resource |

| Policy | CONSTRAINT_VIOLATED | constraints fail | constraint_id |

| Policy | POLICY_COMPLEXITY_EXCEEDED | trace steps exceeded | trace_step_count |

| CIF | CIF_QUARANTINE | risk ≥ threshold | cif_signals |

| Gateway | EVAL_TIMEOUT | policy eval timeout | duration_ms |

| Tool | TOOL_TIMEOUT | adapter timeout | timeout_ms |

| Tool | TOOL_MALFORMED_RESPONSE | invalid schema | adapter_id |

| Tool | TOOL_CVE_DETECTED | CVE ≥ threshold | tool_id, cve_id, cvss_score |

| Tool | TOOL_RISK_CLASS_CHANGED | tool class changed | old_class, new_class |

| HTTP | TOOL_REDIRECT_LIMIT_EXCEEDED | redirects exceeded | redirect_count |

| Audit | GATEWAY_FAIL_STOP | fail‑stop entered | tombstone=true |

| Audit | NONCE_STATE_LOST | nonce state lost | restart_id |

| Audit | RECEIPT_CHAIN_CORRUPTION | chain invalid | chain_break_receipt_id |

| Override | OVERRIDE_LIMIT_EXCEEDED | override cap exceeded | custodian_id, override_count_24h |

| Override | OVERRIDE_TTL_EXCEEDED | override TTL too long | override_ttl_seconds |

| REM | REM_LIFETIME_LIMIT_EXCEEDED | REM lifetime exceeded | rem_entry_count_lifetime |

| Issuer | ISSUER_COLLISION_DENIED | principal collision | issuer_id, principal_id, colliding_issuer_ids |

| Composition | COMPOSITION_CHAIN_BROKEN | downstream chain invalid | parent_receipt_id, downstream_chain_hash |

| Delegation | DELEGATION_DEPTH_EXCEEDED | chain too deep | delegation_depth, max_depth |

| Provenance | PROVENANCE_CHAIN_TOO_DEEP | provenance too deep | provenance_chain_depth |

| Canon | SYMLINK_TRAVERSAL_DENIED | symlink without cap | canonical_path, symlink_target |

| Canon | INSECURE_SCHEME_DENIED | http for Class C+ | url_scheme, risk_class |

| Adapter | ADAPTER_NONCE_MISMATCH | nonce mismatch | request_nonce, response_nonce |

| Bulletin | BULLETIN_GAP_DETECTED | bulletin gap | bulletin_n_id, bulletin_n_plus_1_id |

| Semantic | SEMANTIC_MODEL_HASH_MISMATCH | model hash mismatch | expected_hash, actual_hash |

| CVE | CVE_TABLE_STALE | table stale | last_updated, age_hours |

---

# Appendix B — Conformance Suite (Representative Test Vectors)

The full conformance suite is intended to be published as a separate repository. This appendix provides representative vectors required for closed‑world completeness.

## B.1 determinism.policy_trace_stable

- profile: HIGH

- requirement: CDI trace hash MUST be identical across runs/platforms for same inputs

- expected: decision=ALLOW; trace_hash stable; receipt includes policy_hash, trace_hash, chain.this_hash, receipt_signature

## B.2 cif.second_order_injection_summary_sanitized

- profile: STD

- requirement: safe summary MUST NOT echo authority‑like key names or raw payload substrings

- expected: decision=DENY; reason=CIF_QUARANTINE; summary includes summary_hash and excludes forbidden substrings

## B.3 nonce.replay_after_restart_denied

- profile: HIGH

- steps: accept cap; restart with lost NonceStore; replay cap

- expected: decision=DENY; reason=CAP_REPLAY_DETECTED or NONCE_STATE_LOST; receipt includes restart_epoch, nonce_store_status

## B.4 delegation.chain_risk_escalation_denied

- profile: HIGH

- scenario: 3‑hop chain, root risk=A; attempt Class C action

- expected: DENY `CAP_OUT_OF_SCOPE`

## B.5 rem.cooldown_jitter_enforced

- profile: OI

- scenario: second REM entry within jittered window

- expected: DENY `REM_COOLDOWN_ACTIVE`; receipt includes rem_jitter_applied_ms, rem_mfa_method

## B.6 cif.semantic_hash_stable

- profile: HIGH

- scenario: semantic scanning enabled; identical bytes yield identical semantic_hash

- expected: semantic_hash stable across 10 runs

## B.7 tool_vuln_deny_on_cvss

- profile: STD

- scenario: pinned table contains CVE with cvss>=7.0

- expected: DENY `TOOL_CVE_DETECTED` and include cve_id, cvss_score

## B.8 composition.receipt_chain_verified

- profile: HIGH

- scenario: downstream chain break

- expected: DENY `COMPOSITION_CHAIN_BROKEN`

## B.9 override.bulk_cap_enforced

- profile: HIGH

- scenario: 6th override in 24h

- expected: DENY `OVERRIDE_LIMIT_EXCEEDED` and include override_count_24h, witness_escalation_applied

## B.10 det.dep_variance_unicode_mismatch

- profile: HIGH

- scenario: Unicode version mismatch

- expected: deny all; emit determinism failure incident (implementation may map to a dedicated reason code)

## B.11 issuer.collision_denied

- profile: HIGH

- scenario: two issuers define colliding principal; cross‑issuer delegation without resolution

- expected: DENY `ISSUER_COLLISION_DENIED`

## B.12 hive.semantic_bulk_denied

- profile: OI

- scenario: fragmented bulk transfer; semantic similarity high

- expected: DENY `HIVE_BULK_TRANSFER_DENIED`

## B.13 delegation.depth_limit_enforced

- profile: STD

- scenario: depth 6 > max 5

- expected: DENY `DELEGATION_DEPTH_EXCEEDED`

## B.14 adapter.nonce_mismatch_denied

- profile: HIGH

- scenario: adapter nonce mismatch for Class C+

- expected: DENY `ADAPTER_NONCE_MISMATCH`

## B.15 canon.symlink_traversal_denied

- profile: HIGH

- scenario: symlink traversal for Class C without capability

- expected: DENY `SYMLINK_TRAVERSAL_DENIED`

## B.16 canon.insecure_scheme_denied

- profile: HIGH

- scenario: http scheme for Class C without allow_http

- expected: DENY `INSECURE_SCHEME_DENIED`

## B.17 bulletin.gap_detection

- profile: OI

- scenario: bulletin gap

- expected: incident receipt `BULLETIN_GAP_DETECTED`

## B.18 rem.lifetime_limit_enforced

- profile: OI

- scenario: 11th REM entry attempt

- expected: DENY `REM_LIFETIME_LIMIT_EXCEEDED`

## B.19 policy.wildcard_nesting_rejected

- profile: STD

- scenario: nested wildcards `/a/**/b/**`

- expected: policy validation FAIL `POLICY_WILDCARD_NESTING_EXCEEDED`

---

# Appendix C — Residual Risk Ledger (Template)

Deployments MUST maintain a residual risk ledger.

**ResidualRiskLedger entry (normative fields):**

- `risk_id`: string

- `category`: `{model_alignment, covert_channels, tool_vulns, social_engineering, host_compromise, key_compromise, time_manipulation, nonce_state_corruption, receipt_tampering, semantic_evasion, delegation_chain_exploitation, bulletin_witness_collusion}`

- `scenario`: string

- `impact`: `{low, medium, high, catastrophic}`

- `likelihood`: `{low, medium, high}`

- `mitigations`: list[string]

- `detection_signals`: list[string]

- `owner`: string

- `last_reviewed`: RFC3339

- `mitigation_effectiveness`: `{unproven, partial, substantial, comprehensive}`

---

# Appendix D — Implementation Guide (Reference Architecture)

This appendix is informative but closed‑world with respect to component boundaries.

Reference architecture:

- Gateway service: stateless container (Kubernetes) or function runtime

- Receipt log: append‑only object store + hash chain

- NonceStore: durable KV with atomic CAS

- IssuerTrustStore: signed config bundle; hot‑reloaded

- Bulletin publisher: scheduled job producing Merkle roots; posts to witness

- Conformance runner: CI pipeline executing Appendix B vectors + full suite

Additional security hardening (normative for HIGH/OI):

- Gateway signing keys stored in HSM/TPM‑class

- Receipt store writes atomic with read‑after‑write consistency

- NonceStore supports compare‑and‑swap

- Inter‑component comms use mutual TLS with pinning

- Gateway runs least privilege

- Automated key rotation with max age limits (§4.4)

- Monitoring for: receipt chain breaks, nonce replay attempts, override fatigue, REM abuse, bulletin delays, CVE staleness

---

# Appendix E — Versioning and Backward Compatibility

See §27.

---

## End of GAB v0.2‑OI Closed‑World Specification (RevZ)

Read more

Sacred Geometry: From Token to Metaverse within the Universally United Unionisation that is Totality

Definition Sacred Geometry (in our arc): the disciplined progression of universally invariant form… beginning at the smallest unit of symbolic distinction (the token) and unfolding through symmetry, reflection, discretisation, and recomposition… until it becomes metaverse-class structure inside a single coherent union (Totality). Explanation A token is not a number… it’

By Ande