MAGE: Safeguarding LLM Agents against Long-Horizon Threats via Shadow Memory

Yuhui Wang, Tanqiu Jiang, Jiacheng Liang, Charles Fleming, Ting WangarXiv 2026

TL;DR

MAGE (Memory As Guardrail Enforcement) is a novel defense framework that protects LLM agents from complex, multi-turn attacks by maintaining a dedicated, security-focused "shadow memory." By distilling trajectory-level context and proactively auditing pending actions using reinforcement learning, MAGE thwarts long-horizon threats with minimal impact on agent utility and low computational overhead.

What Problem Does This Paper Address?

As Large Language Model (LLM) agents transition from simple chatbots to autonomous systems capable of executing multi-step workflows (e.g., searching files, managing emails, calling APIs), they become vulnerable to a dangerous new class of exploits: long-horizon threats.

Unlike traditional single-turn jailbreaks, long-horizon attacks—such as sequential tool-attack chaining (STAC) and persistent indirect prompt injection (PI2)—are stealthy. Every individual action taken by the agent might appear completely benign on its own. However, when stitched together over an extended interaction trajectory, their cumulative effect can be disastrous, leading to unauthorized data exfiltration, financial fraud, or compliance violations.

Figure 1: (a) Tool-chaining attack; (b) MAGE defends against long- horizon attacks by distilling and retaining safety-relevant context in shadow memory when evaluating the risks of potential actions.

Standard guardrails (like keyword filters or per-turn classifiers) fail here because they lack the context window to see the big picture, or their attention gets diluted over long interactions.

Methods

Inspired by the "shadow stack" concept in systems security—which keeps a isolated copy of return addresses to prevent control-flow hijacking—the authors introduce MAGE. MAGE runs a parallel, security-centric memory layer alongside the agent's standard working memory.

MAGE consists of two primary components instantiated on a single, cost-effective local LLM (e.g., Qwen3-4B):

  1. Memory Manager ($M$): At each turn $t$, it distills the raw interaction history into a compact, structured representation called the Shadow Memory ($m_t$), filtering out task-irrelevant noise while preserving security-critical signals.
  2. Judge ($J$): Before any proposed tool action ($a_t$) is executed by the agent, the Judge intercepts it and evaluates its risk against the current shadow memory state, deciding whether to approve or reject it.
Figure 2: (a) Architecture of MAGE: at each turn, the memory manager 𝑀updates security-critical context, and the judge 𝐽assesses the risk of the pending action. (b) Agentic workflow of 𝑀𝜃and 𝐽𝜃(with the same underlying LLM 𝜃) within MAGE. (c) Turn-wise RL procedure for optimizing 𝜃.

To train MAGE without breaking the agent's ability to complete benign tasks, the authors utilize a customized Turn-wise Group Relative Policy Optimization (GRPO) pipeline. Instead of using a single trajectory-level reward, they decouple the training of the Memory Manager and the Judge. The Memory Manager is optimized using a temporally-discounted correctness reward, ensuring it learns to retain early-stage indicators that might only become relevant several turns later.

Datasets

The authors evaluated MAGE across two distinct threat models using established benchmarks:

  • SHADE-Arena: Used to simulate user-as-adversary attacks via Sequential Tool-Attack Chaining (STAC). The dataset consists of 247 malicious and 88 benign tasks.
  • AgentDojo (Extended): Used to simulate environment-as-adversary attacks via indirect prompt injections (including short-horizon attacks like InjecAgent and long-horizon PI2 attacks) across Banking and Slack suites, totaling 7,682 test cases.

Key Insights and Ideas

  • Repurposing Agentic Memory for Security: While memory mechanisms in LLMs are traditionally engineered to improve task performance, MAGE demonstrates that memory can be explicitly optimized as a security primitive.
  • Trajectory-Level Intent vs. Turn-Level Actions: Malicious intent is an emergent property of the full execution path. By forcing the system to maintain a continuous security narrative, MAGE prevents the "context dilution" that allows long-horizon attacks to succeed.
  • Overcoming Myopic Updates: A naive reward system only grades the memory on the immediate next turn. MAGE’s temporally-discounted reward propagation ensures the memory manager values long-term causal relevance, capturing subtle, multi-step escalation chains.

Key Results

MAGE demonstrates exceptional defensive capabilities while remaining highly efficient:

  • Defeating Tool-Chaining (STAC): MAGE reduced the Attack Success Rate (ASR) from 100.0% to just 8.3%, while preserving 94.4% Benign Utility (BU).
  • Thwarting Indirect Prompt Injections (PI2): MAGE achieved a 0.0% ASR against adaptive long-horizon injections, maintaining utility on par with an undefended agent.
  • Low Latency & Overhead: MAGE detects the majority of attacks at or near the very first attack turn. Because it compresses the context into a compact shadow memory, it cuts token overhead significantly compared to raw trajectory inspection (consuming only ~2.9K to 7.0K extra tokens per task).
Figure 3: (a) Impact of attack horizon: without defense, ASR rises above 93% at ≥3 attack turns, while MAGE keeps ASR below 10% throughout. (b) Detection latency of MAGE: most attacks are detected at or immediately adjacent to the actual malicious actions.

Limitations and Future Work

While MAGE establishes a strong paradigm, the authors note several areas for expansion:

  1. Broader Attack Coverage: The evaluation focused on STAC and PI2; future work should test MAGE against other long-horizon behaviors like memory poisoning and goal drifting.
  2. Dynamic Schemas: MAGE currently relies on a fixed prompt schema (tracking user intent and known attack patterns). Developing dynamic, adaptive memory schemas could help it generalize to entirely novel attack vectors.
  3. Multi-Agent Systems: MAGE is currently designed for single-agent environments. Extending shadow memory architectures to coordinate security across decentralized, multi-agent networks remains an open challenge.

Summary updated

BibTeX
@misc{wang2026mage,
  author = {Yuhui Wang and Tanqiu Jiang and Jiacheng Liang and Charles Fleming and Ting Wang},
  title = {{MAGE: Safeguarding LLM Agents against Long-Horizon Threats via Shadow Memory}},
  year = {2026},
  eprint = {2605.03228},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2605.03228},
}
Figure