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
Fix Windows repository paths and state filenames
alexsharp231-sysee1a5e6a8e95
diff --git a/tests/test_windows_identity.py b/tests/test_windows_identity.pynew file mode 100644index 0000000..d2e73b2--- /dev/null+++ b/tests/test_windows_identity.py@@ -0,0 +1,44 @@+import os+import tempfile+import unittest+from tokeneconomizer.plugin import paths+++class WindowsIdentityTests(unittest.TestCase):+ def test_local_remote_spellings_share_identity(self):+ expected = 'c:/work/sample/repo'+ self.assertEqual(paths.normalize_remote(r'C:\Work\Sample\Repo'), expected)+ self.assertEqual(paths.normalize_remote(r'C:\\Work\\Sample\\Repo'), expected)+ self.assertEqual(paths.normalize_remote('C:/Work/Sample/Repo.git'), expected)+ self.assertEqual(paths.normalize_remote('[email protected]:Owner/Repo.git'), 'example.com/owner/repo')+ self.assertEqual(paths.normalize_remote('https://example.com/Owner/Repo'), 'example.com/owner/repo')++ def test_state_writers_accept_windows_labels(self):+ from tokeneconomizer.microskills.distiller import Distiller+ from tokeneconomizer.microskills.envfacts import EnvFactsDistiller+ from tokeneconomizer.toolprune.codex import CodexUntoolProfile+ from tokeneconomizer.plugin.repos import _rename_label+ label = r'C:\Work\Sample\Repo'+ with tempfile.TemporaryDirectory() as directory:+ for writer in (Distiller(label), EnvFactsDistiller(label)):+ writer.save(directory)+ self.assertTrue(os.path.isfile(writer._path(directory, label)))+ profile = CodexUntoolProfile(label, directory, fresh=True)+ self.assertNotIn(':', os.path.basename(os.path.dirname(profile.path)))+ _rename_label(directory, label)++ def test_repo_labels_are_valid_single_filenames(self):+ from tokeneconomizer.names import repo_filename+ for label in ('owner/repo', r'C:\Work\Repo', 'owner:repo', 'name?bad', ''):+ filename = repo_filename(label) + '.json'+ self.assertFalse(any(c in filename for c in '<>:"/\\|?*'))+ with tempfile.TemporaryDirectory() as directory:+ path = os.path.join(directory, filename)+ with open(path, 'w', encoding='utf-8') as file:+ file.write('{}')+ self.assertTrue(os.path.isfile(path))+ self.assertEqual(repo_filename('owner/repo'), 'owner__repo')+++if __name__ == '__main__':+ unittest.main()diff --git a/tokeneconomizer/microskills/distiller.py b/tokeneconomizer/microskills/distiller.pyindex 6e3865d..acfe303 100644--- a/tokeneconomizer/microskills/distiller.py+++ b/tokeneconomizer/microskills/distiller.py@@ -20,6 +20,7 @@ import jsonimport osimport re+from ..names import repo_filenamefrom ..trace import call_cwdsfrom ..trace.claude import CONVERSATIONfrom .lifecycle import Lifecycle, edited_files, edited_pyfiles@@ -748,7 +749,7 @@ class Distiller:def _path(root, repo):d = os.path.join(root, STATE_SUBDIR)os.makedirs(d, exist_ok=True)- return os.path.join(d, repo.replace("/", "__") + ".json")+ return os.path.join(d, repo_filename(repo) + ".json")def save(self, root):# The window goes with the facts: a proposer reloaded for each session (the plugin'sdiff --git a/tokeneconomizer/microskills/envfacts.py b/tokeneconomizer/microskills/envfacts.pyindex 00351f2..e4ebf0c 100644--- a/tokeneconomizer/microskills/envfacts.py+++ b/tokeneconomizer/microskills/envfacts.py@@ -36,6 +36,7 @@ import osimport refrom collections import Counter+from ..names import repo_filenamefrom .lifecycle import Lifecyclefrom .observe import (DEFAULT_VOCAB, NETWORK_ERRORS, form_failed, form_worked, is_bare,label_rule, observe_task)@@ -525,7 +526,7 @@ class EnvFactsDistiller:def _path(root, repo):d = os.path.join(root, STATE_SUBDIR)os.makedirs(d, exist_ok=True)- return os.path.join(d, repo.replace("/", "__") + ".json")+ return os.path.join(d, repo_filename(repo) + ".json")def save(self, root):with open(self._path(root, self.repo), "w", encoding="utf-8") as fh:diff --git a/tokeneconomizer/names.py b/tokeneconomizer/names.pynew file mode 100644index 0000000..21f8b14--- /dev/null+++ b/tokeneconomizer/names.py@@ -0,0 +1,10 @@+"""One file or folder name for a repository's state, whatever its label holds."""+import re++_UNSAFE = re.compile(r'[<>:"/\\|?*]+')+++def repo_filename(repo):+ """`owner/repo` becomes `owner__repo`. A label holding a Windows path stays one name: joined as it+ came, its separators or drive would file the state somewhere else, or nowhere."""+ return _UNSAFE.sub("__", repo).strip(". ") or "repo"diff --git a/tokeneconomizer/plugin/paths.py b/tokeneconomizer/plugin/paths.pyindex bac1180..6c4a27c 100644--- a/tokeneconomizer/plugin/paths.py+++ b/tokeneconomizer/plugin/paths.py@@ -190,7 +190,8 @@ def normalize_remote(url):u = (url or "").strip()u = re.sub(r"^[a-z+]+://", "", u) # schemeu = re.sub(r"^[^@/]+@", "", u) # user@- u = u.replace(":", "/", 1) if re.match(r"^[^/]+:[^/\d]", u) else u # scp-style host:path+ u = re.sub(r"/+", "/", u.replace("\\", "/")) # local Windows remotes, including git's escaped slashes+ u = u.replace(":", "/", 1) if not re.match(r"^[a-zA-Z]:/", u) and re.match(r"^[^/]+:[^/\d]", u) else uu = re.sub(r"\.git$", "", u.rstrip("/"))return u.lower()diff --git a/tokeneconomizer/plugin/repos.py b/tokeneconomizer/plugin/repos.pyindex ebda1e4..70fe061 100644--- a/tokeneconomizer/plugin/repos.py+++ b/tokeneconomizer/plugin/repos.py@@ -31,6 +31,7 @@ import shutilimport timeimport traceback+from ..names import repo_filenamefrom . import hosts as hosts_modfrom .paths import (BY_PATH, BY_REMOTE, RepoId, _slug, digest, home_dir, is_git_entry,normalize_remote, origin_url, repo_identity, state_root)@@ -260,7 +261,7 @@ def _rename_label(mech_dir, label):"""Mechanism state is filed by repository name; file what moved under the destination's."""if not label:return- want = label.replace("/", "__")+ want = repo_filename(label)for sub in ("envfacts_state", "manual_state"):d = os.path.join(mech_dir, sub)try:diff --git a/tokeneconomizer/toolprune/codex.py b/tokeneconomizer/toolprune/codex.pyindex 55b32dd..4cab69c 100644--- a/tokeneconomizer/toolprune/codex.py+++ b/tokeneconomizer/toolprune/codex.py@@ -29,6 +29,7 @@ import jsonimport osimport refrom collections import Counter+from tokeneconomizer.names import repo_filename# ===========================================================================@@ -346,7 +347,7 @@ class CodexUntoolProfile:self.repo = repostate_dir = os.path.join(os.path.abspath(results_root), "interface_state",- repo.replace("/", "__"))+ repo_filename(repo))self.path = os.path.join(state_dir, "codex_untool.json")self._pending = Noneself.state = self._new_state()