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
refactor(cli): factor shared wrap-subcommand scaffolding
chopratejasc74ad113a4ce
diff --git a/headroom/cli/wrap.py b/headroom/cli/wrap.pyindex e315e92a8..5f92e9d46 100644--- a/headroom/cli/wrap.py+++ b/headroom/cli/wrap.py@@ -24,6 +24,7 @@ import subprocessimport sysimport tempfileimport time+from collections.abc import Callablefrom pathlib import Pathfrom typing import Any, cast@@ -910,6 +911,141 @@ def _emit_wrap_interrupted(agent: str, marker_path: Path | None) -> None:)+_WRAP_BANNER_INNER_WIDTH = 47+++def _print_wrap_banner(agent: str) -> None:+ """Print a centered ``HEADROOM WRAP: <AGENT>`` banner.++ Every Pattern-B wrap subcommand (proxy-only + watcher loop) used to+ inline this 3-line box by hand with hand-padded spaces, which made+ title-length changes silently miscenter the title. Compute padding+ here so adding a 9th agent just works.+ """+ title = f"HEADROOM WRAP: {agent.upper()}"+ pad_total = _WRAP_BANNER_INNER_WIDTH - len(title)+ pad_left = pad_total // 2+ pad_right = pad_total - pad_left+ click.echo()+ click.echo(" ╔" + "═" * _WRAP_BANNER_INNER_WIDTH + "╗")+ click.echo(f" ║{' ' * pad_left}{title}{' ' * pad_right}║")+ click.echo(" ╚" + "═" * _WRAP_BANNER_INNER_WIDTH + "╝")+ click.echo()+++def _setup_context_tool_for_agent(+ *,+ agent: str,+ agent_display: str,+ marker_path: Path | None,+ on_rtk_ready: Callable[[Path], object] | None = None,+ rtk_required: bool = False,+ verbose: bool = False,+) -> Path | None:+ """Run the rtk-or-lean-ctx context-tool setup with KeyboardInterrupt handling.++ Replaces the ``try / except KeyboardInterrupt / rtk-vs-lean-ctx fork``+ each wrap subcommand was inlining. Returns the rtk binary path if rtk+ mode was selected and the install succeeded; otherwise ``None``.++ Args:+ agent: Internal agent name (used by ``_setup_lean_ctx_agent`` and+ the interrupt message).+ agent_display: User-facing capitalized name for the echo lines+ (e.g. ``"Cline"``, ``"OpenHands"``).+ marker_path: Optional path to report on Ctrl+C interruption. Pass+ ``None`` for env-only agents that never touch disk (openhands).+ on_rtk_ready: Optional callback invoked with the rtk binary path+ when rtk install succeeds. Use to inject into a marker file+ (e.g. ``.clinerules``, ``.goosehints``, ``config.json``).+ rtk_required: If ``True`` and rtk install fails, raise+ ``SystemExit(1)`` instead of silently falling through. Use this+ for env-var-only agents (openhands) where there is no+ fallback marker file to write to.+ verbose: Forwarded to the rtk/lean-ctx installers.+ """+ try:+ if _selected_context_tool() == _CONTEXT_TOOL_LEAN_CTX:+ click.echo(f" Setting up lean-ctx for {agent_display}...")+ _setup_lean_ctx_agent(agent, verbose=verbose)+ return None+ click.echo(f" Setting up rtk for {agent_display}...")+ rtk_path = _ensure_rtk_binary(verbose=verbose)+ if not rtk_path:+ if rtk_required:+ click.echo(+ " Error: rtk install failed; refusing to inject "+ f"context-tool guidance for {agent_display} without rtk. "+ "Install rtk manually and re-run, or pass --no-context-tool "+ "to skip rtk."+ )+ raise SystemExit(1)+ return None+ if on_rtk_ready is not None:+ on_rtk_ready(rtk_path)+ return rtk_path+ except KeyboardInterrupt:+ _emit_wrap_interrupted(+ agent, marker_path if (marker_path and marker_path.exists()) else None+ )+ raise SystemExit(130) from None+++def _run_proxy_only_watcher(+ *,+ agent_label: str,+ port: int,+ no_proxy: bool,+ learn: bool,+ memory: bool,+ agent_type: str,+ print_setup_lines: Callable[[], None],+) -> None:+ """Shared scaffolding for proxy-only wrap subcommands (no child binary launch).++ Pattern-B subcommands (cursor / cline / continue) all start the proxy,+ print agent-specific configuration instructions, then block until+ Ctrl+C. This helper unifies that lifecycle so the per-agent diff is+ just the ``print_setup_lines`` callback.++ The Pattern-A subcommands (aider / copilot / codex / goose / openhands)+ launch a child binary via ``_launch_tool`` instead and never come+ through here. ``_launch_tool`` owns the proxy lifecycle on that path.+ """+ proxy_holder: list[subprocess.Popen | None] = [None]+ cleanup = _make_cleanup(proxy_holder, port)+ signal.signal(signal.SIGINT, cleanup)+ signal.signal(signal.SIGTERM, cleanup)++ try:+ _print_wrap_banner(agent_label)+ proxy_holder[0] = _ensure_proxy(+ port, no_proxy, learn=learn, memory=memory, agent_type=agent_type+ )+ click.echo()+ print_setup_lines()+ click.echo()+ click.echo(" Press Ctrl+C to stop the proxy.")+ click.echo()++ try:+ while True:+ time.sleep(1)+ proc = proxy_holder[0]+ if proc and proc.poll() is not None:+ click.echo(" Proxy process exited unexpectedly.")+ raise SystemExit(1)+ except KeyboardInterrupt:+ click.echo("\n Shutting down...")+ except SystemExit:+ raise+ except Exception as e:+ click.echo(f" Error: {e}")+ raise SystemExit(1) from e+ finally:+ cleanup()++def _inject_rtk_instructions(file_path: Path, verbose: bool = False) -> bool:"""Inject rtk instructions into a file (AGENTS.md, .cursorrules, etc.).@@ -2722,37 +2858,22 @@ def cursor(headroom wrap cursor --no-context-tool # Proxy only, no CLI context toolheadroom wrap cursor --port 9999 # Custom proxy port"""+ cursorrules: Path | None = Path.cwd() / ".cursorrules" if not no_rtk else Noneif not no_rtk:- if _selected_context_tool() == _CONTEXT_TOOL_LEAN_CTX:- click.echo(" Setting up lean-ctx for Cursor...")- _setup_lean_ctx_agent("cursor", verbose=verbose)- else:- click.echo(" Setting up rtk for Cursor...")- rtk_path = _ensure_rtk_binary(verbose=verbose)- if rtk_path:- cursorrules = Path.cwd() / ".cursorrules"- _inject_rtk_instructions(cursorrules, verbose=verbose)+ _setup_context_tool_for_agent(+ agent="cursor",+ agent_display="Cursor",+ marker_path=cursorrules,+ on_rtk_ready=lambda _rtk: _inject_rtk_instructions(+ cast(Path, cursorrules), verbose=verbose+ ),+ verbose=verbose,+ )if prepare_only:return- proxy_holder: list[subprocess.Popen | None] = [None]- cleanup = _make_cleanup(proxy_holder, port)- signal.signal(signal.SIGINT, cleanup)- signal.signal(signal.SIGTERM, cleanup)-- try:- click.echo()- click.echo(" ╔═══════════════════════════════════════════════╗")- click.echo(" ║ HEADROOM WRAP: CURSOR ║")- click.echo(" ╚═══════════════════════════════════════════════╝")- click.echo()-- proxy_holder[0] = _ensure_proxy(- port, no_proxy, learn=learn, memory=memory, agent_type="cursor"- )-- click.echo()+ def _print_cursor_setup() -> None:for line in _render_cursor_setup_lines(port):click.echo(line)if not no_rtk:@@ -2762,28 +2883,16 @@ def cursor(else:click.echo(" rtk instructions injected into .cursorrules")click.echo(" Cursor will use token-optimized commands automatically.")- click.echo()- click.echo(" Press Ctrl+C to stop the proxy.")- click.echo()-- # Block until Ctrl+C- try:- while True:- time.sleep(1)- proc = proxy_holder[0]- if proc and proc.poll() is not None:- click.echo(" Proxy process exited unexpectedly.")- raise SystemExit(1)- except KeyboardInterrupt:- click.echo("\n Shutting down...")- except SystemExit:- raise- except Exception as e:- click.echo(f" Error: {e}")- raise SystemExit(1) from e- finally:- cleanup()+ _run_proxy_only_watcher(+ agent_label="cursor",+ port=port,+ no_proxy=no_proxy,+ learn=learn,+ memory=memory,+ agent_type="cursor",+ print_setup_lines=_print_cursor_setup,+ )# =============================================================================@@ -2846,44 +2955,23 @@ def cline(# its location even if the interrupt fires before _inject_rtk_instructions# returns (e.g., during the inner _ensure_rtk_binary download).clinerules: Path | None = Path.cwd() / ".clinerules" if not no_rtk else None- try:- if not no_rtk:- if _selected_context_tool() == _CONTEXT_TOOL_LEAN_CTX:- click.echo(" Setting up lean-ctx for Cline...")- _setup_lean_ctx_agent("cline", verbose=verbose)- else:- click.echo(" Setting up rtk for Cline...")- rtk_path = _ensure_rtk_binary(verbose=verbose)- if rtk_path and clinerules is not None:- _inject_rtk_instructions(clinerules, verbose=verbose)- except KeyboardInterrupt:- _emit_wrap_interrupted(- "cline", clinerules if (clinerules and clinerules.exists()) else None+ if not no_rtk:+ _setup_context_tool_for_agent(+ agent="cline",+ agent_display="Cline",+ marker_path=clinerules,+ on_rtk_ready=lambda _rtk: _inject_rtk_instructions(+ cast(Path, clinerules), verbose=verbose+ ),+ verbose=verbose,)- raise SystemExit(130) from Noneif prepare_only:return- proxy_holder: list[subprocess.Popen | None] = [None]- cleanup = _make_cleanup(proxy_holder, port)- signal.signal(signal.SIGINT, cleanup)- signal.signal(signal.SIGTERM, cleanup)-- try:- click.echo()- click.echo(" ╔═══════════════════════════════════════════════╗")- click.echo(" ║ HEADROOM WRAP: CLINE ║")- click.echo(" ╚═══════════════════════════════════════════════╝")- click.echo()-- proxy_holder[0] = _ensure_proxy(- port, no_proxy, learn=learn, memory=memory, agent_type="cline"- )-+ def _print_cline_setup() -> None:anthropic_base = _claude_proxy_base_url(port)openai_base = f"http://127.0.0.1:{port}/v1"- click.echo()click.echo(" Configure Cline in VS Code:")click.echo(" Settings > Cline > API Provider")click.echo(f" Anthropic Base URL: {anthropic_base}")@@ -2895,27 +2983,16 @@ def cline(else:click.echo(" rtk instructions injected into .clinerules")click.echo(" Cline will use token-optimized commands automatically.")- click.echo()- click.echo(" Press Ctrl+C to stop the proxy.")- click.echo()-- try:- while True:- time.sleep(1)- proc = proxy_holder[0]- if proc and proc.poll() is not None:- click.echo(" Proxy process exited unexpectedly.")- raise SystemExit(1)- except KeyboardInterrupt:- click.echo("\n Shutting down...")- except SystemExit:- raise- except Exception as e:- click.echo(f" Error: {e}")- raise SystemExit(1) from e- finally:- cleanup()+ _run_proxy_only_watcher(+ agent_label="cline",+ port=port,+ no_proxy=no_proxy,+ learn=learn,+ memory=memory,+ agent_type="cline",+ print_setup_lines=_print_cline_setup,+ )# =============================================================================@@ -3000,42 +3077,23 @@ def continue_dev("""config_file = config_path or (Path.cwd() / ".continue" / "config.json")- try:- if not no_rtk:- if _selected_context_tool() == _CONTEXT_TOOL_LEAN_CTX:- click.echo(" Setting up lean-ctx for Continue...")- _setup_lean_ctx_agent("continue", verbose=verbose)- else:- click.echo(" Setting up rtk for Continue...")- rtk_path = _ensure_rtk_binary(verbose=verbose)- if rtk_path:- _inject_continue_rtk_systemmessage(config_file, verbose=verbose)- except KeyboardInterrupt:- _emit_wrap_interrupted("continue", config_file if config_file.exists() else None)- raise SystemExit(130) from None+ if not no_rtk:+ _setup_context_tool_for_agent(+ agent="continue",+ agent_display="Continue",+ marker_path=config_file,+ on_rtk_ready=lambda _rtk: _inject_continue_rtk_systemmessage(+ config_file, verbose=verbose+ ),+ verbose=verbose,+ )if prepare_only:return- proxy_holder: list[subprocess.Popen | None] = [None]- cleanup = _make_cleanup(proxy_holder, port)- signal.signal(signal.SIGINT, cleanup)- signal.signal(signal.SIGTERM, cleanup)-- try:- click.echo()- click.echo(" ╔═══════════════════════════════════════════════╗")- click.echo(" ║ HEADROOM WRAP: CONTINUE ║")- click.echo(" ╚═══════════════════════════════════════════════╝")- click.echo()-- proxy_holder[0] = _ensure_proxy(- port, no_proxy, learn=learn, memory=memory, agent_type="continue"- )-+ def _print_continue_setup() -> None:anthropic_base = _claude_proxy_base_url(port)openai_base = f"http://127.0.0.1:{port}/v1"- click.echo()click.echo(" Configure Continue in your IDE:")click.echo(f" Edit {config_file} and set, per model:")click.echo(f' "apiBase": "{openai_base}" # OpenAI-compatible models')@@ -3047,27 +3105,16 @@ def continue_dev(else:click.echo(f" rtk instructions injected into {config_file.name} systemMessage")click.echo(" Continue will use token-optimized commands automatically.")- click.echo()- click.echo(" Press Ctrl+C to stop the proxy.")- click.echo()-- try:- while True:- time.sleep(1)- proc = proxy_holder[0]- if proc and proc.poll() is not None:- click.echo(" Proxy process exited unexpectedly.")- raise SystemExit(1)- except KeyboardInterrupt:- click.echo("\n Shutting down...")- except SystemExit:- raise- except Exception as e:- click.echo(f" Error: {e}")- raise SystemExit(1) from e- finally:- cleanup()+ _run_proxy_only_watcher(+ agent_label="continue",+ port=port,+ no_proxy=no_proxy,+ learn=learn,+ memory=memory,+ agent_type="continue",+ print_setup_lines=_print_continue_setup,+ )# =============================================================================@@ -3138,27 +3185,21 @@ def goose(headroom wrap goose -- --provider anthropic # Pass args to gooseheadroom wrap goose --no-context-tool # Skip CLI context-tool setup"""+ # Goose reads .goosehints from the project root as extra context.# Pre-compute the marker path so the KeyboardInterrupt handler can report# its location even if the interrupt fires before _inject_rtk_instructions# returns (e.g., during the inner _ensure_rtk_binary download).goosehints: Path | None = Path.cwd() / ".goosehints" if not no_rtk else None- try:- if not no_rtk:- if _selected_context_tool() == _CONTEXT_TOOL_LEAN_CTX:- click.echo(" Setting up lean-ctx for Goose...")- _setup_lean_ctx_agent("goose", verbose=verbose)- else:- click.echo(" Setting up rtk for Goose...")- rtk_path = _ensure_rtk_binary(verbose=verbose)- if rtk_path and goosehints is not None:- # Goose reads .goosehints from the project root as extra- # context.- _inject_rtk_instructions(goosehints, verbose=verbose)- except KeyboardInterrupt:- _emit_wrap_interrupted(- "goose", goosehints if (goosehints and goosehints.exists()) else None+ if not no_rtk:+ _setup_context_tool_for_agent(+ agent="goose",+ agent_display="Goose",+ marker_path=goosehints,+ on_rtk_ready=lambda _rtk: _inject_rtk_instructions(+ cast(Path, goosehints), verbose=verbose+ ),+ verbose=verbose,)- raise SystemExit(130) from Noneif prepare_only:return@@ -3266,27 +3307,19 @@ def openhands(headroom wrap openhands -- --task ... # Pass args to openhandsheadroom wrap openhands --no-context-tool"""+ # openhands never writes to disk — its rtk guidance ships via the+ # OPENHANDS_INSTRUCTIONS env var below — so marker_path is None and+ # rtk_required gates the env-only path: without an rtk binary there+ # is no fallback marker file to fall through to.rtk_path: Path | None = None- try:- if not no_rtk:- if _selected_context_tool() == _CONTEXT_TOOL_LEAN_CTX:- click.echo(" Setting up lean-ctx for OpenHands...")- _setup_lean_ctx_agent("openhands", verbose=verbose)- else:- click.echo(" Setting up rtk for OpenHands...")- rtk_path = _ensure_rtk_binary(verbose=verbose)- if not rtk_path:- click.echo(- " Error: rtk install failed; refusing to inject "- "OPENHANDS_INSTRUCTIONS without rtk. Install rtk "- "manually and re-run, or pass --no-context-tool to "- "skip rtk."- )- raise SystemExit(1)- except KeyboardInterrupt:- # openhands never writes to disk — no marker file to flag.- _emit_wrap_interrupted("openhands", None)- raise SystemExit(130) from None+ if not no_rtk:+ rtk_path = _setup_context_tool_for_agent(+ agent="openhands",+ agent_display="OpenHands",+ marker_path=None,+ rtk_required=True,+ verbose=verbose,+ )if prepare_only:returndiff --git a/tests/test_cli/test_wrap_cline.py b/tests/test_cli/test_wrap_cline.pydeleted file mode 100644index 3db05527a..000000000--- a/tests/test_cli/test_wrap_cline.py+++ /dev/null@@ -1,127 +0,0 @@-"""Tests for `headroom wrap cline` command (PR-G1, Phase G)."""--from __future__ import annotations--from pathlib import Path-from unittest.mock import patch--import pytest-from click.testing import CliRunner--from headroom.cli import wrap as wrap_mod-from headroom.cli.main import main---def runner() -> CliRunner:- return CliRunner()---def test_wrap_cline_prepare_only_injects_rtk_into_clinerules(- runner: CliRunner,- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- """`wrap cline --prepare-only` writes RTK guidance to .clinerules at cwd."""- monkeypatch.chdir(tmp_path)- monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)-- with patch.object(wrap_mod, "_ensure_rtk_binary", return_value=Path("/tmp/rtk")):- result = runner.invoke(main, ["wrap", "cline", "--prepare-only"])-- assert result.exit_code == 0, result.output- clinerules = tmp_path / ".clinerules"- assert clinerules.exists(), ".clinerules should be created"- content = clinerules.read_text()- assert wrap_mod._RTK_MARKER in content- assert "RTK (Rust Token Killer)" in content---def test_wrap_cline_prepare_only_idempotent_no_duplicate_block(- runner: CliRunner,- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- """Running wrap cline twice must not duplicate the RTK block."""- monkeypatch.chdir(tmp_path)- monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)-- with patch.object(wrap_mod, "_ensure_rtk_binary", return_value=Path("/tmp/rtk")):- runner.invoke(main, ["wrap", "cline", "--prepare-only"])- runner.invoke(main, ["wrap", "cline", "--prepare-only"])-- clinerules = tmp_path / ".clinerules"- content = clinerules.read_text()- assert content.count(wrap_mod._RTK_MARKER) == 1---def test_wrap_cline_no_context_tool_does_not_create_clinerules(- runner: CliRunner,- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- """--no-context-tool must not create .clinerules."""- monkeypatch.chdir(tmp_path)-- # Patch RTK to fail if accidentally called.- with patch.object(wrap_mod, "_ensure_rtk_binary") as ensure:- result = runner.invoke(main, ["wrap", "cline", "--prepare-only", "--no-context-tool"])-- assert result.exit_code == 0, result.output- assert not (tmp_path / ".clinerules").exists()- ensure.assert_not_called()---def test_wrap_cline_preserves_existing_clinerules_content(- runner: CliRunner,- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- """Pre-existing .clinerules content must be preserved when RTK is appended."""- monkeypatch.chdir(tmp_path)- monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)- clinerules = tmp_path / ".clinerules"- original = "# Project conventions\n\nAlways use Python 3.12.\n"- clinerules.write_text(original)-- with patch.object(wrap_mod, "_ensure_rtk_binary", return_value=Path("/tmp/rtk")):- result = runner.invoke(main, ["wrap", "cline", "--prepare-only"])-- assert result.exit_code == 0, result.output- content = clinerules.read_text()- assert "Always use Python 3.12." in content- assert wrap_mod._RTK_MARKER in content---# ----------------------------------------------------------------------------# M4: Ctrl-C during prelude emits a clear "interrupted, marker may be on disk"-# message and exits non-zero.-# ------------------------------------------------------------------------------def test_wrap_cline_keyboardinterrupt_during_prelude_emits_clear_message(- runner: CliRunner,- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- """Ctrl-C between marker injection and proxy startup must signal clearly."""- monkeypatch.chdir(tmp_path)- monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)-- def raise_kbd_interrupt(*args, **kwargs): # noqa: ANN002, ANN003- # Simulate the user hitting Ctrl-C right after the prelude wrote the- # .clinerules marker but before _ensure_proxy returns. We trigger via- # _ensure_rtk_binary side-effect so the marker file exists on disk.- marker_path = tmp_path / ".clinerules"- marker_path.write_text(wrap_mod.RTK_INSTRUCTIONS_BLOCK)- raise KeyboardInterrupt-- with patch.object(wrap_mod, "_ensure_rtk_binary", side_effect=raise_kbd_interrupt):- result = runner.invoke(main, ["wrap", "cline", "--prepare-only"])-- assert result.exit_code == 130- assert "interrupted" in result.output.lower()- assert "idempotent" in result.output.lower()- # marker file is on disk- assert (tmp_path / ".clinerules").exists()- assert str(tmp_path / ".clinerules") in result.outputdiff --git a/tests/test_cli/test_wrap_goose.py b/tests/test_cli/test_wrap_goose.pyindex e0a28af74..b225c7095 100644--- a/tests/test_cli/test_wrap_goose.py+++ b/tests/test_cli/test_wrap_goose.py@@ -1,4 +1,12 @@-"""Tests for `headroom wrap goose` command (PR-G1, Phase G)."""+"""Tests for `headroom wrap goose` command (PR-G1, Phase G).++Hint-file injection tests (.goosehints idempotency, no-context-tool,+existing-content preservation, Ctrl-C handling) live in+`test_wrap_hintfile_agents.py` — the shared parameterized file that+covers `wrap cline` too. This file keeps only goose-specific behavior:+the OPENAI/ANTHROPIC env-var fan-out for the child binary launch, and+the goose-binary-not-found error path.+"""from __future__ import annotations@@ -47,43 +55,6 @@ def test_wrap_goose_sets_provider_envs(assert captured["args"] == ("session",)-def test_wrap_goose_injects_rtk_into_goosehints(- runner: CliRunner,- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- """RTK block must be written to .goosehints at the project root."""- monkeypatch.chdir(tmp_path)- monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)-- with patch.object(wrap_mod, "_ensure_rtk_binary", return_value=Path("/tmp/rtk")):- result = runner.invoke(main, ["wrap", "goose", "--prepare-only"])-- assert result.exit_code == 0, result.output- goosehints = tmp_path / ".goosehints"- assert goosehints.exists()- content = goosehints.read_text()- assert wrap_mod._RTK_MARKER in content- assert "RTK (Rust Token Killer)" in content---def test_wrap_goose_idempotent_no_duplicate_block(- runner: CliRunner,- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- """Re-running prepare-only must not duplicate the .goosehints RTK block."""- monkeypatch.chdir(tmp_path)- monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)-- with patch.object(wrap_mod, "_ensure_rtk_binary", return_value=Path("/tmp/rtk")):- runner.invoke(main, ["wrap", "goose", "--prepare-only"])- runner.invoke(main, ["wrap", "goose", "--prepare-only"])-- content = (tmp_path / ".goosehints").read_text()- assert content.count(wrap_mod._RTK_MARKER) == 1--def test_wrap_goose_missing_binary_errors_clearly(runner: CliRunner,tmp_path: Path,@@ -99,50 +70,3 @@ def test_wrap_goose_missing_binary_errors_clearly(assert result.exit_code == 1assert "'goose' not found in PATH" in result.output---def test_wrap_goose_no_context_tool_skips_goosehints(- runner: CliRunner,- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- """--no-context-tool must not create .goosehints."""- monkeypatch.chdir(tmp_path)-- with patch.object(wrap_mod, "_ensure_rtk_binary") as ensure:- result = runner.invoke(main, ["wrap", "goose", "--prepare-only", "--no-context-tool"])-- assert result.exit_code == 0, result.output- assert not (tmp_path / ".goosehints").exists()- ensure.assert_not_called()---# ----------------------------------------------------------------------------# M4: Ctrl-C during prelude.-# ------------------------------------------------------------------------------def test_wrap_goose_keyboardinterrupt_during_prelude_emits_clear_message(- runner: CliRunner,- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- """Ctrl-C between marker injection and proxy start must signal clearly."""- monkeypatch.chdir(tmp_path)- monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)-- def raise_kbd(*args, **kwargs): # noqa: ANN002, ANN003- # Simulate Ctrl-C after the prelude wrote .goosehints but before the- # tool was launched. The marker file exists on disk.- marker_path = tmp_path / ".goosehints"- marker_path.write_text(wrap_mod.RTK_INSTRUCTIONS_BLOCK)- raise KeyboardInterrupt-- with patch.object(wrap_mod, "_ensure_rtk_binary", side_effect=raise_kbd):- result = runner.invoke(main, ["wrap", "goose", "--prepare-only"])-- assert result.exit_code == 130- assert "interrupted" in result.output.lower()- assert "idempotent" in result.output.lower()- assert (tmp_path / ".goosehints").exists()- assert ".goosehints" in result.outputdiff --git a/tests/test_cli/test_wrap_helpers.py b/tests/test_cli/test_wrap_helpers.pynew file mode 100644index 000000000..cc3b9b12f--- /dev/null+++ b/tests/test_cli/test_wrap_helpers.py@@ -0,0 +1,407 @@+"""Direct unit tests for the shared wrap-subcommand helpers.++These helpers (`_print_wrap_banner`, `_setup_context_tool_for_agent`,+`_run_proxy_only_watcher`) were extracted to remove ~150 LOC of+copy-pasted scaffolding across the wrap subcommands (cursor / cline /+continue / goose / openhands). The wrap-*.py subcommand tests exercise+them indirectly; these tests pin the contract directly so a future+refactor that breaks one of these helpers fails *here* — at the helper+unit boundary — instead of in five different subcommand suites at+once with confusing diffs.+"""++from __future__ import annotations++from pathlib import Path+from typing import Any++import click+import pytest+from click.testing import CliRunner++from headroom.cli import wrap as wrap_mod++# ---------------------------------------------------------------------------+# _print_wrap_banner — centering math + box drawing.+# ---------------------------------------------------------------------------+++def runner() -> CliRunner:+ return CliRunner()+++def _run_in_click_context(fn) -> str: # type: ignore[no-untyped-def]+ """Invoke `fn` inside a Click `runner.invoke` so `click.echo` output is captured."""+ runner = CliRunner()++ @click.command()+ def _cmd() -> None:+ fn()++ result = runner.invoke(_cmd)+ assert result.exit_code == 0, result.output+ return result.output+++ "agent",+ ["cline", "cursor", "continue", "goose", "openhands", "x", "a-very-long-agent-name"],+)+def test_print_wrap_banner_box_is_inner_width_chars_wide(agent: str) -> None:+ """The banner's horizontal rule should always be 47 chars between the `║` corners."""+ output = _run_in_click_context(lambda: wrap_mod._print_wrap_banner(agent))++ lines = [line for line in output.splitlines() if line.strip()]+ assert len(lines) == 3, f"banner should be 3 non-empty lines; got {lines!r}"+ top, title_line, bottom = lines++ # Top and bottom are the `╔════...╗` rules with 47 equals signs between the corners.+ assert top.endswith("╗")+ assert bottom.endswith("╝")+ assert top.count("═") == wrap_mod._WRAP_BANNER_INNER_WIDTH+ assert bottom.count("═") == wrap_mod._WRAP_BANNER_INNER_WIDTH++ # The middle line has the centered title.+ assert title_line.startswith(" ║")+ assert title_line.endswith("║")+ assert f"HEADROOM WRAP: {agent.upper()}" in title_line+++def test_print_wrap_banner_title_is_centered_or_near_centered() -> None:+ """Centering: pad_left and pad_right may differ by at most 1 when total padding is odd."""+ output = _run_in_click_context(lambda: wrap_mod._print_wrap_banner("cline"))++ lines = [line for line in output.splitlines() if line.strip()]+ title_line = lines[1]++ # Strip the leading " ║" and trailing "║" so we can measure spaces.+ inner = title_line[3:-1]+ assert len(inner) == wrap_mod._WRAP_BANNER_INNER_WIDTH++ title = "HEADROOM WRAP: CLINE"+ pad_left = len(inner) - len(inner.lstrip(" "))+ pad_right = len(inner) - len(inner.rstrip(" "))+ assert inner.strip() == title+ assert abs(pad_left - pad_right) <= 1, (+ f"banner not centered: pad_left={pad_left}, pad_right={pad_right}"+ )+++# ---------------------------------------------------------------------------+# _setup_context_tool_for_agent — all five branches:+# 1. lean-ctx mode → calls _setup_lean_ctx_agent, returns None+# 2. rtk install success → calls on_rtk_ready, returns rtk_path+# 3. rtk install fail + rtk_required=False → returns None silently+# 4. rtk install fail + rtk_required=True → SystemExit(1)+# 5. KeyboardInterrupt → _emit_wrap_interrupted, SystemExit(130)+# ---------------------------------------------------------------------------+++def test_setup_context_tool_lean_ctx_calls_lean_ctx_setup(monkeypatch: pytest.MonkeyPatch) -> None:+ """When HEADROOM_CONTEXT_TOOL=lean-ctx, helper calls _setup_lean_ctx_agent."""+ monkeypatch.setenv("HEADROOM_CONTEXT_TOOL", "lean-ctx")+ called_with: dict[str, Any] = {}++ def fake_lean_ctx(agent: str, verbose: bool = False) -> Path | None:+ called_with["agent"] = agent+ called_with["verbose"] = verbose+ return None++ monkeypatch.setattr(wrap_mod, "_setup_lean_ctx_agent", fake_lean_ctx)++ runner = CliRunner()++ @click.command()+ def _cmd() -> None:+ result = wrap_mod._setup_context_tool_for_agent(+ agent="cline",+ agent_display="Cline",+ marker_path=None,+ )+ assert result is None++ inv = runner.invoke(_cmd)+ assert inv.exit_code == 0, inv.output+ assert called_with == {"agent": "cline", "verbose": False}+++def test_setup_context_tool_rtk_success_calls_on_rtk_ready(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """rtk install success → on_rtk_ready receives the rtk binary path."""+ monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)+ fake_rtk = Path("/tmp/rtk-fake")+ received: list[Path] = []++ monkeypatch.setattr(wrap_mod, "_ensure_rtk_binary", lambda verbose=False: fake_rtk)++ runner = CliRunner()++ @click.command()+ def _cmd() -> None:+ result = wrap_mod._setup_context_tool_for_agent(+ agent="cline",+ agent_display="Cline",+ marker_path=tmp_path / ".clinerules",+ on_rtk_ready=lambda rtk: received.append(rtk),+ )+ assert result == fake_rtk++ inv = runner.invoke(_cmd)+ assert inv.exit_code == 0, inv.output+ assert received == [fake_rtk]+++def test_setup_context_tool_rtk_failure_with_not_required_returns_none(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """rtk install failure + rtk_required=False → silent fall-through, None."""+ monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)+ monkeypatch.setattr(wrap_mod, "_ensure_rtk_binary", lambda verbose=False: None)++ on_rtk_called = False++ def _should_not_be_called(_rtk: Path) -> None:+ nonlocal on_rtk_called+ on_rtk_called = True++ runner = CliRunner()++ @click.command()+ def _cmd() -> None:+ result = wrap_mod._setup_context_tool_for_agent(+ agent="cursor",+ agent_display="Cursor",+ marker_path=None,+ on_rtk_ready=_should_not_be_called,+ rtk_required=False,+ )+ assert result is None++ inv = runner.invoke(_cmd)+ assert inv.exit_code == 0, inv.output+ assert not on_rtk_called, "on_rtk_ready should not be called when rtk install fails"+++def test_setup_context_tool_rtk_failure_with_required_exits_1(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """rtk install failure + rtk_required=True → SystemExit(1) with refusal message."""+ monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)+ monkeypatch.setattr(wrap_mod, "_ensure_rtk_binary", lambda verbose=False: None)++ runner = CliRunner()++ @click.command()+ def _cmd() -> None:+ wrap_mod._setup_context_tool_for_agent(+ agent="openhands",+ agent_display="OpenHands",+ marker_path=None,+ rtk_required=True,+ )++ inv = runner.invoke(_cmd)+ assert inv.exit_code == 1, inv.output+ assert "rtk install failed" in inv.output+ assert "refusing to inject" in inv.output+++def test_setup_context_tool_keyboardinterrupt_emits_interrupted_and_exits_130(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """KeyboardInterrupt during setup → _emit_wrap_interrupted, SystemExit(130)."""+ monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)++ marker = tmp_path / ".clinerules"+ marker.write_text("pre-existing")++ def raise_kbd(verbose: bool = False) -> Path | None:+ raise KeyboardInterrupt++ monkeypatch.setattr(wrap_mod, "_ensure_rtk_binary", raise_kbd)++ runner = CliRunner()++ @click.command()+ def _cmd() -> None:+ wrap_mod._setup_context_tool_for_agent(+ agent="cline",+ agent_display="Cline",+ marker_path=marker,+ )++ inv = runner.invoke(_cmd)+ assert inv.exit_code == 130+ assert "interrupted" in inv.output.lower()+ assert "idempotent" in inv.output.lower()+ assert str(marker) in inv.output+++# ---------------------------------------------------------------------------+# _run_proxy_only_watcher — must print banner, call setup callback, install+# signal handlers, and clean up. Heavily mocked since the real watcher+# blocks on `time.sleep` indefinitely.+# ---------------------------------------------------------------------------+++def test_run_proxy_only_watcher_calls_setup_lines_callback(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The print_setup_lines callback runs after the proxy is ready."""+ # Fake proxy: a dummy object whose `.poll()` returns 0 after first iteration+ # so the watcher exits cleanly via the "proxy exited unexpectedly" branch.++ class _FakeProc:+ def __init__(self) -> None:+ self._polls = 0++ def poll(self) -> int | None:+ self._polls += 1+ return 0 if self._polls > 1 else None++ fake_proc = _FakeProc()++ callback_calls: list[None] = []++ def fake_setup() -> None:+ callback_calls.append(None)++ monkeypatch.setattr(wrap_mod, "_ensure_proxy", lambda *a, **kw: fake_proc)+ # Replace time.sleep with a no-op so the loop spins quickly.+ monkeypatch.setattr(wrap_mod.time, "sleep", lambda _s: None)+ # Replace _make_cleanup to avoid side-effects on real ports/files.+ monkeypatch.setattr(wrap_mod, "_make_cleanup", lambda holder, port: lambda *a, **kw: None)+ # Avoid touching real signal handlers in the test process.+ monkeypatch.setattr(wrap_mod.signal, "signal", lambda *a, **kw: None)++ runner = CliRunner()++ @click.command()+ def _cmd() -> None:+ wrap_mod._run_proxy_only_watcher(+ agent_label="cline",+ port=8787,+ no_proxy=False,+ learn=False,+ memory=False,+ agent_type="cline",+ print_setup_lines=fake_setup,+ )++ inv = runner.invoke(_cmd)+ # The watcher exits 1 when the proxy dies (our _FakeProc returns 0 on poll #2).+ assert inv.exit_code == 1+ assert callback_calls == [None]+ # Banner is part of the helper's contract.+ assert "HEADROOM WRAP: CLINE" in inv.output+ # The "proxy exited unexpectedly" message is the documented exit branch.+ assert "Proxy process exited unexpectedly." in inv.output+++def test_run_proxy_only_watcher_keyboardinterrupt_shuts_down_cleanly(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Ctrl-C during the watcher loop prints `Shutting down...` and exits 0."""++ class _FakeProc:+ def poll(self) -> int | None:+ return None # Proxy is healthy; loop would run forever.++ sleep_calls = {"n": 0}++ def raising_sleep(_s: float) -> None:+ sleep_calls["n"] += 1+ if sleep_calls["n"] >= 1:+ raise KeyboardInterrupt++ monkeypatch.setattr(wrap_mod, "_ensure_proxy", lambda *a, **kw: _FakeProc())+ monkeypatch.setattr(wrap_mod.time, "sleep", raising_sleep)+ monkeypatch.setattr(wrap_mod, "_make_cleanup", lambda holder, port: lambda *a, **kw: None)+ monkeypatch.setattr(wrap_mod.signal, "signal", lambda *a, **kw: None)++ runner = CliRunner()++ @click.command()+ def _cmd() -> None:+ wrap_mod._run_proxy_only_watcher(+ agent_label="cursor",+ port=8787,+ no_proxy=False,+ learn=False,+ memory=False,+ agent_type="cursor",+ print_setup_lines=lambda: None,+ )++ inv = runner.invoke(_cmd)+ assert inv.exit_code == 0, inv.output+ assert "Shutting down..." in inv.output+++def test_run_proxy_only_watcher_unexpected_exception_returns_exit_1(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Unexpected exceptions in the body are caught and converted to SystemExit(1)."""++ def boom(*a: Any, **kw: Any) -> None:+ raise RuntimeError("boom")++ monkeypatch.setattr(wrap_mod, "_ensure_proxy", boom)+ monkeypatch.setattr(wrap_mod, "_make_cleanup", lambda holder, port: lambda *a, **kw: None)+ monkeypatch.setattr(wrap_mod.signal, "signal", lambda *a, **kw: None)++ runner = CliRunner()++ @click.command()+ def _cmd() -> None:+ wrap_mod._run_proxy_only_watcher(+ agent_label="cline",+ port=8787,+ no_proxy=False,+ learn=False,+ memory=False,+ agent_type="cline",+ print_setup_lines=lambda: None,+ )++ inv = runner.invoke(_cmd)+ assert inv.exit_code == 1+ assert "Error: boom" in inv.output+++def test_run_proxy_only_watcher_calls_cleanup_on_finally(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Cleanup callable is invoked in the `finally` block regardless of exit path."""++ cleanup_calls = {"n": 0}++ def fake_cleanup(*a: Any, **kw: Any) -> None:+ cleanup_calls["n"] += 1++ def boom(*a: Any, **kw: Any) -> None:+ raise RuntimeError("boom")++ monkeypatch.setattr(wrap_mod, "_ensure_proxy", boom)+ monkeypatch.setattr(wrap_mod, "_make_cleanup", lambda holder, port: fake_cleanup)+ monkeypatch.setattr(wrap_mod.signal, "signal", lambda *a, **kw: None)++ runner = CliRunner()++ @click.command()+ def _cmd() -> None:+ wrap_mod._run_proxy_only_watcher(+ agent_label="cline",+ port=8787,+ no_proxy=False,+ learn=False,+ memory=False,+ agent_type="cline",+ print_setup_lines=lambda: None,+ )++ inv = runner.invoke(_cmd)+ assert inv.exit_code == 1+ assert cleanup_calls["n"] >= 1, "cleanup must run via the finally block"diff --git a/tests/test_cli/test_wrap_hintfile_agents.py b/tests/test_cli/test_wrap_hintfile_agents.pynew file mode 100644index 000000000..8cf5fea08--- /dev/null+++ b/tests/test_cli/test_wrap_hintfile_agents.py@@ -0,0 +1,158 @@+"""Shared hint-file agent tests for `headroom wrap {cline,goose}` (PR-G1).++Cline and Goose are different wrap patterns (cline is proxy-only watcher,+goose launches a child binary) but both inject the RTK guidance into a+*hint file* at the project root — `.clinerules` and `.goosehints` —+through the same code path (`_inject_rtk_instructions` via the shared+`_setup_context_tool_for_agent` helper).++That hint-file plumbing is the same for both, so the tests covering it+parametrize over `(agent, hint_filename)` here. Agent-specific behavior+(goose's env-var fan-out, goose's binary discovery, cline's IDE setup+print-out) lives in `test_wrap_goose.py` / `test_wrap_cline.py`+respectively — those files keep only what genuinely diverges per agent.+"""++from __future__ import annotations++from pathlib import Path+from unittest.mock import patch++import pytest+from click.testing import CliRunner++from headroom.cli import wrap as wrap_mod+from headroom.cli.main import main++# (subcommand, hint-file basename) — used by every test below.+HINTFILE_AGENTS = [+ pytest.param("cline", ".clinerules", id="cline"),+ pytest.param("goose", ".goosehints", id="goose"),+]+++def runner() -> CliRunner:+ return CliRunner()++[email protected]("agent,hintfile", HINTFILE_AGENTS)+def test_prepare_only_injects_rtk_into_hintfile(+ agent: str,+ hintfile: str,+ runner: CliRunner,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """`wrap <agent> --prepare-only` writes the RTK block to the hint file at cwd."""+ monkeypatch.chdir(tmp_path)+ monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)++ with patch.object(wrap_mod, "_ensure_rtk_binary", return_value=Path("/tmp/rtk")):+ result = runner.invoke(main, ["wrap", agent, "--prepare-only"])++ assert result.exit_code == 0, result.output+ marker = tmp_path / hintfile+ assert marker.exists(), f"{hintfile} should be created"+ content = marker.read_text()+ assert wrap_mod._RTK_MARKER in content+ assert "RTK (Rust Token Killer)" in content++[email protected]("agent,hintfile", HINTFILE_AGENTS)+def test_prepare_only_idempotent_no_duplicate_block(+ agent: str,+ hintfile: str,+ runner: CliRunner,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Running prepare-only twice must not duplicate the RTK block in the hint file."""+ monkeypatch.chdir(tmp_path)+ monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)++ with patch.object(wrap_mod, "_ensure_rtk_binary", return_value=Path("/tmp/rtk")):+ runner.invoke(main, ["wrap", agent, "--prepare-only"])+ runner.invoke(main, ["wrap", agent, "--prepare-only"])++ content = (tmp_path / hintfile).read_text()+ assert content.count(wrap_mod._RTK_MARKER) == 1++[email protected]("agent,hintfile", HINTFILE_AGENTS)+def test_no_context_tool_does_not_create_hintfile(+ agent: str,+ hintfile: str,+ runner: CliRunner,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """--no-context-tool must not create the hint file and must not invoke rtk."""+ monkeypatch.chdir(tmp_path)++ with patch.object(wrap_mod, "_ensure_rtk_binary") as ensure:+ result = runner.invoke(main, ["wrap", agent, "--prepare-only", "--no-context-tool"])++ assert result.exit_code == 0, result.output+ assert not (tmp_path / hintfile).exists()+ ensure.assert_not_called()++[email protected]("agent,hintfile", HINTFILE_AGENTS)+def test_preserves_existing_hintfile_content(+ agent: str,+ hintfile: str,+ runner: CliRunner,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Pre-existing hint-file content must be preserved when RTK is appended."""+ monkeypatch.chdir(tmp_path)+ monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)+ marker_path = tmp_path / hintfile+ original = "# Project conventions\n\nAlways use Python 3.12.\n"+ marker_path.write_text(original)++ with patch.object(wrap_mod, "_ensure_rtk_binary", return_value=Path("/tmp/rtk")):+ result = runner.invoke(main, ["wrap", agent, "--prepare-only"])++ assert result.exit_code == 0, result.output+ content = marker_path.read_text()+ assert "Always use Python 3.12." in content+ assert wrap_mod._RTK_MARKER in content+++# ---------------------------------------------------------------------------+# M4: Ctrl-C during prelude emits a clear "interrupted, marker may be on disk"+# message and exits non-zero (130, the conventional shell signal-130 code).+# ---------------------------------------------------------------------------++[email protected]("agent,hintfile", HINTFILE_AGENTS)+def test_keyboardinterrupt_during_prelude_emits_clear_message(+ agent: str,+ hintfile: str,+ runner: CliRunner,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Ctrl-C after marker injection but before proxy startup must report clearly."""+ monkeypatch.chdir(tmp_path)+ monkeypatch.delenv("HEADROOM_CONTEXT_TOOL", raising=False)++ def raise_kbd(*args, **kwargs): # noqa: ANN002, ANN003+ # Simulate the user hitting Ctrl-C right after the prelude wrote the+ # hint-file marker but before _ensure_proxy returns. We trigger via+ # _ensure_rtk_binary side-effect so the marker exists on disk.+ marker_path = tmp_path / hintfile+ marker_path.write_text(wrap_mod.RTK_INSTRUCTIONS_BLOCK)+ raise KeyboardInterrupt++ with patch.object(wrap_mod, "_ensure_rtk_binary", side_effect=raise_kbd):+ result = runner.invoke(main, ["wrap", agent, "--prepare-only"])++ assert result.exit_code == 130+ assert "interrupted" in result.output.lower()+ assert "idempotent" in result.output.lower()+ assert (tmp_path / hintfile).exists()+ assert hintfile in result.output