diff --git a/src/semble/cli.py b/src/semble/cli.py index b625a043a..061208cd3 100644 --- a/src/semble/cli.py +++ b/src/semble/cli.py @@ -1,5 +1,6 @@ import argparse import asyncio +import codecs import io import json import logging @@ -172,7 +173,9 @@ def _load_index(paths: list[str], content: list[ContentType]) -> tuple[SembleInd def _print_results(out: dict, output_format: str) -> None: """Print a format_results() payload as JSON or as human-readable text.""" if output_format == "json": - print(json.dumps(out)) + # Legacy encodings may reject or alter non-ASCII characters, so keep their JSON ASCII-only. + ensure_ascii = not codecs.lookup(sys.stdout.encoding or "ascii").name.startswith("utf") + print(json.dumps(out, ensure_ascii=ensure_ascii)) elif "error" in out: print(out["error"]) else: diff --git a/src/semble/mcp.py b/src/semble/mcp.py index 63af97aff..fb3b7ba4b 100644 --- a/src/semble/mcp.py +++ b/src/semble/mcp.py @@ -120,8 +120,8 @@ async def search( return str(exc) results = index.search(query, top_k=top_k, max_snippet_lines=max_snippet_lines) if not results: - return json.dumps({"error": "No results found."}) - return json.dumps(format_results(query, results, max_snippet_lines, index.sources)) + return json.dumps({"error": "No results found."}, ensure_ascii=False) + return json.dumps(format_results(query, results, max_snippet_lines, index.sources), ensure_ascii=False) @server.tool() async def find_related( @@ -166,9 +166,9 @@ async def find_related( ) results = index.find_related(chunk, top_k=top_k, max_snippet_lines=max_snippet_lines) if not results: - return json.dumps({"error": f"No related chunks found for {file_path}:{line}."}) + return json.dumps({"error": f"No related chunks found for {file_path}:{line}."}, ensure_ascii=False) label = f"Chunks related to {file_path}:{line}" - return json.dumps(format_results(label, results, max_snippet_lines, index.sources)) + return json.dumps(format_results(label, results, max_snippet_lines, index.sources), ensure_ascii=False) return server diff --git a/tests/test_cli.py b/tests/test_cli.py index 716610139..1e923a86f 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1,5 +1,6 @@ import asyncio import hashlib +import io import json import signal import sys @@ -10,8 +11,9 @@ import pytest -from semble.cli import _cli_main, _maybe_save_index, _run_clear, main +from semble.cli import _cli_main, _maybe_save_index, _print_results, _run_clear, main from semble.types import ContentType, SearchResult +from semble.utils import format_results from semble.version import __version__ from tests.conftest import make_chunk @@ -156,6 +158,28 @@ def test_main_dispatches_to_cli( assert "query text" in capsys.readouterr().out +@pytest.mark.parametrize( + ("encoding", "expected"), + [ + ("utf-8", "café 咖啡"), + ("cp65001", "café 咖啡"), + ("cp1251", r"caf\u00e9 \u5496\u5561"), + ], +) +def test_print_results_json_respects_stdout_encoding( + encoding: str, expected: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """CLI JSON uses literal Unicode for UTF streams and ASCII escapes otherwise.""" + payload = format_results("cafe", [SearchResult(chunk=make_chunk('return "café 咖啡"', "example.py"), score=0.9)]) + stdout = io.TextIOWrapper(io.BytesIO(), encoding=encoding) + monkeypatch.setattr(sys, "stdout", stdout) + _print_results(payload, "json") + stdout.flush() + text = stdout.buffer.getvalue().decode(encoding) + assert expected in text + assert json.loads(text) == payload + + @pytest.mark.parametrize( ("argv", "expected_stdout", "expect_system_exit"), [ diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 52cbc7b6b..584a89c35 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -297,11 +297,11 @@ async def test_tool_index_failure(cache: _IndexCache, tool: str, args: dict[str, [ pytest.param( "search", - {"query": "bar", "repo": "/some/path"}, + {"query": "cafe", "repo": "/some/path"}, "search", - [SearchResult(chunk=make_chunk("def bar(): pass", "src/bar.py"), score=0.9)], + [SearchResult(chunk=make_chunk('def cafe():\n return "café 咖啡"', "example.py"), score=0.9)], None, - ["bar", "0.9"], + ["example.py", "0.9", "café 咖啡"], id="search_with_results", ), pytest.param( @@ -317,9 +317,9 @@ async def test_tool_index_failure(cache: _IndexCache, tool: str, args: dict[str, "find_related", {"file_path": "src/foo.py", "line": 1, "repo": "/some/path"}, "find_related", - [SearchResult(chunk=make_chunk("class Foo: pass", "src/foo.py"), score=0.8)], + [SearchResult(chunk=make_chunk('def cafe():\n return "café 咖啡"', "example.py"), score=0.8)], [make_chunk("class Foo: pass", "src/foo.py")], - ["src/foo.py:1", "0.8"], + ["example.py", "src/foo.py:1", "0.8", "café 咖啡"], id="find_related_with_results", ), pytest.param(