Experience-Driven Black-Box Cost Control for Coding Agents
Python agentic-aiagentic-codingai-codingai-coding-assistantanthropicartificial-intelligenceclaude-codecodexcoding-agentcoding-agentscost-optimizationcost-reductiondeveloper-toolsgithub-copilotllmopen-sourceopenaiproductivitytoken-optimization
Windows: encodings, host detection, tests and CI
Aaron6eb1d2156809
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex 8e84c7c..82917d5 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -13,8 +13,13 @@ jobs:strategy:fail-fast: falsematrix:+ os: [ubuntu-latest, windows-latest]python: ["3.10", "3.13"]- runs-on: ubuntu-latest+ runs-on: ${{ matrix.os }}+ defaults:+ run:+ # Git Bash on Windows: the launchers are `sh` scripts, run there as Claude Code runs them.+ shell: bashsteps:- uses: actions/checkout@v5- uses: actions/setup-python@v6diff --git a/plugin/scripts/te_bootstrap.py b/plugin/scripts/te_bootstrap.pyindex 02c2302..f7fc535 100644--- a/plugin/scripts/te_bootstrap.py+++ b/plugin/scripts/te_bootstrap.py@@ -46,7 +46,8 @@ def _marketplace_sources(plugin_root):# its `known_marketplaces.json` records for this marketplace.try:import json- known = json.load(open(os.path.join(home, "plugins", "known_marketplaces.json")))+ known = json.load(open(os.path.join(home, "plugins", "known_marketplaces.json"),+ encoding="utf-8"))entry = known.get(market) or {}source = entry.get("source") or {}for cand in (source.get("path"), entry.get("installLocation")):@@ -77,7 +78,7 @@ def _symlink_stub(plugin_root):try:if not os.path.isfile(stub) or os.path.getsize(stub) > 1024:return None- target = open(stub).read().strip()+ target = open(stub, encoding="utf-8").read().strip()except (IOError, OSError):return Nonereturn os.path.dirname(os.path.normpath(os.path.join(plugin_root, "lib", target)))diff --git a/tests/conftest.py b/tests/conftest.pyindex 7f9dd96..ab07577 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -11,6 +11,14 @@ for p in (_REPO, _TESTS):sys.path.insert(0, p)+def symlink_or_skip(src, dst):+ """`os.symlink`, or skip where this system makes none (Windows without Developer Mode)."""+ try:+ os.symlink(src, dst)+ except OSError as e:+ pytest.skip(f"this system makes no symlinks: {e}")++def pytest_configure(config):config.addinivalue_line("markers", "real_sidecalls: test the side-call functions themselves ""(their subprocess is faked inside the test)")diff --git a/tests/test_live_core.py b/tests/test_live_core.pyindex 8574a19..de45b9c 100644--- a/tests/test_live_core.py+++ b/tests/test_live_core.py@@ -230,7 +230,6 @@ def test_a_compressed_rollout_is_reported_unreadable(tmp_path):# ---- hosts ---------------------------------------------------------------------------------[email protected](os.name == "nt", reason="no `ps` on Windows: Copilot -p is not told apart")def test_host_detection():assert hosts.detect({"turn_id": "t"}).name == "codex"assert hosts.detect({"transcript_path": "/h/.codex/sessions/2026/rollout-a.jsonl"}).name == "codex"diff --git a/tests/test_live_repomap.py b/tests/test_live_repomap.pyindex e6d135d..71a0ee5 100644--- a/tests/test_live_repomap.py+++ b/tests/test_live_repomap.py@@ -8,8 +8,6 @@ import sysimport pytest-pytestmark = pytest.mark.skipif(os.name == "nt", reason="the stand-in Python is a sh script")-from tokeneconomizer.plugin import repomapfrom tokeneconomizer.plugin.config import LiveConfigfrom tests.test_live_hooks import call, env, repo # noqa: F401@@ -25,6 +23,8 @@ echo "| def run(): ranked toward [$4]"def _fake(tmp_path, probe=0, slow=0):+ if os.name == "nt":+ pytest.skip("the stand-in Python is an sh script, which Windows cannot start")p = tmp_path / f"fakepy-{probe}-{slow}"p.write_text(FAKE.format(probe=probe, slow=slow))p.chmod(p.stat().st_mode | stat.S_IEXEC)diff --git a/tests/test_live_repos.py b/tests/test_live_repos.pyindex c82d945..93b3eed 100644--- a/tests/test_live_repos.py+++ b/tests/test_live_repos.py@@ -616,7 +616,8 @@ def test_an_end_with_no_start_and_no_log_records_nothing(tmp_path, env, host):@pytest.mark.skipif(os.name == "nt" or os.geteuid() == 0,- reason="root writes through read-only permissions; Windows ignores chmod on directories")+ reason="root writes through read-only permissions; Windows ignores chmod on "+ "directories")def test_a_change_where_the_state_is_read_only_is_refused_whole(tmp_path, env, monkeypatch,capsys):"""Codex's default sandbox makes ~/.tokeneconomizer read-only. A change must be refuseddiff --git a/tests/test_live_safety.py b/tests/test_live_safety.pyindex b1168de..747b532 100644--- a/tests/test_live_safety.py+++ b/tests/test_live_safety.py@@ -17,6 +17,7 @@ import pytestfrom tokeneconomizer.plugin import denylist, toolcheckfrom tokeneconomizer.plugin.paths import ensure_launcher, secure_rootfrom tokeneconomizer.plugin.store import Store+from tests.conftest import symlink_or_skipfrom tests.test_live_hooks import repo # noqa: F401PLUGIN = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "plugin")@@ -31,7 +32,7 @@ def _mode(path):def test_a_symlinked_settings_directory_is_refused(repo, tmp_path, host, rel):outside = tmp_path / "outside"outside.mkdir()- os.symlink(outside, os.path.join(repo, rel))+ symlink_or_skip(outside, os.path.join(repo, rel))item = {"claude": "Workflow", "copilot": "github-mcp-server", "codex": "goals"}[host]with pytest.raises(RuntimeError, match="symlink"):denylist.apply(repo, [item], Store(str(tmp_path / "st")), host=host)@@ -42,7 +43,7 @@ def test_a_symlinked_settings_file_is_refused_and_its_target_untouched(repo, tmptarget = tmp_path / "elsewhere.json"target.write_text('{"keep": true}\n')os.makedirs(os.path.join(repo, ".claude"))- os.symlink(target, os.path.join(repo, ".claude", "settings.local.json"))+ symlink_or_skip(target, os.path.join(repo, ".claude", "settings.local.json"))st = Store(str(tmp_path / "st"))with pytest.raises(RuntimeError, match="symlink"):denylist.apply(repo, ["Workflow"], st)@@ -76,12 +77,13 @@ def test_a_git_file_pointing_out_of_the_repository_gets_no_exclude_line(repo, tmdef test_a_symlinked_exclude_file_is_not_written_through(repo, tmp_path):victim = tmp_path / "victim"victim.write_text("keep\n")- os.symlink(victim, os.path.join(repo, ".git", "info", "exclude"))+ symlink_or_skip(victim, os.path.join(repo, ".git", "info", "exclude"))denylist.apply(repo, ["Workflow"], Store(str(tmp_path / "st")))assert victim.read_text() == "keep\n"[email protected](os.name == "nt", reason="POSIX permission bits: Windows keeps a profile private by ACL")[email protected](os.name == "nt",+ reason="POSIX permission bits: Windows keeps a profile private by ACL")def test_a_loose_state_root_is_made_private_and_the_launcher_is_owner_only(tmp_path):env = {"TOKENECONOMIZER_HOME": str(tmp_path / "home"), "TE_PLUGIN_ROOT": PLUGIN}os.makedirs(env["TOKENECONOMIZER_HOME"], mode=0o775)@@ -91,7 +93,8 @@ def test_a_loose_state_root_is_made_private_and_the_launcher_is_owner_only(tmp_passert _mode(ensure_launcher(env)) == 0o700[email protected](os.name == "nt", reason="POSIX permission bits: Windows keeps a profile private by ACL")[email protected](os.name == "nt",+ reason="POSIX permission bits: Windows keeps a profile private by ACL")def test_the_command_line_creates_its_state_private(repo, tmp_path):env = dict(os.environ, TOKENECONOMIZER_HOME=str(tmp_path / "home"))subprocess.run(["sh", os.path.join(PLUGIN, "scripts", "te"), "--cwd", repo, "config", "set",diff --git a/tests/test_plugin_package.py b/tests/test_plugin_package.pyindex 7f0e9fd..21c3ca0 100644--- a/tests/test_plugin_package.py+++ b/tests/test_plugin_package.py@@ -211,13 +211,11 @@ def test_the_mechanisms_never_import_the_plugin_runtime():assert out.stdout.strip() == "[]", out.stdout + out.stderr[email protected](not os.path.islink(os.path.join(PLUGIN, "lib", "tokeneconomizer")),- reason="checkout without symlinks (Windows): see the known_marketplaces test")def test_the_plugin_ships_and_loads_no_benchmark_code():"""The benchmark adapters, the facade, the workloads, the baselines and the benchmark-onlycontrollers live with the experiments (`experiments/te_bench/`). The plugin's library is thepackage alone, and running every part of the plugin loads none of them."""- shipped = os.path.join(PLUGIN, "lib", "tokeneconomizer")+ shipped = os.path.join(REPO, "tokeneconomizer") # what lib/ links (below)assert sorted(n for n in os.listdir(shipped)if os.path.isdir(os.path.join(shipped, n)) and n != "__pycache__") == sorted(MECHANISMS + ("plugin",))@@ -255,7 +253,6 @@ def test_the_package_is_stdlib_only_and_never_touches_the_benchmark_harness():"tokeneconomizer", "tomllib"), f"{path} imports non-stdlib {mod}"[email protected](os.name == "nt", reason="the Pi extension is not ported to Windows")def test_a_resumed_pi_conversation_keeps_the_section_it_carries():"""Pi rebuilds a conversation's system message from its system entries, so a resumed one isgiven back the facts section it carries, byte for byte: unwrapped from the `<name>` tags Pi@@ -266,7 +263,8 @@ def test_a_resumed_pi_conversation_keeps_the_section_it_carries():pytest.skip("node is not installed")ext = os.path.join(PLUGIN, "pi", "tokeneconomizer.ts")script = """-const { carriedSection } = await import(process.argv[1]);+const { pathToFileURL } = await import("node:url"); // Windows: a path is no import URL+const { carriedSection } = await import(pathToFileURL(process.argv[1]).href);const sys = (sections) => ({ type: "message", message: { role: "system", sections } });const compact = (sections) => ({ type: "compaction", systemMessage: { sections } });const user = { type: "message", message: { role: "user" } };diff --git a/tokeneconomizer/plugin/hosts.py b/tokeneconomizer/plugin/hosts.pyindex b940ab2..9f586e0 100644--- a/tokeneconomizer/plugin/hosts.py+++ b/tokeneconomizer/plugin/hosts.py@@ -464,9 +464,10 @@ def detect(payload, env=None, hint=None):if "turn_id" in (payload or {}):return Codex()tp = str((payload or {}).get("transcript_path") or "")- if os.path.basename(tp).startswith("rollout-") or f"{os.sep}.codex{os.sep}" in tp:+ sp = tp.replace("\\", "/") # a Windows path, with either separator+ if sp.rsplit("/", 1)[-1].startswith("rollout-") or "/.codex/" in sp:return Codex()- if f"{os.sep}session-state{os.sep}" in tp and tp.endswith("events.jsonl"):+ if "/session-state/" in sp and tp.endswith("events.jsonl"):return Copilot()# Claude Code always sends a transcript path; Copilot sends none before Stop, and marks its# hook processes. (Hooks inherit the parent's environment, so the marker alone would alsodiff --git a/tokeneconomizer/plugin/winspawn.py b/tokeneconomizer/plugin/winspawn.pyindex d81f4b6..db73cb6 100644--- a/tokeneconomizer/plugin/winspawn.py+++ b/tokeneconomizer/plugin/winspawn.py@@ -28,7 +28,7 @@ _BREAKAWAY = 0x01000000 # CREATE_BREAKAWAY_FROM_JOBdef spawn(cmd, cwd, env, log_path):"""Start `cmd` so that it outlives the hook that started it. Returns whether it started."""try:- with open(log_path, "a") as log:+ with open(log_path, "a", encoding="utf-8") as log:subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=log, stderr=log, cwd=cwd,env=env, creationflags=_FLAGS | _BREAKAWAY, close_fds=True)return True@@ -62,13 +62,13 @@ def _spawn_wmi(cmd, cwd, env, log_path):def _run(spec_path):- with open(spec_path) as fh:+ with open(spec_path, encoding="utf-8") as fh:spec = json.load(fh)try:os.remove(spec_path)except OSError:pass- with open(spec["log"], "a") as log:+ with open(spec["log"], "a", encoding="utf-8") as log:return subprocess.call(spec["cmd"], stdin=subprocess.DEVNULL, stdout=log, stderr=log,cwd=spec["cwd"], env=spec["env"], creationflags=0x08000000)