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.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(install): write persistent shell env values verbatim (#4289)
Rudy Mizrahi Celekli89f90bb41115
diff --git a/e2e/init/run.py b/e2e/init/run.pyindex 95166ed8b..2cb642b0c 100644--- a/e2e/init/run.py+++ b/e2e/init/run.py@@ -22,6 +22,8 @@ from ``e2e/init/Dockerfile``).from __future__ import annotationsimport json+import os+import subprocessimport sysfrom pathlib import Path@@ -149,6 +151,59 @@ def _verify_claude_local(ctx: CaseContext) -> None:raise AssertionError(f"Unexpected Claude install commands: {claude_calls}")+def _expect_shell_exports(shell_file: Path, expected: dict[str, str]) -> None:+ """Check exported values in a child process after sourcing an rc file.++ Args:+ shell_file: Scratch shell configuration written by the init case.+ expected: Environment variables that init must export verbatim.++ Raises:+ AssertionError: If sourcing fails or the exported values differ.+ """+ # Clear inherited values so missing exports cannot accidentally pass. A+ # separate Python child also distinguishes assignments from real exports.+ env = {+ name: value+ for name, value in os.environ.items()+ if name not in expected and name not in {"BASH_ENV", "ENV"}+ }+ probe = (+ "import json, os, sys; "+ "print(json.dumps({name: os.environ.get(name) for name in sys.argv[1:]}))"+ )+ try:+ result = subprocess.run(+ [+ "bash",+ "--noprofile",+ "--norc",+ "-c",+ '. "$1" && "$2" -c "$3" "${@:4}"',+ "headroom-env-check",+ str(shell_file),+ sys.executable,+ probe,+ *expected,+ ],+ env=env,+ capture_output=True,+ text=True,+ check=True,+ timeout=10,+ )+ except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc:+ raise AssertionError(f"{shell_file.name} could not be sourced successfully") from exc+ try:+ actual = json.loads(result.stdout)+ except json.JSONDecodeError as exc:+ raise AssertionError(+ f"{shell_file.name} did not produce exported environment values"+ ) from exc+ if actual != expected:+ raise AssertionError(f"{shell_file.name} exported {actual!r}; expected {expected!r}")++def _verify_copilot_global(ctx: CaseContext) -> None:config = json.loads((ctx.home / ".copilot" / "config.json").read_text(encoding="utf-8"))if "SessionStart" not in config["hooks"]:@@ -158,15 +213,13 @@ def _verify_copilot_global(ctx: CaseContext) -> None:session_start = config["hooks"]["SessionStart"][0]["command"]_expect_hook_command(session_start, "init-user")+ expected_env = {+ "COPILOT_PROVIDER_TYPE": "openai",+ "COPILOT_PROVIDER_BASE_URL": "http://127.0.0.1:9005/v1",+ "COPILOT_PROVIDER_WIRE_API": "completions",+ }for shell_file in (ctx.home / ".bashrc", ctx.home / ".zshrc", ctx.home / ".profile"):- content = shell_file.read_text(encoding="utf-8")- for literal in (- 'export COPILOT_PROVIDER_TYPE="openai"',- 'export COPILOT_PROVIDER_BASE_URL="http://127.0.0.1:9005/v1"',- 'export COPILOT_PROVIDER_WIRE_API="completions"',- ):- if literal not in content:- raise AssertionError(f"{shell_file.name} missing {literal!r}")+ _expect_shell_exports(shell_file, expected_env)copilot_calls = [record["argv"] for record in _read_jsonl(ctx.shim_log) if record["tool"] == "copilot"diff --git a/headroom/install/providers.py b/headroom/install/providers.pyindex 12f8818d2..5f5b1af0a 100644--- a/headroom/install/providers.py+++ b/headroom/install/providers.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport osimport re+import shleximport subprocessfrom pathlib import Path@@ -32,7 +33,8 @@ def _merge_marker_block(file_path: Path, block: str, pattern: re.Pattern[str], mif file_path.exists():existing = fsutil.read_text(file_path)if marker in existing:- return pattern.sub(block, existing)+ # A callable replacement: the block is literal text, not a template.+ return pattern.sub(lambda _match: block, existing)return existing.rstrip() + "\n\n" + block + "\n"return block + "\n"@@ -40,7 +42,8 @@ def _merge_marker_block(file_path: Path, block: str, pattern: re.Pattern[str], mdef _env_block(values: dict[str, str]) -> str:lines = [_ENV_MARKER_START]for name, value in values.items():- lines.append(f'export {name}="{value}"')+ # shlex.quote so `$`, `"` and backticks reach the shell verbatim.+ lines.append(f"export {name}={shlex.quote(value)}")lines.append(_ENV_MARKER_END)return "\n".join(lines)diff --git a/tests/test_install/test_init_env_oracle.py b/tests/test_install/test_init_env_oracle.pynew file mode 100644index 000000000..e83dc3433--- /dev/null+++ b/tests/test_install/test_init_env_oracle.py@@ -0,0 +1,103 @@+"""Real-shell regression controls for the init E2E environment assertions."""++import json+import os+import shutil+from pathlib import Path++import pytest++from e2e._lib import CaseContext+from e2e.init.run import _verify_copilot_global+from headroom.install.providers import _env_block++pytestmark = pytest.mark.skipif(+ os.name != "posix" or shutil.which("bash") is None,+ reason="The Docker init E2E oracle requires a native POSIX Bash",+)++EXPECTED = {+ "COPILOT_PROVIDER_TYPE": "openai",+ "COPILOT_PROVIDER_BASE_URL": "http://127.0.0.1:9005/v1",+ "COPILOT_PROVIDER_WIRE_API": "completions",+}+++def copilot_context(tmp_path: Path) -> CaseContext:+ home = tmp_path / "home with spaces"+ (home / ".copilot").mkdir(parents=True)+ config = {+ "hooks": {+ "SessionStart": [{"command": "headroom init hook ensure --profile init-user"}],+ "PreToolUse": [],+ }+ }+ (home / ".copilot" / "config.json").write_text(+ json.dumps(config), encoding="utf-8", newline="\n"+ )+ log = tmp_path / "shim-log.jsonl"+ calls = [+ ["plugin", "marketplace", "add", "/workspace"],+ ["plugin", "install", "headroom@headroom-marketplace"],+ ]+ log.write_text(+ "".join(json.dumps({"tool": "copilot", "argv": argv}) + "\n" for argv in calls),+ encoding="utf-8",+ newline="\n",+ )+ for name in [".bashrc", ".zshrc", ".profile"]:+ (home / name).write_text(_env_block(EXPECTED), encoding="utf-8", newline="\n")+ return CaseContext(+ name="seq_copilot_global",+ home=home,+ project=tmp_path,+ shim_dir=tmp_path,+ shim_log=log,+ stdout="",+ stderr="",+ exit_code=0,+ )++[email protected]("style", ["producer", "double", "single"])+def test_copilot_e2e_accepts_equivalent_export_spellings(+ copilot_context: CaseContext, style: str+) -> None:+ if style != "producer":+ quote = '"' if style == "double" else "'"+ content = "\n".join(+ f"export {name}={quote}{value}{quote}" for name, value in EXPECTED.items()+ )+ for name in [".bashrc", ".zshrc", ".profile"]:+ (copilot_context.home / name).write_text(content, encoding="utf-8", newline="\n")+ _verify_copilot_global(copilot_context)++[email protected]("shell_file", [".bashrc", ".zshrc", ".profile"])[email protected]("mutation", ["missing", "unexported", "wrong", "source-failure"])+def test_copilot_e2e_rejects_invalid_runtime_environment(+ copilot_context: CaseContext, monkeypatch: pytest.MonkeyPatch, shell_file: str, mutation: str+) -> None:+ # Ambient variables must never turn a missing/unexported setting into a pass.+ for name, value in EXPECTED.items():+ monkeypatch.setenv(name, value)+ startup = copilot_context.home / "ambient-startup"+ startup.write_text(_env_block(EXPECTED), encoding="utf-8", newline="\n")+ monkeypatch.setenv("BASH_ENV", str(startup))+ content = _env_block(EXPECTED)+ if mutation == "missing":+ content = "\n".join(+ line+ for line in content.splitlines()+ if not line.startswith("export COPILOT_PROVIDER_TYPE=")+ )+ elif mutation == "unexported":+ content = content.replace("export COPILOT_PROVIDER_TYPE=", "COPILOT_PROVIDER_TYPE=")+ elif mutation == "wrong":+ content = content.replace("COPILOT_PROVIDER_TYPE=openai", "COPILOT_PROVIDER_TYPE=wrong")+ else:+ content = "return 23\n" + content+ (copilot_context.home / shell_file).write_text(content, encoding="utf-8", newline="\n")+ with pytest.raises(AssertionError):+ _verify_copilot_global(copilot_context)diff --git a/tests/test_install/test_providers.py b/tests/test_install/test_providers.pyindex 027b39031..e38a44392 100644--- a/tests/test_install/test_providers.py+++ b/tests/test_install/test_providers.py@@ -1136,3 +1136,51 @@ def test_unix_env_failure_restores_earlier_targets_when_existing_target_rejects_providers._apply_unix_env_scope(manifest)assert bashrc.read_text(encoding="utf-8") == "# bash\n"assert zshrc.read_text(encoding="utf-8") == "# zsh\n"+++def test_unix_env_block_round_trips_shell_special_values(monkeypatch, tmp_path: Path) -> None:+ import shlex+ import shutil+ import subprocess+ import sys++ from headroom.install import providers++ # System32 bash.exe is the WSL launcher and cannot open a Windows fixture path.+ if sys.platform == "win32":+ pytest.skip("Unix shell rc round-trip is not supported on Windows")+ shell = shutil.which("bash")+ if shell is None:+ pytest.skip("bash not available")+ manifest = _manifest(tmp_path)+ manifest.scope = "user"+ manifest.base_env = {+ "HTTPS_PROXY": "http://bob:pa$$w0rd@proxy:3128",+ "HEADROOM_JSON": '{"a": "b"}',+ "HEADROOM_TICK": "`id`",+ }+ bashrc = tmp_path / "dir with spaces" / ".bashrc"+ bashrc.parent.mkdir()+ monkeypatch.setattr(providers, "unix_user_env_targets", lambda: [bashrc])++ providers._apply_unix_env_scope(manifest)+ # Re-apply over the existing block, with a value containing backslashes.+ manifest.base_env["HEADROOM_WORKSPACE_DIR"] = r"C:\new\dir \d+"+ providers._apply_unix_env_scope(manifest)++ quoted = shlex.quote(str(bashrc))+ readable = subprocess.run(+ [shell, "-c", f"test -r {quoted}"],+ capture_output=True,+ text=True,+ )+ if readable.returncode != 0:+ pytest.skip("selected shell cannot read the fixture path")++ names = list(manifest.base_env)+ prints = " && ".join(f'printf "%s\\0" "${name}"' for name in names)+ # A failed source must fail the script; a following printf must not mask it.+ script = f"source {quoted} && {prints}"+ result = subprocess.run([shell, "-c", script], capture_output=True, text=True, check=True)+ assert result.stdout.split("\0")[:-1] == list(manifest.base_env.values())+ assert bashrc.read_text(encoding="utf-8").count("# >>> headroom persistent env >>>") == 1