Serena Memory System
Overview
Serena's persistent memory subsystem is centered on src/…/memory_manager.py. Each project gets a MemoryManager from src/…/project.py, configured with the project's .serena data folder plus global and project-level read_only_memory_patterns and ignored_memory_patterns. Project memories are Markdown files below <project .serena>/memories; global memories are addressed by the reserved global/ topic and stored under SerenaPaths().global_memories_path. Memory names are logical slash-separated names, not raw paths: get_memory_file_path() strips a mistaken mem: prefix and .md suffix, normalizes OS separators to /, rejects .., absolute names, empty segments, and bare global, then maps the name to <name>.md under the project or global memory directory.
MemoryManager owns the filesystem behavior for loading, writing, editing, deleting, moving, and listing memories. load_memory(), save_memory(), delete_memory(), move_memory(), and edit_memory() all sanitize names and reject ignored memories before touching disk. Writes use write_file_atomic() with SERENA_FILE_ENCODING; list operations discover every *.md file with os.walk(..., followlinks=True) so symlinked memory subtrees are visible. Read-only patterns are enforced only when is_tool_context=True, which is how agent-facing tools enter through src/…/mem_api.py and src/…/memory_tools.py; CLI commands in src/…/cli.py pass is_tool_context=False and can perform administrative writes, including read-only memories.
Memory tools are thin API wrappers. WriteMemoryTool, ReadMemoryTool, ListMemoriesTool, DeleteMemoryTool, RenameMemoryTool, and EditMemoryTool in src/…/memory_tools.py delegate to MemoryApi, which retrieves the active project's manager and enforces tool-facing behavior such as max content length in write_memory(). The rename tool is special: MemoryApi.rename_memory() calls MemoryManager.rename_memory_and_propagate_references(), which first moves the file and then rewrites marked mem:OLD_NAME references across memories that are writable in the current context. In tool context, read-only memories are intentionally excluded from propagation so a successful file move is not followed by a late permission failure.
The memory maintenance convention is seeded from src/…/memory_maintenance.md. MemoryManager.ensure_memory_maintenance_memory() returns global/memory_maintenance if that global memory already exists; otherwise it preserves an existing project memory_maintenance, or creates one from the shipped template. MemoryApi.onboarding() calls this before rendering the onboarding prompt, and src/…/simple_tool_outputs.yml tells the agent to read mem:{{ memory_maintenance_name }} before writing onboarding memories. The template defines the intended discovery model: agents start from a list of memory names, read mem:core as the graph root, follow backticked mem: references through progressively narrower memories, and use topic folders to make structure explicit. It also states that references are maintained automatically only when memories are renamed through Serena's rename tool, and that serena memories check reports stale references.
Reference detection and integrity checks live in src/…/memory_reference_analysis.py. Marked references use the mem: prefix and the shared name character class [A-Za-z0-9_\-/]. iter_referenced_names_in_content() finds mem:NAME occurrences using boundary assertions so references embedded in longer memory-name-like runs are ignored. MemoryReferenceAnalyzer.validate_referential_integrity() scans all non-ignored project and global memories, skipping the project-local memory_maintenance memory as a source. It always reports stale marked references and suggests up to three similarly named existing memories using compute_name_similarity(), which handles version suffixes, flat-to-topic moves, shared basenames, token overlap, containment, and short-name false-positive floors. When requested, it also reports exact bare occurrences of existing memory names and fuzzy near-misses from long bare tokens; findings are split into high- and low-confidence groups based on topic separators or name length.
MemoryManager.auto_prefix_bare_references() exposes the autofix path. It first runs validation, then rewrites only exact bare occurrences by adding mem:. By default it skips short flat names, read-only sources, global sources, and all fuzzy near-misses; --include-flat-names, --include-read-only, and --include-global in src/…/cli.py deliberately widen that scope. dry_run=True reports planned rewrites without writing. The CLI surfaces this as serena memories auto-prefix-references, while serena memories check is read-only, defaults to stale marked references only, and can opt into unmarked and fuzzy matching.
scripts/memory_graph.py is standalone graph tooling for visualizing a project's memory-reference structure. It loads the registered project through SerenaConfig.from_config_file(), gets the project's manager, lists project memories only via list_project_memories(), loads each memory, extracts marked references with iter_referenced_names_in_content(), and writes a directed GraphML graph. Existing project memories become nodes, and referenced names are also added as nodes even if no corresponding project memory exists, making stale or global-looking targets visible in the graph output.
Coupling
- If the memory reference syntax changes in src/…/memory_reference_analysis.py, update
MemoryManager.rename_references_to_memory()in src/…/memory_manager.py at the same time. Rename propagation and integrity checks rely on the samemem:prefix and name-boundary rule; if they drift,serena memories checkcan report references that rename does not update, or rename can rewrite text that validation would not consider a reference. - If
read_only_memory_patternssemantics change in src/…/memory_manager.py, verify src/…/mem_api.py, src/…/memory_tools.py, and src/…/cli.py. Agent tools passis_tool_context=Trueand enforce read-only writes, while CLI maintenance commands passFalse; changing this contract can either block administrative repairs or let agent tools mutate protected memories. - If the shipped maintenance template at src/…/memory_maintenance.md changes name, location, or core instructions, also verify
MemoryManager.MEMORY_MAINTENANCE_NAME,_MEMORY_MAINTENANCE_TEMPLATE_PATH,ensure_memory_maintenance_memory(), and the onboarding prompt template in src/…/simple_tool_outputs.yml. Onboarding depends on the manager returning a memory name that the prompt can direct the agent to read before writing any memories. - If memory names are allowed to contain characters outside
[A-Za-z0-9_\-/], update both path validation in src/…/memory_manager.py and all regex helpers in src/…/memory_reference_analysis.py. Otherwise valid memory files may be loadable by name but invisible to reference extraction, rename propagation, graph generation, or auto-prefixing. - If global-memory behavior changes, check scripts/memory_graph.py separately. The graph script intentionally starts from
list_project_memories()and only adds referenced names as extra nodes, so it does not load global memories or show outgoing edges from them.
Risks
- src/…/memory_reference_analysis.py skips only the project-local source name
memory_maintenanceduring validation. Ifensure_memory_maintenance_memory()choosesglobal/memory_maintenancefrom src/…/memory_manager.py,serena memories checkwill analyze that global memory like any other source. A global copy containing example references from src/…/memory_maintenance.md can therefore produce stale-reference noise for memories such asmem:frontend/core. - scripts/memory_graph.py appends one edge for every match yielded by
iter_referenced_names_in_content()and does not de-duplicate source-target pairs. If a memory mentions the same target repeatedly, the GraphML can contain parallel duplicate edges, which may distort visual graph layouts or edge counts. MemoryManager.move_memory()in src/…/memory_manager.py moves the file beforerename_memory_and_propagate_references()rewrites references. If a later load or save fails after the move, the memory has already been renamed and some references may remain stale; tool-context renames reduce this risk by excluding read-only memories from the rewrite set, but ordinary I/O failures can still leave a partial graph update.