Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

[codex] Make Claude project settings injection opt in (#1600)

Feng Lin07b451153750
diff --git a/.claude/.headroom_wrap_settings.lock b/.claude/.headroom_wrap_settings.lock
deleted file mode 100644
index e69de29bb..000000000
diff --git a/.gitignore b/.gitignore
index fd0e2ce49..3445a7647 100644
--- a/.gitignore
+++ b/.gitignore
@@ -214,6 +214,7 @@ examples/vertex_gemini_benchmark/results.json
# Headroom specific
.headroom/
.claude/.headroom_wrap_*.json
+.claude/.headroom_wrap_settings.lock
headroom.db
headroom_*.db
*.jsonl
diff --git a/headroom/cli/wrap.py b/headroom/cli/wrap.py
index 6146bde17..5f6f04df5 100644
--- a/headroom/cli/wrap.py
+++ b/headroom/cli/wrap.py
@@ -363,6 +363,7 @@ _AGENT_SAVINGS_WRAP_AGENTS = {
"grok",
"grok_build",
}
+_CLAUDE_PROJECT_SETTINGS_ENV = "HEADROOM_CLAUDE_PROJECT_SETTINGS"
# 1M context window for `wrap claude` (#1158). Claude Code only sends the
# `context-1m` beta header — unlocking the 1M window for entitled subscription
@@ -1311,6 +1312,16 @@ def _foundry_proxy_url(proxy_url: str) -> str:
return proxy_url.rstrip("/") + "/anthropic"
+def _claude_project_settings_enabled(project_settings: bool) -> bool:
+ """Return whether wrap claude should write project-local Claude settings."""
+ env_enabled = _env_bool_value(os.environ.get(_CLAUDE_PROJECT_SETTINGS_ENV, ""))
+ return project_settings or env_enabled
+
+
+def _claude_project_settings_skip_reason() -> str:
+ return f"use --project-settings or {_CLAUDE_PROJECT_SETTINGS_ENV}=1 to persist proxy routing"
+
+
def _vertex_target_api_url_from_claude_env(proxy_url: str) -> str | None:
"""Return the Vertex upstream that the proxy should use for Claude Code."""
explicit_target = os.environ.get("VERTEX_TARGET_API_URL", "").strip()
@@ -1397,9 +1408,9 @@ def _locked_file(lock_file: Any) -> Any:
import msvcrt
# msvcrt.locking operates on bytes from the current file position.
- lock_file.seek(0)
- if lock_file.read(1) == b"":
- lock_file.seek(0)
+ # Reading the locked byte fails on Windows before a competing
+ # writer can enter the retry loop. Check metadata instead.
+ if os.fstat(lock_file.fileno()).st_size == 0:
lock_file.write(b"0")
lock_file.flush()
lock_file.seek(0)
@@ -1725,16 +1736,41 @@ def _check_and_clear_stale_wrap_marker(settings_path: Path, *, key: str) -> str
Called before writing a fresh base_url entry so a crashed wrap session's
leftover doesn't get treated as this session's own state to restore later.
"""
+ # Preserve the default no-marker path without creating lock artifacts.
marker = _read_wrap_marker(settings_path)
if marker is None or marker.get("key") != key or not _wrap_marker_is_stale(marker):
return None
- previous = marker.get("previous")
- click.echo(
- f"headroom: clearing stale {key} left by crashed wrap session (pid {marker.get('pid')})",
- err=True,
- )
- _restore_claude_wrap_base_url(previous, settings_path=settings_path, _key_override=key)
- return previous
+ with _wrap_settings_lock(settings_path):
+ marker = _read_wrap_marker(settings_path)
+ if marker is None or marker.get("key") != key or not _wrap_marker_is_stale(marker):
+ return None
+ port = marker.get("port")
+ if not isinstance(port, int) or isinstance(port, bool):
+ return None
+ expected_url = f"http://127.0.0.1:{port}"
+ if key == "ANTHROPIC_FOUNDRY_BASE_URL":
+ expected_url = _foundry_proxy_url(expected_url)
+ try:
+ settings = json.loads(_read_text(settings_path))
+ except (OSError, UnicodeError, json.JSONDecodeError):
+ return None
+ env_settings = settings.get("env") if isinstance(settings, dict) else None
+ current_url = env_settings.get(key) if isinstance(env_settings, dict) else None
+ if current_url != expected_url:
+ # The user (or a newer session) has replaced the crashed writer's URL.
+ # Retire its stale marker without changing the current settings.
+ if _read_wrap_marker(settings_path) == marker:
+ _clear_wrap_marker(settings_path, key=key)
+ return None
+ previous = marker.get("previous")
+ click.echo(
+ f"headroom: clearing stale {key} left by crashed wrap session (pid {marker.get('pid')})",
+ err=True,
+ )
+ _restore_claude_wrap_base_url(
+ previous, settings_path=settings_path, _key_override=key, _lock_held=True
+ )
+ return previous
def _check_and_clear_dead_wrap_marker(settings_path: Path, *, key: str) -> str | None:
@@ -2038,6 +2074,7 @@ def _restore_claude_wrap_base_url(
_key_override: str | None = None,
force: bool = False,
dead_ports: frozenset[int] = frozenset(),
+ _lock_held: bool = False,
) -> None:
"""Restore (or remove) the env key written by _write_claude_wrap_base_url.
@@ -2053,11 +2090,13 @@ def _restore_claude_wrap_base_url(
(``unwrap``), and ``dead_ports`` to name proxy ports already proven dead so
holders that outlived their proxy stop counting as live.
"""
+ from contextlib import nullcontext
+
path = settings_path or (Path.cwd() / ".claude" / "settings.local.json")
key = _key_override or _claude_wrap_base_url_env_key(
foundry_mode=foundry_mode, vertex_mode=vertex_mode
)
- with _wrap_settings_lock(path):
+ with nullcontext() if _lock_held else _wrap_settings_lock(path):
# Another live wrap session in this project may still be using the key.
# Restoring underneath it silently unroutes a running session -- traffic
# bypasses the proxy with no error anywhere (#3205).
@@ -5932,6 +5971,16 @@ def _detect_inbound_anthropic_upstream(port: int) -> str | None:
help="Enable the proxy's live code-graph file watcher for the current project.",
)
@click.option("--no-proxy", is_flag=True, help="Skip proxy startup (use existing proxy)")
+ "--project-settings",
+ "--project-settings-injection",
+ "project_settings",
+ is_flag=True,
+ help=(
+ "Write .claude/settings.local.json so daemon-spawned Claude workers inherit "
+ "Headroom routing. Env: HEADROOM_CLAUDE_PROJECT_SETTINGS=1."
+ ),
+)
@click.option(
"--learn", is_flag=True, help="Enable live traffic learning (patterns saved to MEMORY.md)"
)
@@ -5983,6 +6032,7 @@ def claude(
no_serena: bool,
code_graph: bool,
no_proxy: bool,
+ project_settings: bool,
learn: bool,
memory: bool,
tool_search: str | None,
@@ -6006,6 +6056,7 @@ def claude(
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-scope user # Serena in every session, not just here
headroom wrap claude --1m # Preserve the 1M context window
@@ -6028,6 +6079,7 @@ def claude(
_tool_search_not_written = object()
_saved_tool_search: list[object | str | None] = [_tool_search_not_written]
_settings_foundry: list[bool] = [False]
+ _wrote_project_settings: list[bool] = [False]
port_holder: list[int] = [port]
_settings_vertex: list[bool] = [False]
# Bind before the try so the finally can always reference it. It is otherwise
@@ -6255,39 +6307,42 @@ def claude(
else:
env["ANTHROPIC_BASE_URL"] = proxy_url
- # Issue #951: write to settings.json so daemon-spawned conversation
- # workers (which read settings.json fresh rather than inheriting the
- # daemon's environment) also route through Headroom.
+ # Recover an older crashed wrap even when new project settings writes
+ # are disabled. The marker records the prior value to restore; without
+ # one, default wraps leave project settings untouched (#1599).
_settings_vertex[0] = bool(use_vertex)
_settings_foundry[0] = bool(foundry_upstream) and not _settings_vertex[0]
- # _wrap_settings_path is bound before the try (above) so the finally is
- # always safe; the value is unchanged here.
_check_and_clear_stale_wrap_marker(
_wrap_settings_path,
key=_claude_wrap_base_url_env_key(
foundry_mode=_settings_foundry[0], vertex_mode=_settings_vertex[0]
),
)
- _saved_base_url[0] = _write_claude_wrap_base_url(
- (
- _foundry_proxy_url(proxy_url)
- if _settings_foundry[0]
- else env["ANTHROPIC_VERTEX_BASE_URL"]
- if _settings_vertex[0]
- else proxy_url
- ),
- foundry_mode=_settings_foundry[0],
- vertex_mode=_settings_vertex[0],
- settings_path=_wrap_settings_path,
- # The URL above is built from actual_port; stamping the requested
- # port here made the marker/owner claim point at the wrong port
- # whenever _ensure_proxy fell back to another one.
- port=actual_port,
- )
- # Issue #2221: pair the marker just written with a reader. wrap installs
- # no hook of its own, so a session that only ran `wrap` (never `init`)
- # had nothing to clear a dead-proxy base_url. SessionStart-only.
- _ensure_claude_wrap_selfheal_hook(_wrap_settings_path)
+ if _claude_project_settings_enabled(project_settings):
+ _saved_base_url[0] = _write_claude_wrap_base_url(
+ (
+ _foundry_proxy_url(proxy_url)
+ if _settings_foundry[0]
+ else env["ANTHROPIC_VERTEX_BASE_URL"]
+ if _settings_vertex[0]
+ else proxy_url
+ ),
+ foundry_mode=_settings_foundry[0],
+ vertex_mode=_settings_vertex[0],
+ settings_path=_wrap_settings_path,
+ port=actual_port,
+ )
+ # Issue #2221: pair the marker just written with a reader. wrap installs
+ # no hook of its own, so a session that only ran `wrap` (never `init`)
+ # had nothing to clear a dead-proxy base_url. SessionStart-only.
+ _wrote_project_settings[0] = True
+ _ensure_claude_wrap_selfheal_hook(_wrap_settings_path)
+ elif verbose:
+ skip_reason = _claude_project_settings_skip_reason()
+ click.echo(
+ " Skipping project-local Claude settings "
+ f"({skip_reason}); daemon-spawned workers may not inherit Headroom."
+ )
# Per-project savings attribution: tag every request with the launch
# directory's name via X-Headroom-Project (user override wins).
@@ -6298,11 +6353,12 @@ def claude(
# Issue #746: keep Claude Code's on-demand tool loading on through the
# proxy so tool schemas are not eagerly materialized into local context.
_tool_search_value = _configure_tool_search_env(env, tool_search)
- _resolved_tool_search_value = env.get(_TOOL_SEARCH_ENV, "")
- _saved_tool_search[0] = _write_claude_wrap_tool_search(
- _resolved_tool_search_value,
- settings_path=_wrap_settings_path,
- )
+ if _wrote_project_settings[0]:
+ _resolved_tool_search_value = env.get(_TOOL_SEARCH_ENV, "")
+ _saved_tool_search[0] = _write_claude_wrap_tool_search(
+ _resolved_tool_search_value,
+ settings_path=_wrap_settings_path,
+ )
if _tool_search_value is not None:
# Describe what the written value actually does: --tool-search
# false/0/no/off turns deferral OFF, and the banner must say so
@@ -6362,12 +6418,13 @@ def claude(
cast(str | None, _saved_tool_search[0]),
settings_path=_wrap_settings_path,
)
- _restore_claude_wrap_base_url(
- _saved_base_url[0],
- foundry_mode=_settings_foundry[0],
- vertex_mode=_settings_vertex[0],
- settings_path=_wrap_settings_path,
- )
+ if _wrote_project_settings[0]:
+ _restore_claude_wrap_base_url(
+ _saved_base_url[0],
+ foundry_mode=_settings_foundry[0],
+ vertex_mode=_settings_vertex[0],
+ settings_path=_wrap_settings_path,
+ )
cleanup()
diff --git a/tests/test_cli/test_wrap_claude_base_url.py b/tests/test_cli/test_wrap_claude_base_url.py
index 0d376bf9b..431a09e64 100644
--- a/tests/test_cli/test_wrap_claude_base_url.py
+++ b/tests/test_cli/test_wrap_claude_base_url.py
@@ -4,12 +4,55 @@ from __future__ import annotations
import json
from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import patch
import click
import pytest
+from click.testing import CliRunner
from headroom import proxy_client_liveness
from headroom.cli import wrap as wrap_cli
+from headroom.cli.main import main
+
+
+def test_project_settings_are_restored_when_selfheal_install_fails(tmp_path: Path) -> None:
+ runner = CliRunner()
+ with runner.isolated_filesystem(temp_dir=str(tmp_path)):
+ settings_path = Path(".claude/settings.local.json")
+ settings_path.parent.mkdir()
+ original = {
+ "env": {"ANTHROPIC_BASE_URL": "https://user.example", "KEEP": "1"},
+ "permissions": {"allow": ["Read"]},
+ }
+ settings_path.write_text(json.dumps(original), encoding="utf-8")
+ with (
+ patch("headroom.cli.wrap.shutil.which", return_value="claude"),
+ patch("headroom.cli.wrap._ensure_proxy", return_value=(None, 8787)),
+ patch("headroom.cli.wrap._setup_headroom_mcp"),
+ patch("headroom.cli.wrap._setup_coding_compressor"),
+ patch(
+ "headroom.cli.wrap._ensure_claude_wrap_selfheal_hook",
+ side_effect=RuntimeError("selfheal install failed"),
+ ),
+ patch("headroom.cli.wrap.subprocess.run") as run_mock,
+ ):
+ result = runner.invoke(
+ main,
+ [
+ "wrap",
+ "claude",
+ "--project-settings",
+ "--no-mcp",
+ "--no-tokensave",
+ "--no-serena",
+ ],
+ )
+ assert result.exit_code != 0
+ assert "selfheal install failed" in str(result.exception) + result.output
+ assert all(call.args[0] == ["claude", "--version"] for call in run_mock.call_args_list)
+ assert json.loads(settings_path.read_text(encoding="utf-8")) == original
+ assert not settings_path.with_name(".headroom_wrap_settings.json").exists()
def _settings(tmp_path: Path) -> Path:
@@ -248,6 +291,122 @@ def test_write_restore_roundtrip(tmp_path: Path) -> None:
assert payload["model"] == "opus"
+def test_claude_project_settings_enabled_respects_flag_and_env(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.delenv("HEADROOM_CLAUDE_PROJECT_SETTINGS", raising=False)
+ assert wrap_cli._claude_project_settings_enabled(False) is False
+ assert wrap_cli._claude_project_settings_enabled(True) is True
+
+ monkeypatch.setenv("HEADROOM_CLAUDE_PROJECT_SETTINGS", "1")
+ assert wrap_cli._claude_project_settings_enabled(False) is True
+
+
+def test_wrap_claude_skips_project_settings_by_default(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ runner = CliRunner()
+ completed = SimpleNamespace(returncode=0)
+ monkeypatch.delenv("HEADROOM_CLAUDE_PROJECT_SETTINGS", raising=False)
+
+ with runner.isolated_filesystem(temp_dir=str(tmp_path)):
+ settings_path = Path(".claude") / "settings.local.json"
+ settings_path.parent.mkdir()
+ original = {
+ "env": {
+ "ANTHROPIC_BASE_URL": "http://direct.example",
+ "KEEP": "1",
+ }
+ }
+ settings_path.write_text(json.dumps(original, indent=2) + "\n", encoding="utf-8")
+
+ with (
+ patch("headroom.cli.wrap.shutil.which", return_value="claude"),
+ patch("headroom.cli.wrap._ensure_proxy", return_value=(None, 8787)),
+ patch("headroom.cli.wrap._setup_headroom_mcp", return_value=None),
+ patch("headroom.cli.wrap._setup_coding_compressor", return_value=None),
+ patch("headroom.cli.wrap._write_claude_wrap_base_url") as write_mock,
+ patch("headroom.cli.wrap._restore_claude_wrap_base_url") as restore_mock,
+ patch("headroom.cli.wrap._ensure_claude_wrap_selfheal_hook") as selfheal_mock,
+ patch("headroom.cli.wrap.subprocess.run", return_value=completed) as run_mock,
+ ):
+ result = runner.invoke(
+ main,
+ [
+ "wrap",
+ "claude",
+ "--no-mcp",
+ "--no-tokensave",
+ "--no-serena",
+ ],
+ )
+
+ assert result.exit_code == 0, result.output
+ assert json.loads(settings_path.read_text(encoding="utf-8")) == original
+ write_mock.assert_not_called()
+ restore_mock.assert_not_called()
+ selfheal_mock.assert_not_called()
+ launched_env = run_mock.call_args.kwargs["env"]
+ assert launched_env["ANTHROPIC_BASE_URL"] == "http://127.0.0.1:8787"
+
+
+def test_wrap_claude_project_settings_flag_writes_and_restores(tmp_path: Path) -> None:
+ runner = CliRunner()
+ completed = SimpleNamespace(returncode=0)
+
+ with runner.isolated_filesystem(temp_dir=str(tmp_path)):
+ with (
+ patch("headroom.cli.wrap.shutil.which", return_value="claude"),
+ patch("headroom.cli.wrap._ensure_proxy", return_value=(None, 8787)),
+ patch("headroom.cli.wrap._setup_headroom_mcp", return_value=None),
+ patch("headroom.cli.wrap._setup_coding_compressor", return_value=None),
+ patch(
+ "headroom.cli.wrap._write_claude_wrap_base_url", return_value="old"
+ ) as write_mock,
+ patch("headroom.cli.wrap._restore_claude_wrap_base_url") as restore_mock,
+ patch(
+ "headroom.cli.wrap._write_claude_wrap_tool_search", return_value="old-tool-search"
+ ) as write_tool_search_mock,
+ patch("headroom.cli.wrap._restore_claude_wrap_tool_search") as restore_tool_search_mock,
+ patch("headroom.cli.wrap._ensure_claude_wrap_selfheal_hook") as selfheal_mock,
+ patch("headroom.cli.wrap.subprocess.run", return_value=completed),
+ ):
+ result = runner.invoke(
+ main,
+ [
+ "wrap",
+ "claude",
+ "--project-settings",
+ "--no-mcp",
+ "--no-tokensave",
+ "--no-serena",
+ ],
+ )
+
+ assert result.exit_code == 0, result.output
+ write_mock.assert_called_once()
+ write_args, write_kwargs = write_mock.call_args
+ assert write_args == ("http://127.0.0.1:8787",)
+ assert write_kwargs["foundry_mode"] is False
+ assert write_kwargs["vertex_mode"] is False
+ assert write_kwargs["port"] == 8787
+ assert write_kwargs["settings_path"].name == "settings.local.json"
+ assert write_kwargs["settings_path"].parent.name == ".claude"
+ selfheal_mock.assert_called_once_with(write_kwargs["settings_path"])
+ write_tool_search_mock.assert_called_once_with(
+ "true", settings_path=write_kwargs["settings_path"]
+ )
+ restore_tool_search_mock.assert_called_once_with(
+ "old-tool-search", settings_path=write_kwargs["settings_path"]
+ )
+ restore_mock.assert_called_once_with(
+ "old",
+ foundry_mode=False,
+ vertex_mode=False,
+ settings_path=write_kwargs["settings_path"],
+ )
+
+
# --- stale wrap marker (issue #1768) --------------------------------------
@@ -324,9 +483,7 @@ def test_check_and_clear_stale_wrap_marker_restores_previous(tmp_path: Path) ->
path.write_text(
json.dumps({"env": {"ANTHROPIC_BASE_URL": "http://old.proxy:9000"}}), encoding="utf-8"
)
- wrap_cli._write_wrap_marker(
- path, port=8787, key="ANTHROPIC_BASE_URL", previous="http://old.proxy:9000"
- )
+ wrap_cli._write_claude_wrap_base_url("http://127.0.0.1:8787", settings_path=path, port=8787)
marker = json.loads(_marker(tmp_path).read_text(encoding="utf-8"))
marker["pid"] = 999_999_999
_marker(tmp_path).write_text(json.dumps(marker), encoding="utf-8")
@@ -349,3 +506,122 @@ def test_check_and_clear_stale_wrap_marker_leaves_live_marker(tmp_path: Path) ->
def test_check_and_clear_stale_wrap_marker_noop_when_no_marker(tmp_path: Path) -> None:
path = _settings(tmp_path)
assert wrap_cli._check_and_clear_stale_wrap_marker(path, key="ANTHROPIC_BASE_URL") is None
+
+
+def test_default_wrap_recovers_settings_from_old_crashed_wrap(tmp_path, monkeypatch):
+ monkeypatch.delenv("HEADROOM_CLAUDE_PROJECT_SETTINGS", raising=False)
+ runner = CliRunner()
+ with runner.isolated_filesystem(temp_dir=str(tmp_path)):
+ path = Path(".claude/settings.local.json")
+ path.parent.mkdir()
+ original = {"env": {"ANTHROPIC_BASE_URL": "https://direct.example", "KEEP": "1"}}
+ path.write_text(json.dumps(original), encoding="utf-8")
+ wrap_cli._write_claude_wrap_base_url("http://127.0.0.1:9200", settings_path=path, port=9200)
+ marker_path = wrap_cli._wrap_marker_path(path)
+ marker = json.loads(marker_path.read_text(encoding="utf-8"))
+ marker["pid"] = 999_999_999
+ marker_path.write_text(json.dumps(marker), encoding="utf-8")
+ with (
+ patch("headroom.cli.wrap.shutil.which", return_value="claude"),
+ patch("headroom.cli.wrap._ensure_proxy", return_value=(None, 8787)),
+ patch("headroom.cli.wrap._setup_headroom_mcp", return_value=None),
+ patch("headroom.cli.wrap._setup_coding_compressor", return_value=None),
+ patch("headroom.cli.wrap._ensure_claude_wrap_selfheal_hook") as install_hook,
+ patch("headroom.cli.wrap.subprocess.run", return_value=SimpleNamespace(returncode=0)),
+ ):
+ result = runner.invoke(
+ main, ["wrap", "claude", "--no-mcp", "--no-tokensave", "--no-serena"]
+ )
+ assert result.exit_code == 0, result.output
+ assert json.loads(path.read_text(encoding="utf-8")) == original
+ assert not marker_path.exists()
+ install_hook.assert_not_called()
+
+
+ "foundry_mode, vertex_mode", [(False, False), (True, False), (False, True)]
+)
+def test_stale_marker_preserves_manually_repaired_url(tmp_path, foundry_mode, vertex_mode):
+ path = _settings(tmp_path)
+ path.parent.mkdir(parents=True)
+ key = wrap_cli._claude_wrap_base_url_env_key(foundry_mode=foundry_mode, vertex_mode=vertex_mode)
+ path.write_text(
+ json.dumps({"env": {key: "https://old.example", "KEEP": "1"}}), encoding="utf-8"
+ )
+ proxy = "http://127.0.0.1:9200/anthropic" if foundry_mode else "http://127.0.0.1:9200"
+ wrap_cli._write_claude_wrap_base_url(
+ proxy, settings_path=path, port=9200, foundry_mode=foundry_mode, vertex_mode=vertex_mode
+ )
+ marker_path = wrap_cli._wrap_marker_path(path)
+ marker = json.loads(marker_path.read_text(encoding="utf-8"))
+ marker["pid"] = 999_999_999
+ marker_path.write_text(json.dumps(marker), encoding="utf-8")
+ repaired = json.dumps({"env": {key: "https://new.example", "KEEP": "1"}}, indent=2) + "\n"
+ path.write_text(repaired, encoding="utf-8")
+ before = path.read_bytes()
+ wrap_cli._check_and_clear_stale_wrap_marker(path, key=key)
+ assert path.read_bytes() == before
+ assert not marker_path.exists()
+
+
+def test_stale_recovery_serializes_with_new_wrap_writer(tmp_path, monkeypatch):
+ import threading
+
+ path = _settings(tmp_path)
+ path.parent.mkdir(parents=True)
+ wrap_cli._write_claude_wrap_base_url("http://127.0.0.1:9200", settings_path=path, port=9200)
+ marker_path = wrap_cli._wrap_marker_path(path)
+ marker = json.loads(marker_path.read_text(encoding="utf-8"))
+ marker["pid"] = 999_999_999
+ marker_path.write_text(json.dumps(marker), encoding="utf-8")
+ path.write_text('{"env":{"ANTHROPIC_BASE_URL":"https://repaired.example"}}', encoding="utf-8")
+ compared = threading.Event()
+ resume = threading.Event()
+ writer_done = threading.Event()
+ errors = []
+ read_text = wrap_cli._read_text
+
+ def paused_read(target):
+ content = read_text(target)
+ if threading.current_thread().name == "stale-recovery" and target == path:
+ compared.set()
+ assert resume.wait(5)
+ return content
+
+ def recover():
+ try:
+ wrap_cli._check_and_clear_stale_wrap_marker(path, key="ANTHROPIC_BASE_URL")
+ except BaseException as exc:
+ errors.append(exc)
+
+ def write_new():
+ try:
+ wrap_cli._write_claude_wrap_base_url(
+ "http://127.0.0.1:9300", settings_path=path, port=9300
+ )
+ except BaseException as exc:
+ errors.append(exc)
+ finally:
+ writer_done.set()
+
+ monkeypatch.setattr(wrap_cli, "_read_text", paused_read)
+ recovery = threading.Thread(target=recover, name="stale-recovery")
+ writer = threading.Thread(target=write_new, name="new-writer")
+ recovery.start()
+ try:
+ assert compared.wait(5)
+ writer.start()
+ # Give the competing actual writer the opportunity to commit its marker.
+ writer_done.wait(0.2)
+ finally:
+ resume.set()
+ recovery.join(5)
+ if writer.ident is not None:
+ writer.join(5)
+ assert not recovery.is_alive() and not writer.is_alive()
+ assert not errors, errors
+ assert json.loads(marker_path.read_text(encoding="utf-8"))["port"] == 9300
+ assert (
+ json.loads(path.read_text(encoding="utf-8"))["env"]["ANTHROPIC_BASE_URL"]
+ == "http://127.0.0.1:9300"
+ )
diff --git a/tests/test_cli/test_wrap_claude_finally_unbound.py b/tests/test_cli/test_wrap_claude_finally_unbound.py
index be0673a8e..d08276371 100644
--- a/tests/test_cli/test_wrap_claude_finally_unbound.py
+++ b/tests/test_cli/test_wrap_claude_finally_unbound.py
@@ -25,6 +25,7 @@ def test_finally_survives_early_proxy_start_failure(
"ANTHROPIC_VERTEX_BASE_URL",
"ANTHROPIC_FOUNDRY_BASE_URL",
"ANTHROPIC_FOUNDRY_RESOURCE",
+ "HEADROOM_CLAUDE_PROJECT_SETTINGS",
"CLAUDE_CODE_USE_VERTEX",
"CLAUDE_CODE_USE_FOUNDRY",
"VERTEX_TARGET_API_URL",
@@ -62,9 +63,7 @@ def test_finally_survives_early_proxy_start_failure(
["wrap", "claude", "--no-mcp", "--no-tokensave", "--no-serena"],
)
- # The finally must complete: no UnboundLocalError masking the real failure,
- # and both restore and cleanup ran even though the proxy failed before
- # _wrap_settings_path was assigned inside the try.
+ # The finally must complete without masking the real failure, skip restoring settings that this run never wrote, and still clean up.
assert not isinstance(result.exception, UnboundLocalError), result.output
- assert state["restore_called"] is True
+ assert state["restore_called"] is False
assert state["cleanup_called"] is True
diff --git a/tests/test_cli/test_wrap_claude_vertex_proxy_env.py b/tests/test_cli/test_wrap_claude_vertex_proxy_env.py
index 10dab084f..88dbaed2a 100644
--- a/tests/test_cli/test_wrap_claude_vertex_proxy_env.py
+++ b/tests/test_cli/test_wrap_claude_vertex_proxy_env.py
@@ -38,6 +38,7 @@ def _clear_claude_mode_env(monkeypatch: pytest.MonkeyPatch) -> None:
"ANTHROPIC_VERTEX_BASE_URL",
"ANTHROPIC_FOUNDRY_BASE_URL",
"ANTHROPIC_FOUNDRY_RESOURCE",
+ "HEADROOM_CLAUDE_PROJECT_SETTINGS",
"CLAUDE_CODE_USE_VERTEX",
"CLAUDE_CODE_USE_FOUNDRY",
"VERTEX_TARGET_API_URL",
@@ -277,10 +278,10 @@ def test_wrap_claude_tool_search_banner_line_still_accurate_when_active(
assert "on-demand tool loading kept on" in output
assert "keeps it on for this session" in output
assert "DISABLED per your setting" not in output
- assert _captured["write_tool_search_value"] == "true"
+ assert "write_tool_search_value" not in _captured
-def test_wrap_claude_foundry_persists_disabled_tool_search_for_workers(
+def test_wrap_claude_foundry_keeps_disabled_tool_search_process_local_by_default(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch
) -> None:
captured, output = _invoke_wrap_claude(
@@ -293,7 +294,7 @@ def test_wrap_claude_foundry_persists_disabled_tool_search_for_workers(
)
assert captured["child_env"]["ENABLE_TOOL_SEARCH"] == "false"
- assert captured["write_tool_search_value"] == "false"
+ assert "write_tool_search_value" not in captured
# Foundry's default turns deferral off without a --tool-search flag, so the
# compact line must not blame the user's setting (#3426).
assert "On-demand tool loading: off (this session)" in output
@@ -344,6 +345,22 @@ def test_proxy_status_line_keeps_own_signature_and_names_port_once() -> None:
assert line.count("127.0.0.1:8787") == 1
+def test_wrap_claude_foundry_project_settings_opt_in_persists_disabled_tool_search(
+ runner: CliRunner, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ captured, _output = _invoke_wrap_claude(
+ runner,
+ monkeypatch,
+ env={
+ "CLAUDE_CODE_USE_FOUNDRY": "1",
+ "ANTHROPIC_FOUNDRY_BASE_URL": "https://tenant.services.ai.azure.com/anthropic",
+ },
+ extra_args=("--project-settings",),
+ )
+
+ assert captured["write_tool_search_value"] == "false"
+
+
def test_wrap_claude_vertex_passes_custom_base_url_to_proxy_before_child_redirect(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch
) -> None:
@@ -364,13 +381,11 @@ def test_wrap_claude_vertex_passes_custom_base_url_to_proxy_before_child_redirec
ensure_kwargs = captured["ensure_kwargs"]
child_env = captured["child_env"]
- write_kwargs = captured["write_base_url_kwargs"]
assert ensure_kwargs["vertex_api_url"] == custom_vertex_url
assert ensure_kwargs["clear_vertex_api_url"] is False
assert ensure_kwargs["anthropic_api_url"] is None
assert child_env["ANTHROPIC_VERTEX_BASE_URL"] == "http://127.0.0.1:8787"
- assert write_kwargs["vertex_mode"] is True
- assert write_kwargs["foundry_mode"] is False
+ assert "write_base_url_kwargs" not in captured
def test_wrap_claude_vertex_target_env_beats_anthropic_vertex_base_url(
@@ -423,7 +438,7 @@ def test_wrap_claude_vertex_default_or_absent_base_url_does_not_force_vertex_tar
assert child_env["ANTHROPIC_VERTEX_BASE_URL"] == "http://127.0.0.1:8787"
-def test_wrap_claude_foundry_proxy_env_behavior_is_unchanged(
+def test_wrap_claude_foundry_proxy_env_uses_process_environment_only_by_default(
runner: CliRunner, monkeypatch: pytest.MonkeyPatch
) -> None:
foundry_url = "https://my-resource.services.ai.azure.com/anthropic"
@@ -446,8 +461,7 @@ def test_wrap_claude_foundry_proxy_env_behavior_is_unchanged(
assert ensure_kwargs["anthropic_api_url"] == foundry_url
assert ensure_kwargs["vertex_api_url"] is None
assert child_env["ANTHROPIC_FOUNDRY_BASE_URL"] == "http://127.0.0.1:8787/anthropic"
- assert captured["write_base_url_kwargs"]["foundry_mode"] is True
- assert captured["write_base_url_kwargs"]["vertex_mode"] is False
+ assert "write_base_url_kwargs" not in captured
def test_write_vertex_mode_sets_vertex_key(tmp_path: Path) -> None: