Memory Writes Need Authorization: Building a Quarantine-First Boundary for AI Agents
An AI agent's long-term memory can turn untrusted text into future decisions. Design a quarantine-first write boundary with tenant-scoped provenance, deterministic promotion rules, safe retrieval, multi-session attack tests, and auditable rollback.
On this page
Long-term memory is often introduced as a productivity feature: persist useful details so an assistant does not have to rediscover them in every conversation. But persistence changes the security model. A document that would have been untrusted input for one request can become reusable context for many later requests.
That is the boundary I want to design around. A model may propose a memory, but it should not be able to authorize that memory for future use. Those are different responsibilities.
This article describes a *hypothetical* engineering-operations assistant. It reviews service tickets, internal change records, and vendor documentation, then helps engineers prepare maintenance plans. Some of those sources are authoritative within their proper scope; others are merely useful context. If a vendor document claims that an internal production approval is no longer required, the assistant may record that the document makes the claim. It must not turn the claim into an operating rule.
The design here is an architectural proposal and illustrative code, not a report of deployed behavior, security certification, or measured performance. It goes further than my earlier posts on the data model for agent memory, memory lifecycle management, and prompt-injection containment. The focus is the promotion decision between storing a source observation and letting an agent rely on a persistent memory.
Persistence creates a second trust transition
In a stateless application, an untrusted document enters one request, influences an answer if the system is vulnerable, and then leaves the active context. Persistent memory adds a second path:
~~~text Source arrives Another session, perhaps days later | | v v Authenticated ingestion User request | | v v Source-bound observation Scoped memory query | | v v Candidate memory Eligibility gate | | v v Deterministic policy ------> Approved memory projection | (data, never instructions) | | +----+-----------+ v | | Agent reasoning quarantine promote | | | v verify/expire versioned store Action authorization ~~~
The important boundary is not the database insert itself. Teams may need to retain an untrusted observation for investigation. The boundary is *promoting* it into the subset of memories that future sessions may act upon.
A useful distinction is:
- Observation: A source said something. It is not necessarily true.
- Candidate: A model or parser suggests that the observation may be useful later.
- Approved memory: An independently authorized rule says this fact is eligible for a specific type of future use.
- Authoritative state: The actual policy, permission, configuration, or business record in its owning system.
Approved memory is still not authoritative state. For example, a remembered maintenance window may help draft a plan, but a production deployment must consult the current release-control system before proceeding.
Security research supports treating this as more than a prompt-formatting issue. The paper From Untrusted Input to Trusted Memory studies attack paths that turn ordinary inputs into persistent influence. Hidden in Memory evaluates delayed effects after memories are written and later retrieved. These are research results about evaluated systems, not measured results for the architecture proposed here.
Decide what memory is allowed to mean
I would not use one generic "trust score" to authorize every memory. Whether a fact is usable depends on *its purpose* and *who has authority over that purpose*.
For an engineering-operations assistant, a starting policy can look like this:
| Proposed memory | Permitted durable treatment | Source of authority |
|---|---|---|
| A user's stated display preference | Save within that authenticated user's scope | Direct, authenticated user action |
| A service ticket's reported symptoms | Store as a source-bound observation | Ticket record, not the model's summary |
| A verified incident resolution | Promote a factual summary with an evidence reference | Approved internal incident record |
| A vendor page's deployment instructions | Quarantine as external advice | Never the vendor page alone |
| A statement changing production approval rules | Do not promote into agent memory | Current, independently verified policy service |
This is a product-specific policy, not a universal classification. The critical property is that the model cannot elevate a source's authority by wording its proposal confidently.
It also prevents a subtle mistake: authenticity is not truth. A content hash can demonstrate that stored bytes match earlier bytes. A valid source URL can identify where content was fetched. Neither proves the claims in that content are correct, current, authorized, or applicable to the current tenant.
A memory record should carry evidence and state
A useful data model separates the proposed claim from its supporting evidence and its activation state. The following TypeScript types are intentionally small enough to inspect during a code review:
~~~typescript type Origin = | "direct_user" | "approved_internal_tool" | "external_document";
type Kind = "preference" | "observation" | "policy_claim"; type Status = "quarantined" | "approved" | "rejected" | "revoked";
type MemoryCandidate = Readonly<{ id: string; tenantId: string; subjectId: string; kind: Kind; claim: string; origin: Origin;
sourceRef: string; // Immutable evidence locator, not an arbitrary URL. sourceDigest: string; // Digest of the exact evidence bytes. capturedAt: string; // Obtained from the ingestion service. status: Status; revision: number; }>;
type PromotionContext = Readonly<{ tenantId: string; actorId: string; actorRole: "user" | "reviewer" | "service"; sourceVerified: boolean; // Result from a trusted verifier. policyRevision: string; }>;
type PromotionDecision = | { outcome: "promote"; policyRevision: string } | { outcome: "quarantine"; reason: string } | { outcome: "reject"; reason: string }; ~~~
The client must not be able to submit privileged fields such as origin, authenticated actor, verifier result, or policy revision and have the server accept them at face value. Derive those fields from authenticated ingestion, trusted service configuration, and an independent verification workflow.
Treat the proposed claim as data even when the text looks like an instruction. Do not insert it into a system or developer message. The agent might use a selected memory as supporting context, but privilege still belongs to the application layer.
Implement promotion as a deterministic authorization decision
The first gate should be intentionally boring. It checks scope, source eligibility, actor authority, and memory kind. An LLM classifier may help *triage* suspicious candidates, but it should never be the only entity that decides promotion rights.
~~~typescript export function decidePromotion( candidate: MemoryCandidate, context: PromotionContext, ): PromotionDecision { if (candidate.status !== "quarantined") { return { outcome: "reject", reason: "invalid_state" }; }
if (candidate.tenantId !== context.tenantId) { return { outcome: "reject", reason: "tenant_mismatch" }; }
if (!candidate.sourceRef || !candidate.sourceDigest) { return { outcome: "reject", reason: "missing_evidence" }; }
if (candidate.kind === "policy_claim") { return { outcome: "reject", reason: "policy_has_external_owner" }; }
if (!context.sourceVerified) { return { outcome: "quarantine", reason: "source_not_verified" }; }
if (candidate.kind === "preference") { if ( candidate.origin === "direct_user" && context.actorRole === "user" && candidate.subjectId === context.actorId ) { return { outcome: "promote", policyRevision: context.policyRevision, }; } return { outcome: "quarantine", reason: "not_subject_authorized" }; }
if ( candidate.kind === "observation" && candidate.origin === "approved_internal_tool" && context.actorRole === "service" ) { return { outcome: "promote", policyRevision: context.policyRevision, }; }
return { outcome: "quarantine", reason: "requires_review" }; } ~~~
This is a pure decision function, not the whole persistence service. A production handler must also validate the input schema, authenticate the caller, verify the evidence against a trusted source, enforce subject-level authorization, and write the decision atomically. The example assumes those checks return trustworthy fields; it does not make an unsafe caller trustworthy by itself.
I would store the decision in the same database transaction that changes the candidate's state. Use optimistic concurrency on the record revision so an approval cannot quietly attach to a changed claim. The transaction should record the candidate ID, exact source digest, policy revision, decision, actor, and timestamp.
For a high-impact approval, the reviewer should see the *source evidence and candidate diff*, not just a fluent model-generated explanation.
Keep the storage boundary independent of the agent
A common implementation shortcut is to hand the model a general-purpose memory upsert tool. That allows a document's persuasive text to influence both the proposed fact and its durable persistence.
I prefer three application-owned operations:
- Submit candidate. Any permitted workflow can propose a memory, but this operation only writes to an isolated candidate collection.
- Promote or reject. A trusted service evaluates source-specific policy, or routes the candidate to an authorized reviewer. The model does not receive the promotion credential.
- Retrieve approved projection. The runtime only sees authorized, current, approved memories needed for the request.
The backing store should make accidentally bypassing these rules difficult. In PostgreSQL, use separate roles for ingestion and promotion, deny candidate writers the ability to update approved rows, and scope queries at the database layer. PostgreSQL row-level security can help enforce tenant and actor constraints, but application roles that own tables or bypass RLS must be handled carefully. RLS is defense in depth, not a substitute for end-to-end authorization.
LangGraph distinguishes thread-scoped checkpoints from cross-thread stores in its persistence documentation. That distinction matters here: a thread's recent working context and a long-lived, cross-session memory store should not inherit identical write privileges simply because they are both called "memory."
Retrieval needs a second, purpose-specific gate
Even an approved memory can be wrong for the current request. The content may have expired, the subject may differ, an approval may have been revoked, or the action may require a live authoritative read.
A retrieval adapter can make those constraints explicit before the model receives anything. Here is a small Python policy function that operates on already fetched records:
~~~python from dataclasses import dataclass from datetime import datetime, timezone from typing import Literal
Purpose = Literal["draft", "execute"]
@dataclass(frozen=True) class ApprovedMemory: tenant_id: str subject_id: str state: str expires_at: datetime | None permitted_purposes: frozenset[str] superseded: bool
@dataclass(frozen=True) class RequestScope: tenant_id: str subject_id: str purpose: Purpose now: datetime
def eligible(memory: ApprovedMemory, scope: RequestScope) -> bool: if memory.tenant_id != scope.tenant_id: return False if memory.subject_id != scope.subject_id: return False if memory.state != "approved" or memory.superseded: return False if memory.expires_at is not None: expiry = memory.expires_at if expiry.tzinfo is None: return False # Reject ambiguous naive timestamps. if expiry <= scope.now: return False return scope.purpose in memory.permitted_purposes
now = datetime.now(timezone.utc) scope = RequestScope("tenant-a", "service-42", "draft", now) candidate = ApprovedMemory( tenant_id="tenant-a", subject_id="service-42", state="approved", expires_at=None, permitted_purposes=frozenset({"draft"}), superseded=False, )
assert eligible(candidate, scope) assert not eligible(candidate, RequestScope( "tenant-b", "service-42", "draft", now )) assert not eligible(candidate, RequestScope( "tenant-a", "service-42", "execute", now )) ~~~
This is a post-fetch policy example, not an argument for fetching every tenant's memory and filtering afterward. Tenant isolation must already be enforced in the storage query and credentials. The function supplies an additional safeguard before context construction.
Notice that a remembered observation can be eligible to help *draft* a maintenance plan yet ineligible to *execute* it. That is deliberate. A durable memory should not become a deployment authorization token.
For the action layer, use a separate policy gate that checks the current authenticated user and the current system state. I explain that boundary in AI agents and action authorization.
The failures I would expect to find in a real review
Authority laundering through summaries. An external document is summarized by a trusted-looking assistant, and a later component labels the summary as an internal source. The original evidence label must travel through every transformation. A new summary does not create a new authority.
Revision races. A reviewer approves a candidate while an ingestion worker updates its text. Bind approval to the exact digest and candidate revision, and fail closed on mismatch.
Approval without expiration. An operational fact remains approved after its source changes. Record source versions; revoke or revalidate when the owning system emits an update. A time-to-live is a fallback for freshness, not proof of current truth.
Cross-tenant retrieval. A similarity index retrieves an excellent match from another customer. Namespace conventions are not enough if callers can choose namespaces freely. Require server-derived scope and test the data layer with separate tenant credentials.
Dormant malicious content. A harmless-looking note becomes relevant only after several subsequent interactions. Tests that stop immediately after ingestion miss this. Run attack scenarios across sessions and exercise both retrieval and action eligibility.
Cleanup without a paper trail. Deleting the visible memory record may not remove derived summaries, vector embeddings, caches, or downstream copies. Keep lineage so a revocation can invalidate every projection; observe deletion and privacy-retention requirements separately.
Detector overconfidence. A classifier will miss some payloads and flag some legitimate facts. Its job is to surface risk, not to bypass hard authorization rules.
The OWASP AI Agent Security Cheat Sheet explicitly identifies memory poisoning as a risk and recommends memory validation, isolation, and agent security testing. I would treat those as baseline controls and make the actual trust transition visible in application code.
Test the write now and the consequence later
A useful security regression suite models *two different points in time*:
- Ingestion phase: Supply a crafted external ticket, web page, or tool result. Check what candidates were created, which source identities they retained, and whether any were promoted.
- Subsequent phase: Start a clean conversation under the same permitted scope. Ask an ordinary task that might retrieve the planted statement. Check whether the agent used it as evidence or as an instruction.
- Action phase: Attempt the consequential operation. Verify that the independent authorization service still requires current authoritative state.
The adversarial cases should include a source that falsely claims internal authority, a forged tenant identifier inside document text, an innocuous-looking statement that becomes dangerous only on later retrieval, a changed source revision after approval, and a compromised document that tries to make the agent remember a new operating policy.
I would explicitly test at least one legitimate control case for each attack. Otherwise a system that never stores any memory could appear "secure" by simply becoming useless.
Measure the pipeline separately rather than collapsing it into a single accuracy number:
| Signal | What it answers |
|---|---|
| Candidate-to-approved rate, segmented by origin | Are outside sources being promoted unexpectedly? |
| Unsupported promotion count | Did any approval lack qualifying evidence? |
| Delayed unsafe-action rate on adversarial test cases | Did a stored payload influence a later consequential action? |
| Cross-tenant exposure count | Did a memory cross a forbidden scope boundary? |
| Revocation propagation lag | How long until a withdrawn memory stops appearing in active projections? |
| Legitimate-memory recall and false-quarantine rate | Are controls destroying useful continuity? |
For consequential workflows, unauthorized promotions and cross-tenant exposures should be treated as security events, not just dashboard trends. Exact alert thresholds require real workload data and an explicit risk budget; there is no defensible universal percentage to insert here.
The memory-poisoning study and MPBench offer a research direction for constructing adversarial scenarios. My existing piece on multi-turn agent evaluation explains why end-to-end tests must reach beyond a single interaction.
Trade-offs worth making explicit
A quarantine-first boundary introduces latency, review cost, and more stored evidence. It can also create false rejections. Those are genuine product costs, particularly in a low-risk personal assistant where a mistaken preference is easily corrected.
I would vary the gate by consequence. A direct user's cosmetic preference may be eligible for automatic promotion with a clear delete control. A fact extracted from an untrusted website may remain an observation. A statement that would change spending, permissions, deployment approvals, or compliance behavior should never gain authority through long-term memory alone.
There is also a privacy cost: lineage and audit logs can retain information that the user expects to forget. Keep access restricted, redact sensitive payloads in telemetry, define retention periods, and implement deletion that reaches derived indexes. Auditability does not justify keeping private data forever.
Finally, do not overbuild. If your agent has no cross-session memory, there is no reason to add a memory approval service just to look sophisticated. The boundary becomes worthwhile when a statement from one session can affect a later session, user, or tool action.
A release checklist I would use
Before enabling persistent memory for a tool-using agent, I would require:
- A documented list of which memory classes exist and which sources can authorize each one.
- Server-derived tenant, actor, and source identity; no trust elevation from document text.
- A candidate state separate from the approved projection.
- Revision-bound approvals and revocation that propagates to caches and indexes.
- A read gate that enforces scope, validity, and permitted purpose.
- An action gate that consults current authoritative state for consequential operations.
- Multi-session attack tests alongside legitimate-memory regression cases.
- Operational signals and a documented incident procedure for poisoned-memory containment.
The engineering principle is simple: remembering a statement is not permission to believe it, and believing it is not permission to act on it. A durable memory system needs explicit boundaries for all three.
Sources and related reading
- OWASP — AI Agent Security Cheat Sheet
- Dash et al. — From Untrusted Input to Trusted Memory: A Systematic Study of Memory Poisoning Attacks in LLM Agents
- Pulipaka et al. — Hidden in Memory: Sleeper Memory Poisoning in LLM Agents
- LangGraph — Persistence and long-term stores
- PostgreSQL — Row Security Policies
KEEP READING
Related engineering notes
A Failover Route Is Not a Recovery Path: Proving Independence in AI Infrastructure
Two LLM providers can share the same failure domain. Build an evidence-backed recovery graph that checks cloud, networking, identity, control-plane and capacity dependencies before admitting fallback routes, then test correlated outages without weakening safety.
Read articleAn Eval Platform Sunset Can Erase Your Release Evidence: Build an Evidence-Escrow Migration Gate
When a hosted LLM evaluation platform retires, switching runners is not enough. Preserve the historical evidence, reconstruct grader semantics, validate scoring parity, and enforce a fail-closed release gate that survives the service shutdown.
Read articleWhen the Package Runs Before Your App: Quarantining AI Framework Releases
The 2026 agent-framework PyPI compromise exposed a blind spot in AI build pipelines: Python startup hooks execute before application imports. Design an artifact-quarantine gate, inspect wheels without installing them, separate credentials, and recover from suspected exposure.
Read article