Memorydoc/{zh,en}/design/runtime/memory.md

Memory: A Plugin That Recalls and Remembers

Status: 2026-11-16. Built: the first-party plugin memory (plugins/memory, P12), available but off until configured; see section 9 for what it does and what is left. Also built: eve

Status: 2026-11-16. Built: the first-party plugin memory (plugins/memory, P12), available but off until configured; see section 9 for what it does and what is left. Also built: everything it relies on, namely the context, tool, observer, and service roles, Env.DataDir, BackgroundHost.Chat and Embed, and CallContext (pkg/plugin/roles.go, pkg/plugin/registry.go, internal/host/engine). The Agent Runtime has no memory module and needs no change for Memory (owner decision, 2026-11-13).

Memory enters context through the unified entry of retrieval (P46): recall through the context role with context_from limits and group-chat visibility, search through its tools.

1. Responsibility and Boundaries

Three kinds of state are kept apart:

StateWhat it isOwnerLifetime
Working contextThe messages of one runThe agent's checkpointOne run
Conversation historyEarlier succeeded runs, passed as RunInput.HistoryHost (runs table)The Host's retention
Durable MemoryFacts, preferences, episodes, and procedures that outlive runsA Memory plugin, in its data directoryUntil forgotten

A Memory plugin decides what to recall, how items are stored, indexed, merged, and forgotten. The agent only places what the context role returns before the input, and offers the plugin's tools to the model like any other tools. A checkpoint is not Memory, and Memory is not a way to resume a run.

2. One Plugin, Three Roles

yaml
1plugins:
2  - id: memory
3    plugin: memory                 # proposed first-party plugin
4    uses: [kimi]                   # model for extraction in the background
5    config: {extract_from: input, personal_in_groups: false}
6  - id: agent
7    plugin: agent
8    uses: [kimi, localenv, memory]
9    config: {model: kimi}
RoleMethodPathWhen
contextContext(cc, ContextInput)RecallOnce at Turn start, before the first model call; 5 s timeout; a failure leaves Memory out of that run
toolTools(cc), Invoke(call, host)Search, save, forget on the model's requestWhenever the model calls them; through the ledger, guards, and approvals
observerObserve(ev, BackgroundHost)Learn from finished runsAfter each run is committed (run.finished), from a durable cursor, at least once

The plugin keeps its store in Env.DataDir, a private directory that survives restarts and that no other instance can use. Its tools appear to the model with plain names; the proposed set is memory_search, memory_save, and memory_forget. Two instances offering the same tool name are refused by the Host, so an agent has at most one Memory writer for model-requested writes.

3. Kinds and Scopes

KindContentTypical use
ProfileWho the user or group is; standing preferencesReturned first by every recall
SemanticFacts about people, projects, systemsRecalled when relevant
EpisodicWhat happened in earlier runs, as short summaries with the run idRecalled or searched
ProceduralHow a recurring task is doneProposed to the operator as a skill; never installed by the plugin
ScopeKeyed byTaken from
UserPrincipal.UserCallContext or ObservedEvent.Principal
ConversationConnection and Conversation.IDThe same
SharedThe instance itselfEveryone the instance's scope lets in

Scopes come only from the CallContext the Host fills or from the ObservedEvent it delivers, never from tool arguments or message text. Keying by User lets one user's linked accounts share Memory. In a group conversation, or a session several people share (a conversation a second person posted in; CallContext.Shared, review #264 B10), person-scoped items are not recalled unless the config sets personal_in_groups: true, so one person's Memory is not shown to the others. Which people and conversations may use the plugin at all is the instance's scope.

4. The Memory Item

FieldMeaning
id, version, supersedesStable identity and history; an update writes a new version
kind, scopeAs in section 3
contentText
sourceThe run id, and the tool call key or observed event id that produced it
originuser_stated (taken from the user's input), agent_written (saved by the model, or extracted from an answer), or edited (changed by a person in the data directory)
observed_at, valid_untilWhen it was learned; a contradicted fact is closed, not deleted

origin is set by the plugin from the path the content took, never by the model. The model's tool arguments cannot claim user_stated.

5. Recall

The context method receives the latest user text and locale. It returns at most a few items under a size limit: profile items first, then the best matches for the text, each with the date it was learned (an ISO date in the Host's time zone since 2026-12-04, context refactor slice 3: "3 days ago" was wrong the next day in a request kept or cached). The agent places them in the reference message, introduced as information and not instructions (Context, section 2), so recalled Memory can never grant a permission or change a rule. Items are recalled once per run; a resumed attempt reuses them from the checkpoint.

Search beyond that is agentic: the model calls memory_search when it decides to, and the result is an ordinary tool result with the agent's size cap.

The first plugin uses keyword search over human-readable files, which is inspectable and the baseline to evaluate other backends against. A vector backend embeds through the Host: BackgroundHost.Embed in its observer and service, with a model instance that implements Embedder in its uses. Because Context receives no host, a backend that needs to embed the query at recall time keeps the BackgroundHost its Service.Serve received; if that proves awkward, giving Context a host is a contract change that needs an ADR.

6. Writes

PathTriggerProperties
Explicit saveThe model calls memory_save, usually because the user asked it to remember somethingAn ordinary tool call: guards, approvals, and the ledger apply; the plugin also deduplicates by ToolCall.Key
Learning from runsrun.finished with Input, Output, Principal, and ConversationIn the observer, outside the run: extracts candidates with BackgroundHost.Chat, merges duplicates, closes contradicted items; idempotent by event id
ForgettingThe model calls memory_forget at the user's requestRemoves the item and everything derived from it in the plugin's store, and says what it removed
Direct editA person edits the files in the data directoryPicked up as edited

Rules:

  • ◆One store per instance. Each Memory instance writes only its own data directory; two instances never hold copies of one item.
  • ◆Learning is versioned. A learning pass writes new versions and keeps the previous ones, or changes nothing.
  • ◆Only the user's words by default. With extract_from: input (the default) the observer learns only from ObservedEvent.Input. Answers may repeat content from web pages and tools, so extracting from Output is opt-in and its items are agent_written.
  • ◆An explicit save fixes the scope. When memory_save stored anything during the run, in any scope, the observer learns nothing from that run (memory.learn_scoped, reason saved_in_run): a personal copy would undo a memory kept "for this chat only" (Feishu report #61).
  • ◆The run never waits. Observers run after the run is committed; a slow or failing observer delays nothing. A new observer starts at the current position and does not see older runs.

A run no person waited for (a schedule's, a takeover's, a local MCP client's) is marked unattended in its run.finished data, and Memory does not learn from it: a schedule firing every five minutes cost an extraction call each time (Feishu #383). The observer sees each run's input and final text, not its tool calls; P11 (ObservedEvent types model.called and tool.called) would add those. The cut point of compaction (P5) needs no Memory hook: the full run still reaches the observer as run.finished.

7. Safety and Governance

  • ◆Recalled Memory is material. It enters as reference, cannot instruct the model, and cannot cause a tool call that a rule, guard, or approval would refuse.
  • ◆Secrets stay out. The Host never passes credentials to a context, tool, or observer call. The plugin redacts obvious secrets before writing; per-user tokens belong in Caller.GetSecret, not in Memory.
  • ◆Staleness is visible. Recall shows the date an item was learned; a superseded item is not recalled.
  • ◆No leakage across people. Scope comes from the Host (section 3); a tool never accepts a person or conversation from its arguments.
  • ◆Every write is attributable. Each item records its run and its origin, and model-requested writes are in the tool ledger.
  • ◆Children start clean. A delegated child (P8) receives no recalled Memory, and the Memory tools only if its subagents entry lists them.

8. Acceptance

Required for P12:

  • ◆The plugin is added and replaced with no change to internal/host, pkg/plugin, or plugins/agent.
  • ◆Recall that passes the 5 s timeout is left out and the run completes.
  • ◆A person's Memory is not recalled in another person's run, nor in a group conversation under the default config.
  • ◆A save repeated with the same key creates one item, also across a Host restart.
  • ◆With extract_from: input, text that only appeared in an answer or a tool result is never stored.
  • ◆memory_forget removes the item from recall and from memory_search.
  • ◆A restarted Host delivers each run.finished to the observer at least once, and the store holds one result per event.

Open items: the size limit of recall, the extraction prompt, the file layout of the store, how procedural items are proposed as skills, and the benchmark set used to compare backends.

9. The First Plugin (2026-11-16)

yaml
1  - id: memory
2    plugin: memory
3    uses: [kimi]                  # the model that learns; without config.model it only keeps saves
4    grants: [conversation]        # without it the observer receives no input and learns nothing (P11)
5    config: {model: kimi, extract_from: input, personal_in_groups: false, recall_chars: 2000}
Open itemDecision in the first plugin
File layoutOne indented JSON file per scope in Env.DataDir: user-<user>.json and conversation-<digest>.json, each a list of item versions with the fields of section 4 (supersedes is implied: the versions of an item share its id). Writes replace a file atomically. A current item whose content no longer matches its digest was edited by a person and becomes a new version with origin edited.
Recall sizerecall_chars (default 2,000), and never more than the Budget the Host passes (P46). One reference item per scope: the user's with visibility person, the conversation's with conversation; each line carries the item's id and the date it was learned, and, for a conversation memory recalled in a thread, the thread that saved it: this thread, saved in another thread <id>, or thread unknown for one saved outside a thread or before threads were recorded (source.thread, 2026-11-29, Feishu #277), so a request limited to its thread can leave the others out.
SearchKeyword search: lower-case words, inflections by a shared prefix of at least four letters, and Han text as character bigrams; score is the share of query tokens found. Recall puts profile items first; memory_search lists only matches.
Extraction promptplugins/memory/learn.go: at most five items per run, as JSON, with the user's current items listed so a correction names the item it replaces; temperature 0.
Toolsmemory_search{query, limit}, memory_save{content, kind: profile|semantic, scope: user|chat, replaces}, memory_forget{id}; a save repeated with the same call key, or with the same content, writes nothing.
SecretsAPI keys, tokens, bearer headers, and values after password/token/secret/api_key/密码/口令 are replaced with [redacted] before anything is stored or sent to the learning model.

Not built: the shared scope, procedural items proposed as skills, vector backends, and a benchmark set. Learning writes into the user scope only.

Verified: unit tests in plugins/memory for the acceptance list of section 8 except the 5 s timeout (Host behaviour, tested in internal/host/engine); live over the console with glm-5.3-flash (console-agent-memory in veruqelo): a fact saved with memory_save was answered again after /new. No change to internal/host, pkg/plugin or plugins/agent was needed for the plugin itself.