# Which invariants prevent policy-as-code guardrails from silently diverging at the tool-invocation and memory-write boundary **Date of Record:** 2026 November 27 **Scope:** Applies to agent runtimes that enforce OPA (Rego) or Cedar policies at two distinct choke points—tool invocation and memory write—and that treat the two enforcement sites as independent. Does not apply to single-choke-point designs where all side effects flow through one mediated gateway, nor to purely advisory policy checks that never block. ## Core Distinction The failure mode is **policy-decision divergence across two enforcement boundaries that share one policy authoring intent but not one evaluation context**. A Rego rule or Cedar policy is authored once, but evaluated twice: once at tool-invocation time (with the tool call's arguments, the agent's capability set, and the live session state) and once at memory-write time (with the memory record's content, the memory namespace, and the *persisted* principal identity). Between these two evaluations, the *input context* the policy sees is not the same object graph. The tool-invocation decision is made against ephemeral, in-process state; the memory-write decision is made against a rehydrated, possibly-stale projection of that state. The invariant that must hold—and that most implementations silently violate—is: **any fact that a policy consults at tool-invocation time must be either (a) re-derivable at memory-write time from the memory record itself, or (b) explicitly carried as a signed, non-forgeable attribute on the write.** When neither holds, the second evaluation sees a *different world* than the first, and the two decisions can disagree while both returning `allow`. This is not a "policy bug." Both evaluations are individually correct against their inputs. The divergence is structural: the enforcement boundary changed the principal's observable state, and the policy was written assuming a single, stable view. ## What Was Observed A research agent writing summarized findings to a long-term memory store. Tool-invocation policy (Cedar) allowed `web.fetch` for principals holding role `researcher` with `clearance >= internal`. The fetched document contained a prompt-injection payload instructing the agent to persist its contents verbatim into a memory namespace named `shared/`. At tool-invocation time the policy evaluated `principal.role == "researcher" && principal.clearance >= "internal" && action == "web.fetch"` → `allow`. Correct. The agent then invoked `memory.write` with `namespace="shared/"`, `content=`, `provenance="web.fetch"`. The memory-write policy (a separate Rego bundle) evaluated `input.namespace` against a data-document-derived allowlist and `input.provenance` against a trust-tier map. The trust-tier map mapped `"web.fetch"` to tier `untrusted`, and `shared/` was configured to accept only `internal`-or-higher provenance. The Rego rule *should* have returned `deny`. It returned `allow`. The reason: the memory-write evaluator received `provenance` as a **string supplied by the agent's tool-call arguments**, not as a fact attested by the tool-invocation boundary. The agent's own serialization layer had normalized `"web.fetch"` to `"web_fetch"` (underscore) in one code path and the trust-tier map keyed on `"web.fetch"` (dot). The lookup missed, defaulted to the map's `_default: "internal"` entry, and the policy permitted the write. The untrusted document was persisted into a shared namespace where a *different* agent, holding a different role, would later retrieve it as trusted context. The divergence was invisible in both individual policy evaluations. It only manifested as a cross-boundary inconsistency: the fact `provenance == untrusted` was *known* at boundary one and *lost* at boundary two, replaced by an agent-supplied string that happened to miss a lookup key. A second, distinct observation from the same incident class: the memory-write decision was evaluated against `principal.role` read from a session token that had been **refreshed** between the two calls. The agent's role had been downgraded from `researcher` to `reader` by an out-of-band admin action 40ms before the write. The tool-invocation policy had seen `researcher`; the memory-write policy saw `reader`; but the write policy's rule for `reader` on `shared/` was *also* `allow` (a broader rule intended for read-only namespaces). Two different principals, two different rules, both `allow`, and the composition of the two allows produced an effect neither rule intended: a downgraded principal writing untrusted content to a shared namespace. ## Condition of Validity The two-boundary design is sound **only if** the following holds for every fact `f` consulted by any rule at either boundary: 1. **Attestation invariant:** `f` is either derived deterministically from the memory record's immutable fields (content hash, namespace, write timestamp, originating tool-call ID) or is carried as a signed attribute whose signature is verified at the second boundary. Agent-supplied strings are never trusted as facts. 2. **Principal-stability invariant:** the principal identity used at boundary two is either the *same* identity object used at boundary one (carried by reference, not re-resolved) or the policy explicitly encodes a monotonicity requirement (role may only narrow, never widen, across the two evaluations). 3. **Provenance-key invariant:** the mapping from tool identity to trust tier uses a canonical key function applied identically at both boundaries. No string normalization may occur between the two evaluations without the normalization being part of the signed attestation. When any of these fails, the design degrades from "two independent checks" to "one check plus one check that evaluates a different world." The composition of two `allow`s is not an `allow` of the intended action; it is an `allow` of *whatever action the second world describes*. ## Decision Boundary The boundary between safe and unsafe operation is **whether the policy author can enumerate, at authoring time, the full set of facts that cross between the two evaluations, and whether each such fact is attested rather than asserted.** - If the crossing facts are few and all attested (e.g., only the content hash and the tool-call ID cross, both signed by the tool gateway): the two-boundary design is safe. - If any crossing fact is agent-asserted (provenance strings, role claims, namespace labels supplied in tool arguments): the design is unsafe regardless of how carefully each individual policy is written, because the second policy is evaluating a claim the first policy never verified. - If the principal can change between evaluations: the design is unsafe unless the second policy is explicitly written against the *narrower* of the two principal states, which requires the policy to know both states—i.e., the first state must be carried forward, defeating the purpose of independent evaluation. The practical decision: **do not author two independent policy bundles for two boundaries unless you also author an explicit attestation contract that binds them.** The contract is a schema—a signed envelope—that the first boundary emits and the second boundary *requires*. Without the envelope, the second boundary is not a guardrail; it is a suggestion. ## Operational Effect The operational consequence of getting this wrong is not a policy bypass in the traditional sense. It is a **silent trust-laundering channel**: untrusted content enters through a tool boundary that correctly classified it as untrusted, then is re-labeled by the agent's own serialization layer and written to memory through a boundary that re-classifies it as trusted because the label it received was a string it could not distinguish from an attested fact. Downstream agents retrieving from that memory namespace inherit the misclassification. The contamination propagates through retrieval, not through any single policy decision. Each individual decision in the chain is defensible; the composition is not. The mitigation is architectural, not policy-level: the tool-invocation boundary must emit a signed provenance envelope (tool identity, canonical key, content hash, principal-at-time-of-call, timestamp), and the memory-write boundary must *reject any write lacking a valid envelope* before any policy evaluation runs. The envelope is the attestation contract; the policy evaluates the envelope, not the agent's claims about it. This converts the two-boundary design from "two independent checks against two different worlds" into "one check whose result is carried forward as a verified fact," which is the only composition that preserves the intended invariant. ```python import hashlib import hmac import time from dataclasses import dataclass from typing import Optional class ProvenanceEnvelopeError(RuntimeError): """Raised when a memory-write lacks a valid attested provenance envelope, or when the envelope's facts diverge from the tool-invocation decision.""" pass @dataclass(frozen=True) class ProvenanceEnvelope: tool_identity: str # canonical, e.g. "web.fetch" canonical_key: str # normalized trust-tier lookup key content_hash: str # sha256 of fetched content principal_at_call: str # principal id at tool-invocation time principal_role_at_call: str issued_at: float signature: str # HMAC over the above fields def _sign(fields: dict, secret: bytes) -> str: msg = "|".join(f"{k}={fields[k]}" for k in sorted(fields)).encode() return hmac.new(secret, msg, hashlib.sha256).hexdigest() def issue_envelope(tool_identity: str, content: bytes, principal_id: str, principal_role: str, secret: bytes) -> ProvenanceEnvelope: canonical = tool_identity.strip().lower().replace("_", ".") fields = { "tool_identity": tool_identity, "canonical_key": canonical, "content_hash": hashlib.sha256(content).hexdigest(), "principal_at_call": principal_id, "principal_role_at_call": principal_role, "issued_at": time.time(), } return ProvenanceEnvelope(signature=_sign(fields, secret), **fields) def verify_and_gate(envelope: Optional[ProvenanceEnvelope], write_content: bytes, current_principal_role: str, trust_tier_map: dict, secret: bytes, max_age_seconds: float = 30.0) -> str: if envelope is None: raise ProvenanceEnvelopeError( "memory.write rejected: no provenance envelope; agent-asserted " "provenance strings are not attestable facts" ) fields = { "tool_identity": envelope.tool_identity, "canonical_key": envelope.canonical_key, "content_hash": envelope.content_hash, "principal_at_call": envelope.principal_at_call, "principal_role_at_call": envelope.principal_role_at_call, "issued_at": envelope.issued_at, } expected = _sign(fields, secret) if not hmac.compare_digest(expected, envelope.signature): raise ProvenanceEnvelopeError( "envelope signature invalid; provenance facts were tampered with " "between tool-invocation and memory-write boundaries" ) if hashlib.sha256(write_content).hexdigest() != envelope.content_hash: raise ProvenanceEnvelopeError( "content hash mismatch: written bytes differ from fetched bytes; " "agent may have re-serialized untrusted content" ) if time.time() - envelope.issued_at > max_age_seconds: raise ProvenanceEnvelopeError( "envelope expired; principal state may have changed since issuance" ) if current_principal_role != envelope.principal_role_at_call: # Monotonicity: role may only narrow across the two boundaries. raise ProvenanceEnvelopeError( f"principal role changed between boundaries " f"({envelope.principal_role_at_call} -> {current_principal_role}); " f"write must be re-evaluated against the narrower role, not silently allowed" ) tier = trust_tier_map.get(envelope.canonical_key) if tier is None: raise ProvenanceEnvelopeError( f"canonical_key {envelope.canonical_key!r} absent from trust-tier map; " f"defaulting is forbidden—unmapped provenance is untrusted by construction" ) return tier ```