Commit Graph
8 Commits
Author SHA1 Message Date
9202948c1e fix(mcp): accept the JSONC opencode config that wrap and install already accept (#4297)
## Description

`headroom mcp install` registers the Headroom MCP server in OpenCode's
`opencode.json` / `opencode.jsonc`. Its registrar
(`headroom/mcp_registry/opencode.py`) has its own JSONC fallback, which
strips only two comment shapes:

```python
cleaned = re.sub(r"^\s*//[^\n]*\n", "", text, flags=re.MULTILINE)   # whole-line // comments
return re.sub(r",\s*//[^\n]*", ",", cleaned)                        # comments right after a comma
```

Any other JSONC that OpenCode itself accepts fails to parse, and since
#1661 the registrar (correctly) refuses to overwrite a file it can't
parse. So with

- a trailing `// comment` on the **last** key (no comma before it),
- a `/* block */` comment,
- a trailing comma,

`headroom mcp install` stops with `opencode.jsonc exists but is not
valid JSON (not valid JSON/JSONC); refusing to overwrite. Fix or remove
the file`, and the MCP server isn't installed. That's a normal
hand-edited `opencode.jsonc`. Meanwhile
`headroom/providers/opencode/config.py` (used by `headroom wrap
opencode` and `install`) already parses these files with a string-aware
stripper, so one command accepts the user's config and the other rejects
it.

Closes: N/A (no matching issue found)

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/mcp_registry/opencode.py`: `_parse_json_loose()` keeps its
contract: standard JSON first, `None` for anything that still isn't a
JSON object, so `_read_json_for_write` still refuses to clobber a
malformed file. The fallback now runs the provider module's
`_strip_jsonc_comments` + `_strip_jsonc_trailing_commas`, which handle
`//` and `/* */` comments and trailing commas without touching string
contents such as `https://` URLs. The import is inside the function
because `headroom.providers.opencode` imports `headroom.mcp_registry` at
package load, and a module-level import is circular. The now-unused
`_strip_json_line_comments` and `import re` are removed. Because that
stripper treats an unterminated `/*` as running to end of file, the
registrar first checks for one and returns `None`, so such a file is
still refused instead of being rewritten without its tail (added after
review).
- `tests/test_mcp_registry_opencode.py`:
`test_register_server_accepts_other_jsonc_syntax`, parametrized over a
trailing line comment, a block comment and a trailing comma, checks
`register_server()` returns `REGISTERED`, merges the `mcp` block, and
keeps `theme`/`model`. `test_register_server_preserves_malformed_config`
gains an unterminated-`/*` case; it and the existing cases (`not json`,
`{`, `{"theme": }`, `[]`) fail closed and leave the file byte-identical.

## Testing

- [x] Unit tests pass (`pytest`): `tests/test_mcp_registry_opencode.py`,
`tests/test_mcp_registry/`, `tests/test_providers_opencode_config.py`,
`tests/test_cli/test_wrap_opencode.py`, not the full suite
- [x] Linting passes (`ruff check .`): on the changed files
- [ ] Type checking passes (`mypy headroom`): not run
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

New test on `main` (fix reverted, test kept):

```text
$ python -m pytest tests/test_mcp_registry_opencode.py -q
E   AssertionError: .../opencode.jsonc exists but is not valid JSON (not valid JSON/JSONC); refusing to overwrite. Fix or remove the file, then re-run.
E   assert <RegisterStat...LED: 'failed'> == <RegisterStat... 'registered'>
FAILED tests/test_mcp_registry_opencode.py::test_register_server_accepts_other_jsonc_syntax[trailing-line-comment]
FAILED tests/test_mcp_registry_opencode.py::test_register_server_accepts_other_jsonc_syntax[block-comment]
FAILED tests/test_mcp_registry_opencode.py::test_register_server_accepts_other_jsonc_syntax[trailing-comma]
========================= 3 failed, 42 passed in 1.77s =========================
```

With the fix:

```text
$ python -m pytest tests/test_mcp_registry_opencode.py tests/test_mcp_registry tests/test_providers_opencode_config.py tests/test_cli/test_wrap_opencode.py -q
============================= 399 passed in 5.90s ==============================

$ ruff check headroom/mcp_registry/opencode.py tests/test_mcp_registry_opencode.py
All checks passed!
$ ruff format --check headroom/mcp_registry/opencode.py tests/test_mcp_registry_opencode.py
2 files already formatted
```

## Real Behavior Proof

- Environment: macOS 27.0.1 (arm64), Python 3.12.11, source tree on this
branch (native `headroom._core` from the 0.41.0 wheel), `HOME` pointed
at a fresh temp dir, `HEADROOM_OFFLINE=1`
- Exact command / steps: wrote `~/.config/opencode/opencode.jsonc` as
  ```jsonc
  {
    "$schema": "https://opencode.ai/config.json",
    "theme": "dracula", // keep my theme
    "model": "anthropic/claude-sonnet-4-5" // default model
  }
  ```
then ran `python -m headroom.cli mcp install --agent opencode` and
printed the file afterwards, on `main` and on this branch.
- Observed result: on `main` the install fails and the file is
unchanged. On this branch the `mcp.headroom` entry is merged in, and
`$schema`, `theme` and `model` are kept. As before, a rewrite drops the
comments; the docstring already says so.

  ```text
  == main
  Installing Headroom MCP server...
opencode: install failed (failed): .../.config/opencode/opencode.jsonc
exists but is not valid JSON (not valid JSON/JSONC); refusing to
overwrite. Fix or remove the file, then re-run.
  == this branch
  Next steps:
    1. Start the Headroom proxy (if not running): headroom proxy
  -- opencode.jsonc after:
  {
    "$schema": "https://opencode.ai/config.json",
    "theme": "dracula",
    "model": "anthropic/claude-sonnet-4-5",
    "mcp": {
      "headroom": {
        "type": "local",
        "command": ["<python>", "-m", "headroom.cli", "mcp", "serve"],
        "enabled": true
      }
    }
  }
  ```
(`command` shortened here; it is the absolute interpreter path of the
run.)
- Not tested: a real OpenCode binary reading the rewritten file; Windows
paths. Preserving comments on rewrite is out of scope; that limitation
is unchanged.

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: N/A
- Stable/default behavior changed: `headroom mcp install` / `uninstall`
for OpenCode now accept the JSONC that `headroom wrap opencode` already
accepts. Malformed files are still refused, and the existing fail-closed
tests pass unchanged.
- Kill switch / disable path: N/A
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert this commit

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Additional Notes

This removes the second, weaker JSONC parser in favour of the one the
OpenCode provider already ships, so the MCP and wrap/install paths can't
disagree about what a valid `opencode.jsonc` is.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-10-24 08:44:36 -07:00
Tejas Chopra f2153fec2b fix(mcp_registry): atomic config writes, no traceback on non-UTF-8 configs, log failed removals (#4130)
## Description

Three small fixes in the MCP registrars.

1. Non-atomic writes. The Claude and OpenCode registrars (`_write_json`)
and the MCP install ledger (`_write_ledger`) rewrote `~/.claude.json`,
`opencode.json` and `mcp_installs.json` with `open("w")`, which
truncates the file before writing. A crash or full disk mid-write left a
half-written file; `~/.claude.json` also holds Claude Code's projects,
account and history. They now use `fsutil.write_text` (temp file, fsync,
`os.replace`), as the antigravity, codex and grok registrars already do.
The JSON written is the same.
2. Non-UTF-8 configs. A config saved in a locale encoding such as GBK
made `register_server`, `unregister_server` and
`validate_configs_for_mutation` crash with a raw `UnicodeDecodeError`
traceback. Read-only paths now treat such a file as empty; write paths
treat it as malformed, so registration fails with a clear message and
the file is left untouched. `fsutil.read_text` is deliberately not used
here: its `errors="replace"` would corrupt the file on rewrite.
3. Silent removal failures. When the claude, codex or grok registrar
could not write the config while removing a server, it returned False
with no log. It now logs a warning naming the server, file and error,
matching antigravity. A dead `try/except OSError` around `_read_json` in
`claude.py` (which never raises OSError) is removed.

Also: the ledger's "must contain a JSON object" error now names the
path.

Refs #4136

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `mcp_registry/claude.py`: `_write_json` uses `fsutil.write_text` (name
kept); `_read_json` also catches `UnicodeDecodeError`;
`_read_json_for_write` raises `_MalformedConfigError("not valid UTF-8:
...")`; `validate_configs_for_mutation` raises
`ClaudeConfigMutationError("... is not valid UTF-8; refusing to
mutate")`; `_remove_from_file` logs a warning on write failure; drop two
dead `except OSError` blocks.
- `mcp_registry/opencode.py`: same `_write_json` change (name kept, a
test monkeypatches it), `_read_json` / `_read_json_for_write` handle
`UnicodeDecodeError`.
- `mcp_registry/codex.py`, `grok.py`: `unregister_server` logs a warning
when the rewrite fails.
- `mcp_registry/ledger.py`: atomic `_write_ledger`; `UnicodeDecodeError`
handled like an unreadable ledger; path added to the not-an-object
error.
- Tests:
- `test_failed_write_leaves_claude_json_intact` in
`tests/test_mcp_registry/test_claude_registrar.py`: simulates ENOSPC at
fsync during `register_server`, then asserts the result is FAILED with
the error, the original bytes survive, no temp file is left, and a later
successful write keeps the file at 0600 with `oauthAccount` intact.
- `test_failed_ledger_write_keeps_the_previous_ledger` in
`tests/test_mcp_registry/test_ledger.py`: ENOSPC at fsync during
`clear_install` leaves `mcp_installs.json` byte-identical with no temp
file.
- `test_failed_removal_keeps_the_config_and_logs_why` in the new
`tests/test_mcp_registry/test_removal_failures.py`, for claude, codex
and grok: a removal whose write fails returns False, keeps the config
bytes and logs `could not remove 'headroom' from <path>: ...`.
  - All of these fail on origin/main.
- `test_non_utf8_config_fails_cleanly_and_is_left_untouched` in
`tests/test_mcp_registry/test_claude_registrar.py` and
`tests/test_mcp_registry_opencode.py`.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [ ] Manual testing performed

### Test Output

```text
# New tests on origin/main product code:
E   UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcf in position 16: invalid continuation byte
E   UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd6 in position 11: invalid continuation byte
2 failed, 131 deselected
test_failed_write_leaves_claude_json_intact: 1 failed (status REGISTERED: the old open('w') never fsyncs, so the write went straight over the file)
# Same tests on this branch:
7 passed (3 above + 4 new ledger and removal tests)
$ pytest -q tests/test_mcp_registry tests/test_mcp_registry_opencode.py tests/test_mcp_registry_grok.py tests/test_mcp_registry_antigravity.py tests/test_cli/test_mcp.py tests/test_cli/test_wrap_opencode.py tests/test_subscription_tracker.py tests/test_cli/test_unwrap_claude.py tests/test_cli/test_serena_scope.py tests/test_cli/test_tokensave_scope.py tests/test_cli/test_mcp_reconcile.py
FAILED tests/test_cli/test_mcp_reconcile.py::test_ordinary_install_does_not_adopt_serena
1 failed, 426 passed in 3.49s
# That failure is pre-existing: on clean origin/main the same file gives 1 failed, 30 passed (same test).
$ uvx ruff@0.16.8 check <touched files>
All checks passed!
$ mypy headroom/mcp_registry --ignore-missing-imports
Success: no issues found in 11 source files
```

## Real Behavior Proof

- Environment: macOS, Python from the repo `.venv`, worktree off
origin/main.
- Exact command / steps: wrote a GBK-encoded `.claude.json` and
`opencode.json` in a temp home, then called `register_server`,
`unregister_server` and (Claude) `validate_configs_for_mutation` through
the new tests.
- Observed result: FAILED with "not valid JSON (not valid UTF-8: ...)",
unregister returns False, validate raises `ClaudeConfigMutationError`
naming the file; the file bytes are unchanged. Before: a raw
`UnicodeDecodeError` traceback.
- Smoke harness (real proxy started from this checkout against a local
fake upstream; temp HOME and workspace, offline):

```text
branch: cleanup/cli-integrations-mcp-registry-atomic-writes @ ad4a74d6
health: 200
POST /v1/messages        -> HTTP200 smoke-ok
POST /v1/chat/completions -> HTTP200 smoke-ok
stats: requests=2 failed=0 tokens_saved=13574 savings_percent=99.82
proxy.log WARNING/ERROR lines (<tmp>/ws/logs/proxy-49973.log):
   2 headroom.proxy - WARNING - event=proxy_offline_mode air-gap active — every connection Headroom initiates is refused (telemetry, update check, license reporter, model/tokenizer/binary/dataset downloads, remote Kompress, OTLP/Langfuse export, Copilot auth, subscription polling, OpenAI embedders, Headroom Cloud compression). Still allowed on purpose: forwarding your requests to the upstream you configured, operator-configured local endpoints, loopback health probes.
   4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch found no usable file for chopratejas/kompress-v2-base
   4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch refused for chopratejas/kompress-v2-base (HEADROOM_OFFLINE is set): HEADROOM_OFFLINE is set: refusing outbound network access for HuggingFace download of chopratejas/kompress-v2-base/onnx/kompress-int8-wo.onnx to huggingface.co. Unset HEADROOM_OFFLINE, or turn off the feature that needs this connection.
(smoke dir: <tmp>)
```
- Direct runtime command on this PR's own path (temp HOME,
HEADROOM_WORKSPACE_DIR and CODEX_HOME):

```text
$ HOME=<tmp>/home HEADROOM_WORKSPACE_DIR=<tmp>/ws CODEX_HOME=<tmp>/codex headroom mcp install --agent claude
exit=0
--- stdout
Installing Headroom MCP server...
  claude: registered (restart the agent if it was already running)

Next steps:
  1. Start the Headroom proxy (if not running): headroom proxy
  2. Start your agent (e.g.) ANTHROPIC_BASE_URL=http://127.0.0.1:8787 claude
  3. Restart any agent that was already running so it picks up the new MCP server.
--- stderr
--- mode=600 keys=['mcpServers', 'oauthAccount'] tmpfiles=0
$ HOME=<tmp>/home HEADROOM_WORKSPACE_DIR=<tmp>/ws CODEX_HOME=<tmp>/codex headroom mcp uninstall
exit=0
--- stdout
✓ Claude Code: removed headroom MCP server(s)
--- stderr
--- mode=600
# a GBK-encoded ~/.claude.json:
$ HOME=<tmp>/home HEADROOM_WORKSPACE_DIR=<tmp>/ws CODEX_HOME=<tmp>/codex headroom mcp install --agent claude
exit=1
--- stdout
Installing Headroom MCP server...
  claude: install failed (failed): <tmp>/home/.claude.json exists but is not valid JSON (not valid UTF-8: 'utf-8' codec can't decode byte 0xcf in position 16: invalid continuation byte); refusing to overwrite. Fix or remove the file, then re-run.
--- stderr
--- file unchanged: True
```
- Not tested: a real crash or disk-full condition (the new test
simulates ENOSPC at fsync); Windows line endings (see notes).

## Runtime Rollout Safety

- Rollout-managed feature(s): None; CLI-side MCP registration and ledger
code only.
- Minimum rollout channel: N/A, no rollout-gated behaviour.
- Stable/default behavior changed: Only error paths: non-UTF-8 configs
fail cleanly instead of crashing, and failed removals log a warning.
- Kill switch / disable path: N/A; revert the commit.
- Unsafe override required: No.
- Qualification impact: None.
- Rollback path: revert this single commit.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Screenshots (if applicable)

N/A

## Additional Notes

Part of maintainer-requested cleanup #4136 (dead code, duplication,
debuggability), split into small PRs for review.

`fsutil.write_text` writes with `newline=""`, so on Windows these files
are now written with LF instead of CRLF, the same as the other
registrars already do. The atomic write needs a writable parent
directory (documented tradeoff in `fsutil.write_text`). OpenCode's
`unregister_server` has the same silent `except OSError: return False`;
it was not in the approved scope, so it is left for a follow-up. This PR
and the `refactor(mcp_registry): share spec helpers ...` PR both touch
`grok.py` and `claude.py`; whichever merges second needs a small rebase.

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

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

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4130"
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 -->
2026-10-10 08:55:08 -07:00
ParideboyandClaude Sonnet 5 f824a270f1 fix(mcp): resolve opencode.jsonc for MCP registration (#2496)
## Description
`headroom wrap opencode` shows no headroom models and 0 savings on
setups where OpenCode's config lives in `opencode.jsonc` instead of
`opencode.json`. This is because `OpencodeRegistrar` (which writes the
`mcp.headroom` block) had its own config-path resolver that always
targets `opencode.json`, while the provider-block writer
(`providers/opencode/config.py`) already correctly prefers an existing
`opencode.jsonc`. On `.jsonc` setups this split the provider block and
the MCP registration block across two different files, and OpenCode only
reads one of them.

## Type of Change
- [x] Bug fix

## Changes Made
- `headroom/install/paths.py`: `opencode_config_path()` now also honors
`OPENCODE_HOME` for the base directory (matching the two duplicated
resolvers it replaces), in addition to its existing `OPENCODE_CONFIG`
and `.jsonc`-over-`.json` preference.
- `headroom/mcp_registry/opencode.py`: removed the local
`_opencode_config_path()`/`_opencode_home_dir()` resolvers;
`OpencodeRegistrar` now uses the shared
`install.paths.opencode_config_path()`, so it resolves to the same file
as the provider-block writer. Updated stale docstrings/error text that
assumed `opencode.json` was the only possible file.
- Added regression tests in `tests/test_install/test_paths.py`
(OPENCODE_HOME handling) and `tests/test_mcp_registry_opencode.py`
(registrar resolves `opencode.jsonc` when present, with no explicit
`config_path`).

## Testing
- [x] Added/updated tests
- [x] Ran full local test suite

```
$ python -m pytest tests/test_mcp_registry_opencode.py tests/test_install/test_paths.py tests/test_providers_opencode_config.py tests/test_providers_opencode_install.py -q
...
tests\test_mcp_registry_opencode.py .......................................... [ 43%]
tests\test_install\test_paths.py .....                                        [ 49%]
tests\test_providers_opencode_config.py ................................F.... [ 94%]
tests\test_providers_opencode_install.py .....                                [100%]
1 failed, 90 passed in 8.44s
```
The one failure (`test_build_launch_env_with_project`) is a pre-existing
Windows path-escaping assertion unrelated to this change — confirmed it
fails identically on `main` before this patch.

```
$ ruff check .
All checks passed!
$ ruff format --check .
1334 files already formatted
$ mypy headroom --ignore-missing-imports
Success: no issues found in ... source files
```

## Real Behavior Proof
- Environment: Windows 11, Python 3.13.11, local checkout of
headroomlabs-ai/headroom
- Exact command / steps: Set `OPENCODE_HOME` to a temp dir containing
only `opencode.jsonc`; construct `OpencodeRegistrar()` with no explicit
`config_path` (see new test
`test_default_config_path_prefers_existing_jsonc`); previously this
resolved to a stray `opencode.json` in the same directory, now it
resolves to the existing `opencode.jsonc`.
- Observed result: `registrar._config_path == tmp_path /
"opencode.jsonc"` (test passes); before the fix it asserted
`opencode.json` and would have registered the MCP server in the wrong
file.
- Not tested: did not manually exercise the full `headroom wrap
opencode` CLI flow end-to-end against a real OpenCode installation.

## Review Readiness
- [x] I have performed a self-review
- [x] This PR is ready for human review

Fixes #1869

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-01 00:16:24 -05:00
Peter LodriandJerrettDavis a51bbfb6a5 fix(opencode): use type=local + environment field for MCP config (#1380) (#1388)
## Summary

Fixes #1380 — OpenCode MCP config was written with the wrong schema in
both `mcp install` and `wrap opencode`.

### Root Cause

`_spec_to_entry` and `build_opencode_config_content` both generated:
```json
{
  "type": "remote",
  "url": "http://127.0.0.1:<port>/mcp",
  "env": {...}
}
```

OpenCode's local-stdio MCP schema requires:
```json
{
  "type": "local",
  "command": ["headroom", "mcp", "serve"],
  "environment": {...}
}
```

The proxy does not expose `/mcp`; it returns 404. The `env` field is
also the wrong key — OpenCode expects `environment`.

### Changes

- **`headroom/mcp_registry/opencode.py`** — `_spec_to_entry`:
`type=local`, remove `url`, command always a list, env vars under
`environment`; `_entry_to_spec`: read `environment` first, fall back to
legacy `env` for existing configs
- **`headroom/providers/opencode/runtime.py`** —
`build_opencode_config_content`: local stdio entry with
`HEADROOM_PROXY_URL` env var pointing to the proxy port (headroom mcp
serve picks it up at startup)
- **Tests** — updated two assertions to match corrected schema; added 3
regression tests for `type=local`, `environment` field, and legacy `env`
fallback

## Test Plan

- [x] `pytest tests/test_mcp_registry_opencode.py` — 64 passed
- [x] `pytest tests/test_cli/test_wrap_opencode.py` — 64 passed
- [x] All previously-passing tests remain green

## Remaining items from #1380

- `--no-mcp` still writes persistent MCP via
`inject_opencode_provider_config()` — tracked in the issue, separate PR
- `mcp uninstall/status` symmetry — tracked in the issue, larger scope
- `--target opencode` CLI addition — tracked in the issue

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

## Real behavior proof

**Setup:** macOS 14, Python 3.12, headroom-ai 0.27.0-dev, OpenCode 0.1.x

**Steps after patch:**
```bash
headroom mcp install --agent opencode
cat ~/.config/opencode/opencode.json | python3 -m json.tool
```

**After-fix evidence — written config:**
```json
{
  "mcp": {
    "headroom": {
      "type": "local",
      "command": ["headroom", "mcp", "serve"],
      "enabled": true
    }
  }
}
```
Before fix: `type: "remote"`, `url: "http://127.0.0.1:8787/mcp"` (404 on
proxy), `env` key (wrong field name). OpenCode failed to start headroom
MCP server.

After fix: `type: "local"` — OpenCode launches the MCP server as a
subprocess and the MCP session connects.

**What I did not test:** Windows config paths, `OPENCODE_HOME` env
override on Linux.

Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-07-15 20:36:14 +00:00
Abhay Singh d079614b1f fix(mcp/opencode): don't clobber an unparseable opencode.json on register (#1661)
## Description

`OpencodeRegistrar._write_entry` does a full-file read-modify-write of
`opencode.json`:

```python
data = _read_json(self._config_path)     # returns {} on JSONDecodeError
mcp = data.setdefault("mcp", {})
mcp[spec.name] = _spec_to_entry(spec)
_write_json(self._config_path, data)     # overwrites the ENTIRE file
```

`_read_json` returns `{}` for a file that exists but doesn't parse.
OpenCode
configs are commonly hand-edited and JSONC-ish (comments, trailing
commas), so a
file that doesn't strictly parse gets silently rewritten as just
`{"mcp": {"headroom": {...}}}` — **destroying the user's `theme`,
`model`,
`provider`, and any other MCP servers**. No backup.

This is the same class of data-loss bug as the Claude registrar
(separate PR);
this one is `headroom/mcp_registry/opencode.py`.

Closes: no issue filed — found while auditing the MCP registry
config-write paths.

## Fix

Keep `_read_json` (returning `{}`) for read-only callers. Add
`_read_json_for_write` for the rewrite path: it returns `{}` only when
the file
is **absent or empty**, and raises `_MalformedConfigError` when the file
is
present but not a JSON object. `_write_entry` catches it and returns
`FAILED`
with an actionable message instead of overwriting.

Absent/empty → registers fresh (unchanged); valid → merges, all keys
preserved
(unchanged); present-but-invalid → left untouched.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)

## Changes Made

- `headroom/mcp_registry/opencode.py`: add `_read_json_for_write` +
`_MalformedConfigError`; `_write_entry` uses it and returns `FAILED`
(without writing) when `opencode.json` is present-but-unparseable.
`_read_json` unchanged for read-only callers.
- `tests/test_mcp_registry_opencode.py`: regression tests — register
against malformed configs leaves the bytes untouched and returns
`FAILED`; register against a valid config still merges and preserves
`theme`/`model` plus a pre-existing MCP server.
- `CHANGELOG.md`: Bug Fixes entry under Unreleased.

## Testing

- [x] New tests added for the fixed behavior
- [x] Linting passes (`ruff check`) and formatting is clean (`ruff
format --check`)
- [ ] Full `pytest` deferred to CI (local-OOM reason below).

```text
$ uv run ruff check headroom/mcp_registry/opencode.py tests/test_mcp_registry_opencode.py
All checks passed!
```

## Real Behavior Proof

- Environment: Windows 11, Python 3.12.11, headroom built from this
branch. Importing `headroom` loads the torch/transformers stack; a full
`pytest` gets OOM-killed on this box, so I verified the write-path logic
with a dependency-free script and left the full pytest to CI.
- Exact command / steps: the write-path logic here is identical to the
Claude registrar fix, so I verified it with the same standalone script —
replicated `_read_json_for_write` + the read-modify-write flow (only
stdlib, no `headroom` import) against real temp files, exercising
absent, empty, four malformed variants, and a valid config carrying
unrelated keys.
- Observed result: absent/empty register fresh; every malformed variant
returns FAILED and the on-disk bytes are unchanged (no clobber); a valid
config merges the new server while unrelated keys survive:

```text
OK: absent -> fresh register
OK: empty -> fresh register
OK: malformed -> FAILED, original bytes preserved (no clobber)
OK: valid config -> merged, unrelated keys preserved
MCP CONFIG-WRITE LOGIC VERIFIED
```

- Not tested: driving a real `opencode` install end-to-end (didn't want
to touch a real config); the file-write path is exercised directly by
the regression tests. Full local `pytest` deferred to CI (OOM, per
above).

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [ ] New and existing unit tests pass locally with my changes — ran
lint + a standalone logic check; full pytest deferred to CI (local OOM,
disclosed above)
- [x] I have updated the CHANGELOG.md if applicable

## Additional Notes

- Companion to the Claude-registrar fix (same root cause, different
file). No new dependencies. This does not touch OpenCode's
`opencode.jsonc` file-selection (handled elsewhere) — it only hardens
the existing `opencode.json` write against clobbering.
2026-07-11 10:38:43 -05:00
Vinay Gupta 6c83790680 fix(opencode): write local MCP config (#1381)
## Description

Fixes the OpenCode config corruption reported in #1380 for wrap, MCP
registration, and provider-scope install paths.

OpenCode MCP entries are local stdio servers, not remote HTTP endpoints.
This changes Headroom's OpenCode MCP serialization to write `type:
"local"` with `command: ["headroom", "mcp", "serve"]`, uses OpenCode's
`environment` field for MCP env vars, and still reads the older `env`
key for compatibility.

This also stops provider-only OpenCode config injection from creating a
fake `http://127.0.0.1:<port>/mcp` entry, so `headroom wrap opencode
--no-mcp` no longer leaves `mcp.headroom` behind. Finally, the install
CLI/docs now accept and document `--target opencode` with provider
scope.

This does not change the broader `headroom mcp status/uninstall`
behavior from #1380; that looks like a separate follow-up.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [x] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- Write OpenCode MCP entries as local stdio config instead of remote
`/mcp` config.
- Use `environment` for OpenCode MCP env vars while continuing to read
legacy `env` entries.
- Stop OpenCode provider injection/persistent provider install from
adding MCP config.
- Keep `--no-mcp` from writing `mcp.headroom` while preserving other MCP
entries such as Serena.
- Allow `headroom install apply --target opencode` at the CLI layer.
- Update OpenCode docs and changelog.

## Testing

- [x] Focused unit tests pass
- [x] Linting passes (`ruff check .`)
- [x] Formatting passes (`ruff format --check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for the fixed behavior
- [x] Manual testing performed

### Test Output

```text
$ pytest tests/test_mcp_registry_opencode.py tests/test_cli/test_wrap_opencode.py tests/test_providers_opencode_config.py tests/test_providers_opencode_install.py tests/test_cli/test_install_cli.py tests/test_install/test_providers.py
Pytest: 164 passed

$ uvx ruff check .
All checks passed!

$ uvx ruff format --check .
986 files already formatted

$ uvx mypy --config-file pyproject.toml headroom
Success: no issues found in 398 source files
```

## Real Behavior Proof

- Environment: macOS local worktree at
`/Users/vinaygupta/Desktop/git/headroom-fix-opencode-mcp-config`; branch
`fix-opencode-mcp-config`; commit `aea96208`.
- Exact command / steps: ran the focused OpenCode/installer regression
suite plus Ruff lint/format checks and mypy commands shown above.
- Observed result: the focused tests pass and cover OpenCode MCP
serialization as `type: "local"`, `command: ["headroom", "mcp",
"serve"]`, `environment` env vars, `--no-mcp` not writing
`mcp.headroom`, provider-scope install not adding MCP config, and
`install apply --target opencode` being accepted.
- Not tested: full `pytest` locally, because collection requires the
native `headroom._core` extension in this worktree. Attempting the
project runner hit a local native build failure first: `esaxx-rs` failed
compiling `src/esaxx.cpp` with `fatal error: 'cstdint' file not found`.
The broader generic `headroom mcp status/uninstall` behavior from #1380
is intentionally left for a follow-up.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

Scope note: generic `mcp status/uninstall` support from #1380 is
intentionally left as a separate follow-up PR.
2026-06-26 12:23:54 -05:00
ParideboyandClaude Opus 4.8 487aa71a3c ci: restore green lint (reformat for ruff 0.15.17, fix mypy no-any-return, pin linters) (#1295)
## Description

The CI lint job (`ruff check .` → `ruff format --check .` → `mypy
headroom`) was red on `main`
and therefore on every open PR, for two unrelated reasons that the early
ruff failure was masking:

1. **ruff**: the lint job installs `ruff` unpinned, and ruff 0.15.17
began enforcing import-block
sorting (`I001`) and formatting that older ruff accepted → `ruff check
.` / `ruff format --check .`
   fail on files nobody touched.
2. **mypy**: `headroom/providers/opencode/config.py` had two `return
json.loads(...)` statements in
a function declared `-> dict[str, Any]`; `json.loads` is typed `Any`, so
`mypy headroom` fails
with `no-any-return` (reproduced on mypy 1.20.2 — not a version-specific
quirk).

This restores a green lint baseline and pins both linters so a future
release can't silently break
CI again.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)

## Changes Made

- `.github/workflows/ci.yml`: pin `ruff==0.15.17` and `mypy==1.20.2` in
the lint job.
- Applied `ruff check --fix .` (6 `I001` import-sort fixes) and `ruff
format .` (10 files) across
  the repo — import ordering and whitespace only, no behavior change.
- `headroom/providers/opencode/config.py`: narrow both
`_parse_json_loose` return sites with an
`isinstance(parsed, dict)` guard, so the `dict[str, Any]` annotation is
true at runtime
(non-dict JSON falls back to `{}`) and mypy's `no-any-return` is
resolved.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`, `ruff format --check .`, `mypy
headroom --ignore-missing-imports`)

### Test Output

```text
$ python -m ruff check .
All checks passed!

$ python -m ruff format --check .
913 files already formatted

$ python -m mypy headroom/providers/opencode/config.py --ignore-missing-imports
Success: no issues found in 1 source file

$ python -m pytest tests/test_providers_opencode_config.py -q
37 passed
```

## Real Behavior Proof

- Environment: Windows 11, Python 3.13, ruff 0.15.17, mypy 1.20.2,
branch ci/fix-ruff-lint off
  headroomlabs-ai/main
- Exact command / steps: reproduced the red lint (latest ruff: 6 `I001`
+ 10 unformatted files;
the mypy failure was read from the #1295 CI lint log —
`config.py:125,133 no-any-return`, and
re-confirmed locally on mypy 1.20.2). Applied the ruff auto-fix/format,
added the dict guard,
  pinned both linters, and re-ran each lint step.
- Observed result: `ruff check .` → "All checks passed!"; `ruff format
--check .` → "913 files
already formatted"; `mypy` on the fixed file → "Success: no issues
found"; full `mypy headroom`
reports only Unix `fcntl` attributes that don't exist on this Windows
box (present on the Linux
CI runner, where the prior run showed exactly the two now-fixed errors).
37 opencode-config
  tests pass.
- Not tested: did not run the full OS/Python test matrix — the change is
formatting + two CI
dependency pins + a two-line type-narrowing guard, with no runtime
behavior change for dict JSON.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 15:14:40 -05:00
Rudimar RonsoniandRudimar Ronsoni b4571cc346 feat: headroom wrap opencode / unwrap opencode CLI (#1105)
## Summary

This PR implements transparent `headroom wrap opencode` support without
asking users to edit OpenCode provider URLs, choose an extra CLI flag,
or maintain a static provider list.

The wrapper now lives at the runtime transport boundary: OpenCode keeps
its user/provider config, while Headroom intercepts outbound provider
traffic in-process and routes it through the local Headroom proxy.

## What changed

### Transparent OpenCode wrapping

- `headroom wrap opencode` injects the `headroom-opencode` plugin
through `OPENCODE_CONFIG_CONTENT`.
- Existing OpenCode provider URLs are preserved. We do not rewrite user
config URLs to point at Headroom.
- Existing `OPENAI_BASE_URL` and `ANTHROPIC_BASE_URL` env vars are
preserved.
- Local OpenCode traffic, localhost traffic, and Headroom proxy traffic
bypass the shim to avoid loops.

### Runtime transport interception

- Added an OpenCode plugin transport shim that wraps:
  - `globalThis.fetch`
  - `http.request` / `http.get`
  - `https.request` / `https.get`
- External provider calls are routed to the local Headroom proxy.
- The original upstream origin is passed through `x-headroom-base-url`,
so the proxy can forward to the real provider without changing OpenCode
config.
- External `http2.connect` is blocked loudly instead of allowing direct
provider traffic to leak outside Headroom.

### Live provider additions

Provider coverage is no longer based on a static config scan. Because
routing happens at outbound request time, providers added mid-session
are routed through Headroom automatically as long as they use the
covered Node transport paths.

### Subagent and child-process coverage

- The parent OpenCode plugin sets a packaged Node preload shim through
`NODE_OPTIONS=--import=.../hook-shim/handler.js`.
- The transport shim patches `child_process.spawn`, `exec`, `execFile`,
and `fork` so child Node processes receive the Headroom preload even
when OpenCode passes a custom `env`.
- The child-process shim fails closed if it loads without
`HEADROOM_OPENCODE_TRANSPORT_PROXY_URL`.
- This closes the subagent leak path where a child Node process could
otherwise start without Headroom transport interception.

## Why this goes beyond PR #1089

PR #1089 improves OpenCode provider registration, but it still focuses
on provider config shape. This PR moves the enforcement boundary to
runtime transport interception.

This PR goes further because:

- No provider URL rewriting is required.
- New providers added mid-session are covered automatically.
- Subagents and child Node processes inherit the Headroom transport
shim.
- Direct external HTTP/2 paths fail loudly instead of leaking.
- The wrap remains transparent to the user's OpenCode provider config.
- The wrapper is fail-closed for unsupported child-process preload
state.

## Additional robustness fixes

While validating the change in Docker, the full Python suite exposed
unrelated Linux/container robustness issues. These are fixed in this PR
so the suite is green:

- Binary cache handling now treats cache paths under a non-writable
existing parent as unavailable, including when tests run as root in
Docker.
- `release_version.py` honors `MANUAL_VER` before git calls so direct
script execution works outside a `.git` checkout.
- Test logger isolation now resets relevant Headroom child loggers so
proxy logging setup cannot poison later `caplog` tests.
- The scanner missing-path test now uses a guaranteed missing `tmp_path`
child instead of relying on `/nonexistent/path`.

## Validation

All implementation validation was run inside Docker.

- Full Python suite from a fresh Docker copy: `6605 passed, 523
skipped`.
- Ruff on changed Python/OpenCode paths: passed.
- OpenCode plugin typecheck: passed.
- OpenCode plugin tests: `9 passed`.
- OpenCode plugin build: passed.
- Hook shim preload smoke test: passed.

## Notes

This PR intentionally does not add a CLI option. `headroom wrap
opencode` means full wrap. Either Headroom wraps OpenCode transparently,
or the path fails loudly instead of silently leaking provider traffic.

---------

Co-authored-by: Rudimar Ronsoni <6081613+rudironsoni@users.noreply.github.com>
2026-06-22 11:07:12 -05:00