Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(mcp): name how a session ended instead of leaving it to look like a crash (#2283)
Raghav Chamadiya3586aaf9dedf
diff --git a/packages/cli/src/repowise/cli/commands/mcp_cmd.py b/packages/cli/src/repowise/cli/commands/mcp_cmd.pyindex 900c4268e..0934f48d1 100644--- a/packages/cli/src/repowise/cli/commands/mcp_cmd.py+++ b/packages/cli/src/repowise/cli/commands/mcp_cmd.py@@ -195,8 +195,12 @@ def mcp_command(tools_override: str | None = "all" if all_tools else tools+ # Which of the ways a session can end this one was. Recorded in a finally+ # so a fault is reported as one: leaving the field off for every failed+ # session would make its absence mean either "faulted" or "older build".+ outcome = "server_fault"try:- run_mcp(+ outcome = run_mcp(transport=transport,repo_path=str(repo_path),host=resolved_host,@@ -207,3 +211,7 @@ def mcp_command(except StoreUnavailableError as exc:# One line on stderr and exit 1, not a traceback the host respawns on.raise click.ClickException(str(exc)) from exc+ finally:+ from repowise.cli.platform import telemetry++ telemetry.add_command_outcome(transport=transport, transport_outcome=outcome)diff --git a/packages/server/src/repowise/server/mcp_server/_server.py b/packages/server/src/repowise/server/mcp_server/_server.pyindex de5acebd0..901214294 100644--- a/packages/server/src/repowise/server/mcp_server/_server.py+++ b/packages/server/src/repowise/server/mcp_server/_server.py@@ -7,7 +7,7 @@ import contextlibimport osimport sysfrom contextlib import asynccontextmanager-from typing import Any+from typing import Any, NoReturnfrom mcp.server.fastmcp import FastMCPfrom mcp.server.transport_security import TransportSecuritySettings@@ -27,6 +27,14 @@ from repowise.core.platform.telemetry import GROUP_LEAF_TYPES_ATTRfrom repowise.core.providers.embedding.base import KeylessEmbedder, is_semantic_embedderfrom repowise.core.providers.embedding.caching import CachingEmbedderfrom repowise.server.mcp_server import _state+from repowise.server.mcp_server._transport import (+ CLIENT_CLOSED,+ SERVER_FAULT,+ classify_termination,+ client_closure_types,+ guard_stdout,+ log_outcome,+)_log = __import__("logging").getLogger("repowise.mcp")@@ -827,6 +835,77 @@ def group_leaves(exc: BaseException, *, _depth: int = 0) -> list[BaseException]:return [leaf for child in exc.exceptions for leaf in group_leaves(child, _depth=_depth + 1)]+def _raise_group_leaf(+ group: BaseExceptionGroup, transport: str, leaves: list[BaseException] | None = None+) -> NoReturn:+ """Log every leaf of a failed task group and re-raise the first.++ The first carries the class names of all of them in+ :data:`GROUP_LEAF_TYPES_ATTR`, which is what lets the layer recording the+ outcome say whether one fault or several killed the server without+ reaching back in here to re-derive it.+ """+ found = leaves if leaves is not None else group_leaves(group)+ for leaf in found:+ # A cancelled run is how a client-initiated shutdown looks, not a fault.+ if isinstance(leaf, Exception):+ _log.error("MCP server (%s) stopped: %r", transport, leaf, exc_info=leaf)+ log_outcome(SERVER_FAULT, transport, type(found[0]).__name__)+ first = found[0]+ # Best effort: a leaf class with __slots__ refuses the attribute, and the+ # sibling names are not worth losing the exception over.+ with contextlib.suppress(AttributeError, TypeError):+ setattr(+ first,+ GROUP_LEAF_TYPES_ATTR,+ tuple(sorted({type(leaf).__name__ for leaf in found})),+ )+ raise first from group+++def _warn_on_open_bind(transport: str, host: str) -> None:+ """One line when a network transport is reachable and unauthenticated."""+ if host in ("0.0.0.0", "::") and not os.environ.get("REPOWISE_API_KEY"):+ _log.warning(+ "SECURITY WARNING: MCP server (%s) is binding to %s without "+ "REPOWISE_API_KEY. All tools are unauthenticated and "+ "network-accessible. Set REPOWISE_API_KEY or bind to 127.0.0.1.",+ transport,+ host,+ )+++def _run_network_transport(transport: str, host: str, port: int) -> None:+ mcp.settings.host = host+ mcp.settings.port = port+ _configure_transport_security(host)+ _warn_on_open_bind(transport, host)+ mcp.run(transport=transport)+++def _run_stdio_transport() -> int:+ """Run the stdio transport; returns how many stray stdout writes it saw."""+ # stdout is the JSON-RPC channel on stdio, so every log line written there+ # arrives at the client as a malformed protocol frame. Move the log sinks+ # to stderr before anything can log.+ from repowise.server.mcp_server._stdio_logging import route_logging_to_stderr++ route_logging_to_stderr()+ # stdio servers are spawned per-session by the MCP client; when the client+ # dies abnormally the stdio loop doesn't exit (and Windows never kills+ # children), leaking servers that hold wiki.db handles. The watchdog exits+ # this process once the client is gone.+ from repowise.server.mcp_server._watchdog import start_parent_watchdog++ start_parent_watchdog()+ # The SDK writes frames through stdout's buffer, so anything arriving at+ # the text layer is a stray print. The guard moves it to stderr, counts it,+ # and the count is what names the session protocol_corrupted.+ with guard_stdout() as guard:+ mcp.run(transport="stdio")+ return guard.writes++def run_mcp(transport: str = "stdio",repo_path: str | None = None,@@ -834,21 +913,29 @@ def run_mcp(port: int = 7338,tools: str | list[str] | None = None,workspace_mode: bool = True,-) -> None:- """Run the MCP server with the specified transport.+) -> str:+ """Run the MCP server with the specified transport, and name how it ended.``tools`` overrides which tools are advertised (see:func:`repowise.server.mcp_server._tool_selection.apply_tool_selection`);when omitted, the ``mcp.tools`` config block is honoured.+ Returns one of the outcomes in :mod:`._transport`. A client closing a+ transport it owns is one of them and returns normally: it is how a stdio+ session ends, and raising there made an ordinary hang-up look like the+ crash a host should respawn on. Only a genuine fault still raises.+A task-group failure is unwrapped over the whole body, not around ``mcp.run``alone: surface construction and transport security run outside that call, and- a group raised by either escaped with its wrapper class intact. Every leaf is- logged, and the first is re-raised carrying the class names of all of them in- :data:`GROUP_LEAF_TYPES_ATTR`. That is what lets the layer recording the- outcome say whether one fault or several killed the server, without reaching- back in here to re-derive it.+ a group raised by either escaped with its wrapper class intact. See+ :func:`_raise_group_leaf` for what travels out of one."""+ stray_writes = 0+ # Startup and the transport run are caught separately. Both unwrap a task+ # group, but only the run may end in a closure: a corrupt index artifact+ # read during surface construction raises EOFError, which is a hang-up+ # class, and classifying it as one would have reported a broken index as a+ # clean session and exited 0.try:_state._repo_path = repo_path_state._force_single_repo = not workspace_mode@@ -857,59 +944,29 @@ def run_mcp(ensure_full_surface()apply_tool_selection(mcp, repo_path=repo_path, override=tools)+ except BaseExceptionGroup as group:+ _raise_group_leaf(group, transport)- if transport == "sse":- mcp.settings.host = host- mcp.settings.port = port- _configure_transport_security(host)- if host in ("0.0.0.0", "::") and not os.environ.get("REPOWISE_API_KEY"):- _log.warning(- "SECURITY WARNING: MCP server (sse) is binding to %s without "- "REPOWISE_API_KEY. All tools are unauthenticated and "- "network-accessible. Set REPOWISE_API_KEY or bind to 127.0.0.1.",- host,- )- mcp.run(transport="sse")- elif transport == "streamable-http":- mcp.settings.host = host- mcp.settings.port = port- _configure_transport_security(host)- if host in ("0.0.0.0", "::") and not os.environ.get("REPOWISE_API_KEY"):- _log.warning(- "SECURITY WARNING: MCP server (streamable-http) is binding to %s without "- "REPOWISE_API_KEY. All tools are unauthenticated and "- "network-accessible. Set REPOWISE_API_KEY or bind to 127.0.0.1.",- host,- )- mcp.run(transport="streamable-http")+ try:+ if transport in ("sse", "streamable-http"):+ _run_network_transport(transport, host, port)else:- # stdout is the JSON-RPC channel on stdio, so every log line written- # there arrives at the client as a malformed protocol frame. Move the- # log sinks to stderr before anything can log.- from repowise.server.mcp_server._stdio_logging import route_logging_to_stderr-- route_logging_to_stderr()- # stdio servers are spawned per-session by the MCP client; when the- # client dies abnormally the stdio loop doesn't exit (and Windows- # never kills children), leaking servers that hold wiki.db handles.- # The watchdog exits this process once the client is gone.- from repowise.server.mcp_server._watchdog import start_parent_watchdog-- start_parent_watchdog()- mcp.run(transport="stdio")+ stray_writes = _run_stdio_transport()except BaseExceptionGroup as group:leaves = group_leaves(group)- for leaf in leaves:- # A cancelled run is how a client-initiated shutdown looks, not a fault.- if isinstance(leaf, Exception):- _log.error("MCP server (%s) stopped: %r", transport, leaf, exc_info=leaf)- first = leaves[0]- # Best effort: a leaf class with __slots__ refuses the attribute, and the- # sibling names are not worth losing the exception over.- with contextlib.suppress(AttributeError, TypeError):- setattr(- first,- GROUP_LEAF_TYPES_ATTR,- tuple(sorted({type(leaf).__name__ for leaf in leaves})),- )- raise first from group+ if classify_termination(transport, group, leaves=group_leaves) == CLIENT_CLOSED:+ log_outcome(CLIENT_CLOSED, transport, type(leaves[0]).__name__)+ return CLIENT_CLOSED+ _raise_group_leaf(group, transport, leaves=leaves)+ except client_closure_types() as exc:+ # An ungrouped hang-up: the pipe broke, or the run was cancelled under+ # us. The clause names those classes rather than catching broadly, so+ # an interrupt and a server fault are never swallowed here.+ if transport != "stdio":+ raise+ log_outcome(CLIENT_CLOSED, transport, type(exc).__name__)+ return CLIENT_CLOSED++ outcome = classify_termination(transport, None, stray_writes=stray_writes)+ log_outcome(outcome, transport)+ return outcomediff --git a/packages/server/src/repowise/server/mcp_server/_transport.py b/packages/server/src/repowise/server/mcp_server/_transport.pynew file mode 100644index 000000000..c391a871f--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/_transport.py@@ -0,0 +1,254 @@+"""How an MCP session ended, named rather than left to look like success.++A stdio server is spawned per session by the client that owns the pipe, and+the ordinary end of one is that client hanging up. It arrives as EOF, a broken+pipe, or a cancelled task, and until this module existed all three were+indistinguishable from a server that had crashed: the hang-up escaped as a+traceback the host respawns on, and a clean end produced no line at all. The+outcomes here are what a probe needs to tell a closure the client chose from a+fault this server is answerable for.++Nothing here reconnects anything. A stdio transport belongs to the client that+spawned the process, so a server that "reconnected" would be a second server+writing down a pipe nobody reads. Retry-once belongs in a client adapter, and+only where Repowise owns that adapter.+"""++from __future__ import annotations++import asyncio+import contextlib+import io+import logging+import sys+from collections.abc import Iterator+from typing import Any, Protocol++_log = logging.getLogger(__name__)++#: The client closed a transport it owns: stdin at EOF, a pipe broken from the+#: far end, or the run cancelled under us. Not a fault, and not silence either.+CLIENT_CLOSED = "client_closed"++#: The watchdog saw the client process itself die, so nothing will ever read+#: what we write. Distinct from CLIENT_CLOSED: nobody hung up, the far end+#: stopped existing.+CLIENT_GONE = "client_gone"++#: Something in this process wrote to stdout beside the JSON-RPC frames. The+#: guard below moves it to stderr, so this names a session whose protocol+#: channel was written to, not one whose frames were definitely mangled.+PROTOCOL_CORRUPTED = "protocol_corrupted"++#: A network transport's own run returned. Nobody hung up on us; we stopped.+SERVER_STOPPED = "server_stopped"++#: Anything else that ended the run. The only outcome that is this server's+#: fault, and the only one that exits non-zero.+SERVER_FAULT = "server_fault"+++def client_closure_types() -> tuple[type[BaseException], ...]:+ """Exception classes that mean the far end of the transport went away.++ Public because an ``except`` clause naming exactly these is how the caller+ catches a hang-up without also catching an interrupt or a fault.++ Resolved per call rather than at import: anyio's cancelled class is+ backend-dependent, and importing it at module scope would pull anyio into+ every process that merely imports the server package.++ Deliberately narrow. ``OSError`` itself is not here — "address in use" is a+ server fault and shares that base class with a broken pipe.+ """+ types: list[type[BaseException]] = [+ BrokenPipeError,+ ConnectionResetError,+ EOFError,+ # A cancelled run is how a client-initiated shutdown arrives. The+ # asyncio class is named outright because the lookup below only works+ # from inside a running loop, and by the time anything classifies a+ # termination the loop has already unwound.+ asyncio.CancelledError,+ ]+ with contextlib.suppress(Exception):+ import anyio++ types += [+ anyio.EndOfStream,+ anyio.ClosedResourceError,+ anyio.BrokenResourceError,+ ]+ # Separate from the block above on purpose: outside an event loop this+ # raises, and sharing one suppress silently discarded every class before+ # it.+ with contextlib.suppress(Exception):+ import anyio++ types.append(anyio.get_cancelled_exc_class())+ return tuple(types)+++def is_client_closure(exc: BaseException) -> bool:+ """Whether *exc* is the far end hanging up rather than a fault here."""+ return isinstance(exc, client_closure_types())+++class _LeafReader(Protocol):+ def __call__(self, exc: BaseException) -> list[BaseException]: ...+++def classify_termination(+ transport: str,+ error: BaseException | None,+ *,+ stray_writes: int = 0,+ leaves: _LeafReader | None = None,+) -> str:+ """Name the outcome of one session.++ *error* is what ended the run, or ``None`` when it returned on its own.+ *leaves* unwraps a task group; a group counts as a closure only when every+ leaf does, because one genuine fault beside a hang-up is still a fault.++ Only stdio can end in a closure. A network server does not hold a pipe+ some particular client owns, so a reset socket there is one connection+ failing inside a server that is still running, never the end of its life.++ ``stray_writes`` outranks a clean stdio close on purpose: how a session+ ended matters less than the discovery that something was writing down the+ protocol channel while it ran, and that is the outcome worth acting on.+ Only a clean run reports it — a session that ended some other way reports+ that, and the guard's own warning still carries the count.+ """+ if error is not None:+ if transport != "stdio":+ return SERVER_FAULT+ found = leaves(error) if leaves is not None else [error]+ return CLIENT_CLOSED if all(map(is_client_closure, found)) else SERVER_FAULT+ if stray_writes:+ return PROTOCOL_CORRUPTED+ # stdin reaching EOF is how a stdio client says the session is over; it is+ # the only way that run returns without an error.+ return CLIENT_CLOSED if transport == "stdio" else SERVER_STOPPED+++def _ensure_outcome_sink() -> None:+ """Give this module's logger a stderr handler, once.++ ``repowise mcp`` configures no logging, so a record with no handler falls+ through to logging's last-resort sink — which is WARNING-only. Measured:+ the fault line printed and ``client_closed`` printed nothing, which left+ the clean outcomes exactly as silent as before.++ The alternatives are worse. Raising every outcome to WARNING says a+ client hanging up is a problem, and turning on INFO for the whole server+ puts a session's worth of chatter on the same stderr a host is reading.+ One line per process, from the one logger that must always be heard, gets+ its own sink instead. ``propagate`` stays off so a host that does+ configure logging gets it once, not twice.+ """+ if _log.handlers:+ return+ handler = logging.StreamHandler(sys.stderr)+ handler.setFormatter(logging.Formatter("%(message)s"))+ _log.addHandler(handler)+ _log.setLevel(logging.INFO)+ _log.propagate = False+++def log_outcome(outcome: str, transport: str, detail: str = "") -> None:+ """Emit the one line that says how a session ended, on stderr.++ Every outcome is logged, including the clean ones. A stdio session that+ ends without a word is the case this exists to remove: it reads as a+ server that answered nothing, which is also what a crash looks like.+ """+ _ensure_outcome_sink()+ tail = f" ({detail})" if detail else ""+ level = logging.ERROR if outcome == SERVER_FAULT else logging.INFO+ if outcome == PROTOCOL_CORRUPTED:+ level = logging.WARNING+ _log.log(level, "MCP session (%s) ended: %s%s", transport, outcome, tail)+++class _StrayStdout(io.TextIOBase):+ """Stands in for ``sys.stdout`` while a stdio session runs.++ The MCP SDK re-wraps ``sys.stdout.buffer`` in its own text layer and writes+ every frame through that, so by the time a write reaches *this* object it+ is by definition not the protocol: it is a ``print`` that would interleave+ with the frames and mangle whichever one it landed inside. Forward it to+ stderr, where it is merely noise, and count it.++ ``buffer`` is the real one, which is what keeps the SDK writing frames to+ the client rather than into stderr with everything else.++ :class:`io.TextIOBase` supplies ``writelines`` (which routes through the+ override below, so the count stays right), ``closed`` and the no-op close.+ It does not supply ``writable``, which defaults to False on ``IOBase`` and+ would tell a caller that checks before writing that stdout is read-only.++ ``fileno`` is deliberately the real descriptor, so anything writing+ straight to fd 1 bypasses this and still corrupts the channel. Nothing in+ this process does, and a guard that lied about the descriptor would break+ subprocesses that inherit it.+ """++ def __init__(self, real: Any, stderr: Any) -> None:+ super().__init__()+ self._real = real+ self._stderr = stderr+ self.writes = 0++ @property+ def buffer(self) -> Any:+ return self._real.buffer++ @property+ def encoding(self) -> str:+ return getattr(self._real, "encoding", "utf-8")++ def write(self, data: str) -> int:+ if data:+ self.writes += 1+ return self._stderr.write(data)++ def flush(self) -> None:+ with contextlib.suppress(ValueError):+ self._stderr.flush()++ def fileno(self) -> int:+ return self._real.fileno()++ def isatty(self) -> bool:+ return False++ def writable(self) -> bool:+ return True++ @property+ def name(self) -> str:+ return getattr(self._real, "name", "<stdout>")+++def guard_stdout() -> Iterator[_StrayStdout]:+ """Keep stray ``print`` output off the JSON-RPC channel for the duration.++ Restores the real stream on the way out, including when the body raises,+ so a fault does not leave the process with a swapped stdout.+ """+ real = sys.stdout+ guard = _StrayStdout(real, sys.stderr)+ sys.stdout = guard # type: ignore[assignment]+ try:+ yield guard+ finally:+ sys.stdout = real+ if guard.writes:+ _log.warning(+ "MCP stdio: %d write(s) to stdout were moved to stderr; stdout "+ "carries JSON-RPC frames and nothing else may write there.",+ guard.writes,+ )diff --git a/packages/server/src/repowise/server/mcp_server/_watchdog.py b/packages/server/src/repowise/server/mcp_server/_watchdog.pyindex 11f995513..b10b9a6c9 100644--- a/packages/server/src/repowise/server/mcp_server/_watchdog.py+++ b/packages/server/src/repowise/server/mcp_server/_watchdog.py@@ -31,6 +31,7 @@ import sysimport threadingfrom repowise.core.procutils import ProcInfo, ancestor_chain, pid_alive, process_create_token+from repowise.server.mcp_server._transport import CLIENT_GONE, log_outcome_log = logging.getLogger(__name__)@@ -124,10 +125,13 @@ def start_parent_watchdog() -> threading.Thread | None:try:for info in watch:if _ancestor_died(info):- _log.info(- "MCP watchdog: ancestor %s(%d) is gone — exiting",- info.name or "?",- info.pid,+ # Named in the same vocabulary as every other way a+ # session ends, so one grep over a host's stderr tells+ # a dead client from a dead server.+ log_outcome(+ CLIENT_GONE,+ "stdio",+ f"ancestor {info.name or '?'}({info.pid}) is gone",)# os._exit skips interpreter shutdown, which includes# flushing, so the line above can sit in a buffer anddiff --git a/tests/unit/cli/test_mcp_transport.py b/tests/unit/cli/test_mcp_transport.pyindex d8426de2e..baa2207d3 100644--- a/tests/unit/cli/test_mcp_transport.py+++ b/tests/unit/cli/test_mcp_transport.py@@ -483,3 +483,43 @@ def test_an_interrupt_is_not_reported_as_a_crash(monkeypatch, tmp_path: Path) ->CliRunner().invoke(cli, ["mcp", str(tmp_path)])assert "error_leaves" not in recorded+++def test_the_way_a_session_ended_reaches_the_invocation_outcome(+ monkeypatch, tmp_path: Path+) -> None:+ """A clean end is recorded, not inferred from the absence of an error."""+ from repowise.cli.platform import telemetry++ (tmp_path / ".repowise").mkdir()+ recorded: dict[str, object] = {}+ monkeypatch.setattr(telemetry, "add_command_outcome", recorded.update)+ monkeypatch.setattr(+ "repowise.server.mcp_server.run_mcp", lambda **_kw: "client_closed"+ )++ result = CliRunner().invoke(cli, ["mcp", str(tmp_path)])++ assert result.exit_code == 0+ assert recorded["transport_outcome"] == "client_closed"+ assert recorded["transport"] == "stdio"+++def test_a_client_hanging_up_is_not_an_error_exit(monkeypatch, tmp_path: Path) -> None:+ """A broken pipe used to leave a traceback the host respawns on."""+ from repowise.server.mcp_server import _server++ (tmp_path / ".repowise").mkdir()+ monkeypatch.setattr(+ "repowise.server.mcp_server._watchdog.start_parent_watchdog", lambda: None+ )+ monkeypatch.setattr(+ _server.mcp,+ "run",+ lambda **_kw: (_ for _ in ()).throw(BrokenPipeError("hung up")),+ )++ result = CliRunner().invoke(cli, ["mcp", str(tmp_path)])++ assert result.exit_code == 0+ assert "Traceback" not in result.outputdiff --git a/tests/unit/server/mcp/test_transport_lifecycle.py b/tests/unit/server/mcp/test_transport_lifecycle.pynew file mode 100644index 000000000..ac2dc6c23--- /dev/null+++ b/tests/unit/server/mcp/test_transport_lifecycle.py@@ -0,0 +1,354 @@+"""A session that ends must say which way it ended.++The four ways are not interchangeable: a client closing a transport it owns is+an ordinary end, a client process dying is a different one, stray stdout is a+protocol hazard, and only the fourth is this server's fault. Before these,+every one of them was either a traceback the host respawns on or no line at+all.+"""++from __future__ import annotations++import logging+import sys++import anyio+import pytest++from repowise.server.mcp_server import _server, _transport+from repowise.server.mcp_server._transport import (+ CLIENT_CLOSED,+ CLIENT_GONE,+ PROTOCOL_CORRUPTED,+ SERVER_FAULT,+ SERVER_STOPPED,+ classify_termination,+ guard_stdout,+ is_client_closure,+ log_outcome,+)+++def no_watchdog(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ "repowise.server.mcp_server._watchdog.start_parent_watchdog", lambda: None+ )+++ "exc",+ [+ BrokenPipeError("the client hung up"),+ ConnectionResetError("reset by peer"),+ EOFError("stdin at EOF"),+ anyio.EndOfStream(),+ anyio.ClosedResourceError(),+ anyio.BrokenResourceError(),+ ],+)+def test_a_hang_up_is_not_a_fault(exc: BaseException) -> None:+ assert is_client_closure(exc) is True+++ "exc",+ [+ OSError("address already in use"),+ PermissionError("wiki.db is locked"),+ RuntimeError("bad state"),+ ModuleNotFoundError("no mcp"),+ ],+)+def test_a_fault_is_not_a_hang_up(exc: BaseException) -> None:+ """OSError shares a base class with a broken pipe and must not match."""+ assert is_client_closure(exc) is False+++def test_a_clean_stdio_return_is_the_client_closing_the_transport() -> None:+ assert classify_termination("stdio", None) == CLIENT_CLOSED+++def test_a_clean_network_return_is_this_server_stopping() -> None:+ """Nobody hung up on an HTTP server that returned; it shut down."""+ assert classify_termination("streamable-http", None) == SERVER_STOPPED+++def test_stray_stdout_names_itself() -> None:+ assert classify_termination("stdio", None, stray_writes=2) == PROTOCOL_CORRUPTED+++def test_a_group_of_hang_ups_is_still_a_hang_up() -> None:+ group = ExceptionGroup("closed", [BrokenPipeError(), anyio.ClosedResourceError()])++ assert (+ classify_termination("stdio", group, leaves=_server.group_leaves)+ == CLIENT_CLOSED+ )+++def test_one_real_fault_beside_a_hang_up_is_a_fault() -> None:+ """A crash that also broke the pipe is a crash, not a clean close."""+ group = ExceptionGroup("mixed", [BrokenPipeError(), PermissionError("locked")])++ assert (+ classify_termination("stdio", group, leaves=_server.group_leaves)+ == SERVER_FAULT+ )+++def test_a_clean_outcome_reaches_stderr_with_no_logging_configured(capsys) -> None:+ """The regression a level-forcing test hid.++ ``repowise mcp`` configures no logging, so an INFO record fell through to+ logging's last-resort sink, which is WARNING-only: the fault line printed+ and the clean ones printed nothing at all. Asserting at the default level+ is the whole point — do not add ``caplog.at_level`` here.+ """+ _transport._log.handlers.clear()+ _transport._log.propagate = True+ try:+ log_outcome(CLIENT_CLOSED, "stdio")+ finally:+ _transport._log.handlers.clear()+ _transport._log.propagate = True++ assert "client_closed" in capsys.readouterr().err+++def test_the_sink_is_attached_once(capsys) -> None:+ """One line per process; a handler per call would multiply it."""+ _transport._log.handlers.clear()+ _transport._log.propagate = True+ try:+ log_outcome(CLIENT_CLOSED, "stdio")+ log_outcome(SERVER_STOPPED, "sse")+ handlers = len(_transport._log.handlers)+ finally:+ _transport._log.handlers.clear()+ _transport._log.propagate = True++ assert handlers == 1+ assert capsys.readouterr().err.count("MCP session") == 2+++def test_a_fault_is_logged_at_error_and_a_close_is_not() -> None:+ """A client hanging up is not a problem; only a fault is.++ Read off this module's own logger rather than caplog: the sink sets+ ``propagate = False``, so records never reach the root handler caplog+ attaches to. That is deliberate — see :func:`_ensure_outcome_sink`.+ """+ records: list[logging.LogRecord] = []++ class _Capture(logging.Handler):+ def emit(self, record: logging.LogRecord) -> None:+ records.append(record)++ _transport._log.handlers.clear()+ _transport._log.addHandler(_Capture())+ _transport._log.setLevel(logging.INFO)+ try:+ log_outcome(CLIENT_CLOSED, "stdio")+ log_outcome(SERVER_FAULT, "stdio", "PermissionError")+ finally:+ _transport._log.handlers.clear()+ _transport._log.propagate = True++ levels = {+ record.getMessage().split("ended: ")[1].split()[0]: record.levelno+ for record in records+ }+ assert levels["client_closed"] == logging.INFO+ assert levels["server_fault"] == logging.ERROR+++# --- the stdout guard ------------------------------------------------------+++def test_a_stray_print_goes_to_stderr_and_is_counted(capsys) -> None:+ """stdout carries JSON-RPC frames; a print would land inside one."""+ with guard_stdout() as guard:+ print("this would have mangled a frame")++ captured = capsys.readouterr()+ assert "mangled a frame" not in captured.out+ assert "mangled a frame" in captured.err+ assert guard.writes >= 1+++def test_the_protocol_channel_itself_is_untouched() -> None:+ """The SDK writes frames through sys.stdout.buffer, which must be real."""+ real = sys.stdout+ with guard_stdout() as guard:+ assert sys.stdout is guard+ assert guard.buffer is real.buffer+ assert sys.stdout is real+++def test_the_real_stream_comes_back_after_a_failure() -> None:+ real = sys.stdout+ with pytest.raises(RuntimeError), guard_stdout():+ raise RuntimeError("boom")++ assert sys.stdout is real+++# --- run_mcp ---------------------------------------------------------------+++def test_a_closed_transport_returns_instead_of_raising(+ monkeypatch: pytest.MonkeyPatch, no_watchdog: None+) -> None:+ """The regression: an ordinary hang-up escaped as a traceback."""+ def hang_up(**_kw):+ raise BrokenPipeError("the client hung up")++ monkeypatch.setattr(_server.mcp, "run", hang_up)++ assert _server.run_mcp(transport="stdio") == CLIENT_CLOSED+++def test_a_grouped_closed_transport_returns_too(+ monkeypatch: pytest.MonkeyPatch, no_watchdog: None+) -> None:+ def hang_up(**_kw):+ raise ExceptionGroup("closed", [anyio.ClosedResourceError()])++ monkeypatch.setattr(_server.mcp, "run", hang_up)++ assert _server.run_mcp(transport="stdio") == CLIENT_CLOSED+++def test_a_server_fault_still_raises(+ monkeypatch: pytest.MonkeyPatch, no_watchdog: None+) -> None:+ """Classification must not turn a real crash into a quiet exit."""+ def boom(**_kw):+ raise ExceptionGroup("task failed", [PermissionError("wiki.db is locked")])++ monkeypatch.setattr(_server.mcp, "run", boom)++ with pytest.raises(PermissionError):+ _server.run_mcp(transport="stdio")+++def test_a_clean_stdio_session_names_its_ending(+ monkeypatch: pytest.MonkeyPatch, no_watchdog: None+) -> None:+ monkeypatch.setattr(_server.mcp, "run", lambda **_kw: None)++ assert _server.run_mcp(transport="stdio") == CLIENT_CLOSED+++def test_a_session_that_printed_to_stdout_says_so(+ monkeypatch: pytest.MonkeyPatch, no_watchdog: None+) -> None:+ monkeypatch.setattr(_server.mcp, "run", lambda **_kw: print("stray"))++ assert _server.run_mcp(transport="stdio") == PROTOCOL_CORRUPTED+++def test_a_network_transport_reports_its_own_shutdown(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(_server.mcp, "run", lambda **_kw: None)++ assert _server.run_mcp(transport="streamable-http") == SERVER_STOPPED+++def test_a_network_transport_never_reports_a_closure() -> None:+ """An HTTP server holds no pipe a particular client owns."""+ assert classify_termination("streamable-http", BrokenPipeError()) == SERVER_FAULT+++def test_a_startup_fault_is_never_read_as_a_clean_close(+ monkeypatch: pytest.MonkeyPatch, no_watchdog: None+) -> None:+ """A truncated index artifact raises EOFError, which is a hang-up class.++ Classifying it as one reported a broken index as an ordinary session and+ exited 0, which is the failure this whole module exists to prevent.+ """+ def boom():+ raise EOFError("compressed file ended before the end-of-stream marker")++ monkeypatch.setattr("repowise.server.mcp_server.ensure_full_surface", boom)++ with pytest.raises(EOFError):+ _server.run_mcp(transport="stdio")+++def test_a_grouped_startup_fault_is_not_a_closure_either(+ monkeypatch: pytest.MonkeyPatch, no_watchdog: None+) -> None:+ def boom():+ raise ExceptionGroup("startup", [EOFError("truncated artifact")])++ monkeypatch.setattr("repowise.server.mcp_server.ensure_full_surface", boom)++ with pytest.raises(EOFError):+ _server.run_mcp(transport="stdio")+++def test_an_interrupt_is_not_a_closure(+ monkeypatch: pytest.MonkeyPatch, no_watchdog: None+) -> None:+ """Ctrl-C ends a server; it is not the client hanging up."""+ monkeypatch.setattr(+ _server.mcp, "run", lambda **_kw: (_ for _ in ()).throw(KeyboardInterrupt())+ )++ with pytest.raises(KeyboardInterrupt):+ _server.run_mcp(transport="stdio")+++def test_an_unopenable_store_is_not_a_closure(+ monkeypatch: pytest.MonkeyPatch, no_watchdog: None+) -> None:+ monkeypatch.setattr(+ _server.mcp,+ "run",+ lambda **_kw: (_ for _ in ()).throw(_server.StoreUnavailableError("locked")),+ )++ with pytest.raises(_server.StoreUnavailableError):+ _server.run_mcp(transport="stdio")+++def test_the_watchdog_speaks_the_shared_vocabulary(capsys, monkeypatch) -> None:+ """A dead client and a dead server must be one grep apart."""+ from repowise.server.mcp_server import _watchdog++ _transport._log.handlers.clear()+ _transport._log.propagate = True+ try:+ _watchdog.log_outcome(CLIENT_GONE, "stdio", "ancestor code(123) is gone")+ finally:+ _transport._log.handlers.clear()+ _transport._log.propagate = True++ err = capsys.readouterr().err+ assert "client_gone" in err+ assert "code(123)" in err+++def test_a_session_that_printed_and_then_hung_up_reports_the_hang_up(+ monkeypatch: pytest.MonkeyPatch, no_watchdog: None+) -> None:+ """How it ended outranks what happened during it; the guard still warns."""+ def print_then_hang_up(**_kw):+ print("stray")+ raise BrokenPipeError("hung up")++ monkeypatch.setattr(_server.mcp, "run", print_then_hang_up)++ assert _server.run_mcp(transport="stdio") == CLIENT_CLOSED+++def test_the_guard_says_stdout_is_writable() -> None:+ """io.TextIOBase defaults writable() to False, which would read as a+ read-only stdout to anything that checks before writing."""+ with guard_stdout() as guard:+ assert guard.writable() is True+ assert sys.stdout.writable() is True