arXiv:2610.27700cs.CLOct 2026

Manuscript Offprint

arXiv:2610.27700

Memory as Code: Declarative Retrieval over Codified Long-Term Memory

Aoting Zeng, Yuxin Du, Jianwei Wang, Yizhang He, Shan Jiang, Xuemin Lin, Kai Wang

ABSTRACT

In long-term memory systems, memories are constructed from interaction histories and retrieved in response to queries, enhancing the reasoning ability of LLM agents. In complex scenarios, facts are scattered across sessions and their relationships evolve over time, making it difficult for existing memory systems to compose them to adapt to diverse queries. Motivated by the modularity and composability of code, we propose Memory as Code (MaC), a unified memory framework that jointly designs memory construction and retrieval through a shared code abstraction. MaC couples codified construction, which establishes executable memory abstractions, with declarative retrieval, which translates queries into structured retrieval programs. Specifically, codified construction builds a three-layer executable memory structure that progresses from an atomic function layer, through a relational layer, to a modular composition layer. Declarative retrieval recasts retrieval from relevance-based fact selection into declarative query processing over memory. Experiments on LOCoMo and LONGMEMEVAL show relative gains of up to 15.91% in overall LLM-judge accuracy over the strongest baseline in each setting, while substantially reducing token consumption, highlighting the effectiveness of memory as code for long-horizon memory tasks.

1 INTRODUCTION

Long-term memory enables Large Language Model (LLM) agents to retain and use information across interactions, supporting personalized assistance and long-horizon tasks (Zhong et al., 2024; Park et al., 2023). A memory system Xu et al. (2026a); Packer et al. (2023) comprises memory construction, which organizes interaction histories into memory data, and memory retrieval, which processes memory queries over memory data. For memory construction, MemoryOS (Kang et al., 2025) organizes dialogue into topic segments and summaries, Mem0 (Chhikara et al., 2025) consolidates facts through update operations, and A-Mem (Xu et al., 2026b) constructs dynamically linked memory notes. These methods support memory organization and maintenance, but provide limited support for encapsulating computations over stored facts for reuse across queries. For memory retrieval, existing approaches combine search with contextual or relational expansion to gather relevant evidence (Borgeaud et al., 2022; Liu et al., 2023), using either predefined pipelines (Han et al., 2024; Rasmussen et al., 2025) or agentic workflows (Yao et al., 2022; Li et al., 2025; Ji et al., 2026). However, predefined pipelines offer limited flexibility for diverse queries, whereas stepwise agentic methods achieve this flexibility through repeated LLM planning, incurring additional inference overhead (Kim et al., 2023; Tan et al., 2025).

The above observations motivate a joint design in which memory construction encapsulates reusable computations over stored facts, and retrieval composes them for each query while reducing the need for repeated planning. Code provides a suitable foundation: shared references preserve consistent fact identities, functions expose reusable computations through explicit interfaces, and programs specify their composition and conditional branches before execution begins. This leads to a code-

(i) Construction

Facts

F1 · Mar 2023: Alex had a work gap due to a vacation

F2 · Jun 2023: Alex was off work with the flu.

F3 · Sep 2023: Alex took leave to attend a wedding.

Similarity-based

Graph-based

[0.12 ... 0.09]

[MemoryOS]

[0.67 ... 0.42]

[Mem0]

[A-Mem]

[MRAgent]

MaC: Code-based

vacation_f1()

sick_leave_f2()

wedding_leave_f3()

def gap_count():

events = [vacation_f1(), sick_leave_f2(),

wedding_leave_f3()]

return len({e.id for e in events})

Figure

(ii) Retrieval

Fixed flow [MemoryOS, A-Mem, Mem0]

Search: work gap

Keyword mismatch may omit events.

F1

F2, F3 missed

Count

1 gap

Question

How many work

gaps has Alex had?

Stepwise [MRAgent]

LLM

Search gap: F1

LLM

Search illness: F2

LLM

Count

2 gaps

Repeated planning; stops before wedding leave.

F3 missed

MaC

Execute query-specific program

answer = gap_count()

3 gaps

Declarative retrieval

F1 + F2 + F3

(a)

LLM-Judge Accuracy (%)

90

MaC

MRAgent

Mem0

A-Mem

LongMemEval

10

LLM-Judge Accuracy (%)

90

MaC

MRAgent

Mem0

A-Mem

Token Consumption (log scale)

(b)

Figure 1: (a) An example illustrating the limitations of relevant methods. (b) MaC achieves the highest LLM-judge accuracy with the lowest token consumption among the compared methods on both LoCoMo and LONGMEMEVAL.

centric formulation in which memory is a library of callable computations and retrieval is a query-specific program over that library.

However, achieving these goals through a shared code abstraction poses two challenges: (1) How can interaction histories be transformed into executable memory code? Facts expressed across sessions may overlap, supplement one another, or supersede earlier states, distinctions that are not automatically resolved by encoding facts as functions. Preserving consistent fact identities and distinguishing current from historical states is a key challenge. (2) How can retrieval compose memory code to accommodate diverse queries? Relevant functions alone do not specify how their outputs should be combined, and subsequent operations may depend on intermediate results. Capturing these dependencies and conditional continuations in a complete retrieval program while reducing repeated LLM planning is another key challenge.

To address these challenges, we propose Memory as Code (MaC), a framework that represents long-term memory as executable code and retrieves information through query-specific programs. The framework comprises two components: (1) codified construction transforms facts extracted from interaction histories into a three-level executable memory structure. The atomic function layer encodes facts as functions with canonical identifiers and source references; the relational layer connects fact functions through explicit supersession relations while retaining historical evidence; and the modular composition layer composes base functions into reusable current-state and history computations. A compact memory index exposes function capabilities, arguments, and available operators for retrieval. (2) Declarative retrieval interprets each query as a high-level specification and compiles it into a complete retrieval program in one LLM planning call. Using the memory index, the program selects and composes the required memory computations, specifying operator arguments, dependencies, and conditional continuations. An executor checks and runs the program, following predefined branches based on intermediate results and assembling supporting evidence without stepwise LLM planning during successful execution. The two components work together through the memory index and a common evidence representation. The index connects constructed capabilities to query requirements, while the evidence representation supports result composition and source tracing. As illustrated in Figure 1, this design connects facts distributed across sessions through reusable functions to answer the query.

Our main contributions are as follows:

• We study long-term memory for LLM agents to support reasoning over evolving information across interactions. We propose Memory as Code (MaC), a framework that uses a shared code abstraction to connect memory capabilities with query-specific composition.

• We develop two complementary techniques: codified construction organizes facts, their evolving relations, and reusable computations in a three-level executable memory structure with consistent state semantics and source provenance; declarative retrieval compiles each query into a complete retrieval program that selects and composes these capabilities in one LLM planning call.

• Extensive experiments on widely used memory benchmarks show that MaC achieves the highest overall LLM-judge accuracy in all four evaluation settings, improving over the strongest baseline by up to 15.91% on LoCoMo and 9.06% on LONGMEMEVAL. Ablation studies further support the benefits of both techniques.

a) Codified Construction

Figure

Figure 2: Overview of MaC. (a) Codified construction extracts atomic facts from dialogue history and builds a code library of fact functions, relations, derived functions, and concept and session views, along with an interface index that maps views to function identifiers (view index), identifiers to callable entry points (function index), and lists available memory operations (operators index). (b) Declarative retrieval passes the question and indexed interfaces to an LLM planner, which generates a retrieval program; after checking, an executor runs the program over the library to assemble supporting evidence for the answer LLM.

References (22)