diff --git a/docs-agent-mcp/mcp-server/compressor.py b/docs-agent-mcp/mcp-server/compressor.py index 7c43eae2..91029c3a 100644 --- a/docs-agent-mcp/mcp-server/compressor.py +++ b/docs-agent-mcp/mcp-server/compressor.py @@ -103,7 +103,54 @@ def _is_heading(line: str) -> bool: - return bool(re.match(r"^#{1,6}\s", line)) + return bool(re.match(r"^\s*#{1,6}\s", line)) + + +def _is_list_item(line: str) -> bool: + return bool(re.match(r"^\s*([-*+]|\d+\.)\s", line)) + + +def _is_table(text: str) -> bool: + stripped = text.strip() + return stripped.startswith("|") and stripped.endswith("|") + + +def _is_code_fence(text: str) -> bool: + return text.strip().startswith("```") + + +def _join_blocks(parts: list[str]) -> str: + """Join compressed blocks while preserving Markdown document hierarchy.""" + if not parts: + return "" + + result = parts[0] + for curr in parts[1:]: + prev_last_line = result.splitlines()[-1] if result else "" + + prev_is_h = _is_heading(prev_last_line) + prev_is_list = _is_list_item(prev_last_line) + prev_is_code = _is_code_fence(prev_last_line) + prev_is_table = _is_table(prev_last_line) + + curr_first_line = curr.splitlines()[0] if curr else "" + curr_is_h = _is_heading(curr_first_line) + curr_is_list = _is_list_item(curr_first_line) + curr_is_code = _is_code_fence(curr_first_line) + curr_is_table = _is_table(curr_first_line) + + if prev_is_h or curr_is_h or prev_is_code or curr_is_code or prev_is_table or curr_is_table: + sep = "\n\n" + elif prev_is_list and curr_is_list: + sep = "\n" + elif prev_is_list or curr_is_list: + sep = "\n\n" + else: + sep = " " + + result += sep + curr + + return result def _logical_lines(para: str) -> list[str]: @@ -311,7 +358,7 @@ def compress_hits(query: str, hits: list[dict], max_chars: int) -> list[dict]: surplus_budget = max(0, allocated_budget - used_chars) parts = [b["text"] for b in selected] - combined_text = "\n\n".join(parts) if any(p.startswith("```") for p in parts) else " ".join(parts) + combined_text = _join_blocks(parts) hit_copy = hit.copy() hit_copy["entity"] = hit_copy["entity"].copy() diff --git a/tests/test_reranker_and_compressor.py b/tests/test_reranker_and_compressor.py index c2f2f3d3..ef80644e 100644 --- a/tests/test_reranker_and_compressor.py +++ b/tests/test_reranker_and_compressor.py @@ -156,3 +156,97 @@ def test_wrapped_sentence_is_not_cut(): "Katib searches the latest reported `accuracy` metrics for each Trial.", "Check the metrics strategies example.", ] + + +def test_compressor_preserves_heading_and_list_hierarchy_without_code_blocks(): + """Headings and list items must not be space-joined into a single heading line.""" + doc = ( + "### Katib Configuration\n- Set `parallelTrialCount: 3` in the experiment spec.\n- Enable metrics collector.\n" + ) + hits = [{"entity": {"content_text": doc}}] + # Query mentions metrics collector; budget forces compression + compressed = compressor.compress_hits("Katib metrics", hits, max_chars=80) + + assert len(compressed) == 1 + content = compressed[0]["entity"]["content_text"] + + # Heading must be followed by newlines and not consume list items into the header + assert content.startswith("### Katib Configuration\n\n") + assert "- Enable metrics collector." in content + # The heading must not swallow the bullet point on the same line + assert "### Katib Configuration - " not in content + + +def test_compressor_preserves_tables_and_prose_transitions(): + """Tables must retain newline boundaries with adjacent prose and headings.""" + doc = ( + "### Compatibility Matrix\n\n" + "| Kubeflow | Kubernetes |\n" + "| --- | --- |\n" + "| v1.9 | v1.29 |\n\n" + "Review requirements before installation." + ) + hits = [{"entity": {"content_text": doc}}] + compressed = compressor.compress_hits("Kubeflow v1.29 compatibility", hits, max_chars=150) + + assert len(compressed) == 1 + content = compressed[0]["entity"]["content_text"] + + assert "| Kubeflow | Kubernetes |" in content + assert "| v1.9 | v1.29 |" in content + # Table must not be joined inline with space + assert "### Compatibility Matrix |" not in content + assert "| v1.29 | Review" not in content + + +def test_compressor_preserves_multi_row_tables_without_splitting(): + """Multi-row tables must remain intact as single blocks without row-splitting double newlines.""" + doc = ( + "### Compatibility Matrix\n\n" + "| Kubeflow | Kubernetes |\n" + "| --- | --- |\n" + "| v1.8 | v1.28 |\n" + "| v1.9 | v1.29 |\n" + "| v1.10 | v1.30 |\n\n" + "Review requirements before installation." + ) + hits = [{"entity": {"content_text": doc}}] + compressed = compressor.compress_hits("Kubeflow v1.29 compatibility", hits, max_chars=250) + + assert len(compressed) == 1 + content = compressed[0]["entity"]["content_text"] + + expected_table = ( + "| Kubeflow | Kubernetes |\n" + "| --- | --- |\n" + "| v1.8 | v1.28 |\n" + "| v1.9 | v1.29 |\n" + "| v1.10 | v1.30 |" + ) + assert expected_table in content + # Consecutive rows must NOT be separated by double newlines (\n\n) + assert "| v1.8 | v1.28 |\n\n| v1.9 | v1.29 |" not in content + assert "| v1.9 | v1.29 |\n\n| v1.10 | v1.30 |" not in content + + +def test_join_blocks_helper_handles_all_markdown_boundaries(): + parts = [ + "### Section Header", + "- First bullet point", + "- Second bullet point", + "Intro sentence for paragraph.", + "Second sentence in paragraph.", + "```yaml\nkey: value\n```", + "Trailing prose after code.", + ] + joined = compressor._join_blocks(parts) + + expected = ( + "### Section Header\n\n" + "- First bullet point\n" + "- Second bullet point\n\n" + "Intro sentence for paragraph. Second sentence in paragraph.\n\n" + "```yaml\nkey: value\n```\n\n" + "Trailing prose after code." + ) + assert joined == expected