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(code): keep semicolon-separated statements valid (#4630)
X54f48fb1c2f3
diff --git a/headroom/transforms/code_compressor.py b/headroom/transforms/code_compressor.pyindex 1e664beab..6efca3806 100644--- a/headroom/transforms/code_compressor.py+++ b/headroom/transforms/code_compressor.py@@ -643,6 +643,10 @@ class CodeStructure:comments: list[str] = field(default_factory=list)top_level_code: list[str] = field(default_factory=list)other: list[str] = field(default_factory=list)+ # Set when the fixed assembly order (declarations before top-level code)+ # moves a definition across executable code, changing class bases,+ # decorators, or default expressions evaluated at definition time.+ reorder_unsafe: bool = False@dataclass@@ -1611,6 +1615,14 @@ class CodeAwareCompressor(Transform):else:structure = self._extract_generic_structure(root, code)+ # Declarations are assembled before the top-level code bucket, so+ # executable code that precedes a definition would be moved after it.+ # That changes definition-time behavior (class bases, decorators,+ # default expressions), so keep the original instead of returning a+ # semantically reordered result.+ if structure.reorder_unsafe:+ return code, structure, {}+# Assemble compressed codecompressed = self._assemble_compressed(structure, language)@@ -1645,6 +1657,11 @@ class CodeAwareCompressor(Transform):"""structure = CodeStructure()captured_byte_ranges: list[tuple[int, int]] = []+ # Import text keyed by start byte, so a root-level import that turns+ # out to follow executable code can later be moved back out of+ # ``structure.imports`` (which is emitted first) unchanged.+ import_entries: dict[int, str] = {}+ demoted_import_starts: set[int] = set()def _validated_candidate(node: Any, compressed: str) -> str:if candidate_validator is None:@@ -1664,7 +1681,9 @@ class CodeAwareCompressor(Transform):# Import statementsif node_type in lang_config.import_nodes:leading = _get_leading_comment_text(node, code, captured_byte_ranges)- structure.imports.append(leading + _get_node_text(node, code))+ entry = leading + _get_node_text(node, code)+ structure.imports.append(entry)+ import_entries[node.start_byte] = entrycaptured_byte_ranges.append((node.start_byte, node.end_byte))return@@ -1816,15 +1835,62 @@ class CodeAwareCompressor(Transform):# e.g. tree-sitter-c-sharp rejects top-level `#region` after a type# declaration, which would fail validation and forfeit compression.first_captured = min((r[0] for r in captured_byte_ranges), default=None)+ declaration_nodes = (+ lang_config.function_nodes+ | lang_config.class_nodes+ | lang_config.type_nodes+ | (lang_config.container_node_types or frozenset())+ )+ if lang_config.decorator_node:+ declaration_nodes = declaration_nodes | {lang_config.decorator_node}+ saw_top_level_code = Falsefor child in root.children:child_range = (child.start_byte, child.end_byte)- if child_range not in captured_byte_ranges:- text = _get_node_text(child, code).strip()- if text:- if first_captured is not None and child.end_byte <= first_captured:- structure.header_code.append(text)- else:- structure.top_level_code.append(text)+ if child_range in captured_byte_ranges:+ # Python runs top-level statements in source order. An import+ # that follows executable code cannot be hoisted above it:+ # `import sys; sys.path.insert(0, 'vendor'); import plugin`+ # would import the plugin before the path update. Emit such+ # imports in place with the rest of the top-level code.+ if (+ language == CodeLanguage.PYTHON+ and saw_top_level_code+ and child.type in lang_config.import_nodes+ ):+ entry = import_entries.get(child.start_byte)+ if entry is not None:+ structure.top_level_code.append(entry)+ demoted_import_starts.add(child.start_byte)+ # Declarations are emitted before the top-level code bucket,+ # so a definition after executable code would run before it.+ if (+ language == CodeLanguage.PYTHON+ and saw_top_level_code+ and child.type in declaration_nodes+ ):+ structure.reorder_unsafe = True+ continue+ # In Python a `;` between two statements on one physical line+ # is a root-level anonymous token. Emitted as its own fragment+ # it becomes a bare `;` line and invalidates the output.+ if not child.is_named and child.type in (";", ","):+ continue+ text = _get_node_text(child, code).strip()+ if text:+ if first_captured is not None and child.end_byte <= first_captured:+ structure.header_code.append(text)+ else:+ structure.top_level_code.append(text)+ saw_top_level_code = True++ if demoted_import_starts:+ # Python only: the import branch above is the sole producer of+ # ``structure.imports`` entries for this language.+ structure.imports = [+ entry+ for start, entry in import_entries.items()+ if start not in demoted_import_starts+ ]return structure@@ -2043,6 +2109,21 @@ class CodeAwareCompressor(Transform):continuebody_stmts.append((child.start_point[0], child.end_point[0]))+ # Statements can share a physical line (`a = 1; b = 2`). Lines are kept+ # whole, so merge overlapping ranges into one entry: keeping both would+ # duplicate the shared line, and dropping the later range would lose+ # continuation lines of a multi-line statement after the `;`.+ merged_stmts: list[tuple[int, int]] = []+ for start_row, end_row in body_stmts:+ if merged_stmts and start_row <= merged_stmts[-1][1]:+ merged_stmts[-1] = (+ merged_stmts[-1][0],+ max(merged_stmts[-1][1], end_row),+ )+ else:+ merged_stmts.append((start_row, end_row))+ body_stmts = merged_stmts+# Calculate lines per statement and keep whole statements until budgetkept_lines: list[str] = []kept_line_count = 0@@ -2160,6 +2241,7 @@ class CodeAwareCompressor(Transform):# Process each child of the class body individuallybody_parts: list[str] = []processed_ranges: list[tuple[int, int]] = []+ last_processed_end = -1for child in body_node.children:if not child.is_named:@@ -2170,6 +2252,14 @@ class CodeAwareCompressor(Transform):child_end = child.end_point[0]if child.end_point[1] == 0 and child_end > child_start:child_end -= 1+ # Statements can share a physical line (`x = 1; y = 2`). The line+ # slice already carries all of them; skip only rows already+ # emitted, keeping any continuation lines of this node.+ if child_start <= last_processed_end:+ child_start = last_processed_end + 1+ if child_start > child_end:+ continue+ last_processed_end = child_endchild_text = "\n".join(code_lines[child_start : child_end + 1])# Methods/functions inside the class — compress individuallydiff --git a/tests/test_transforms/test_code_compressor.py b/tests/test_transforms/test_code_compressor.pyindex 167288ba1..d844b43ca 100644--- a/tests/test_transforms/test_code_compressor.py+++ b/tests/test_transforms/test_code_compressor.py@@ -9,6 +9,8 @@ Comprehensive tests covering:- Edge cases: Empty content, unavailable dependency, fallbacks"""+import decimal+import sysimport textwrapfrom unittest.mock import patch@@ -2426,3 +2428,146 @@ class TestRustAttributeAttachment:assert result.syntax_valid is Trueassert "#[inline]\npub fn record" in result.compressedassert not result.compressed.rstrip().endswith("#[inline]")++[email protected](not TREE_SITTER_INSTALLED, reason="tree-sitter-languages not installed")+class TestSemicolonSeparatedStatements:+ """``a = 1; b = 2`` must not corrupt or duplicate the compressed output."""++ def _compressor(self):+ return CodeAwareCompressor(+ CodeCompressorConfig(+ min_tokens_for_compression=1,+ max_body_lines=5,+ enable_ccr=False,+ )+ )++ def test_top_level_separator_does_not_become_a_bare_line(self):+ """Python exposes the ``;`` as a root-level token; emitting it as a+ standalone fragment puts a bare ``;`` on its own line and makes the+ whole result invalid, so compression falls back to the original."""+ code = (+ "import json\n"+ "B='/tmp/'\n"+ "v=json.load(open(B+'v.json')); m=json.load(open(B+'m.json'))\n"+ "print('oe', m['order_expire']); print('pay', m['pay_url'])\n"+ )+ result = self._compressor().compress(code, language="python")++ assert result.syntax_valid is True+ assert result.compressed != code+ assert [line for line in result.compressed.splitlines() if line.strip() == ";"] == []+ assert "v=json.load(open(B+'v.json'))" in result.compressed+ assert "m=json.load(open(B+'m.json'))" in result.compressed++ def test_class_body_statement_is_not_duplicated(self):+ code = "class C:\n x=1; y=2\n z=3\n"+ result = self._compressor().compress(code, language="python")++ assert result.syntax_valid is True+ assert result.compressed.count("x=1; y=2") == 1++ def test_class_body_statement_continuation_is_kept(self):+ """The second statement starts on the already-emitted row and+ continues on the next one; trimming the shared row must not drop+ the continuation line."""+ code = "class C:\n x=1; y=(2 +\n 3)\n z=4\n"+ result = self._compressor().compress(code, language="python")++ assert result.syntax_valid is True+ assert result.compressed.count("x=1; y=(2 +") == 1+ assert result.compressed.count(" 3)") == 1+ assert result.compressed.count("z=4") == 1++ def test_import_after_statement_keeps_source_order(self, tmp_path):+ """Imports are hoisted to the top of the output, but an import that+ follows executable code must not jump above it: importing the plugin+ before the path update fails at runtime."""+ vendor = tmp_path / "vendor"+ vendor.mkdir()+ module_name = "semicolon_order_plugin"+ (vendor / f"{module_name}.py").write_text("VALUE = 42\n")+ code = f"import sys; sys.path.insert(0, {str(vendor)!r}); import {module_name}\n"++ result = self._compressor().compress(code, language="python")++ assert result.syntax_valid is True+ assert result.compressed != code+ assert (+ result.compressed.index("import sys")+ < result.compressed.index("sys.path.insert")+ < result.compressed.index(f"import {module_name}")+ )++ saved_path = list(sys.path)+ saved_modules = set(sys.modules)+ try:+ exec(result.compressed, {})+ assert module_name in sys.modules+ finally:+ sys.path[:] = saved_path+ for name in set(sys.modules) - saved_modules:+ del sys.modules[name]++ def test_declaration_after_top_level_code_keeps_source_order(self):+ """Declarations are assembled before the top-level code bucket, so a+ class defined after executable code would move ahead of it. Safe+ reassembly cannot be guaranteed, so the original snippet is kept."""+ code = "import sys; marker = 1; import decimal\nclass Money(decimal.Decimal):\n pass\n"+ result = self._compressor().compress(code, language="python")++ assert result.syntax_valid is True+ assert result.compressed == code+ namespace: dict[str, object] = {}+ exec(result.compressed, namespace)+ assert issubclass(namespace["Money"], decimal.Decimal)++ def test_decorator_default_after_top_level_code_keeps_source_order(self):+ """A decorator and a default expression are evaluated when the+ function is defined, so they cannot move ahead of the import they+ use."""+ code = (+ "import sys; marker = 1; import functools\n"+ "@functools.lru_cache(maxsize=None)\n"+ "def compute(value=marker):\n"+ " return value\n"+ )+ result = self._compressor().compress(code, language="python")++ assert result.syntax_valid is True+ assert result.compressed == code+ namespace: dict[str, object] = {}+ exec(result.compressed, namespace)+ assert namespace["compute"]() == 1++ def test_function_body_keeps_each_line_once(self):+ """Both statements share one physical line. The line slice already+ carries the whole line, so adding the second statement's range again+ duplicates it; dropping it instead would lose a continuation line."""+ code = (+ "def f():\n"+ " x=1; y=(2 +\n"+ " 3)\n"+ " a=3\n"+ " b=4\n"+ " c=5\n"+ " d=6\n"+ " e=7\n"+ " return x+y\n"+ )+ compressor = self._compressor()+ parser = cc._get_parser("python")+ root = parser.parse(code.encode("utf-8")).root_node+ analysis = compressor._analyze_symbol_importance(root, code, CodeLanguage.PYTHON, "")+ compressed = compressor._compress_function_ast(+ root.children[0],+ code,+ CodeLanguage.PYTHON,+ cc._LANG_CONFIGS[CodeLanguage.PYTHON],+ {},+ analysis,+ )++ assert compressed.count("x=1; y=(2 +") == 1+ assert compressed.count(" 3)") == 1