feat(wrap): make the Serena code-memory MCP opt-in (#4509)

## What changes

`headroom wrap claude|codex|grok|opencode` no longer registers Serena by
default.

| | Before | After |
|---|---|---|
| Default | Serena registered | No code-memory MCP |
| Opt in | (default) | `--code-memory serena` or
`HEADROOM_CODE_MEMORY=serena` (deprecated `--serena` still works) |
| Opt out | `--code-memory none` / `--no-serena` | Still accepted |
| Upgrading user, Serena installed by Headroom | Kept | Removed on next
wrap, with the message "Serena is now off by default; pass --code-memory
serena to keep it" |
| Upgrading user, Serena added by hand | Kept | Kept, no message (shown
only with `--verbose` or an explicit opt-out) |

OpenCode now accepts `--code-memory` and uses the same setup path as the
other agents. Its `--no-serena` flag is hidden and deprecated.

## Why

Measured on 2026-10-27, Serena started exactly as `wrap` registers it:

- It adds 22 tools, about 5.9K tokens of tool definitions on every
request where tools aren't deferred. Its server instruction tells the
model to call `initial_instructions`, which costs another 2K tokens.
- Each launch takes about 6 s cold via `uvx`, plus a background `serena
project index` that starts language servers. It also writes a `.serena/`
folder into the user's repo.
- Serena was registered in 6 of our own Claude Code sessions and called
0 times. Separately, an offline replay of about 108K tool calls found
that symbol-level reads have little to recover for Claude Code.

## Not in this PR

- `headroom.integrations.strands` still defaults
`enable_serena_mcp=True`. It's public integration API, so it needs a
deprecation step instead of a silent flip.
- The opt-in `--serena-instructions` block in CLAUDE.md/AGENTS.md is
never removed, by unwrap or anything else. Users who opted into it keep
instructions that point at tools no longer registered. This predates
this PR and will be fixed separately.
- For Claude Code, Serena entries are per project, so removal happens
the next time `wrap` or `unwrap` runs in each project. The docs say so.

## Tests

- `pytest tests/test_wrap_code_memory.py tests/test_cli
tests/test_mcp_registry`: 1368 passed. 5 failed, and those 5 fail the
same way on `main` in my local venv:
`test_mcp_reconcile.py::test_ordinary_install_does_not_adopt_serena` and
4 in `test_wrap_persistent.py`, all from an environment/install
mismatch.
- New tests:
- The default wrap removes a Serena entry Headroom installed and prints
how to keep it.
- The default wrap leaves a hand-added Serena alone and prints nothing.
  - `--serena --no-serena` resolves to none.
- `wrap opencode --code-memory serena` registers Serena with the `agent`
context.
- `ruff check`, `ruff format --check` and `mypy` are clean on the
changed files.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

## Real Behavior Proof

- **Environment:** macOS (Darwin 27.2), Python 3.12.13, Claude Code
2.1.318, real `claude` CLI doing every `claude mcp add`/`remove`. A
temporary `HOME`, so `~/.claude.json` starts empty, and a fresh git repo
per case.
- **Builds:** "before" = `main` at `12864fc8`; "after" = this PR at
`56557dc9`.
- **Command:** `headroom wrap claude --no-proxy [flags] -- --version`.
Wrap does its full MCP setup, then launches Claude Code, which prints
its version and exits, so no model call is made. `state` is read from
`~/.claude.json` (user scope and this project's local scope) and the
project's `.mcp.json` after each run.

```
== 1. Upgrade: Serena installed by Headroom (project/local scope)
    $ headroom wrap claude --no-proxy -- --version    (cwd=projA, build=12864fc8)
    exit=0
    wrap|   Serena MCP: registered (restart Claude Code if it was already running)
    wrap|     scoped to this project — pass --code-memory-scope user to register it for every Claude Code session
    wrap| 2.1.318 (Claude Code)
    state| user: ['headroom'] | local(projA): ['serena'] | .mcp.json: -
    $ headroom wrap claude --no-proxy -- --version    (cwd=projA, build=56557dc9)
    exit=0
    wrap|   Removed previously-installed Serena MCP (Serena is now off by default; pass --code-memory serena to keep it)
    wrap| 2.1.318 (Claude Code)
    state| user: ['headroom'] | local(projA): - | .mcp.json: -

== 2. Upgrade: Serena added by hand (claude mcp add)
    state| user: ['headroom'] | local(projB): ['serena'] | .mcp.json: -
    $ headroom wrap claude --no-proxy -- --version    (cwd=projB, build=56557dc9)
    exit=0
    wrap| 2.1.318 (Claude Code)
    state| user: ['headroom'] | local(projB): ['serena'] | .mcp.json: -
    $ headroom wrap claude --no-proxy --code-memory none -- --version    (cwd=projB, build=56557dc9)
    exit=0
    wrap|   Serena MCP is present but user-managed — leaving it in place (Headroom only removes entries it installed)
    wrap| 2.1.318 (Claude Code)
    state| user: ['headroom'] | local(projB): ['serena'] | .mcp.json: -

== 3. Explicit opt-in, then rollback to the default
    $ headroom wrap claude --no-proxy --code-memory serena -- --version    (cwd=projC, build=56557dc9)
    exit=0
    wrap|   Serena MCP: registered (restart Claude Code if it was already running)
    wrap|     scoped to this project — pass --code-memory-scope user to register it for every Claude Code session
    wrap| 2.1.318 (Claude Code)
    state| user: ['headroom'] | local(projC): ['serena'] | .mcp.json: -
    $ headroom wrap claude --no-proxy -- --version    (cwd=projC, build=56557dc9)
    exit=0
    wrap|   Removed previously-installed Serena MCP (Serena is now off by default; pass --code-memory serena to keep it)
    wrap| 2.1.318 (Claude Code)
    state| user: ['headroom'] | local(projC): - | .mcp.json: -
    $ headroom wrap claude --no-proxy -- --version    (cwd=projC, build=56557dc9)
    exit=0
    wrap|   Serena MCP: registered (restart Claude Code if it was already running)
    wrap|     scoped to this project — pass --code-memory-scope user to register it for every Claude Code session
    wrap| 2.1.318 (Claude Code)
    state| user: ['headroom'] | local(projC): ['serena'] | .mcp.json: -
    $ headroom wrap claude --no-proxy --serena -- --version    (cwd=projC, build=56557dc9)
    exit=0
    wrap| 2.1.318 (Claude Code)
    state| user: ['headroom'] | local(projC): ['serena'] | .mcp.json: -

== 4. User scope: installed by Headroom with --code-memory-scope user
    $ headroom wrap claude --no-proxy --code-memory-scope user -- --version    (cwd=projD, build=12864fc8)
    exit=0
    wrap|   Serena MCP: registered (restart Claude Code if it was already running)
    wrap|     registered for every Claude Code session on this machine (--code-memory-scope user)
    wrap| 2.1.318 (Claude Code)
    state| user: ['headroom', 'serena'] | local(projD): - | .mcp.json: -
    $ headroom wrap claude --no-proxy -- --version    (cwd=projD, build=56557dc9)
    exit=0
    wrap|   Removed previously-installed Serena MCP (Serena is now off by default; pass --code-memory serena to keep it)
    wrap| 2.1.318 (Claude Code)
    state| user: ['headroom'] | local(projD): - | .mcp.json: -

== 5. User scope opt-in on the PR build
    $ headroom wrap claude --no-proxy --code-memory serena --code-memory-scope user -- --version    (cwd=projE, build=56557dc9)
    exit=0
    wrap|   Serena MCP: registered (restart Claude Code if it was already running)
    wrap|     registered for every Claude Code session on this machine (--code-memory-scope user)
    wrap| 2.1.318 (Claude Code)
    state| user: ['headroom', 'serena'] | local(projE): - | .mcp.json: -
    $ headroom wrap claude --no-proxy -- --version    (cwd=projE, build=56557dc9)
    exit=0
    wrap|   Removed previously-installed Serena MCP (Serena is now off by default; pass --code-memory serena to keep it)
    wrap| 2.1.318 (Claude Code)
    state| user: ['headroom'] | local(projE): - | .mcp.json: -
```

What this shows:
1. A Serena entry Headroom installed on `main` is removed on the first
wrap after upgrading, with the "off by default" message. This holds for
both scopes (cases 1 and 4).
2. A hand-added Serena entry is kept, and the default wrap prints
nothing. `--code-memory none` keeps it and says it's user-managed (case
2).
3. Opting in works with `--code-memory serena`,
`HEADROOM_CODE_MEMORY=serena` and the deprecated `--serena`, at project
scope and user scope (cases 3 and 5). Running the default afterwards
rolls it back.
4. Project scope here means Claude Code's `local` scope, which is where
wrap registers. Wrap never writes `.mcp.json`.

Not tested live: `wrap codex|grok|opencode` (unit tests only), Windows,
and an interactive Claude session that calls Serena tools.

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4509"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->

## Maintainer post-merge qualification
Published `983b6bb15119a3ecb8f6e20bf014b8bed123e95d` includes upstream
main `e4a60ed72f6ef5b28569f8bfbe2163cfda32c948`. 19 selector/Serena
tests pass,1optional skip; Ruff/format/diff pass. Clean main sync;
contributor selector/ownership code unchanged. Existing real
upgrade/configuration/launch proof requirement remains; jCodeMunch
proposal is unrelated to this source delta. Contributor correctness
logic was not rewritten. Existing Changes Requested decision retained
without duplicate findings. Scoped Windows validation uses the existing
development native extension, not a fresh build. Hosted qualification is
handled by maintainers; nothing merged.


### Maintainer current-main requalification

Exact head `e8e3011187a2ffdfbb6c9932db26b22ec911ab39`, upstream main
`ecbaf86d78cf52d185fbffa306157b9a4cc1b906`.

Mechanically updated from upstream/main
ecbaf86d78 without changing contributor
selector/ownership logic. Reviewed the current discussion and
integration delta. All 29 focused code-memory/Serena-disable/Gemini
tests pass with one optional skip; Ruff0.17.3 lint/format and whitespace
checks pass. Existing Windows HOME/USERPROFILE fixture isolation remains
intact.

The prior upgrade/runtime qualification requirement remains unresolved:
post-patch real configuration/launch evidence must cover an existing
Headroom-owned Serena entry, a hand-managed entry, explicit opt-in, and
Claude project/user scopes, with commands/results and untested-agent
limits. No new author evidence was found to close it. This pass does not
claim those actual launch/upgrade flows were executed; passing unit
tests and the main sync do not establish that deployment behavior. The
hold is not an inherited-main CI defect. Maintainers handle hosted
checks; no contributor CI execution requested. Nothing merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `0b49a79cb192b294dde7ecb1c72b75fffa2733d5`, upstream main
`8d3e9e5ca7cd645eb73084b848edbea5fc796e1a`.

Clean mechanical sync with upstream
main8d3e9e5ca7cd645eb73084b848edbea5fc796e1a without changing
contributor selector/ownership logic. Current source, author discussion
and Devin findings reviewed.29focused code-memory/Serena-disable/Gemini
tests pass with1optional skip; changed Python Ruff0.17.3check/format and
whitespace pass. Windows HOME/USERPROFILE fixture isolation preserved.

Existing real upgrade/runtime qualification remains missing: existing
Headroom-owned Serena versus hand-managed entry, explicit opt-in, and
Claude project/user scopes need observed configuration/launch results
with explicit untested-agent limits. No new evidence found to close it;
these launch/upgrade paths were not executed in this pass. Passing unit
tests and clean main integration do not establish deployment behavior.
No new provider/native-build claim or inherited-main pipeline
attribution. Maintainers handle hosted checks; nothing merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `30dfb386fa7284c9817bf5d7db0648fb10830055`, upstream main
`7592e681459f14a2041eb5f524a658cb6ad1dd92`.

Clean current-main
sync7592e681459f14a2041eb5f524a658cb6ad1dd92,including HNSW re-index and
memory relation-key fixes after917release-recovery merge. Contributor
selector/ownership logic unchanged; fresh discussion
considered.37wrapper/Serena/memory-regression/Gemini tests pass
with1optional skip;whitespace passes. PriorRuff0.17.3validation applies
to unchanged PR files.

Existing real upgrade/launch evidence hold remains: Headroom-owned
versus hand-managed Serena
entries,explicitoptin,andClaudeproject/userscopes need
observedpostpatchresults. No newevidence closesit;actualupgrade/launch
pathsnotrerun. No freshnativebuild/provider claim.
MaintainershandleCI;nothingmerged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `e1778a5368626547ad958926d5570edf153182f6`, upstream main
`2d3ee51846435ef5b320eea4806af14e602b0d8c`.

Clean integration with upstream/main
2d3ee51846 after the external 0.43.1
release merge. Exact headroom/crates/tests comparison against previously
reviewed 30dfb386f shows no changes. Re-reviewed generated metadata; 78
release/version/MCP tests pass on this tree and whitespace passes.
Earlier 37 wrapper/Serena/memory/Gemini passes and one optional skip
remain scoped to unchanged inputs.

Existing actual upgrade/launch proof hold remains: Headroom-owned versus
hand-managed Serena entries, explicit opt-in, and Claude project/user
scopes need observed postpatch results. Those runtime paths were not
rerun and no new evidence closes the hold. No contributor ownership
policy changed, no fresh native-build/provider claim. Maintainers handle
checks; nothing merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `173c5739d7357ca9398faa41b4d1ce3b72d6c550`, upstream main
`7877241d84c93b3ec487e07324245838ddae85cc`.

Cleanly integrated upstream/main7877241d84c93b3ec487e07324245838ddae85cc
and re-reviewed the wrapper overlap with Hermes registration and port
discovery.35 selector/Serena-disable/Hermes provider and wrapper tests
pass,1optional skip; Ruff and whitespace pass. Contributor
ownership/default policy is unchanged. Existing actual
upgrade/configuration/launch proof requirement remains open for
Headroom-owned versus user-managed entries, explicit opt-in, and Claude
project/user scopes. No runtime proof is inferred from mocks or
native-build claim made. Maintainers handle hosted checks; nothing
merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `eb1c3d66669cf71f881f1ba06dc049d36b20da7b`, upstream main
`c01cf07d943d816cfd9d97e6838ed4e38f1ff9a4`.

Final post-Dependabot requalification against upstream/main
c01cf07d94. All six Dependabot updates are
now merged. Relative to this branch's freshly tested prepared tree, the
final main sync changes only the three intended Cargo.lock records;
Python/source/test inputs are unchanged. Re-reviewed the integration and
confirmed complete native source/lock/toolchain objects match the tested
combined build and exact fresh native DLL used for this branch's local
tests.

Focused fresh-native qualification: 35 passed, 1 skipped in 2.93s.
Selected real dependency overlays and native DLL paths are recorded in
final4509-fresh-native-tests.log; the DLL provenance/input hashes are in
final-native-artifact-proof.json. No redundant rerun is implied after
this Cargo-only merge. Whitespace passes. Prior source review and scoped
real-behavior evidence remain applicable to unchanged contributor
inputs.

Existing real upgrade/configuration/launch qualification remains open
for Headroom-owned versus user-managed Serena entries, explicit
opt-in/rollback, and Claude project/user scopes. No new author evidence
closes it; contributor ownership/default policy is unchanged.

Maintainers handle hosted checks; no external-provider claim,
contributor semantic rewrite or non-Dependabot merge.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `43bfea8a164c21ab69793b3905fbf1457fef7bc2`, upstream main
`da6d9736cd82074988c7d0a2360b49d9d8b6c0a0`.

Current-main requalification against
da6d9736cd. All69 integration patches
exactly match c01cf07-to-current-main delta after diff-location
normalization; contributor selector/default/Serena ownership logic
unchanged.162 focused code-memory,Serena disable,Hermes,Windows
supervisor,search-compressor tests pass;3 platform/optional skips. All31
changed Python files pass Ruff lint/format; offline lock and whitespace
pass. Native pr3982 DLL verified against complete tracked native-input
hash proof and artifact checksum; no fresh native-build claim.
Author/Devin discussion checked. Existing real
upgrade/configuration/launch qualification remains open: prior
Headroom-owned Serena entry versus user-managed entry, explicit
opt-in/rollback, Claude project/user scopes. No new author evidence
closes it; this run does not assert actual agent launch or deployment
proof. Maintainers handle hosted checks; no contributor policy rewrite
or merge.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.


### Maintainer current-main requalification

Exact head `56557dc91725422257f90c3cb5c5f04a665e6043`, upstream main
`0ddaa56c21cdc01c4774391fdcc69e987ecc4e5c`.

Clean integration with upstream/main
0ddaa56c21. All 19 integration patches
exactly match the prior-reviewed-main da6d9736 to current-main delta
after diff-location normalization; contributor selector/default/Serena
ownership logic is unchanged. Fresh code-memory/Serena
disable/scope/reconciliation/migration, doctor and incoming
Vertex/backend/CLI tests: 330 passed, 12 skipped, 1 warning. Fourteen
changed Python files pass Ruff lint/format; offline lock and whitespace
checks pass.

Author/Devin discussion read. Existing real upgrade/configuration/launch
qualification remains open: prior Headroom-owned entry versus
user-managed entry, explicit opt-in/rollback, Claude project/user
scopes. This run establishes no actual agent launch or deployment proof.
Static source/test scope and security inspection found no new workflow,
dependency or setup path; the inherited flagged workflow-validation job
is excluded by the exact PR's unchanged workflow paths. Native DLL
reused after complete tracked input-set/hash and artifact-checksum
verification; no fresh build claimed. Maintainers handle exact-head
hosted checks; no PR merged.


Exact-head hosted checks are being handled by maintainers. Existing
correctness/qualification holds remain; nothing merged.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JD Davis <mxjerrett@gmail.com>
This commit is contained in:
Tejas Chopra
2026-11-09 12:23:08 -06:00
committed by GitHub
co-authored by Claude Opus 5.5 JD Davis
parent b25c45b08f
commit 2649835a51
9 changed files with 134 additions and 70 deletions
+7 -7
View File
@@ -160,12 +160,12 @@ print(f"Saved {result.tokens_saved} tokens ({result.compression_ratio:.0%})")
```
Launch a wrapped agent session each time, so the setup runs. `headroom wrap`
starts a local proxy, installs **[Serena](https://github.com/oraios/serena)** for
semantic code navigation, and launches the agent configured to route through
Headroom. For Claude Code, Serena is registered for the wrapped project only
(as a `local`-scope MCP server in `~/.claude.json`). Use
`--code-memory-scope user` to make it available in every project, or
`--code-memory none` to skip it. `headroom unwrap` removes either registration.
starts a local proxy and launches the agent configured to route through
Headroom. Add `--code-memory serena` to also install
**[Serena](https://github.com/oraios/serena)** for semantic code navigation (off
by default). For Claude Code, Serena is registered for the wrapped project only
(as a `local`-scope MCP server in `~/.claude.json`); use `--code-memory-scope user`
to make it available in every project. `headroom unwrap` removes either registration.
`headroom wrap ...` is session-scoped: its proxy exits with the wrapped agent.
For a proxy that survives reboots, use the turnkey `headroom deploy` command.
@@ -720,7 +720,7 @@ framework, and is reversible.
Headroom is the proxy, and it compresses everything flowing through it whatever
sits upstream. Our recommended companion is
**[Serena](https://github.com/oraios/serena)** for semantic code navigation,
installed by default when you wrap an agent, plus **Ponytail** if you want leaner
installed with `headroom wrap --code-memory serena`, plus **Ponytail** if you want leaner
model output. Everything else is your call — attach a code-memory MCP, Graphify,
Caveman, or any other MCP server, and Headroom compresses downstream of all of it.
+2 -2
View File
@@ -28,7 +28,7 @@ headroom unwrap opencode
| Runtime env | Sets `OPENCODE_CONFIG_CONTENT` with provider, plugin, and optional local MCP config so OpenCode picks up Headroom at launch |
| Provider compatibility | Leaves `OPENAI_BASE_URL` and `ANTHROPIC_BASE_URL` untouched so OpenCode `/connect` providers keep their own routing |
| MCP setup | Registers the Headroom MCP server (`headroom_compress`, `headroom_retrieve`, `headroom_stats`) |
| Serena MCP | Optionally registers Serena code graph tools (`--no-serena` to skip) |
| Serena MCP | Off by default; `--code-memory serena` registers Serena code navigation tools |
| Backup | Snapshots `opencode.json` to `opencode.json.headroom-backup` before making any changes |
| Launch | Starts the `opencode` binary through the proxy |
@@ -38,7 +38,7 @@ headroom unwrap opencode
headroom wrap opencode \
--port 8787 \
--no-mcp \
--no-serena \
--code-memory serena \
--code-graph \
--no-proxy \
--openai-api-url https://api.deepseek.com/v1 \
+5 -3
View File
@@ -91,11 +91,13 @@ Avoid setting process-wide variables such as `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_P
#### Code-memory MCP (Serena)
`headroom wrap` registers **[Serena](https://github.com/oraios/serena)** as the code-memory MCP for semantic, symbol-level code navigation. Serena runs on demand via `uvx` — Headroom downloads and executes no binary of its own — and indexes the current project locally. Pass `--code-memory none` to register no code-memory MCP.
`headroom wrap` registers no code-memory MCP by default. Pass `--code-memory serena` (or set `HEADROOM_CODE_MEMORY=serena`) to register **[Serena](https://github.com/oraios/serena)** for semantic, symbol-level code navigation. Serena runs on demand via `uvx` — Headroom downloads and executes no binary of its own — and indexes the current project locally. It is opt-in because its ~20 tool definitions add about 6K tokens to every request where the agent does not defer tools, and indexing runs at each launch.
For Claude Code, the entry is written at `local` scope, which means it applies to the directory you wrapped and nothing else. That keeps a Serena that cannot start from breaking Claude Code sessions in unrelated projects. Pass `--code-memory-scope user` (or set `HEADROOM_CODE_MEMORY_SCOPE=user`) to register it machine-wide instead, which is how releases before this change behaved. If an earlier version already registered Serena machine-wide, the next `headroom wrap claude` moves it into the project scope for you — but only when Headroom installed that entry itself; a Serena you registered by hand is left alone.
> **Upgrading?** Earlier releases registered Serena by default. On your next `headroom wrap`, Headroom removes the Serena entry it installed and says so; pass `--code-memory serena` to keep it. For Claude Code the entry is per project, so it is removed the next time you run `headroom wrap claude` (or `headroom unwrap claude`) in that directory. A Serena you registered yourself is left alone.
> **Upgrading from tokensave?** Earlier releases registered a `tokensave` MCP server (a downloaded Rust binary). tokensave has been retired in favour of Serena. On your next `headroom wrap` / `headroom unwrap`, Headroom removes the `tokensave` MCP entry it installed and switches you to Serena — nothing to migrate, since both are just indexes rebuilt from your source. The leftover `tokensave` binary in `~/.local/bin` and any `.tokensave/` folders are unused and safe to delete.
For Claude Code, the entry is written at `local` scope, which means it applies to the directory you wrapped and nothing else. That keeps a Serena that cannot start from breaking Claude Code sessions in unrelated projects. Pass `--code-memory-scope user` (or set `HEADROOM_CODE_MEMORY_SCOPE=user`) to register it machine-wide instead, which is how releases before #2787 behaved. If an earlier version already registered Serena machine-wide, the next `headroom wrap claude --code-memory serena` moves it into the project scope for you — but only when Headroom installed that entry itself; a Serena you registered by hand is left alone.
> **Upgrading from tokensave?** Earlier releases registered a `tokensave` MCP server (a downloaded Rust binary). tokensave has been retired in favour of Serena. On your next `headroom wrap` / `headroom unwrap`, Headroom removes the `tokensave` MCP entry it installed — nothing to migrate, since it was just an index rebuilt from your source. The leftover `tokensave` binary in `~/.local/bin` and any `.tokensave/` folders are unused and safe to delete.
By default, the proxy uses the shared **ContentRouter** pipeline. It routes text, logs, JSON, code, images, and tool outputs through the currently enabled compressors and preserves reversible CCR markers where applicable.
+57 -40
View File
@@ -1128,7 +1128,7 @@ _serena_instructions_option = click.option(
# --- Code-memory MCP selection ------------------------------------------------
# The code-memory MCP is Serena by default; turn it off with --code-memory none.
# No code-memory MCP is registered by default; opt into Serena with --code-memory serena.
# Selection flows through HEADROOM_CODE_MEMORY (set by the eager --code-memory
# callback) so it works the same on every agent without threading a param
# through each subcommand — the same approach as _serena_instructions_option above.
@@ -1143,10 +1143,10 @@ def _resolve_code_memory(kwargs: dict[str, Any]) -> str:
Precedence: the explicit selector (``--code-memory`` / ``HEADROOM_CODE_MEMORY``)
wins; otherwise the deprecated ``--serena`` / ``--no-serena`` flags map into
it; otherwise the default is ``serena`` — mature, offline, symbol-level code
navigation. The retired ``tokensave`` option is accepted gracefully: an
explicit ``tokensave`` selector (or the deprecated ``--no-tokensave`` flag)
now resolves to Serena.
it; otherwise the default is ``none``. Serena adds ~6K tokens of tool
definitions to every request where tools are not deferred, plus launch-time
indexing, so it is opt-in. The retired ``tokensave`` option is accepted
gracefully: an explicit ``tokensave`` selector resolves to Serena.
"""
env = os.environ.get(_CODE_MEMORY_ENV, "").strip().lower()
if env == "tokensave":
@@ -1158,9 +1158,9 @@ def _resolve_code_memory(kwargs: dict[str, Any]) -> str:
f"{_CODE_MEMORY_ENV} must be one of: {', '.join(sorted(_VALID_CODE_MEMORY))}"
)
return env
if kwargs.get("no_serena"):
return _CODE_MEMORY_NONE
return _CODE_MEMORY_SERENA
if kwargs.get("serena") and not kwargs.get("no_serena"):
return _CODE_MEMORY_SERENA
return _CODE_MEMORY_NONE
def _code_memory_flag_callback(ctx: Any, param: Any, value: str | None) -> str | None:
@@ -1172,7 +1172,7 @@ def _code_memory_flag_callback(ctx: Any, param: Any, value: str | None) -> str |
return value
# Shared selector applied to code-memory-capable subcommands (claude/codex/grok).
# Shared selector applied to code-memory-capable subcommands (claude/codex/grok/opencode).
# ``expose_value=False`` so no subcommand signature changes; it flows purely
# through HEADROOM_CODE_MEMORY.
_code_memory_option = click.option(
@@ -1183,7 +1183,7 @@ _code_memory_option = click.option(
is_eager=True,
callback=_code_memory_flag_callback,
help=(
"Code-memory MCP to register: 'serena' (default) or 'none'. "
"Code-memory MCP to register: 'none' (default) or 'serena'. "
"Also set by HEADROOM_CODE_MEMORY. Replaces --serena/--no-serena."
),
)
@@ -1266,7 +1266,7 @@ def _legacy_code_memory_options(command: Any) -> Any:
"--no-tokensave",
is_flag=True,
hidden=True,
help="Deprecated and ignored: tokensave was retired; Serena is the default code memory.",
help="Deprecated and ignored: tokensave was retired.",
),
):
command = decorator(command)
@@ -2876,19 +2876,22 @@ def _remove_headroom_installed_serena_mcp(registrar: Any) -> str:
return "failed"
def _disable_serena_mcp(
registrar: Any, *, verbose: bool = False, reason: str = "--no-serena"
) -> None:
def _disable_serena_mcp(registrar: Any, *, verbose: bool = False, explicit: bool = True) -> None:
"""Actively disable a Headroom-installed Serena entry, not merely skip it.
Serena used to be registered by default, so a prior ``headroom wrap``
persists a ``serena`` entry into the agent's MCP config; the agent then
keeps launching Serena on startup. Just *skipping* registration on a later
run leaves that stale entry in place — so this removes the entry Headroom
installed. A user-managed Serena (absent from our ledger) is reported but
left untouched. ``reason`` is surfaced in the message (e.g. ``--no-serena``
or ``--code-memory none`` when the user opted out).
installed. A user-managed Serena (absent from our ledger) is left
untouched, and only reported when the user opted out (``explicit``) or
asked for ``verbose`` output — otherwise every default wrap would say so.
"""
reason = (
"--code-memory none / HEADROOM_CODE_MEMORY=none"
if explicit
else "Serena is now off by default; pass --code-memory serena to keep it"
)
if not registrar.detect():
if verbose:
click.echo(f" Serena MCP: {registrar.display_name} not detected — skipping")
@@ -2904,10 +2907,11 @@ def _disable_serena_mcp(
click.echo(f" Removed previously-installed Serena MCP ({reason})")
click.echo(f" restart {registrar.display_name} if it was already running")
elif status == "not_headroom_owned":
click.echo(
" Serena MCP is present but user-managed — leaving it in place "
"(--no-serena only removes entries Headroom installed)"
)
if explicit or verbose:
click.echo(
" Serena MCP is present but user-managed — leaving it in place "
"(Headroom only removes entries it installed)"
)
else: # "failed"
click.echo(
" Serena MCP: removal failed — remove the 'serena' entry from your MCP config manually"
@@ -2980,13 +2984,18 @@ def _disable_tokensave_mcp(registrar: Any, *, verbose: bool = False) -> None:
)
def _code_memory_opted_out(kwargs: dict[str, Any]) -> bool:
"""Whether 'none' was chosen explicitly rather than reached by default."""
return bool(os.environ.get(_CODE_MEMORY_ENV, "").strip() or kwargs.get("no_serena"))
def _setup_coding_compressor(registrar: Any, *, serena_context: str, **kwargs: Any) -> None:
"""Set up the code-memory MCP, selected via ``--code-memory`` (default serena).
"""Set up the code-memory MCP, selected via ``--code-memory`` (default none).
Selection (see :func:`_resolve_code_memory`):
* ``serena`` (default) — register Serena (mature, offline, symbol-level).
* ``none`` — register nothing.
* ``none`` (default) — register nothing; remove a Serena entry Headroom installed.
* ``serena`` — register Serena (offline, symbol-level).
Either way, any Headroom-installed ``tokensave`` entry from a prior release
is removed (tokensave was retired in favour of Serena). The deprecated
@@ -3001,7 +3010,7 @@ def _setup_coding_compressor(registrar: Any, *, serena_context: str, **kwargs: A
_disable_tokensave_mcp(registrar, verbose=verbose)
if selection == _CODE_MEMORY_NONE:
_disable_serena_mcp(registrar, verbose=verbose, reason="--code-memory none")
_disable_serena_mcp(registrar, verbose=verbose, explicit=_code_memory_opted_out(kwargs))
return
_setup_serena_mcp(registrar, context=serena_context, verbose=verbose, force=force)
@@ -6179,13 +6188,13 @@ def claude(
\b
Examples:
headroom wrap claude # Start everything (Serena code memory)
headroom wrap claude # Start proxy + claude
headroom wrap claude --memory # With persistent memory
headroom wrap claude --resume <id> # Resume a session
headroom wrap claude -- -p # Claude in print mode
headroom wrap claude --no-mcp # Skip MCP retrieve tool registration
headroom wrap claude --project-settings # Persist proxy routing in .claude/settings.local.json
headroom wrap claude --code-memory none # No code-memory MCP
headroom wrap claude --code-memory serena # Also register the Serena code-memory MCP
headroom wrap claude --code-memory-scope user # Serena in every session, not just here
headroom wrap claude --1m # Preserve the 1M context window
"""
@@ -7517,7 +7526,7 @@ def codex(
headroom wrap codex # Start proxy + mcp + codex
headroom wrap codex -- "fix the bug" # Pass prompt to codex
headroom wrap codex --no-mcp # Skip MCP retrieve tool registration
headroom wrap codex --code-memory none # No code-memory MCP
headroom wrap codex --code-memory serena # Also register the Serena code-memory MCP
headroom wrap codex --port 9999 # Custom proxy port
headroom wrap codex --backend anyllm --anyllm-provider groq
"""
@@ -7832,6 +7841,7 @@ def grok(
headroom wrap grok # Start proxy + grok
headroom wrap grok -- -p "fix the bug" # Pass prompt to grok
headroom wrap grok --no-mcp # Skip MCP retrieve tool registration
headroom wrap grok --code-memory serena # Also register the Serena code-memory MCP
headroom wrap grok --port 9999 # Custom proxy port
"""
if not no_mcp:
@@ -8611,7 +8621,13 @@ def openclaw(
@_serena_instructions_option
@proxy_port_option()
@click.option("--no-mcp", is_flag=True, help="Skip headroom MCP server registration")
@click.option("--no-serena", is_flag=True, help="Skip Serena MCP server registration")
@_code_memory_option
@click.option(
"--no-serena",
is_flag=True,
hidden=True,
help="Deprecated: Serena is off by default. Register no code-memory MCP.",
)
@click.option(
"--code-graph",
is_flag=True,
@@ -8674,7 +8690,7 @@ def opencode(
headroom wrap opencode # Start proxy + opencode
headroom wrap opencode -- "fix the bug" # Pass prompt to opencode
headroom wrap opencode --no-mcp # Skip MCP retrieve tool registration
headroom wrap opencode --no-serena # Skip Serena MCP registration
headroom wrap opencode --code-memory serena # Also register the Serena MCP
headroom wrap opencode --port 9999 # Custom proxy port
headroom wrap opencode --backend anyllm --anyllm-provider groq
headroom wrap opencode --copilot-subscription # Use a GitHub Copilot subscription
@@ -8747,17 +8763,18 @@ def opencode(
elif verbose:
click.echo(" Skipping MCP retrieve tool (--no-mcp)")
if not no_serena:
from headroom.mcp_registry import OpencodeRegistrar
from headroom.mcp_registry import OpencodeRegistrar
# Serena ships no "opencode" context (only agent/codex/claude-code/ide/…);
# passing --context opencode crashes Serena on launch (#1549/#1572). Use
# the generic "agent" context, which OpenCode is.
_setup_serena_mcp(OpencodeRegistrar(), context="agent", verbose=verbose, force=True)
else:
from headroom.mcp_registry import OpencodeRegistrar
_disable_serena_mcp(OpencodeRegistrar(), verbose=verbose)
# Serena ships no "opencode" context (only agent/codex/claude-code/ide/…);
# passing --context opencode crashes Serena on launch (#1549/#1572). Use
# the generic "agent" context, which OpenCode is.
_setup_coding_compressor(
OpencodeRegistrar(),
serena_context="agent",
no_serena=no_serena,
verbose=verbose,
force=True,
)
# Setup memory MCP server for OpenCode (native tool integration)
if memory:
+3 -3
View File
@@ -54,9 +54,9 @@ def build_serena_spec(context: str) -> ServerSpec:
"""Construct the canonical Serena MCP server spec for an agent context.
``--open-web-dashboard False`` suppresses Serena's browser popup on
startup. Headroom installs Serena by default, so without this flag every
wrapped session opens the Serena dashboard tab even for users who never
opted into Serena or created a ``~/.serena/serena_config.yml``. The flag
startup. Without this flag every session Headroom wraps with Serena
opens the Serena dashboard tab, even for users who never created a
``~/.serena/serena_config.yml``. The flag
overrides Serena's own config at startup (it sets
``web_dashboard_open_on_launch=False``), so it works regardless of the
user's local config. The dashboard backend still runs and remains
+37 -6
View File
@@ -1,10 +1,10 @@
"""`--no-serena` must actively disable Serena, not merely skip adding it.
Serena is installed by default, so a prior `headroom wrap` persists a
`serena` MCP entry and the agent keeps launching it (dashboard popup and
all). These tests pin that a later `--no-serena` removes the entry Headroom
installed, leaves a user-managed entry alone, and that Codex unwrap also
removes Serena.
Earlier releases installed Serena by default, so a prior `headroom wrap`
persisted a `serena` MCP entry and the agent keeps launching it (dashboard
popup and all). These tests pin that a later `--no-serena` or a default wrap
removes the entry Headroom installed, leaves a user-managed entry alone, and
that Codex unwrap also removes Serena.
"""
from __future__ import annotations
@@ -86,7 +86,7 @@ def test_disable_noop_when_serena_absent(
wrap_cli._disable_serena_mcp(registrar, verbose=True)
assert registrar.unregistered == []
assert "Skipping Serena MCP (--no-serena)" in capsys.readouterr().out
assert "Skipping Serena MCP (--code-memory none" in capsys.readouterr().out
def test_disable_noop_when_agent_not_detected(
@@ -123,3 +123,34 @@ def test_unwrap_codex_removes_headroom_installed_serena(
assert result.exit_code == 0, result.output
assert registrar.unregistered == ["serena"]
assert "Removed Headroom-installed Serena MCP server from Codex" in result.output
def test_default_wrap_removes_headroom_installed_serena_and_says_how_to_keep_it(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
) -> None:
# Serena is off by default now: an upgrading user's Headroom-installed entry
# is removed on the next wrap, with the way to opt back in.
monkeypatch.setenv("HEADROOM_WORKSPACE_DIR", str(tmp_path / ".headroom"))
monkeypatch.delenv("HEADROOM_CODE_MEMORY", raising=False)
spec = build_serena_spec("claude-code")
record_install("claude", spec)
registrar = _FakeRegistrar("claude", server=spec)
wrap_cli._setup_coding_compressor(registrar, serena_context="claude-code")
assert registrar.unregistered == ["serena"]
assert "pass --code-memory serena to keep it" in capsys.readouterr().out
def test_default_wrap_leaves_user_managed_serena_silently(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
) -> None:
# A Serena the user registered is theirs: kept, and no notice on every wrap.
monkeypatch.setenv("HEADROOM_WORKSPACE_DIR", str(tmp_path / ".headroom"))
monkeypatch.delenv("HEADROOM_CODE_MEMORY", raising=False)
registrar = _FakeRegistrar("claude", server=ServerSpec(name="serena", command="serena"))
wrap_cli._setup_coding_compressor(registrar, serena_context="claude-code")
assert registrar.unregistered == []
assert "Serena" not in capsys.readouterr().out
+2 -1
View File
@@ -2040,6 +2040,7 @@ def test_wrap_codex_prepare_only_registers_serena_when_uvx_exists(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_set_test_home(monkeypatch, tmp_path)
monkeypatch.setenv("HEADROOM_CODE_MEMORY", "serena")
config_file = tmp_path / ".codex" / "config.toml"
config_file.parent.mkdir(parents=True)
@@ -2049,7 +2050,7 @@ def test_wrap_codex_prepare_only_registers_serena_when_uvx_exists(
return None
with patch("headroom.cli.wrap.shutil.which", side_effect=fake_which):
# Serena is the code-memory MCP; assert it lands in the codex config.
# Serena is opted in; assert it lands in the codex config.
result = runner.invoke(main, ["wrap", "codex", "--prepare-only"])
assert result.exit_code == 0, result.output
+5 -1
View File
@@ -567,9 +567,13 @@ def test_wrap_opencode_prepare_only_registers_serena_with_agent_context(
monkeypatch.chdir(tmp_path)
monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)
_set_test_home(monkeypatch, tmp_path)
# The eager --code-memory callback writes os.environ; delenv restores it after.
monkeypatch.delenv("HEADROOM_CODE_MEMORY", raising=False)
with patch.object(wrap_mod.shutil, "which", return_value="opencode"):
result = runner.invoke(main, ["wrap", "opencode", "--prepare-only"])
result = runner.invoke(
main, ["wrap", "opencode", "--prepare-only", "--code-memory", "serena"]
)
assert result.exit_code == 0, result.output
config_file = tmp_path / ".config" / "opencode" / "opencode.json"
+16 -7
View File
@@ -1,9 +1,9 @@
"""Code-memory MCP is selectable via --code-memory (default serena).
"""Code-memory MCP is selectable via --code-memory (default none; Serena is opt-in).
Covers the resolver precedence (selector > deprecated flags > default), the
graceful retirement of the removed ``tokensave`` option, the orchestrator
dispatch for each selection, and that --code-memory is exposed on the
code-memory-capable subcommands (claude/codex/grok) but not others.
code-memory-capable subcommands (claude/codex/grok/opencode) but not others.
"""
from __future__ import annotations
@@ -24,9 +24,9 @@ def _clean_env() -> dict[str, str]:
return env
def test_default_is_serena() -> None:
def test_default_is_none() -> None:
with patch.dict(os.environ, _clean_env(), clear=True):
assert wrap._resolve_code_memory({}) == wrap._CODE_MEMORY_SERENA
assert wrap._resolve_code_memory({}) == wrap._CODE_MEMORY_NONE
def test_selector_env_wins() -> None:
@@ -39,10 +39,14 @@ def test_selector_env_wins() -> None:
def test_deprecated_flags_map_into_selector() -> None:
with patch.dict(os.environ, _clean_env(), clear=True):
assert wrap._resolve_code_memory({"serena": True}) == wrap._CODE_MEMORY_SERENA
# tokensave is retired: --no-tokensave is now a no-op → default serena
assert wrap._resolve_code_memory({"no_tokensave": True}) == wrap._CODE_MEMORY_SERENA
# tokensave is retired: --no-tokensave is a no-op → default none
assert wrap._resolve_code_memory({"no_tokensave": True}) == wrap._CODE_MEMORY_NONE
# --no-serena means "no code memory" now that tokensave is gone
assert wrap._resolve_code_memory({"no_serena": True}) == wrap._CODE_MEMORY_NONE
# opt-out wins over opt-in when both legacy flags are given
assert (
wrap._resolve_code_memory({"serena": True, "no_serena": True}) == wrap._CODE_MEMORY_NONE
)
def test_retired_tokensave_selector_maps_to_serena() -> None:
@@ -54,6 +58,7 @@ def test_retired_tokensave_selector_maps_to_serena() -> None:
def test_serena_dashboard_disabled_flips_existing_config(tmp_path, monkeypatch) -> None:
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.setenv("USERPROFILE", str(tmp_path))
cfg = tmp_path / ".serena" / "serena_config.yml"
cfg.parent.mkdir(parents=True)
cfg.write_text(
@@ -80,6 +85,7 @@ def test_serena_config_is_never_created_by_headroom(tmp_path, monkeypatch) -> No
pins our own key list would go on passing while users broke again.
"""
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.setenv("USERPROFILE", str(tmp_path))
wrap._ensure_serena_dashboard_disabled()
@@ -96,6 +102,7 @@ def test_serena_dashboard_disabled_repairs_config_missing_projects(tmp_path, mon
import yaml
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.setenv("USERPROFILE", str(tmp_path))
cfg = tmp_path / ".serena" / "serena_config.yml"
cfg.parent.mkdir(parents=True)
cfg.write_text("web_dashboard_open_on_launch: false\n")
@@ -112,6 +119,7 @@ def test_serena_dashboard_disabled_preserves_registered_projects(tmp_path, monke
import yaml
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.setenv("USERPROFILE", str(tmp_path))
cfg = tmp_path / ".serena" / "serena_config.yml"
cfg.parent.mkdir(parents=True)
cfg.write_text(
@@ -131,6 +139,7 @@ def test_serena_dashboard_disabled_preserves_registered_projects(tmp_path, monke
def test_serena_dashboard_disabled_is_idempotent(tmp_path, monkeypatch) -> None:
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.setenv("USERPROFILE", str(tmp_path))
cfg = tmp_path / ".serena" / "serena_config.yml"
cfg.parent.mkdir(parents=True)
cfg.write_text("projects: []\nweb_dashboard_open_on_launch: true\n")
@@ -202,7 +211,7 @@ def test_orchestrator_dispatch() -> None:
def test_code_memory_option_present_only_on_code_memory_agents() -> None:
runner = CliRunner()
for tool in ("claude", "codex", "grok"):
for tool in ("claude", "codex", "grok", "opencode"):
out = runner.invoke(wrap.wrap, [tool, "--help"]).output
assert "--code-memory" in out, f"--code-memory missing from `wrap {tool} --help`"
# aider does not register a code-memory MCP → no flag