serena-usage
Use for Serena MCP work - semantic symbol search, find references, code navigation, memory read/write, and organizing memory as a linked reference graph rather than a flat list. Also covers recovering
SKILL.mdhome-manager/ai-tools/agent-skills/skills/serena-usage/SKILL.md
GitHubSerena's tool schemas are injected by the harness and are not restated here. This file covers tool choice, the failure modes that make a Serena result misleading, and how a memory corpus stays worth reading. Tool availability depends on the server and runtime. Use the injected catalog as the authority; if an operation is absent, name the limitation and use a scoped text-based fallback rather than inventing a tool call.
Tool choice
Serena owns code intelligence; standard tools own the filesystem.
| Need | Tool |
|---|---|
| Find files by name | aitools find |
| Search file contents | aitools search for discovery, then Serena for navigation |
| File structure | get_symbols_overview: depth 0 first, then depth 1 |
| A named function, class, or method | find_symbol; substring_matching=true when the name is uncertain |
| Its implementation | find_symbol with include_body=true |
| A definition, from a call site | find_declaration with a regex capturing the symbol: for obj.process(x), pass "obj\.(process)\(" |
| Implementations of an interface | find_implementations (relative_path must be a file, not a directory) |
| Callers and impact | find_referencing_symbols |
| Replace a whole symbol | replace_symbol_body |
| Change a few lines inside one | replace_content, regex mode with wildcards ("beginning.*?end") to avoid transcribing large sections. DOTALL and MULTILINE are on; backreferences are $!1, $!2 |
| Rename across the codebase | rename_symbol: never update references by hand |
| Delete a symbol | safe_delete_symbol; inspect the returned references if it refuses |
| Confirm a file is clean after editing | get_diagnostics_for_file with min_severity=2 to drop hint noise |
Restrict any search with relative_path when the scope is known. Read a whole code file only when symbol
operations were tried and were insufficient, or the language is unsupported (next section). Start
get_symbols_overview at depth 0 and increase only if needed.
Prefer symbol operations strongly in strongly-typed languages, where LSP resolution is accurate. In dynamic
languages add substring_matching=true. For configuration and prose formats, go straight to aitools search and Read.
Before the first symbol operation in a session: initial_instructions, then activate_project. For a project
root inside .worktrees/, resolve the repository root as the path before .worktrees/ and use its shared
.state/.serena/memories directory. Managed worktrees expose it at .serena/memories; if that link is absent,
read relevant entries directly from the shared directory. Skip check_onboarding_performed and onboarding
for that worktree. For other project roots, check onboarding (check_onboarding_performed, then onboarding
if it returns false) and list memories only when prior knowledge could change the work.
When symbol tools cannot work
In a multi-language repository, language detection may fix the project's active language on the dominant one.
Symbol tools then fail for files of a secondary language, with an error naming the active languages and
refusing to extract symbols for the target. get_current_config confirms it.
Read get_current_config's active language before trusting any empty symbol result, because the failure
is not always loud. Detection routinely settles on a language the repository merely contains (build or
configuration files are enough to swing it), and the symbol tools then return nothing rather than erroring.
An empty find_symbol is then indistinguishable from a symbol that genuinely does not exist, and the
conclusion drawn from it ("no references, safe to delete", "this module is unreachable") is wrong in the most
expensive direction.
The control is the same one an empty grep needs. Before reading an empty result as an absence, run the query against a symbol you already know is there; if that comes back empty too, the tool is not answering your question and no result from it counts as evidence.
Treat this as an ongoing constraint of that repository, not a transient glitch to retry against. Confirm it
once, then commit to the text-based path: locate definitions and references with aitools search across source
and tests, edit with replace_content or the standard Edit tool, and verify with the language's own build or
load step; get_diagnostics_for_file is unavailable for an inactive language too. This section is the record:
do not write a per-repository memory restating it.
Failure can also be per-symbol rather than wholesale. When the tree is changing under a concurrent session, a lookup can succeed for one symbol and come back empty for the next in the same session; that pattern points to the concurrent change rather than to the repository, so name the fallback for the symbol that failed instead of abandoning symbol operations entirely.
The active-project pointer is shared
Concurrent sessions can move it out from under each other. edit_memory returning not-found for a memory known
to exist, or list_memories returning an unrelated set, can indicate a routing problem. Inspect the active
project, re-run activate_project with this session's own absolute path, then retry. If the expected memory
is still absent, investigate its storage; pointer drift alone does not prove that the data is intact.
A subagent reporting "no relevant memory exists" during a parallel dispatch may be hitting the same confusion. Do not treat that negative as authoritative: acting on it means writing a duplicate of an entry that already exists under the project the pointer drifted away from.
Recovering a lost subagent report
Completion notifications for parallel subagents can be delayed or lost, so their absence is not evidence the agent failed; and re-running on that assumption discards completed work and doubles the cost.
- Check the runtime's agent status and queued messages first.
- If the runtime exposes session transcripts, locate the actual transcript path. Claude-style
subagents/agent-*.jsonlpaths are not a portable assumption for Codex or OpenCode. - Read the terminal status and final report identified by that runtime's transcript format. Message length and file mtime do not establish completion: a long intermediate message is not a final report, and a quiet file may belong to an agent waiting on a tool.
If neither status nor a transcript establishes completion, report it as unknown before deciding whether to retry. Inspect possible partial edits before re-dispatching a write-capable agent.
Memory
CLAUDE.md's memory_policy holds the short rule; the full policy is this section. Record durable learning when
it is established: user conventions, decisions, costly traps, rejected options with their evidence, and the
conditions for revisiting them. Read-only work grants no memory writes; when the store is unavailable or writing
is prohibited, return the entry as a candidate. Do not record session diffs, verdicts or scores, unfinished
verification, or facts already in the repository. Keep absolute paths and raw counts out of bodies and retain the
reproducible command instead. Recheck carried-forward work before proposing it. Update a stale claim in place
rather than appending a contradiction.
Naming
Names may contain / to organize into subtopics; list_memories enumerates nested paths transparently.
convention-{topic} forward-looking project conventions
decision-{topic} architectural decision records, with the rejected options
{feature}-patterns feature-specific reusable patterns
{domain}-patterns domain-specific patterns
global/{topic} shared across all projects (only when the user explicitly asks for
a project-independent memory)
Name a memory by the durable topic, never by a date or review round: deduplication-phase2-2026-01 records
when someone worked, which is chronology this store excludes.
Which store, before what to write
Choose the store by scope and by what the runtime actually exposes, not by the client name.
- Serena stores durable project knowledge: architectural invariants, conventions, rejected design options, and costly debugging traps. Include source references or reproducible commands so a later agent can recheck the claim. Knowledge can span files; it need not be attached to one symbol or line number.
- A runtime-provided personal or auto-memory store may hold cross-project preferences and session-independent working conventions. Use only an exposed store with the appropriate scope; do not invent Claude, Codex, or OpenCode paths or assume another client's memory is injected.
- Rules that must govern future work belong in the repository's authoritative instructions when that edit is requested. Do not keep a competing policy in memory or write facts already documented in the repository.
Read-only work returns candidates without persisting them. If no suitable store is available or writing is unauthorized, report the candidate and its intended scope. A missing store is not evidence of no prior history. Search the available stores before writing, keep each fact authoritative in one place, and use links rather than duplicate bodies when another store needs to point to it.
What earns a memory
Write for: a significant architectural pattern, a reusable debugging insight from a hard bug, a reusable implementation pattern, a convention or preference the user stated, a transferable refactoring approach.
Do not write:
- Session verdicts and review chronology. A deferred-finding ledger may retain an identifier, location, severity, and deferral reason; do not turn it into a session transcript.
- A note that names one file and would not change what you do in a different file. That is a commit message.
- Anything volatile enough to be wrong within weeks: line numbers, file counts, current status, an in-flight branch's state. Volatility is the load-bearing exclusion, because it rejects at write time exactly the entries the staleness check would otherwise have to catch later.
- Generic language or framework knowledge, and facts a single quick read would establish. A memory earns its place by preventing an expensive rediscovery, not by recording something true.
- One-off fixes, temporary preferences, workarounds due to be replaced, anything already documented elsewhere.
The positive trigger list is monotone (every extraction is "a refactoring approach", every fix is "a bug insight"), so it can only ever argue for writing. A corpus grown from it alone becomes an index no agent can afford to read, which pushes the next session toward reading nothing at all. Write dense agent notes: invariants and terse bullets, rationale and worked examples omitted unless they prevent a likely mistake. A maintained corpus looks like a handful of short files; an accumulated one looks like dozens of long ones.
Frontmatter
---
domain: <nixvim | home-manager | ai-prompts | nix | general>
status: active
created: YYYY-MM
last-verified: YYYY-MM
---
status: active (current and verified), archived (superseded), draft (unverified hypothesis). On
write_memory, set last-verified only for content checked against current evidence. On edit_memory,
leave created unchanged and bump last-verified only for reverified content, recording the checked scope.
Apply to new memories only: do not migrate retroactively, but add frontmatter when editing a memory that
lacks it.
The body states the present, not a history
This store is a cache of current truth, read top-down under a context budget, so the part most likely to be read must be the part most likely to be right. (A decision log that exists to show how a position was reached is the opposite kind: append-only. Know which kind you are writing into.)
- Correct in place. If an addition invalidates something already written, rewriting or deleting that passage is part of the same edit; an append-only memory grows less true with reading order.
- A retraction goes in the lead, before anything else is done with the memory. One buried under dated update markers does not reach a reader who stops after the first paragraph.
- A correction reaches every sibling carrying the same claim. Search the stale claim's distinctive words before finishing, and quote the wrong claim verbatim while negating it, so a reader who half-remembers it finds the file that settles it.
- Store the command, never the count. Test counts, file counts, coverage, and line numbers are stale one
commit later, and
last-verifiedcannot protect them. Put the re-verification command verbatim next to each claim, behavioural ones included: a claim that stays plausible after it stops being true is the one most in need of a command. Historical measurements belong in the task's evidence report. - Record what constituted done: the commands that had to pass, and any non-zero output accepted as normal. Without the accepted-warning detail, the next agent reads a pre-existing warning as a fresh regression.
Editing hygiene
Each of these has a recorded failure behind it, and each failure is silent: the edit reports success and the damage is visible only to a later reader.
- Read the whole memory before editing, not just the region being changed. Editing from a partial view is how a second complete frontmatter block ends up stacked on the first, after which a consumer parsing the first block and one parsing the last get different answers.
- After the edit, the file must contain exactly one frontmatter block. Check it rather than assuming it.
- Any programmatic in-place substitution whose replacement contains a metacharacter must be verified by reading the result, not by the command's exit status. A replacement with a capture-group reference and no corresponding group substitutes the empty string silently and truncates the sentence; a replacement written through a layer that does not interpret escapes emits the escape sequence literally. Neither fails loudly, and both destroy content in a file nobody will re-read.
Finding the duplicate before writing
"Check list_memories first" stops working the moment the namespace is split by domain prefix, which is
exactly when the corpus is large enough for duplication to matter. Working inside one domain, the natural name
for a new memory carries that domain's prefix, so the identical fact filed under a different domain never comes
into view. The bodies diverge in vocabulary too, so neither a name scan nor a grep for the obvious term finds
it. Duplicate entries can each carry only part of the evidence, leaving the decisive detail in one copy.
- Search by the words describing the symptom, not the words you would use to name the file. "Tests run stale logic", "the edit did not take effect": a reader hits the memory through the problem they are having, never through the taxonomy someone else chose.
- A fact that crosses domains goes in one cross-cutting place, not under whichever domain happened to hit it first.
- When you find the duplicate, merge rather than adding another copy, and keep the detail that appears in only one of them. That detail is usually the reason the memory is worth having.
- Record that the search happened and came back empty, in the memory you then write. A later reader otherwise cannot tell a genuinely new fact from one whose author never looked, and re-runs the search you already paid for.
Point at an external standard rather than copying it
A convention owned outside this repository (an organization-wide policy document, a sibling repository's standard) is named and located, never restated. A restated policy is a copy that stops tracking its original the day either changes, and the copy is what the next session reads. Give the document's name and the command that fetches it. Where a project's own docs already restate such a policy, say so in the memory: the restating sites are the ones that go stale, and nothing else records that they exist.
The corpus as a graph, not a list
At small scale a flat set is fine, because listing it is cheap. Past a few dozen memories, an agent that must read everything to find what matters pays that cost on every task, so the corpus needs to be traversable: one designated root that every session reads first and that holds no domain detail of its own, domain memories linked from it, and leaf memories reached by traversal rather than by scanning the index.
- A reference carries a description of what the target covers, precise enough to decide whether to follow it. The target's name alone tells you the topic, not whether the content bears on the question in hand.
- A memory should not contain instructions about when to read itself. That guidance belongs to the referrer, the only place with the context to judge relevance. Self-describing read conditions duplicate across every referrer and go stale independently.
- Add the reference from the parent in the same edit that adds the memory. An unreferenced memory is unreachable by traversal and effectively invisible, however good its content.
- When writing a link, confirm the target exists, or say in the same line that it is a placeholder. A dangling reference reads exactly like a valid one until someone follows it, so the graph degrades silently.
- When a task finds itself reading more than a handful of memories on one topic, that is the signal to write the linking entry that gathers them, not to add another leaf. A cluster held together only by a shared filename prefix is not a graph.
Without a root, select by task type as execution-workflow's Analyze step describes; with one, start at the root and let the task type decide which branches to follow.
Staleness, checked lazily
Freshness is maintained opportunistically, against only the memories a task actually read. Never read a memory solely to check its freshness: that turns every task into an index sweep, charged to a task that never needed it. There is deliberately no scheduled full-index pass: a memory nothing has read in months is also a memory nothing has needed. Consolidating the index is user-initiated.
Signals: last-verified more than three months old; frontmatter absent entirely (treat as a stale candidate
and add frontmatter when editing). But for a memory naming something checkable (a symbol, a file, a path, a
condition), the test that matters is whether the thing it names still exists, not how old the memory is. Those
have different answers: a memory verified two months ago can name a symbol deleted last week and pass the date
gate untouched. Checking costs one search, far less than the review round that re-derives the item and re-files
it as an action. Apply this especially to any memory carrying forward a deferred work item, which gets
re-proposed on the strength of a name that may no longer resolve.
Bumping last-verified is one edit; verifying content requires reading the code. If only the first
happens, the stamp comes to mean "recently touched" rather than "checked": worse for a reader than no stamp at
all, since an unmarked memory invites suspicion and a freshly-dated one invites trust. State what was compared
against what, naming a file path or command output, whenever the date is bumped.
Partial re-verification is the normal case, not the exception. Record the boundary of what was checked in the body, naming both sides: bumping the date for the whole file after confirming one section lends false freshness to everything else; not bumping at all sends the confirmed part back through verification next time. Record a discrepancy found during a scoped check at the moment it is found, even when it lies outside what the task set out to verify: noting that a named function no longer exists costs a line and closes the finding, while deferring it means an independent investigation later that starts from nothing.
Outcomes: still accurate → bump; partially outdated → correct the stale section and bump; fully superseded →
rename_memory with an -archived suffix and note the reason.
For a memory whose value is mixed, preserve the verified claims and replace stale claims in place. State which earlier claim the correction negates and which sections remain unverified; do not retain a stale statement as current guidance beneath a banner.
A rename reaches only whoever consults the index next, so the superseding memory names the old one and states what it wrongly claimed. Where the old claim is likely to be re-derived from the same code, keep it visible with its correction rather than deleting it, or the next session reaches the same wrong conclusion with no sign it has been here before. A recorded rejection keeps its reasoning, not just its verdict: it goes stale when its premise is invalidated, even though its conclusion still sounds right.
When several small memories cover related topics, merge them into one.
Rules
- When prior project knowledge could affect the task, check
list_memoriesonce. For authorized persistence, useedit_memoryfor an existing topic andwrite_memoryonly for a genuinely new one. - Never
delete_memorywithout an explicit user request.
Extending Serena to a new language
An LSP-integration task, not a parser-writing task. Wrap an existing language server: prefer the
single-core-dependency provider when the server is one executable or archive. Register the language in the
Language enum with a filename matcher for its extensions and add the factory branch. Provide a minimal test
repository exercising symbols, within-file references, and cross-file references.
Write tests asserting the actual expected symbol names and reference locations. Asserting only that a non-empty list came back is insufficient and is the most common reason such contributions are rejected.
documentSymbol, definition, and references are mandatory: a server missing any of them cannot back
find_symbol or find_referencing_symbols and should be deferred, or offered only as experimental
completion/hover support. Installation footprint determines adoption cost and CI feasibility.
Related
- investigation-patterns: investigation methodology using these tools
- workflow-patterns: shared escalation and decision-criteria templates
- execution-workflow: where memory checks sit in the orchestration