> ## Documentation Index
> Fetch the complete documentation index at: https://anthale.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# AI Memory Security Guide

> Prevent saved summaries, conversation state, and long-term memory from becoming a persistent prompt injection or data leakage path.

Use this guide when your system stores conversation summaries, user preferences, notes, plans, or reusable state. Memory is useful because it survives across requests. That is also what makes it dangerous when attacker-controlled content gets promoted into it.

## Assumptions

* Your application has a memory or state layer that can persist across model calls.
* You can control which events are allowed to write into that layer.
* Anthale can evaluate both the write path and the replay path around stored content.

## Secure the memory layer

<Steps>
  <Step title="Decide what is allowed into memory">
    Separate durable facts, short-lived task state, user preferences, and generated summaries. Not every useful string
    belongs in long-term storage.
  </Step>

  <Step title="Tag memory by source and trust level">
    Record whether the content came from a user, a retrieved document, a tool result, another agent, or a model summary.
    Provenance matters when you replay the memory later.
  </Step>

  <Step title="Evaluate before write and before replay">
    Run Anthale before content is persisted and again before saved content is merged back into model context. A clean
    write path does not guarantee a safe replay path forever.
  </Step>

  <Step title="Keep summaries from becoming policy">
    Store summaries as context, not as hidden instruction. A model-generated note should not silently upgrade itself
    into a higher-authority rule for future tasks.
  </Step>

  <Step title="Expire or review privileged memory">
    Put retention limits and review paths around memory that can affect access, workflow routing, or high-impact tool
    use.
  </Step>

  <Step title="Test for persistence attacks">
    Check whether one malicious note, summary, or retrieved chunk can keep influencing later sessions after the original
    trigger is gone.
  </Step>
</Steps>

<Warning>
  Persistent prompt injection is harder to spot than one-shot injection because the source often disappears from the
  current request while the bad instruction survives in stored state.
</Warning>

## What this looks like in code

<CodeGroup>
  ```python title="Python" theme={null}
  from os import environ

  from anthale import Anthale

  client = Anthale(api_key=environ["ANTHALE_API_KEY"])
  MEMORY_WRITE_POLICY_ID = environ["ANTHALE_MEMORY_WRITE_POLICY_ID"]
  MEMORY_REPLAY_POLICY_ID = environ["ANTHALE_MEMORY_REPLAY_POLICY_ID"]

  def sanitize_memory_write(entry: dict) -> dict | None:
  response = client.organizations.policies.enforce(
  policy_identifier=MEMORY_WRITE_POLICY_ID,
  direction="input",
  messages=[{"role": "user", "content": entry["content"]}],
  metadata={
  "boundary": "memory_write",
  "feature": "support-agent",
  "sourceType": entry["source_type"],
  "memoryKind": entry["memory_kind"],
  },
  )
  if response.action == "block":
  return None

      safe_content = response.redacted_messages[0]["content"] if response.action == "redact" else entry["content"]
      return {**entry, "content": safe_content}

  def build_memory_context(memory_entries: list[dict]) -> list[dict]:
  safe_context: list[str] = []
  for entry in memory_entries:
  response = client.organizations.policies.enforce(
  policy_identifier=MEMORY_REPLAY_POLICY_ID,
  direction="input",
  messages=[{"role": "user", "content": entry["content"]}],
  metadata={
  "boundary": "memory_replay",
  "feature": "support-agent",
  "sourceType": entry["source_type"],
  "memoryKind": entry["memory_kind"],
  },
  )
  if response.action == "block":
  continue

          safe_messages = response.redacted_messages if response.action == "redact" else [{"content": entry["content"]}]
          safe_context.append(safe_messages[0]["content"])

      return [{"role": "system", "content": "Saved memory:\n" + "\n".join(safe_context)}]

  ```

  ```text title="TypeScript" theme={null}
  import Anthale from "anthale"

  const client = new Anthale({ apiKey: process.env.ANTHALE_API_KEY })
  const MEMORY_WRITE_POLICY_ID = process.env.ANTHALE_MEMORY_WRITE_POLICY_ID!
  const MEMORY_REPLAY_POLICY_ID = process.env.ANTHALE_MEMORY_REPLAY_POLICY_ID!

  type MemoryEntry = {
    content: string
    memory_kind: string
    source_type: string
  }

  export async function sanitizeMemoryWrite(entry: MemoryEntry): Promise<MemoryEntry | null> {
    const response = await client.organizations.policies.enforce(MEMORY_WRITE_POLICY_ID, {
      direction: "input",
      messages: [{ role: "user", content: entry.content }],
      metadata: {
        boundary: "memory_write",
        feature: "support-agent",
        sourceType: entry.source_type,
        memoryKind: entry.memory_kind,
      },
    })

    if (response.action === "block") {
      return null
    }

    const safeContent = response.action === "redact" ? response.redacted_messages[0].content : entry.content
    return { ...entry, content: safeContent }
  }

  export async function buildMemoryContext(
    memoryEntries: MemoryEntry[],
  ): Promise<Array<{ role: "system"; content: string }>> {
    const safeContext: string[] = []

    for (const entry of memoryEntries) {
      const response = await client.organizations.policies.enforce(MEMORY_REPLAY_POLICY_ID, {
        direction: "input",
        messages: [{ role: "user", content: entry.content }],
        metadata: {
          boundary: "memory_replay",
          feature: "support-agent",
          sourceType: entry.source_type,
          memoryKind: entry.memory_kind,
        },
      })

      if (response.action === "block") {
        continue
      }

      const safeMessages = response.action === "redact" ? response.redacted_messages : [{ content: entry.content }]
      safeContext.push(safeMessages[0].content)
    }

    return [{ role: "system", content: `Saved memory:\n${safeContext.join("\n")}` }]
  }
  ```
</CodeGroup>

This keeps Anthale on both sides of the memory lifecycle: before the application saves the content and again before the
workflow replays it into model context.

## Common failure patterns

* A summary job copies user or tool text into memory without trust tagging.
* Long-term memory is replayed as if it were system instruction.
* Sensitive data is retained longer than the workflow requires.
* Teams protect the first request but not the later replay of stored state.

## Related deep dives

* [Advanced Prompt Injection Paths](/docs/learn/guardrails/prompt-injection/advanced-attack-paths)
* [Prompt Injection Impact Paths](/docs/learn/guardrails/prompt-injection/impact-paths)
* [Data Leakage Prevention](/docs/learn/guardrails/data-leakage)

## Next steps

Continue with [Log Security Events](/docs/learn/secure-ai-systems/log-security-events) or [Data Leakage Prevention](/docs/learn/guardrails/data-leakage).
