diff --git a/plugins/cidx_git_backend/cidx_git_backend/__init__.py b/plugins/cidx_git_backend/cidx_git_backend/__init__.py new file mode 100644 index 000000000..324e1bfcd --- /dev/null +++ b/plugins/cidx_git_backend/cidx_git_backend/__init__.py @@ -0,0 +1,1100 @@ +""" +Delegate cidx's internal git operations to the the git service spoke (). + +cidx's ``GitBackend`` seam routes every internal git call through one +object. Its default ``LocalGitBackend`` shells out to git in-process. In the EKS +deployment cidx must do NO git itself — git (like cloning) belongs in a spoke that +owns the credentials and the shared volume. This plugin supplies a ``GitBackend`` +that forwards each op to **the git service**, exactly as the clone seam forwards cloning to +the content service. + +Addressing is BY PATH, matching the clone seam: the git service's tools accept a +``cow_path`` that runs the op directly on that path on the shared +FlexVol — cidx passes its own ``repo_path``, no workspace_id it never registered. + +Transport: JSON-RPC ``tools/call`` over ``POST {CIDX_GIT_MCP_URL}/v1/git/mcp``, +stdlib ``urllib`` only (no third-party deps in the cidx image). the git service returns a +structured JSON result; a few GitBackend methods hand cidx RAW git output it parses +(``status_porcelain``, ``remote_list``, ``diff_name_only``, ``list_branches``, +``show_ref``), so those are reconstructed faithfully here. + +``run`` (cidx's git tools: blame, log, show, ...) uses the git service's raw endpoint, +``POST {CIDX_GIT_MCP_URL}/v1/git/exec/raw``: git's stdout as raw bytes, then a +NUL, then a JSON trailer proving the output is whole. A the git service without it (404) +or without its shared secret (503) gets MCP ``git_exec`` instead. No answer is +ever accepted in part: a ``_pagination`` page from ANY tool, a truncated raw +stream and a byte tool's ``OUTPUT_TOO_LARGE`` all raise. + +Large-but-legitimate output: a read whose MCP tool answers with a page or +``OUTPUT_TOO_LARGE`` (``ls_files``, ``diff_name_only``, ``list_branches``, +``status_porcelain``, ``log_raw``, ``for_each_ref`` on a big repo) re-runs the +same git command through the raw endpoint, whose whole output -- or an error +-- is the answer. ``ls_remote`` reads only ``reachable``; a page that cut +nothing but the ``refs`` list (a remote with many refs) still answers it whole. + +Configuration (env) +------------------- +CIDX_GIT_MCP_URL the git service base URL. + Default: http://localhost:3000 +CIDX_GIT_MCP_TOKEN Bearer token. The raw exec endpoint requires it to equal + the git service's GIT_MCP_SHARED_SECRET (401 otherwise). +CIDX_GIT_MCP_TIMEOUT Per-request HTTP timeout seconds (default: 120). + +Enable with the server config ``git_backend='delegated'`` (installing the package +registers it on the ``code_indexer.git_backend`` entry point; +``CIDX_GIT_BACKEND=cidx_git_backend:make_git_backend`` is an equivalent override). +""" + +from __future__ import annotations + +import base64 +import io +import json +import math +import os +import subprocess +import threading +import time +import urllib.error +import urllib.request +from typing import Any, Dict, List, Optional, Sequence, Tuple + + +import socket + + +def _is_timeout(exc: BaseException) -> bool: + """True when *exc* is a transport-level timeout (socket or urllib).""" + if isinstance(exc, socket.timeout): + return True + if isinstance(exc, TimeoutError): + return True + if isinstance(exc, urllib.error.URLError) and isinstance( + exc.reason, (socket.timeout, TimeoutError) + ): + return True + if isinstance(exc, urllib.error.URLError) and "timed out" in str(exc.reason): + return True + return False + + +def _decode_like_text_mode(raw: bytes) -> str: + """*raw* git stdout exactly as a local ``subprocess.run(text=True)`` (cidx's + ``run_git_command``) returns it: the locale encoding, strict errors (an + undecodable byte raises ``UnicodeDecodeError`` as the local run does), and + universal newlines (``\\r\\n`` / ``\\r`` -> ``\\n``).""" + with io.TextIOWrapper(io.BytesIO(raw), encoding=None) as text: + return text.read() + + +_DEFAULT_URL = "http://localhost:3000" + +#: Items the git service accepts in one git_diff_commits / git_show_objects call. A +#: larger request is split into calls of this size -- still a batch per call. +_MAX_HISTORY_BATCH = 256 + + +class GitMcpBackendError(subprocess.CalledProcessError): + """A the git service call failed (transport, JSON-RPC, or tool error). + + Subclasses ``subprocess.CalledProcessError`` — NOT a bare ``RuntimeError`` — + because the ``GitBackend`` contract (``storage/shared/git_backend.py``) + guarantees that a failed op raises ``CalledProcessError`` "whose ``stderr`` + callers already use", and ``LocalGitBackend`` honours that via ``check=True``. + ~30 cidx call sites do ``except subprocess.CalledProcessError`` and read + ``e.stderr`` to drive recovery (remote-already-exists fallback, divergent-branch + auto-recovery, fetch-error classification). A ``RuntimeError`` would miss every + one of those handlers and escape uncaught, so the delegated backend must raise + the same type — with ``stderr`` populated from the git service's error text so the + substring checks (`"already exists"`, …) still fire. + """ + + def __init__( + self, + message: str, + *, + stderr: Optional[str] = None, + returncode: int = 1, + cmd: str = "the git service", + ) -> None: + super().__init__( + returncode, + cmd, + output=None, + stderr=stderr if stderr is not None else message, + ) + self.message = message + + def __str__(self) -> str: + return self.message + + +class GitMcpTimeoutError(GitMcpBackendError): + """A the git service call failed because of a transport or git-level timeout.""" + + +class GitMcpPaginatedResultError(GitMcpBackendError): + """A the git service tool result carried ``_pagination``: it is a PAGE, not the result. + + the git service's shared MCP response layer pages any result over its size budget + and marks it with a ``_pagination`` key. For ``git_exec`` that cuts + ``stdout_b64`` mid-stream -- what arrives is a prefix of git's output (and + usually not even valid base64); for a structured tool it is a truncated + list. No caller here pages, and accepting a prefix silently would report a + short history, a partial blame or a missing file as the whole answer. So + the marker is a hard error for EVERY tool, wherever it appears. + """ + + +#: The key the git service's response layer adds to a result it truncated into pages. +_PAGINATION_KEY = "_pagination" + +#: the git service's raw exec endpoint: ``git_exec``'s request, answered with git's +#: stdout as raw bytes, one NUL, then a JSON trailer -- never paged, never +#: base64, never truncated silently (see :meth:`GitMcpBackend._exec_raw`). +_RAW_EXEC_ROUTE = "/v1/git/exec/raw" +#: The trailer's separator from stdout. The split is at the LAST one: stdout +#: may contain NULs (``-z`` output), the JSON trailer never does. +_RAW_TRAILER_SEPARATOR = b"\x00" +#: How long a the git service without the raw endpoint (404) or without its shared +#: secret (503) is not asked again before falling back to MCP ``git_exec``. +_RAW_RETRY_SECONDS = 300.0 +#: The ``code`` a byte tool's ``isError`` result carries when git's output is +#: over the git service's budget (it refuses rather than truncating). +_OUTPUT_TOO_LARGE = "OUTPUT_TOO_LARGE" + + +class GitMcpOutputTooLargeError(GitMcpBackendError): + """git's output exceeded the git service's budget and was refused, not truncated. + + Raised for a byte tool's ``OUTPUT_TOO_LARGE`` error and for a raw exec + whose trailer says ``truncated``: a prefix of the output is never handed + on as all of it. + """ + + +class _RawExecUnavailable(Exception): + """The raw exec endpoint cannot serve this the git service: use MCP ``git_exec``.""" + + +#: What a too-big MCP answer raises: a page (a structured tool's list cut +#: into pages) or a byte tool's refusal. A read that can be large legitimately +#: answers either by re-running its git command through the raw endpoint. +_OVER_MCP_CEILING = (GitMcpPaginatedResultError, GitMcpOutputTooLargeError) + + +def _page_marker(text: str) -> Optional[Dict[str, Any]]: + """The ``_pagination`` block when one text chunk of a tool result is a + the git service page (an empty dict when the block is not an object), else None.""" + if _PAGINATION_KEY not in text: + return None + try: + parsed = json.loads(text) + except json.JSONDecodeError: + return None + if not isinstance(parsed, dict) or _PAGINATION_KEY not in parsed: + return None + marker = parsed[_PAGINATION_KEY] + return marker if isinstance(marker, dict) else {} + + +# simple-git's timeout plugin kills the subprocess with this exact message. +# git itself (via GIT_HTTP_LOW_SPEED_TIME) produces curl errors that vary by +# libcurl version, so "timed out" is kept as a broad fallback. +_TOOL_TIMEOUT_PATTERNS = ("block timeout reached", "timed out") + + +def _http_error_detail(exc: urllib.error.HTTPError) -> str: + """the git service's refusal message from an HTTP error body (bounded).""" + try: + raw = exc.read(4096) + except OSError: + raw = b"" + text = raw.decode("utf-8", "replace") + try: + parsed = json.loads(text) + except ValueError: + return text or str(exc) + if isinstance(parsed, dict): + message = parsed.get("message") or parsed.get("error") + if message: + return str(message) + return text + + +def _complete_raw_output( + body: bytes, args: Sequence[str] +) -> subprocess.CompletedProcess: + """The raw exec 200 body as a finished git run, or a raise. + + Split at the LAST NUL; none means the connection was cut. + """ + at = body.rfind(_RAW_TRAILER_SEPARATOR) + if at < 0: + raise GitMcpBackendError( + "the git service raw exec response has no trailer: the stream was cut, so " + "the output may be partial" + ) + stdout, raw_trailer = body[:at], body[at + 1 :] + try: + trailer = json.loads(raw_trailer.decode("utf-8")) + except (ValueError, UnicodeDecodeError) as exc: + raise GitMcpBackendError( + f"the git service raw exec trailer is not JSON: {exc}" + ) from exc + if not isinstance(trailer, dict): + raise GitMcpBackendError("the git service raw exec trailer is not an object") + stderr = str(trailer.get("stderr") or "") + if trailer.get("timed_out") is not False: + if trailer.get("timed_out") is True: + raise GitMcpTimeoutError( + f"the git service raw exec: git timed out: {stderr}", stderr=stderr + ) + raise GitMcpBackendError("the git service raw exec trailer has no timed_out flag") + if trailer.get("truncated") is not False: + if trailer.get("truncated") is True: + raise GitMcpOutputTooLargeError( + "the git service raw exec: git's output is over the git service's budget", + stderr=stderr, + ) + raise GitMcpBackendError("the git service raw exec trailer has no truncated flag") + if trailer.get("error"): + raise GitMcpBackendError( + f"the git service raw exec could not run git: {trailer['error']}", stderr=stderr + ) + exit_code = trailer.get("exit_code") + if isinstance(exit_code, bool) or not isinstance(exit_code, int): + raise GitMcpBackendError( + f"the git service raw exec trailer exit_code is not a number: {exit_code!r}" + ) + declared = trailer.get("stdout_bytes") + if isinstance(declared, bool) or declared != len(stdout): + raise GitMcpBackendError( + f"the git service raw exec sent {len(stdout)} stdout bytes but declared " + f"{declared!r}: the output is not whole" + ) + return subprocess.CompletedProcess( + args=["the git service", "git_exec", *args], + returncode=exit_code, + stdout=stdout, + stderr=stderr, + ) + + +class GitMcpBackend: + """A ``GitBackend`` that forwards every op to the git service, addressed by cow_path. + + Implements the same method surface as ``LocalGitBackend`` (structural typing — + cidx's ``GitBackend`` is a ``typing.Protocol``), so it needs no import from cidx + and stays a stdlib-only plugin. + + ``credentials_url`` on the network operations is accepted and not + forwarded: the git service supplies its own credential (``owns_credentials``), so + cidx's registered URL credential never leaves the pod. A request is + bounded by its HTTP timeout rather than killed mid-flight -- cidx checks + its job's cancellation between operations. + """ + + def __init__( + self, + base_url: Optional[str] = None, + token: Optional[str] = None, + timeout: Optional[float] = None, + ) -> None: + base = (base_url or os.environ.get("CIDX_GIT_MCP_URL") or _DEFAULT_URL).rstrip( + "/" + ) + self._url = base + "/v1/git/mcp" + self._raw_url = base + _RAW_EXEC_ROUTE + self._token = token or os.environ.get("CIDX_GIT_MCP_TOKEN") or "" + env_timeout = os.environ.get("CIDX_GIT_MCP_TIMEOUT") + self._timeout = timeout or (float(env_timeout) if env_timeout else 120.0) + self._id = 0 + self._id_lock = threading.Lock() + #: ``time.monotonic()`` before which the raw exec endpoint is not + #: tried (it answered 404 or 503); 0.0 = try it. + self._raw_unavailable_until = 0.0 + + # ── capabilities ─────────────────────────────────────────────────────────── + + @property + def owns_credentials(self) -> bool: + """True: the git service holds the git credential (``GIT_CLONE_TOKEN`` → its own + credential helper) and injects it for every network op, so cidx must NOT + embed a token in repo URLs and should strip any credential before storing + one. The PAT then lives ONLY in the git service.""" + return True + + # ── transport ──────────────────────────────────────────────────────────── + + def _call( + self, + tool: str, + arguments: Dict[str, Any], + timeout: Any = None, + *, + unread_list: Optional[str] = None, + ) -> Dict[str, Any]: + """One tool call's parsed result, or a raise. + + *unread_list* names a top-level list of the result the caller never + reads: a page that cut THAT list -- and nothing else -- is accepted, + because every field the caller does read arrived whole. Any other page + raises :class:`GitMcpPaginatedResultError`. + """ + result = self._rpc( + "tools/call", {"name": tool, "arguments": arguments}, tool, timeout + ) + text = self._text(result) + if result.get("isError"): + if _OUTPUT_TOO_LARGE in text: + raise GitMcpOutputTooLargeError( + f"the git service {tool}: git's output is over the git service's budget: {text}", + stderr=text, + ) + if any(pattern in text for pattern in _TOOL_TIMEOUT_PATTERNS): + raise GitMcpTimeoutError( + f"the git service {tool} tool error: {text}", stderr=text + ) + raise GitMcpBackendError(f"the git service {tool} tool error: {text}", stderr=text) + self._refuse_paginated(tool, result, unread_list) + return self._parse(tool, text) + + @staticmethod + def _refuse_paginated( + tool: str, result: Dict[str, Any], unread_list: Optional[str] = None + ) -> None: + """Raise when ANY text chunk of *result* is a the git service page -- except a + page whose cut ``path`` is exactly *unread_list*.""" + for chunk in result.get("content") or []: + if not (isinstance(chunk, dict) and chunk.get("type") == "text"): + continue + marker = _page_marker(str(chunk.get("text", ""))) + if marker is None: + continue + if unread_list is None or marker.get("path") != unread_list: + raise GitMcpPaginatedResultError( + f"the git service {tool} returned a paginated (truncated) result; " + "refusing to treat one page of the output as all of it" + ) + + def _rpc( + self, method: str, params: Dict[str, Any], tool: str, timeout: Any + ) -> Dict[str, Any]: + """One JSON-RPC request; its ``result`` object, or a raise. *tool* + names the request in errors.""" + with self._id_lock: + self._id += 1 + call_id = self._id + body = { + "jsonrpc": "2.0", + "id": call_id, + "method": method, + "params": params, + } + req = urllib.request.Request( + self._url, + data=json.dumps(body).encode(), + headers=self._headers(), + method="POST", + ) + http_timeout = timeout if isinstance(timeout, (int, float)) else self._timeout + try: + with urllib.request.urlopen(req, timeout=http_timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, OSError) as exc: + if _is_timeout(exc): + raise GitMcpTimeoutError( + f"the git service {tool} request to {self._url} timed out: {exc}", + stderr=str(exc), + ) from exc + raise GitMcpBackendError( + f"the git service {tool} request to {self._url} failed: {exc}", stderr=str(exc) + ) from exc + payload = json.loads(raw) if raw else {} + if "error" in payload: + raise GitMcpBackendError( + f"the git service {tool} JSON-RPC error: {payload['error']}", + stderr=str(payload["error"]), + ) + result = payload.get("result", {}) or {} + return result if isinstance(result, dict) else {} + + def _headers(self) -> Dict[str, str]: + headers = {"Content-Type": "application/json"} + if self._token: + headers["Authorization"] = "Bearer " + self._token + return headers + + def _exec_raw( + self, arguments: Dict[str, Any], args: Sequence[str], http_timeout: float + ) -> subprocess.CompletedProcess: + """``git_exec`` through the git service's raw endpoint: git's exact stdout bytes. + + 200 is `` 0x00 ``; the output is the + WHOLE output only when the trailer parses, carries a numeric + ``exit_code``, is neither ``truncated`` nor ``timed_out``, has no + ``error``, and ``stdout_bytes`` equals the bytes received. Anything + else raises -- a cut or capped stream is never returned as complete. + 404 (a the git service predating the endpoint) and 503 (no shared secret + configured) raise :class:`_RawExecUnavailable` so the caller falls + back to MCP ``git_exec``; they are remembered for + ``_RAW_RETRY_SECONDS``. Any other refusal is the git service's answer and + raises, as MCP ``git_exec`` would have. + """ + req = urllib.request.Request( + self._raw_url, + data=json.dumps(arguments).encode(), + headers=self._headers(), + method="POST", + ) + try: + with urllib.request.urlopen(req, timeout=http_timeout) as resp: + body = resp.read() + except urllib.error.HTTPError as exc: + detail = _http_error_detail(exc) + if exc.code in (404, 503): + self._raw_unavailable_until = time.monotonic() + _RAW_RETRY_SECONDS + raise _RawExecUnavailable(f"{exc.code}: {detail}") from exc + if exc.code == 504: + raise GitMcpTimeoutError( + f"the git service raw exec timed out: {detail}", stderr=detail + ) from exc + raise GitMcpBackendError( + f"the git service raw exec refused git {args[0] if args else ''}: {detail}", + stderr=detail, + returncode=128, + ) from exc + except (urllib.error.URLError, OSError) as exc: + if _is_timeout(exc): + raise GitMcpTimeoutError( + f"the git service raw exec to {self._raw_url} timed out: {exc}", + stderr=str(exc), + ) from exc + raise GitMcpBackendError( + f"the git service raw exec to {self._raw_url} failed: {exc}", stderr=str(exc) + ) from exc + return _complete_raw_output(body, args) + + @staticmethod + def _text(result: Dict[str, Any]) -> str: + for chunk in result.get("content") or []: + if isinstance(chunk, dict) and chunk.get("type") == "text": + return str(chunk.get("text", "")) + return "" + + @staticmethod + def _parse(tool: str, text: str) -> Dict[str, Any]: + # A 200 with an empty body is legitimate for mutations (they return + # nothing the backend reads). A 200 with a NON-empty body that is not JSON, + # however, must NOT degrade to a benign default — a read like + # status_porcelain / ls_files would then report a dirty repo as clean or an + # indexed repo as empty, silently corrupting cidx's git-state view. So an + # unparseable non-empty body fails loud; per-method key validation + # (``_require``) guards the structured reads against a wrong-shape 200. + if not text: + return {} + try: + parsed = json.loads(text) + except json.JSONDecodeError as exc: + raise GitMcpBackendError( + f"the git service {tool} returned an unparseable body: {text[:200]!r}", + stderr=text, + ) from exc + return parsed if isinstance(parsed, dict) else {"_list": parsed} + + @staticmethod + def _require(tool: str, result: Dict[str, Any], key: str) -> Any: + """Return ``result[key]`` or fail loud — a structured read whose expected + key is absent means the git service returned a wrong-shape (but valid-JSON) 200; + defaulting it would mask a dirty/indexed repo as clean/empty.""" + if key not in result: + raise GitMcpBackendError( + f"the git service {tool} response missing {key!r} (got keys {sorted(result)})" + ) + return result[key] + + def _cow(self, repo_path: str, **extra: Any) -> Dict[str, Any]: + args: Dict[str, Any] = {"cow_path": repo_path} + args.update({k: v for k, v in extra.items() if v is not None}) + return args + + # ── remote-only ops ────────────────────────────────────────────────────── + + def ls_remote( + self, url: str, timeout: Any = None, credentials_url: Any = None + ) -> bool: + # git_ls_remote also lists every ref; for a remote with many (~900+) + # that list is over the git service's MCP ceiling and arrives as a page cut at + # ``refs``. Only ``reachable`` is read, and a page keeps it whole -- so + # that page is the answer, while a page cut anywhere else still raises. + # (Raw exec cannot serve this: git_exec runs no network subcommand.) + r = self._call( + "git_ls_remote", {"remote_url": url}, timeout, unread_list="refs" + ) + return bool(self._require("git_ls_remote", r, "reachable")) + + def clone( + self, + url: str, + dest_path: str, + branch: Optional[str] = None, + no_fsync: bool = False, + timeout: Any = None, + retry: bool = False, + credentials_url: Any = None, + ) -> None: + self._call( + "git_clone", self._cow(dest_path, remote_url=url, branch=branch), timeout + ) + + # ── working-tree / index ops (cow_path-addressed) ──────────────────────── + + def fetch( + self, + repo_path: str, + remote: str = "origin", + no_fsync: bool = False, + timeout: Any = None, + retry: bool = False, + credentials_url: Any = None, + ref: Optional[str] = None, + ) -> None: + # ``ref``: only that branch (refs/remotes//), never the + # clone's configured refspec -- which may name a deleted branch. + self._call("git_fetch", self._cow(repo_path, remote=remote, ref=ref), timeout) + + def pull( + self, + repo_path: str, + remote: Optional[str] = None, + branch: Optional[str] = None, + mode: str = "default", + no_fsync: bool = False, + timeout: Any = None, + retry: bool = False, + credentials_url: Any = None, + ) -> None: + args = self._cow(repo_path, remote=remote, branch=branch) + # Map every documented LocalGitBackend pull mode to its the git service flag. A + # mode that matched no branch used to degrade to a plain `git pull` (so + # 'no-ff' silently fast-forwarded — the opposite of --no-ff); reject an + # unrecognised mode instead of silently downgrading. + mode_flags = { + "rebase": "rebase", + "ff-only": "ff_only", + "ff_only": "ff_only", + "no-ff": "no_ff", + "no_ff": "no_ff", + } + if mode not in ("default", None): + flag = mode_flags.get(mode) + if flag is None: + raise GitMcpBackendError(f"the git service pull: unsupported mode {mode!r}") + args[flag] = True + self._call("git_pull", args, timeout) + + def merge(self, repo_path: str, ref: str, timeout: Any = None) -> None: + self._call("git_merge", self._cow(repo_path, branch=ref), timeout) + + def checkout( + self, + repo_path: str, + ref: str, + create: bool = False, + force_new: bool = False, + force: bool = False, + start_point: Optional[str] = None, + timeout: Any = None, + ) -> None: + # Forward create (-b), force_new (-B), and force (-f) as DISTINCT signals — + # the git service orders them as git does (-f, then -B|-b). Collapsing force_new + # into create would break cidx's force-switch strategy (checkout of an + # existing branch with force_new=True must force-reset, not fail as -b). + self._call( + "git_checkout", + self._cow( + repo_path, + target=ref, + create=create or None, + force_new=force_new or None, + force=force or None, + start_point=start_point, + ), + timeout, + ) + + def current_branch(self, repo_path: str, timeout: Any = None) -> str: + r = self._call("git_symbolic_ref", self._cow(repo_path, short=True), timeout) + return str(self._require("git_symbolic_ref", r, "ref")).strip() + + def list_branches( + self, + repo_path: str, + remote: bool = False, + all_refs: bool = False, + fmt: Optional[str] = None, + timeout: Any = None, + ) -> List[str]: + # the git service git_branch_list already returns names in `%(refname:short)` shape + # (local -> `main`, remote -> `origin/main`), which is the only fmt any cidx + # caller passes, so that fmt is honoured by the reconstruction below. Any + # OTHER fmt cannot be reproduced (the git service exposes no --format), so fail loud + # rather than silently return the wrong string shape. + if fmt not in (None, "%(refname:short)"): + raise GitMcpBackendError( + f"the git service git_branch_list cannot honour fmt={fmt!r}; only the " + "default / '%(refname:short)' shape is available" + ) + try: + result = self._call( + "git_branch_list", + self._cow(repo_path, include_remote=bool(remote or all_refs)), + timeout, + ) + except _OVER_MCP_CEILING: + # Too many branches for one MCP answer: git's own listing, whole. + scope = ["-a"] if all_refs else ["-r"] if remote else [] + stdout = self._exec_text( + repo_path, + ["branch", *scope, "--format=%(refname:short)"], + timeout, + ) + return [line.strip() for line in stdout.splitlines() if line.strip()] + branches = self._require("git_branch_list", result, "branches") + names: List[str] = [] + for b in branches: + if not isinstance(b, dict): + continue + btype = b.get("type") + if ( + all_refs + or (remote and btype == "remote") + or (not remote and btype == "local") + ): + names.append(str(b.get("name", ""))) + return [n for n in names if n] + + def rev_parse(self, repo_path: str, *args: str, timeout: Any = None) -> str: + r = self._call("git_rev_parse", self._cow(repo_path, args=list(args)), timeout) + return str(self._require("git_rev_parse", r, "output")).strip() + + def rev_list_count( + self, repo_path: str, range_expr: str, timeout: Any = None + ) -> int: + r = self._call( + "git_rev_list_count", self._cow(repo_path, range=range_expr), timeout + ) + return int(self._require("git_rev_list_count", r, "count")) + + def symbolic_ref( + self, repo_path: str, short: bool = True, timeout: Any = None + ) -> str: + r = self._call("git_symbolic_ref", self._cow(repo_path, short=short), timeout) + return str(self._require("git_symbolic_ref", r, "ref")).strip() + + def status_porcelain(self, repo_path: str, timeout: Any = None) -> str: + # the git service git_status is structured; reconstruct `git status --porcelain` + # faithfully enough for cidx (which filters untracked `??` and warns on any + # remaining TRACKED line). + try: + r = self._call("git_status", self._cow(repo_path), timeout) + except _OVER_MCP_CEILING: + # Too many changed paths for one MCP answer: git's own porcelain. + return self._exec_text(repo_path, ["status", "--porcelain"], timeout) + # Guard against a valid-JSON but wrong-shape 200 (e.g. `{}`) reading as a + # clean tree: a real git_status always carries these buckets. + if not any(k in r for k in ("staged", "unstaged", "untracked", "conflicts")): + raise GitMcpBackendError( + f"the git service git_status returned no status buckets (keys {sorted(r)})" + ) + lines: List[str] = [] + for e in r.get("staged") or []: + lines.append(f"M {e.get('path', '')}") + for e in r.get("unstaged") or []: + code = "D" if e.get("status") == "deleted" else "M" + lines.append(f" {code} {e.get('path', '')}") + for e in r.get("conflicts") or []: + lines.append(f"UU {e.get('path', '')}") + for e in r.get("untracked") or []: + lines.append(f"?? {e.get('path', '')}") + return "\n".join(lines) + + def diff_name_only( + self, repo_path: str, spec: str, timeout: Any = None + ) -> List[str]: + # Use the git service's name_only mode, which returns git's OWN `git diff + # --name-only -z` path list. Parsing the changed paths out of a unified + # diff was lossy — a quoted path (non-ASCII / special chars) has no literal + # `" b/"` token, so it was dropped and the file left un-reindexed. These + # paths feed reindex decisions, so a dropped file diverges the index. + try: + r = self._call( + "git_diff", self._cow(repo_path, base=spec, name_only=True), timeout + ) + except _OVER_MCP_CEILING: + # Too many paths for one MCP answer: the same NUL-delimited list. + stdout = self._exec_text( + repo_path, ["diff", "--name-only", "-z", spec], timeout + ) + return [path for path in stdout.split("\x00") if path] + return list(self._require("git_diff", r, "files")) + + def ls_files(self, repo_path: str, timeout: Any = None) -> List[str]: + try: + r = self._call("git_ls_files", self._cow(repo_path), timeout) + except _OVER_MCP_CEILING: + # Too many files for one MCP answer: git's own listing, whole. + stdout = self._exec_text(repo_path, ["ls-files"], timeout) + return [line for line in stdout.splitlines() if line] + return list(self._require("git_ls_files", r, "files")) + + def show_ref( + self, repo_path: str, *args: str, timeout: Any = None + ) -> subprocess.CompletedProcess: + r = self._call("git_show_ref", self._cow(repo_path, args=list(args)), timeout) + output = str(r.get("output", "")) + return subprocess.CompletedProcess( + args=["git", "show-ref", *args], + returncode=0 if r.get("found") else 1, + stdout=output, + stderr="", + ) + + def reset( + self, repo_path: str, mode: str, target: str, timeout: Any = None + ) -> None: + self._call("git_reset", self._cow(repo_path, mode=mode, target=target), timeout) + + def restore(self, repo_path: str, pathspec: str = ".", timeout: Any = None) -> None: + self._call("git_restore", self._cow(repo_path, pathspec=pathspec), timeout) + + def update_index_refresh(self, repo_path: str, timeout: Any = None) -> None: + self._call("git_update_index_refresh", self._cow(repo_path), timeout) + + def config_set( + self, repo_path: str, key: str, value: str, timeout: Any = None + ) -> None: + self._call( + "git_config_set", self._cow(repo_path, key=key, value=value), timeout + ) + + # ── history (cidx temporal indexing and queries) ───────────────────────── + # the git service returns git's own stdout base64-encoded, so these hand cidx the + # exact bytes a local run would; cidx decodes them as local git output. + + def log_raw( + self, + repo_path: str, + fmt: str, + revs: Sequence[str] = (), + *, + all_refs: bool = False, + since: Optional[str] = None, + skip: Optional[int] = None, + max_count: Optional[int] = None, + timeout: Any = None, + ) -> bytes: + try: + r = self._call( + "git_log_raw", + self._cow( + repo_path, + format=fmt, + revs=list(revs) or None, + all=all_refs or None, + since=since, + skip=skip or None, + max_count=max_count, + ), + timeout, + ) + except _OVER_MCP_CEILING: + # The argv git_log_raw runs, through the raw endpoint. + args = ["log", f"--format={fmt}"] + if all_refs: + args.append("--all") + if since is not None: + args.append(f"--since={since}") + if skip: + args.append(f"--skip={skip}") + if max_count is not None: + args.append(f"--max-count={max_count}") + return self._exec_checked( + "git_log_raw", repo_path, [*args, *revs, "--"], timeout + ) + out = self._raw_output("git_log_raw", r) + self._check("git_log_raw", out) + return bytes(out.stdout) + + def for_each_ref( + self, + repo_path: str, + fmt: str, + patterns: Sequence[str] = (), + *, + sort: Optional[str] = None, + count: Optional[int] = None, + timeout: Any = None, + ) -> bytes: + """``git for-each-ref`` in ONE call: every matching ref with its fields. + + the git service validates the arguments (patterns are never option-shaped and + at most 256; ``sort`` is a key name, optionally ``-``-prefixed) and + runs ``git for-each-ref --format= [--sort] [--count] -- ``. + """ + try: + r = self._call( + "git_for_each_ref", + self._cow( + repo_path, + format=fmt, + patterns=list(patterns) or None, + sort=sort, + count=count, + ), + timeout, + ) + except _OVER_MCP_CEILING: + # Many refs (a big repo's branch listing): the argv + # git_for_each_ref runs, through the raw endpoint. + args = ["for-each-ref", f"--format={fmt}"] + if sort is not None: + args.append(f"--sort={sort}") + if count is not None: + args.append(f"--count={count}") + return self._exec_checked( + "git_for_each_ref", repo_path, [*args, "--", *patterns], timeout + ) + out = self._raw_output("git_for_each_ref", r) + self._check("git_for_each_ref", out) + return bytes(out.stdout) + + def diff_commits( + self, + repo_path: str, + pairs: Sequence[Tuple[str, str]], + context_lines: int, + timeout: Any = None, + ) -> List[bytes]: + diffs: List[bytes] = [] + for batch in self._batches(pairs): + r = self._call( + "git_diff_commits", + self._cow( + repo_path, + pairs=[{"base": base, "commit": commit} for base, commit in batch], + context_lines=context_lines, + ), + timeout, + ) + items = self._items("git_diff_commits", r, "diffs", len(batch)) + for item in items: + out = self._raw_output("git_diff_commits", item) + self._check("git_diff_commits", out) + diffs.append(bytes(out.stdout)) + return diffs + + def show_objects( + self, + repo_path: str, + specs: Sequence[Tuple[str, str]], + timeout: Any = None, + ) -> List[subprocess.CompletedProcess]: + objects: List[subprocess.CompletedProcess] = [] + for batch in self._batches(specs): + r = self._call( + "git_show_objects", + self._cow( + repo_path, specs=[{"rev": rev, "path": path} for rev, path in batch] + ), + timeout, + ) + items = self._items("git_show_objects", r, "objects", len(batch)) + objects.extend(self._raw_output("git_show_objects", i) for i in items) + return objects + + @staticmethod + def _batches(items: Sequence[Any]) -> List[Sequence[Any]]: + return [ + items[i : i + _MAX_HISTORY_BATCH] + for i in range(0, len(items), _MAX_HISTORY_BATCH) + ] + + def _items( + self, tool: str, result: Dict[str, Any], key: str, expected: int + ) -> List[Dict[str, Any]]: + """``result[key]``: exactly one dict per requested item, or fail loud.""" + items = self._require(tool, result, key) + if not isinstance(items, list) or len(items) != expected: + raise GitMcpBackendError( + f"the git service {tool} returned {len(items) if isinstance(items, list) else items!r} " + f"results for {expected} items" + ) + return [i if isinstance(i, dict) else {} for i in items] + + def _raw_output( + self, tool: str, result: Dict[str, Any] + ) -> subprocess.CompletedProcess: + """One git process's result: returncode, raw stdout bytes, stderr text.""" + returncode = self._require(tool, result, "exit_code") + encoded = self._require(tool, result, "stdout_b64") + try: + stdout = base64.b64decode(str(encoded), validate=True) + except ValueError as exc: + raise GitMcpBackendError( + f"the git service {tool} returned stdout that is not base64" + ) from exc + return subprocess.CompletedProcess( + args=["the git service", tool], + returncode=int(returncode), + stdout=stdout, + stderr=str(result.get("stderr", "")), + ) + + @staticmethod + def _check(tool: str, out: subprocess.CompletedProcess) -> None: + """Raise as a local ``check=True`` run would, with git's own stderr.""" + if out.returncode != 0: + raise GitMcpBackendError( + f"the git service {tool}: git exited {out.returncode}: {out.stderr}", + stderr=out.stderr, + returncode=out.returncode, + ) + + # ── cidx's git tools on an activated working copy (GitCommandRunner) ───── + + def run( + self, + repo_path: str, + args: Sequence[str], + timeout: Any = None, + identity: Optional[Dict[str, str]] = None, + ) -> subprocess.CompletedProcess: + """``git `` through the git service ``git_exec``: git's own output, the + exit code returned (not raised) exactly as a local ``check=False`` run.""" + out = self._exec_bytes(repo_path, args, timeout, identity) + return subprocess.CompletedProcess( + args=["git", *args], + returncode=out.returncode, + stdout=_decode_like_text_mode(bytes(out.stdout)), + stderr=out.stderr, + ) + + def _exec_checked( + self, tool: str, repo_path: str, args: Sequence[str], timeout: Any + ) -> bytes: + """git's exact stdout bytes for *args*; raises as ``check=True`` would.""" + out = self._exec_bytes(repo_path, args, timeout) + self._check(tool, out) + return bytes(out.stdout) + + def _exec_text(self, repo_path: str, args: Sequence[str], timeout: Any) -> str: + """git's stdout for *args* as a local text-mode run decodes it; raises + as ``check=True`` would.""" + return _decode_like_text_mode( + self._exec_checked(f"git {args[0]}", repo_path, args, timeout) + ) + + def _exec_bytes( + self, + repo_path: str, + args: Sequence[str], + timeout: Any = None, + identity: Optional[Dict[str, str]] = None, + ) -> subprocess.CompletedProcess: + """``git `` via raw exec (MCP ``git_exec`` when the git service lacks + it): returncode, git's exact stdout BYTES, stderr. Whole or a raise.""" + # Whole seconds, rounded UP and at least 1 (the git service's minimum): a + # fractional remaining budget is never cut to 0 or silently shortened. + seconds = ( + max(1, math.ceil(timeout)) if isinstance(timeout, (int, float)) else None + ) + arguments = self._cow( + repo_path, + args=list(args), + timeout_seconds=seconds, + identity=dict(identity) if identity else None, + ) + http_timeout = self._timeout if seconds is None else seconds + 30 + out: Optional[subprocess.CompletedProcess] = None + if time.monotonic() >= self._raw_unavailable_until: + # The raw endpoint first: unpaged, unencoded, with a trailer that + # proves the output is whole -- blame and every large output. + try: + out = self._exec_raw(arguments, args, http_timeout) + except _RawExecUnavailable: + out = None + if out is None: + result = self._call("git_exec", arguments, http_timeout) + out = self._raw_output("git_exec", result) + return out + + def push( + self, + repo_path: str, + remote: str, + branch: Optional[str] = None, + timeout: Any = None, + ) -> subprocess.CompletedProcess: + """the git service ``git_push`` with the git service's credentials; raises on failure.""" + result = self._call( + "git_push", self._cow(repo_path, remote=remote, branch=branch), timeout + ) + guidance = result.get("_guidance") or {} + message = str(guidance.get("message", "")) if isinstance(guidance, dict) else "" + return subprocess.CompletedProcess( + args=["git", "push", remote] + ([branch] if branch else []), + returncode=0, + stdout=message, + stderr="", + ) + + # ── remotes ────────────────────────────────────────────────────────────── + + def remote_list( + self, repo_path: str, verbose: bool = False, timeout: Any = None + ) -> str: + result = self._call("git_remote_list", self._cow(repo_path), timeout) + remotes = self._require("git_remote_list", result, "remotes") or [] + if not verbose: + return "\n".join( + sorted({str(r.get("name", "")) for r in remotes if r.get("name")}) + ) + lines: List[str] = [] + for r in remotes: + name = str(r.get("name", "")) + lines.append(f"{name}\t{r.get('fetch', '')} (fetch)") + lines.append(f"{name}\t{r.get('push', '')} (push)") + return "\n".join(lines) + + def remote_get_url(self, repo_path: str, name: str, timeout: Any = None) -> str: + r = self._call("git_remote_get_url", self._cow(repo_path, name=name), timeout) + return str(self._require("git_remote_get_url", r, "url")).strip() + + def remote_add( + self, repo_path: str, name: str, url: str, timeout: Any = None + ) -> None: + self._call("git_set_remote", self._cow(repo_path, name=name, url=url), timeout) + + def remote_set_url( + self, repo_path: str, name: str, url: str, timeout: Any = None + ) -> None: + self._call("git_set_remote", self._cow(repo_path, name=name, url=url), timeout) + + def remote_rename( + self, repo_path: str, old: str, new: str, timeout: Any = None + ) -> None: + self._call( + "git_remote_rename", + self._cow(repo_path, old_name=old, new_name=new), + timeout, + ) + + def remote_remove(self, repo_path: str, name: str, timeout: Any = None) -> None: + self._call("git_remote_remove", self._cow(repo_path, name=name), timeout) + + +def make_git_backend() -> GitMcpBackend: + """Factory for the ``code_indexer.git_backend`` seam. Reads config from env.""" + return GitMcpBackend() diff --git a/plugins/cidx_git_backend/pyproject.toml b/plugins/cidx_git_backend/pyproject.toml new file mode 100644 index 000000000..cad3060cf --- /dev/null +++ b/plugins/cidx_git_backend/pyproject.toml @@ -0,0 +1,20 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "cidx-git-backend" +version = "0.4.0" +description = "Delegate cidx's internal git operations to the the git service spoke ()" +requires-python = ">=3.9" +dependencies = [] + +# Registers on cidx's code_indexer.git_backend seam, so the plugin is active as +# soon as it is installed. CIDX_GIT_BACKEND=cidx_git_backend:make_git_backend is +# an equivalent override and takes precedence. Only USED when the server's +# git_backend config is 'delegated'. +[project.entry-points."code_indexer.git_backend"] +gitmcp = "cidx_git_backend:make_git_backend" + +[tool.hatch.build.targets.wheel] +packages = ["cidx_git_backend"] diff --git a/plugins/cidx_git_backend/test_cidx_git_backend.py b/plugins/cidx_git_backend/test_cidx_git_backend.py new file mode 100644 index 000000000..99548ee2f --- /dev/null +++ b/plugins/cidx_git_backend/test_cidx_git_backend.py @@ -0,0 +1,1263 @@ +""" +Tests for the the git service-backed GitBackend (). + +The GitBackend contract is structural (cidx's Protocol) — so these pin the two +things that can silently drift from the git service: (1) the JSON-RPC envelope and +cow_path addressing every method sends, and (2) the reconstruction of the handful +of methods cidx expects as RAW git output (status_porcelain, remote_list -v, +diff_name_only, list_branches, show_ref→CompletedProcess). Transport/tool errors +must surface as GitMcpBackendError, never a silent empty result — a delegated +backend that quietly "succeeded" would corrupt cidx's git state view. + +The live end-to-end pass (against the deployed the git service on a real repo) proved the +happy path; this locks the contract with no cluster needed. +""" + +from __future__ import annotations + +import json +import subprocess +import urllib.error + +import pytest + +import cidx_git_backend as plugin +from cidx_git_backend import GitMcpBackend, GitMcpBackendError + +REPO = "/data/data/golden-repos/foo/master" + + +class _FakeResp: + def __init__(self, text: str): + self._text = text + + def read(self): + return self._text.encode("utf-8") + + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + +def _rpc(result: dict) -> str: + return json.dumps({"jsonrpc": "2.0", "id": 1, "result": result}) + + +def _content(payload) -> dict: + """the git service wraps a tool's JSON return as content[0].text.""" + return {"content": [{"type": "text", "text": json.dumps(payload)}]} + + +def _content_raw(text: str) -> dict: + """A success result whose content text is NOT valid JSON.""" + return {"content": [{"type": "text", "text": text}]} + + +@pytest.fixture() +def backend(monkeypatch): + monkeypatch.delenv("CIDX_GIT_MCP_URL", raising=False) + monkeypatch.delenv("CIDX_GIT_MCP_TOKEN", raising=False) + monkeypatch.delenv("CIDX_GIT_MCP_TIMEOUT", raising=False) + return GitMcpBackend(base_url="http://the git service:3000") + + +class _FakeBytesResp(_FakeResp): + def __init__(self, data: bytes): + self._data = data + + def read(self): + return self._data + + +def _http_error(url: str, code: int, payload: dict) -> urllib.error.HTTPError: + import io + + return urllib.error.HTTPError( + url, code, "error", {}, io.BytesIO(json.dumps(payload).encode()) + ) + + +#: How NestJS answers a route it does not have: a the git service predating raw exec. +_NO_RAW_ROUTE = {"statusCode": 404, "message": "Cannot POST /v1/git/exec/raw"} + + +def _install(monkeypatch, responder, raw=None): + """Patch urlopen; `responder(parsed_body) -> raw_json_str` answers the MCP + endpoint, `raw(parsed_body) -> bytes | HTTPError` the raw exec endpoint + (default: a the git service without it, 404). Records calls.""" + calls = [] + + def fake_urlopen(req, timeout=None): + body = json.loads(req.data.decode("utf-8")) + calls.append({"req": req, "body": body, "timeout": timeout}) + if req.full_url.endswith("/v1/git/exec/raw"): + answer = ( + raw(body) + if raw is not None + else _http_error(req.full_url, 404, _NO_RAW_ROUTE) + ) + if isinstance(answer, Exception): + raise answer + return _FakeBytesResp(answer) + return _FakeResp(responder(body)) + + monkeypatch.setattr(plugin.urllib.request, "urlopen", fake_urlopen) + return calls + + +def _tool_calls(calls): + """The MCP ``tools/call`` requests among *calls* (``run`` first tries + the raw exec endpoint).""" + return [c for c in calls if c["body"].get("method") == "tools/call"] + + +class TestTransportEnvelope: + def test_jsonrpc_shape_tool_and_cow_path(self, backend, monkeypatch): + calls = _install(monkeypatch, lambda b: _rpc(_content({"ref": "master"}))) + backend.current_branch(REPO) + body = calls[-1]["body"] + assert body["jsonrpc"] == "2.0" + assert body["method"] == "tools/call" + assert body["params"]["name"] == "git_symbolic_ref" + # cow_path addressing: cidx passes its own repo path, no workspace_id. + assert body["params"]["arguments"]["cow_path"] == REPO + assert "workspace_id" not in body["params"]["arguments"] + + def test_bearer_header_sent_when_token_set(self, monkeypatch): + b = GitMcpBackend(base_url="http://the git service:3000", token="tok123") + calls = _install(monkeypatch, lambda body: _rpc(_content({"ref": "m"}))) + b.current_branch(REPO) + assert calls[-1]["req"].headers["Authorization"] == "Bearer tok123" + + def test_no_auth_header_without_token(self, backend, monkeypatch): + calls = _install(monkeypatch, lambda body: _rpc(_content({"ref": "m"}))) + backend.current_branch(REPO) + assert "Authorization" not in calls[-1]["req"].headers + + def test_per_call_timeout_forwarded(self, backend, monkeypatch): + calls = _install(monkeypatch, lambda body: _rpc(_content({"reachable": True}))) + backend.ls_remote("http://x/y.git", timeout=7) + assert calls[-1]["timeout"] == 7 + + +class TestStructuredReads: + def test_ls_remote_bool(self, backend, monkeypatch): + _install(monkeypatch, lambda b: _rpc(_content({"reachable": True}))) + assert backend.ls_remote("http://x/y.git") is True + _install(monkeypatch, lambda b: _rpc(_content({"reachable": False}))) + assert backend.ls_remote("http://x/y.git") is False + + def test_rev_parse_strips(self, backend, monkeypatch): + _install(monkeypatch, lambda b: _rpc(_content({"output": "abc123\n"}))) + assert backend.rev_parse(REPO, "HEAD") == "abc123" + + def test_rev_list_count_int(self, backend, monkeypatch): + _install(monkeypatch, lambda b: _rpc(_content({"count": 5}))) + assert backend.rev_list_count(REPO, "a..b") == 5 + + def test_ls_files_list(self, backend, monkeypatch): + _install(monkeypatch, lambda b: _rpc(_content({"files": ["a.txt", "b/c.py"]}))) + assert backend.ls_files(REPO) == ["a.txt", "b/c.py"] + + +class TestReconstruction: + def test_status_porcelain_untracked_and_tracked(self, backend, monkeypatch): + _install( + monkeypatch, + lambda b: _rpc( + _content( + { + "unstaged": [{"path": "a.txt", "status": "modified"}], + "untracked": [{"path": "c.txt"}], + } + ) + ), + ) + out = backend.status_porcelain(REPO) + lines = out.splitlines() + # cidx filters `??`; a tracked line must survive as non-`??`. + assert " M a.txt" in lines + assert "?? c.txt" in lines + + def test_status_porcelain_deleted_and_conflict(self, backend, monkeypatch): + _install( + monkeypatch, + lambda b: _rpc( + _content( + { + "unstaged": [{"path": "d.txt", "status": "deleted"}], + "conflicts": [{"path": "e.txt"}], + "staged": [{"path": "s.txt"}], + } + ) + ), + ) + lines = backend.status_porcelain(REPO).splitlines() + assert " D d.txt" in lines + assert "UU e.txt" in lines + assert "M s.txt" in lines + + def test_remote_list_verbose_format(self, backend, monkeypatch): + _install( + monkeypatch, + lambda b: _rpc( + _content( + { + "remotes": [ + { + "name": "origin", + "fetch": "http://x/y.git", + "push": "http://x/y.git", + } + ] + } + ) + ), + ) + out = backend.remote_list(REPO, verbose=True) + assert out == ("origin\thttp://x/y.git (fetch)\norigin\thttp://x/y.git (push)") + + def test_remote_list_names_only(self, backend, monkeypatch): + _install( + monkeypatch, + lambda b: _rpc( + _content({"remotes": [{"name": "origin"}, {"name": "upstream"}]}) + ), + ) + assert backend.remote_list(REPO) == "origin\nupstream" + + def test_list_branches_filters_by_type(self, backend, monkeypatch): + payload = { + "branches": [ + {"name": "master", "type": "local"}, + {"name": "origin/master", "type": "remote"}, + ] + } + _install(monkeypatch, lambda b: _rpc(_content(payload))) + assert backend.list_branches(REPO) == ["master"] + _install(monkeypatch, lambda b: _rpc(_content(payload))) + assert backend.list_branches(REPO, remote=True) == ["origin/master"] + _install(monkeypatch, lambda b: _rpc(_content(payload))) + assert backend.list_branches(REPO, all_refs=True) == [ + "master", + "origin/master", + ] + + def test_diff_name_only_uses_git_mcp_name_only_files(self, backend, monkeypatch): + # Uses the git service's own --name-only list (never a lossy unified-diff parse), so + # even a quoted / non-ASCII path survives intact. + calls = _install( + monkeypatch, lambda b: _rpc(_content({"files": ["x.py", "dir/café.py"]})) + ) + assert backend.diff_name_only(REPO, "HEAD~1") == ["x.py", "dir/café.py"] + args = calls[-1]["body"]["params"]["arguments"] + assert args["name_only"] is True + assert args["base"] == "HEAD~1" + + def test_show_ref_completed_process(self, backend, monkeypatch): + _install( + monkeypatch, + lambda b: _rpc( + _content({"output": "abc refs/heads/master\n", "found": True}) + ), + ) + cp = backend.show_ref(REPO, "--heads") + assert cp.returncode == 0 + assert "refs/heads/master" in cp.stdout + + def test_show_ref_not_found_returncode_1(self, backend, monkeypatch): + _install(monkeypatch, lambda b: _rpc(_content({"output": "", "found": False}))) + cp = backend.show_ref(REPO, "refs/heads/nope") + assert cp.returncode == 1 + + +class TestMutationArguments: + def test_checkout_create_only(self, backend, monkeypatch): + calls = _install(monkeypatch, lambda b: _rpc(_content({}))) + backend.checkout(REPO, "feature", create=True) + args = calls[-1]["body"]["params"]["arguments"] + assert args["cow_path"] == REPO + assert args["target"] == "feature" + assert args["create"] is True + # create (-b) and force_new (-B) must NOT collapse — force_new absent here. + assert "force_new" not in args + + def test_checkout_force_new_and_start_point_are_distinct( + self, backend, monkeypatch + ): + calls = _install(monkeypatch, lambda b: _rpc(_content({}))) + backend.checkout(REPO, "feature", force_new=True, start_point="origin/feature") + args = calls[-1]["body"]["params"]["arguments"] + assert args["force_new"] is True + assert args["start_point"] == "origin/feature" + # force_new is a separate signal from create (-B vs -b). + assert "create" not in args + + def test_checkout_force(self, backend, monkeypatch): + calls = _install(monkeypatch, lambda b: _rpc(_content({}))) + backend.checkout(REPO, "HEAD", force=True) + assert calls[-1]["body"]["params"]["arguments"]["force"] is True + + def test_pull_rebase_mode(self, backend, monkeypatch): + calls = _install(monkeypatch, lambda b: _rpc(_content({}))) + backend.pull(REPO, mode="rebase") + assert calls[-1]["body"]["params"]["arguments"]["rebase"] is True + + def test_pull_no_ff_mode(self, backend, monkeypatch): + calls = _install(monkeypatch, lambda b: _rpc(_content({}))) + backend.pull(REPO, mode="no-ff") + assert calls[-1]["body"]["params"]["arguments"]["no_ff"] is True + + def test_pull_rejects_unknown_mode(self, backend, monkeypatch): + _install(monkeypatch, lambda b: _rpc(_content({}))) + with pytest.raises(GitMcpBackendError, match="unsupported mode"): + backend.pull(REPO, mode="bogus") + + def test_reset_hard(self, backend, monkeypatch): + calls = _install(monkeypatch, lambda b: _rpc(_content({}))) + backend.reset(REPO, "hard", "origin/master") + args = calls[-1]["body"]["params"]["arguments"] + assert args["mode"] == "hard" and args["target"] == "origin/master" + + def test_config_set(self, backend, monkeypatch): + calls = _install(monkeypatch, lambda b: _rpc(_content({}))) + backend.config_set(REPO, "user.name", "x") + args = calls[-1]["body"]["params"]["arguments"] + assert args["key"] == "user.name" and args["value"] == "x" + + def test_fetch_of_one_branch_sends_ref(self, backend, monkeypatch): + """change_branch fetches only the target branch, never the + clone's refspec (which may name a branch upstream deleted).""" + calls = _install(monkeypatch, lambda b: _rpc(_content({}))) + backend.fetch(REPO, remote="origin", ref="master") + args = calls[-1]["body"]["params"]["arguments"] + assert calls[-1]["body"]["params"]["name"] == "git_fetch" + assert args["ref"] == "master" and args["remote"] == "origin" + + def test_plain_fetch_sends_no_ref(self, backend, monkeypatch): + calls = _install(monkeypatch, lambda b: _rpc(_content({}))) + backend.fetch(REPO) + assert "ref" not in calls[-1]["body"]["params"]["arguments"] + + +class TestErrorsFailLoud: + def test_tool_error_raises(self, backend, monkeypatch): + _install( + monkeypatch, + lambda b: json.dumps( + { + "jsonrpc": "2.0", + "id": 1, + "result": { + "isError": True, + "content": [{"type": "text", "text": "boom"}], + }, + } + ), + ) + with pytest.raises(GitMcpBackendError, match="tool error"): + backend.current_branch(REPO) + + def test_jsonrpc_error_raises(self, backend, monkeypatch): + _install( + monkeypatch, + lambda b: json.dumps( + {"jsonrpc": "2.0", "id": 1, "error": {"code": -32601, "message": "x"}} + ), + ) + with pytest.raises(GitMcpBackendError, match="JSON-RPC error"): + backend.current_branch(REPO) + + def test_transport_error_raises(self, backend, monkeypatch): + def boom(req, timeout=None): + raise urllib.error.URLError("connection refused") + + monkeypatch.setattr(plugin.urllib.request, "urlopen", boom) + with pytest.raises(GitMcpBackendError, match="request to .* failed"): + backend.current_branch(REPO) + + +class TestExceptionContract: + """The ~30 seam callers do `except subprocess.CalledProcessError` and read + `.stderr`; the delegated backend MUST raise that type, with the git service's error + text in `.stderr`, or every recovery path goes dead (a raw RuntimeError would + escape uncaught).""" + + def test_error_is_called_process_error(self): + assert issubclass(GitMcpBackendError, subprocess.CalledProcessError) + + def test_tool_error_populates_stderr_for_recovery_matching( + self, backend, monkeypatch + ): + # e.g. remote-already-exists fallback greps e.stderr for "already exists". + _install( + monkeypatch, + lambda b: json.dumps( + { + "jsonrpc": "2.0", + "id": 1, + "result": { + "isError": True, + "content": [ + { + "type": "text", + "text": "fatal: remote origin already exists", + } + ], + }, + } + ), + ) + try: + backend.remote_add(REPO, "origin", "http://x/y.git") + raise AssertionError("expected raise") + except subprocess.CalledProcessError as e: # caught as the contract type + assert "already exists" in (e.stderr or "") + + +class TestWrongShapeBodyFailsLoud: + """A valid-transport 200 with an unexpected body must NOT read as clean/empty — + that would silently corrupt cidx's git-state view.""" + + def test_unparseable_nonempty_body_raises(self, backend, monkeypatch): + _install(monkeypatch, lambda b: _rpc(_content_raw("not json at all"))) + with pytest.raises(GitMcpBackendError, match="unparseable body"): + backend.current_branch(REPO) + + def test_status_missing_buckets_raises_not_clean(self, backend, monkeypatch): + # `{}` would previously read as a CLEAN tree; now it fails loud. + _install(monkeypatch, lambda b: _rpc(_content({}))) + with pytest.raises(GitMcpBackendError, match="status buckets"): + backend.status_porcelain(REPO) + + def test_ls_files_missing_key_raises_not_empty(self, backend, monkeypatch): + _install(monkeypatch, lambda b: _rpc(_content({}))) + with pytest.raises(GitMcpBackendError, match="missing 'files'"): + backend.ls_files(REPO) + + def test_rev_parse_missing_output_raises(self, backend, monkeypatch): + _install(monkeypatch, lambda b: _rpc(_content({}))) + with pytest.raises(GitMcpBackendError, match="missing 'output'"): + backend.rev_parse(REPO, "HEAD") + + def test_list_branches_rejects_unsupported_fmt(self, backend, monkeypatch): + _install(monkeypatch, lambda b: _rpc(_content({"branches": []}))) + with pytest.raises(GitMcpBackendError, match="cannot honour fmt"): + backend.list_branches(REPO, fmt="%(objectname)") + + def test_list_branches_accepts_refname_short_fmt(self, backend, monkeypatch): + _install( + monkeypatch, + lambda b: _rpc(_content({"branches": [{"name": "main", "type": "local"}]})), + ) + assert backend.list_branches(REPO, fmt="%(refname:short)") == ["main"] + + +class TestCapabilities: + def test_owns_credentials_true(self, backend): + # the git service holds the token and injects it, so cidx must strip any credential + # before storing a URL — the PAT lives only in the git service. + assert backend.owns_credentials is True + + +class TestFactory: + def test_make_git_backend_reads_env(self, monkeypatch): + monkeypatch.setenv("CIDX_GIT_MCP_URL", "http://custom:9/") + monkeypatch.setenv("CIDX_GIT_MCP_TIMEOUT", "42") + b = plugin.make_git_backend() + assert b._url == "http://custom:9/v1/git/mcp" + assert b._timeout == 42.0 + + +class TestHistoryOps: + """cidx temporal history: paged log, batched diffs and object reads. + + the git service returns git's stdout base64-encoded; the plugin hands cidx those + exact bytes and fails as a local ``check=True`` run would. + """ + + @staticmethod + def _raw(stdout: bytes, exit_code: int = 0, stderr: str = "") -> dict: + import base64 + + return { + "exit_code": exit_code, + "stdout_b64": base64.b64encode(stdout).decode(), + "stderr": stderr, + } + + def test_log_raw_sends_a_page_and_returns_bytes(self, backend, monkeypatch): + calls = _install(monkeypatch, lambda b: _rpc(_content(self._raw(b"\xff\x1e")))) + out = backend.log_raw(REPO, "%H", ["abc"], since="2024-01-01", max_count=5) + assert out == b"\xff\x1e" + params = calls[0]["body"]["params"] + assert params["name"] == "git_log_raw" + assert params["arguments"] == { + "cow_path": REPO, + "format": "%H", + "revs": ["abc"], + "since": "2024-01-01", + "max_count": 5, + } + + def test_log_raw_git_failure_raises_with_git_stderr(self, backend, monkeypatch): + _install( + monkeypatch, + lambda b: _rpc(_content(self._raw(b"", 128, "fatal: bad object"))), + ) + with pytest.raises(GitMcpBackendError) as exc: + backend.log_raw(REPO, "%H") + assert exc.value.returncode == 128 + assert exc.value.stderr == "fatal: bad object" + + def test_for_each_ref_sends_one_call_and_returns_bytes(self, backend, monkeypatch): + calls = _install( + monkeypatch, lambda b: _rpc(_content(self._raw(b"main|\xff\n"))) + ) + out = backend.for_each_ref( + REPO, + "%(refname:short)|%(objectname)", + ["refs/heads/", "refs/remotes/origin/"], + sort="-committerdate", + count=5, + timeout=7, + ) + assert out == b"main|\xff\n" + assert len(calls) == 1 + params = calls[0]["body"]["params"] + assert params["name"] == "git_for_each_ref" + assert params["arguments"] == { + "cow_path": REPO, + "format": "%(refname:short)|%(objectname)", + "patterns": ["refs/heads/", "refs/remotes/origin/"], + "sort": "-committerdate", + "count": 5, + } + assert calls[0]["timeout"] == 7 + + def test_for_each_ref_omits_unset_options(self, backend, monkeypatch): + calls = _install(monkeypatch, lambda b: _rpc(_content(self._raw(b"")))) + assert backend.for_each_ref(REPO, "%(refname)") == b"" + assert calls[0]["body"]["params"]["arguments"] == { + "cow_path": REPO, + "format": "%(refname)", + } + + def test_for_each_ref_git_failure_raises_with_git_stderr( + self, backend, monkeypatch + ): + _install( + monkeypatch, + lambda b: _rpc(_content(self._raw(b"", 129, "error: unknown field"))), + ) + with pytest.raises(GitMcpBackendError) as exc: + backend.for_each_ref(REPO, "%(bogus)") + assert exc.value.returncode == 129 + assert exc.value.stderr == "error: unknown field" + + def test_for_each_ref_wrong_shape_fails_loud(self, backend, monkeypatch): + _install(monkeypatch, lambda b: _rpc(_content({"exit_code": 0}))) + with pytest.raises(GitMcpBackendError, match="stdout_b64"): + backend.for_each_ref(REPO, "%(refname)") + + def test_for_each_ref_tool_error_fails_loud(self, backend, monkeypatch): + _install( + monkeypatch, + lambda b: _rpc( + {"isError": True, "content": [{"type": "text", "text": "bad sort"}]} + ), + ) + with pytest.raises(GitMcpBackendError, match="bad sort"): + backend.for_each_ref(REPO, "%(refname)", sort="--x") + + def test_diff_commits_is_one_call_per_batch(self, backend, monkeypatch): + def respond(body): + pairs = body["params"]["arguments"]["pairs"] + return _rpc( + _content({"diffs": [self._raw(p["commit"].encode()) for p in pairs]}) + ) + + calls = _install(monkeypatch, respond) + pairs = [(f"{i:040x}", f"{i + 1:040x}") for i in range(300)] + out = backend.diff_commits(REPO, pairs, 5) + assert out == [c.encode() for _, c in pairs] + assert [len(c["body"]["params"]["arguments"]["pairs"]) for c in calls] == [ + 256, + 44, + ] + assert calls[0]["body"]["params"]["arguments"]["context_lines"] == 5 + + def test_diff_commits_raises_for_a_failed_item(self, backend, monkeypatch): + _install( + monkeypatch, + lambda b: _rpc(_content({"diffs": [self._raw(b"", 128, "bad object")]})), + ) + with pytest.raises(GitMcpBackendError, match="bad object"): + backend.diff_commits(REPO, [("a" * 40, "b" * 40)], 5) + + def test_diff_commits_rejects_a_short_answer(self, backend, monkeypatch): + _install(monkeypatch, lambda b: _rpc(_content({"diffs": []}))) + with pytest.raises(GitMcpBackendError, match="results for 1 items"): + backend.diff_commits(REPO, [("a" * 40, "b" * 40)], 5) + + def test_show_objects_returns_completed_processes(self, backend, monkeypatch): + calls = _install( + monkeypatch, + lambda b: _rpc( + _content( + { + "objects": [ + self._raw(b"\x00bin"), + self._raw(b"", 128, "fatal: path 'x' does not exist"), + ] + } + ) + ), + ) + out = backend.show_objects(REPO, [("a" * 40, "bin.dat"), ("a" * 40, "x")]) + assert calls[0]["body"]["params"]["arguments"]["specs"] == [ + {"rev": "a" * 40, "path": "bin.dat"}, + {"rev": "a" * 40, "path": "x"}, + ] + assert (out[0].returncode, out[0].stdout) == (0, b"\x00bin") + assert out[1].returncode == 128 and "does not exist" in out[1].stderr + + def test_a_wrong_shape_item_fails_loud(self, backend, monkeypatch): + _install(monkeypatch, lambda b: _rpc(_content({"objects": [{"exit_code": 0}]}))) + with pytest.raises(GitMcpBackendError, match="stdout_b64"): + backend.show_objects(REPO, [("a" * 40, "x")]) + + def test_stdout_that_is_not_base64_fails_loud(self, backend, monkeypatch): + _install( + monkeypatch, + lambda b: _rpc( + _content({"exit_code": 0, "stdout_b64": "!!!", "stderr": ""}) + ), + ) + with pytest.raises(GitMcpBackendError, match="not base64"): + backend.log_raw(REPO, "%H") + + +class TestGitToolsRunner: + """cidx's git tools on an activated copy: git_exec (raw, exit code + returned) and git_push (the git service's credentials).""" + + @staticmethod + def _raw(stdout: bytes, exit_code: int = 0, stderr: str = "") -> dict: + import base64 + + return { + "exit_code": exit_code, + "stdout_b64": base64.b64encode(stdout).decode(), + "stderr": stderr, + } + + def test_backend_is_a_git_command_runner(self, backend): + from code_indexer.server.storage.shared.git_backend import GitCommandRunner + + assert isinstance(backend, GitCommandRunner) + + def test_run_sends_git_exec_and_returns_text(self, backend, monkeypatch): + calls = _install( + monkeypatch, lambda b: _rpc(_content(self._raw(" M a.txt\n".encode()))) + ) + out = backend.run( + REPO, + ["status", "--porcelain"], + timeout=30, + identity={"author_name": "A", "author_email": "a@example.com"}, + ) + assert (out.returncode, out.stdout, out.args) == ( + 0, + " M a.txt\n", + ["git", "status", "--porcelain"], + ) + params = _tool_calls(calls)[0]["body"]["params"] + assert params["name"] == "git_exec" + assert params["arguments"] == { + "cow_path": REPO, + "args": ["status", "--porcelain"], + "timeout_seconds": 30, + "identity": {"author_name": "A", "author_email": "a@example.com"}, + } + + def test_run_returns_a_git_failure_instead_of_raising(self, backend, monkeypatch): + _install(monkeypatch, lambda b: _rpc(_content(self._raw(b"", 1, "fatal: x")))) + out = backend.run(REPO, ["checkout", "nope"]) + assert (out.returncode, out.stderr) == (1, "fatal: x") + + def test_run_omits_unset_options(self, backend, monkeypatch): + calls = _install(monkeypatch, lambda b: _rpc(_content(self._raw(b"")))) + backend.run(REPO, ["log"]) + assert _tool_calls(calls)[0]["body"]["params"]["arguments"] == { + "cow_path": REPO, + "args": ["log"], + } + + @staticmethod + def _local_text(raw: bytes, tmp_path) -> str: + """What a local ``subprocess.run(text=True)`` returns for *raw* stdout.""" + path = tmp_path / "stdout.bin" + path.write_bytes(raw) + return subprocess.run( + ["cat", str(path)], capture_output=True, text=True, check=True + ).stdout + + def test_run_decodes_exactly_as_a_local_run(self, backend, monkeypatch, tmp_path): + raw = "crlf\r\nlone cr\rünïcode – 日本\n".encode() + _install(monkeypatch, lambda b: _rpc(_content(self._raw(raw)))) + out = backend.run(REPO, ["diff"]) + assert out.stdout == self._local_text(raw, tmp_path) + assert out.stdout == "crlf\nlone cr\nünïcode – 日本\n" + + def test_run_undecodable_output_raises_as_a_local_run_does( + self, backend, monkeypatch, tmp_path + ): + raw = b"caf\xe9\n" + _install(monkeypatch, lambda b: _rpc(_content(self._raw(raw)))) + with pytest.raises(UnicodeDecodeError): + backend.run(REPO, ["diff"]) + with pytest.raises(UnicodeDecodeError): + self._local_text(raw, tmp_path) + + def test_run_transport_error_raises(self, backend, monkeypatch): + def boom(req, timeout=None): + raise urllib.error.URLError("refused") + + monkeypatch.setattr(plugin.urllib.request, "urlopen", boom) + with pytest.raises(GitMcpBackendError): + backend.run(REPO, ["status"]) + + def test_push_sends_git_push(self, backend, monkeypatch): + calls = _install( + monkeypatch, + lambda b: _rpc( + _content({"branch": "w", "_guidance": {"message": "Pushed w"}}) + ), + ) + out = backend.push(REPO, "origin", "w") + assert (out.returncode, out.stdout) == (0, "Pushed w") + params = calls[0]["body"]["params"] + assert params["name"] == "git_push" + assert params["arguments"] == { + "cow_path": REPO, + "remote": "origin", + "branch": "w", + } + + def test_push_tool_error_raises(self, backend, monkeypatch): + _install( + monkeypatch, + lambda b: _rpc( + {"isError": True, "content": [{"type": "text", "text": "rejected"}]} + ), + ) + with pytest.raises(GitMcpBackendError) as exc: + backend.push(REPO, "origin", "main") + assert exc.value.stderr == "rejected" + + +class TestPaginatedResultsRefused: + """the git service's response layer pages an oversized result and marks it with + ``_pagination``. A page is never the answer: every tool refuses it.""" + + @staticmethod + def _page(payload: dict) -> dict: + return {**payload, "_pagination": {"page": 1, "total_pages": 3}} + + def test_git_exec_page_is_an_error(self, backend, monkeypatch): + import base64 + + page = self._page( + { + "exit_code": 0, + "stdout_b64": base64.b64encode(b"a" * 30).decode(), + "stderr": "", + } + ) + _install(monkeypatch, lambda b: _rpc(_content(page))) + with pytest.raises(plugin.GitMcpPaginatedResultError, match="paginated"): + backend.run(REPO, ["log"]) + + def test_page_with_cut_base64_is_reported_as_pagination(self, backend, monkeypatch): + page = self._page({"exit_code": 0, "stdout_b64": "YWJj", "stderr": ""}) + page["stdout_b64"] = "YWJjZG" # cut mid-quantum, as a real page is + _install(monkeypatch, lambda b: _rpc(_content(page))) + with pytest.raises(plugin.GitMcpPaginatedResultError): + backend.log_raw(REPO, "%H") + + @pytest.mark.parametrize( + "call, payload", + [ + (lambda b: b.ls_files(REPO), {"files": ["a.py"]}), + (lambda b: b.remote_list(REPO), {"remotes": [{"name": "origin"}]}), + (lambda b: b.ls_remote("https://example.com/r.git"), {"reachable": True}), + ], + ) + def test_structured_tool_page_is_an_error( + self, backend, monkeypatch, call, payload + ): + _install(monkeypatch, lambda b: _rpc(_content(self._page(payload)))) + with pytest.raises(plugin.GitMcpPaginatedResultError): + call(backend) + + def test_page_in_a_later_content_chunk_is_an_error(self, backend, monkeypatch): + result = { + "content": [ + {"type": "text", "text": json.dumps({"reachable": True})}, + {"type": "text", "text": json.dumps({"_pagination": {"page": 1}})}, + ] + } + _install(monkeypatch, lambda b: _rpc(result)) + with pytest.raises(plugin.GitMcpPaginatedResultError): + backend.ls_remote("https://example.com/r.git") + + def test_pagination_error_is_a_backend_error(self): + assert issubclass(plugin.GitMcpPaginatedResultError, GitMcpBackendError) + + def test_the_word_alone_in_output_is_not_a_page(self, backend, monkeypatch): + """A commit subject mentioning _pagination is data, not the marker.""" + import base64 + + raw = { + "exit_code": 0, + "stdout_b64": base64.b64encode(b"fix _pagination bug\n").decode(), + "stderr": "", + } + _install(monkeypatch, lambda b: _rpc(_content(raw))) + assert backend.run(REPO, ["log"]).stdout == "fix _pagination bug\n" + + +def _raw_body( + stdout: bytes, + exit_code: object = 0, + stderr: str = "", + **overrides: object, +) -> bytes: + trailer = { + "exit_code": exit_code, + "stderr": stderr, + "stdout_bytes": len(stdout), + "truncated": False, + "timed_out": False, + } + trailer.update(overrides) + return stdout + b"\x00" + json.dumps(trailer).encode() + + +def _no_mcp(body): + raise AssertionError("MCP git_exec used although raw exec answered") + + +class TestRawExec: + """``run`` goes through the git service's raw exec endpoint, falling back to MCP + ``git_exec`` only for a the git service without it (404) or without its secret + (503). A partial answer is never accepted.""" + + def test_raw_request_and_exact_bytes(self, monkeypatch): + backend = GitMcpBackend(base_url="http://the git service:3000", token="s3cret") + calls = _install( + monkeypatch, _no_mcp, raw=lambda b: _raw_body(b"a\x00b\r\nc\n") + ) + out = backend.run( + REPO, + ["blame", "--porcelain", "--", "a.py"], + timeout=20, + identity={"author_name": "A"}, + ) + assert (out.returncode, out.stdout) == (0, "a\x00b\nc\n") + assert out.args == ["git", "blame", "--porcelain", "--", "a.py"] + (call,) = calls + assert call["req"].full_url == "http://the git service:3000/v1/git/exec/raw" + assert call["req"].headers["Authorization"] == "Bearer s3cret" + assert call["timeout"] == 50 + assert call["body"] == { + "cow_path": REPO, + "args": ["blame", "--porcelain", "--", "a.py"], + "timeout_seconds": 20, + "identity": {"author_name": "A"}, + } + + @pytest.mark.parametrize("given,sent", [(14.2, 15), (0.3, 1), (30, 30)]) + def test_a_fractional_timeout_rounds_up(self, backend, monkeypatch, given, sent): + calls = _install(monkeypatch, _no_mcp, raw=lambda b: _raw_body(b"")) + backend.run(REPO, ["log"], timeout=given) + assert calls[0]["body"]["timeout_seconds"] == sent + + def test_git_failure_is_returned_not_raised(self, backend, monkeypatch): + _install(monkeypatch, _no_mcp, raw=lambda b: _raw_body(b"", 128, "fatal: x")) + out = backend.run(REPO, ["show", "nope"]) + assert (out.returncode, out.stderr) == (128, "fatal: x") + + @pytest.mark.parametrize("code", [404, 503]) + def test_missing_endpoint_or_secret_falls_back_and_is_remembered( + self, backend, monkeypatch, code + ): + import base64 + + raw_calls = [] + + def raw(body): + raw_calls.append(body) + return _http_error("http://the git service:3000/v1/git/exec/raw", code, {}) + + mcp = {"exit_code": 0, "stdout_b64": base64.b64encode(b"ok\n").decode()} + calls = _install(monkeypatch, lambda b: _rpc(_content(mcp)), raw=raw) + assert backend.run(REPO, ["log"]).stdout == "ok\n" + assert backend.run(REPO, ["log"]).stdout == "ok\n" + assert len(raw_calls) == 1 # not asked again within the retry window + assert len(_tool_calls(calls)) == 2 + monkeypatch.setattr( + plugin.time, "monotonic", lambda: backend._raw_unavailable_until + 1 + ) + backend.run(REPO, ["log"]) + assert len(raw_calls) == 2 # and asked again after it + + def test_a_token_bearing_backend_falls_back_on_503(self, monkeypatch): + """The production failure mode: cidx holds a token but the git service has no + shared secret configured (or it was rotated away) -- 503, not 401.""" + import base64 + + backend = GitMcpBackend(base_url="http://the git service:3000", token="s3cret") + mcp = {"exit_code": 0, "stdout_b64": base64.b64encode(b"ok\n").decode()} + calls = _install( + monkeypatch, + lambda b: _rpc(_content(mcp)), + raw=lambda b: _http_error( + "http://the git service:3000/v1/git/exec/raw", 503, {"message": "no secret"} + ), + ) + assert backend.run(REPO, ["log"]).stdout == "ok\n" + assert calls[0]["req"].headers["Authorization"] == "Bearer s3cret" + assert calls[-1]["req"].headers["Authorization"] == "Bearer s3cret" + + @pytest.mark.parametrize( + "code,error", + [ + (400, GitMcpBackendError), + (401, GitMcpBackendError), + (504, plugin.GitMcpTimeoutError), + ], + ) + def test_a_refusal_raises_and_never_falls_back( + self, backend, monkeypatch, code, error + ): + _install( + monkeypatch, + _no_mcp, + raw=lambda b: _http_error( + "http://the git service:3000/v1/git/exec/raw", + code, + {"message": "git subcommand not allowed"}, + ), + ) + with pytest.raises(error) as raised: + backend.run(REPO, ["gc"]) + if code == 400: + assert raised.value.stderr == "git subcommand not allowed" + + @pytest.mark.parametrize( + "body,error", + [ + (b"partial output, connection cut", GitMcpBackendError), + (b"out\x00{not json", GitMcpBackendError), + (_raw_body(b"out", None), GitMcpBackendError), + (_raw_body(b"out", "0"), GitMcpBackendError), + (_raw_body(b"out", 0, truncated=True), plugin.GitMcpOutputTooLargeError), + (_raw_body(b"out", None, timed_out=True), plugin.GitMcpTimeoutError), + (_raw_body(b"out", 0, error="spawn failed"), GitMcpBackendError), + (_raw_body(b"out", 0, stdout_bytes=10), GitMcpBackendError), + (_raw_body(b"out", 0, truncated=None), GitMcpBackendError), + ], + ids=[ + "no-trailer", + "bad-trailer", + "null-exit", + "string-exit", + "truncated", + "timed-out", + "error", + "short", + "no-flag", + ], + ) + def test_an_incomplete_answer_is_never_accepted( + self, backend, monkeypatch, body, error + ): + _install(monkeypatch, _no_mcp, raw=lambda b: body) + with pytest.raises(error): + backend.run(REPO, ["log"]) + + def test_the_split_is_at_the_last_nul(self, backend, monkeypatch): + stdout = b"a\x00b\x00" + _install(monkeypatch, _no_mcp, raw=lambda b: _raw_body(stdout)) + assert backend.run(REPO, ["ls-files", "-z"]).stdout == "a\x00b\x00" + + def test_a_raw_timeout_is_a_typed_timeout(self, backend, monkeypatch): + import socket + + def raw(body): + return urllib.error.URLError(socket.timeout("timed out")) + + _install(monkeypatch, _no_mcp, raw=raw) + with pytest.raises(plugin.GitMcpTimeoutError): + backend.run(REPO, ["log"], timeout=5) + + def test_output_too_large_from_a_byte_tool_is_typed(self, backend, monkeypatch): + _install( + monkeypatch, + lambda b: _rpc( + { + "isError": True, + "content": [ + { + "type": "text", + "text": json.dumps( + {"code": "OUTPUT_TOO_LARGE", "message": "over 128 MiB"} + ), + } + ], + } + ), + ) + with pytest.raises(plugin.GitMcpOutputTooLargeError): + backend.log_raw(REPO, "%H") + + def test_typed_tools_never_use_raw(self, backend, monkeypatch): + calls = _install(monkeypatch, lambda b: _rpc(_content({"reachable": True}))) + backend.ls_remote("https://example.com/r.git") + assert [c["req"].full_url for c in calls] == ["http://the git service:3000/v1/git/mcp"] + + +def _auto_page(payload: dict, path: str, kept: int) -> dict: + """*payload* as @example/mcp-tools' autoPage cuts it: the list at + *path* sliced to *kept* items, the scalars untouched, a ``_pagination`` + block naming the cut list.""" + full = payload[path] + return { + **payload, + path: full[:kept], + "_pagination": { + "truncated": True, + "totalItems": len(full), + "returnedItems": kept, + "offset": 0, + "nextOffset": kept, + "arrayKey": path, + "path": path, + "hint": "Response exceeded 80000 bytes.", + }, + } + + +def _too_large(body) -> str: + """A byte tool refusing output over the MCP ceiling.""" + return _rpc( + { + "isError": True, + "content": [ + { + "type": "text", + "text": json.dumps( + {"code": "OUTPUT_TOO_LARGE", "message": "over 80000"} + ), + } + ], + } + ) + + +def _raw_requests(calls): + return [c["body"] for c in calls if c["req"].full_url.endswith("/v1/git/exec/raw")] + + +class TestLsRemoteManyRefs: + """a remote with ~900 refs (fresca) made git_ls_remote's ref list + exceed the git service's MCP ceiling; the page was refused and cidx reported the + repo as invalid. Only ``reachable`` is read, and a page cut at ``refs`` + keeps it whole.""" + + _REFS = [{"sha": f"{i:040x}", "ref": f"refs/heads/b{i}"} for i in range(919)] + + def test_page_cut_at_refs_answers_reachable(self, backend, monkeypatch): + page = _auto_page( + {"reachable": True, "ref_count": 919, "refs": self._REFS}, "refs", 600 + ) + calls = _install(monkeypatch, lambda b: _rpc(_content(page))) + assert backend.ls_remote("https://example.com/fresca.git") is True + assert _raw_requests(calls) == [] + + def test_page_cut_at_refs_still_reports_unreachable(self, backend, monkeypatch): + page = _auto_page({"reachable": False, "refs": [{"ref": "x"}]}, "refs", 1) + _install(monkeypatch, lambda b: _rpc(_content(page))) + assert backend.ls_remote("https://example.com/r.git") is False + + def test_page_cut_elsewhere_is_an_error(self, backend, monkeypatch): + page = _auto_page( + {"reachable": True, "refs": [], "other": [1, 2, 3]}, "other", 1 + ) + _install(monkeypatch, lambda b: _rpc(_content(page))) + with pytest.raises(plugin.GitMcpPaginatedResultError): + backend.ls_remote("https://example.com/r.git") + + def test_page_without_reachable_is_an_error(self, backend, monkeypatch): + page = _auto_page({"refs": [{"ref": "a"}, {"ref": "b"}]}, "refs", 1) + _install(monkeypatch, lambda b: _rpc(_content(page))) + with pytest.raises(GitMcpBackendError, match="reachable"): + backend.ls_remote("https://example.com/r.git") + + def test_other_tools_never_accept_a_page_cut_at_refs(self, backend, monkeypatch): + page = _auto_page({"remotes": [], "refs": [1, 2]}, "refs", 1) + _install(monkeypatch, lambda b: _rpc(_content(page))) + with pytest.raises(plugin.GitMcpPaginatedResultError): + backend.remote_list(REPO) + + +class TestLargeOutputThroughRawExec: + """A read whose MCP answer is over the ceiling (a page, or a byte tool's + OUTPUT_TOO_LARGE) re-runs the same git command through raw exec: the whole + output, or an error -- never the page.""" + + @staticmethod + def _paged(key: str): + payload = {key: [f"p{i}" for i in range(5)]} + return lambda b: _rpc(_content(_auto_page(payload, key, 2))) + + def test_ls_files(self, backend, monkeypatch): + calls = _install( + monkeypatch, + self._paged("files"), + raw=lambda b: _raw_body(b"a.py\nsrc/b.py\n"), + ) + assert backend.ls_files(REPO) == ["a.py", "src/b.py"] + (req,) = _raw_requests(calls) + assert req["cow_path"] == REPO + assert req["args"] == ["ls-files"] + + def test_diff_name_only_keeps_nul_delimited_paths(self, backend, monkeypatch): + calls = _install( + monkeypatch, + self._paged("files"), + raw=lambda b: _raw_body("a b.py\x00ü.py\x00".encode()), + ) + assert backend.diff_name_only(REPO, "A..B") == ["a b.py", "ü.py"] + assert _raw_requests(calls)[0]["args"] == [ + "diff", + "--name-only", + "-z", + "A..B", + ] + + @pytest.mark.parametrize( + "kwargs, scope", + [({}, []), ({"remote": True}, ["-r"]), ({"all_refs": True}, ["-a"])], + ) + def test_list_branches(self, backend, monkeypatch, kwargs, scope): + calls = _install( + monkeypatch, + self._paged("branches"), + raw=lambda b: _raw_body(b"main\norigin/dev\n\n"), + ) + assert backend.list_branches(REPO, **kwargs) == ["main", "origin/dev"] + assert _raw_requests(calls)[0]["args"] == [ + "branch", + *scope, + "--format=%(refname:short)", + ] + + def test_status_porcelain_is_gits_own(self, backend, monkeypatch): + calls = _install( + monkeypatch, + self._paged("untracked"), + raw=lambda b: _raw_body(b" M a.py\n?? c.py\n"), + ) + assert backend.status_porcelain(REPO) == " M a.py\n?? c.py\n" + assert _raw_requests(calls)[0]["args"] == ["status", "--porcelain"] + + def test_for_each_ref_too_large_returns_exact_bytes(self, backend, monkeypatch): + listing = b"refs/heads/a\x00abc\n" * 3 + calls = _install(monkeypatch, _too_large, raw=lambda b: _raw_body(listing)) + out = backend.for_each_ref( + REPO, + "%(refname)%00%(objectname)", + ["refs/heads", "refs/remotes/origin"], + sort="-committerdate", + count=5, + timeout=10, + ) + assert out == listing + req = _raw_requests(calls)[0] + assert req["args"] == [ + "for-each-ref", + "--format=%(refname)%00%(objectname)", + "--sort=-committerdate", + "--count=5", + "--", + "refs/heads", + "refs/remotes/origin", + ] + assert req["timeout_seconds"] == 10 + + def test_log_raw_too_large_returns_exact_bytes(self, backend, monkeypatch): + calls = _install( + monkeypatch, _too_large, raw=lambda b: _raw_body(b"c1\r\nc2\n") + ) + out = backend.log_raw( + REPO, + "%H", + ["main"], + all_refs=True, + since="2020-01-01", + skip=4, + max_count=50, + ) + assert out == b"c1\r\nc2\n" + assert _raw_requests(calls)[0]["args"] == [ + "log", + "--format=%H", + "--all", + "--since=2020-01-01", + "--skip=4", + "--max-count=50", + "main", + "--", + ] + + def test_small_results_never_use_raw(self, backend, monkeypatch): + calls = _install(monkeypatch, lambda b: _rpc(_content({"files": ["a"]}))) + assert backend.ls_files(REPO) == ["a"] + assert _raw_requests(calls) == [] + + def test_truncated_raw_output_is_an_error(self, backend, monkeypatch): + _install( + monkeypatch, + self._paged("files"), + raw=lambda b: _raw_body(b"a.py\n", truncated=True), + ) + with pytest.raises(plugin.GitMcpOutputTooLargeError): + backend.ls_files(REPO) + + def test_git_failure_raises_like_check_true(self, backend, monkeypatch): + _install( + monkeypatch, + _too_large, + raw=lambda b: _raw_body(b"", exit_code=128, stderr="fatal: bad ref"), + ) + with pytest.raises(GitMcpBackendError) as exc: + backend.for_each_ref(REPO, "%(refname)") + assert exc.value.returncode == 128 + assert exc.value.stderr == "fatal: bad ref" + + def test_no_raw_endpoint_and_mcp_too_large_is_an_error(self, backend, monkeypatch): + # A the git service without raw exec (404) falls back to MCP git_exec, which + # refuses the same oversized output: an error, never the first page. + def responder(body): + if body["params"]["name"] == "git_exec": + return _too_large(body) + return self._paged("files")(body) + + _install(monkeypatch, responder) + with pytest.raises(plugin.GitMcpOutputTooLargeError): + backend.ls_files(REPO) diff --git a/plugins/cidx_orchestrator_invoker/cidx_orchestrator_invoker/__init__.py b/plugins/cidx_orchestrator_invoker/cidx_orchestrator_invoker/__init__.py new file mode 100644 index 000000000..723c1f7ab --- /dev/null +++ b/plugins/cidx_orchestrator_invoker/cidx_orchestrator_invoker/__init__.py @@ -0,0 +1,402 @@ +""" +Run cidx's description/analysis prompts as agent-orchestrator jobs. + +cidx dispatches every description/analysis LLM call -- golden-repo registration +lifecycle, dep-map passes, description refresh, self-monitoring -- through one +CliDispatcher, whose primary invoker normally shells out to the ``claude`` CLI. +In a clustered deployment the CLI is deliberately NOT in the cidx image: LLM +execution belongs inside the orchestrator's sandboxed worker, not in a +long-lived service pod. Without a replacement, every ``lifecycle_registration`` +job died with ``ClaudeInvoker: non-zero exit 127`` and ``/health`` degraded. + +This module provides an ``IntelligenceCliInvoker`` that satisfies cidx's plugin +seam (``code_indexer.cli_invoker``) by handing the prompt to the orchestrator: + + POST /auth/login -> JWT (cached, 8h; a 401 forces one re-auth) + POST /jobs/with-capabilities -> jobId (429 honours retryAfterSeconds) + GET /jobs/{jobId} -> poll to terminal -> InvocationResult + +The orchestrator runs the agent in its own sandbox, so Claude never runs in the +cidx image. Blocking is fine: the dispatcher already blocks on a subprocess in a +worker thread, so polling occupies the same thread for the same budget. + +Configuration (env) +------------------- +CIDX_ORCH_URL Orchestrator base URL. + Default: http://localhost:3001 +CIDX_ORCH_USER Orchestrator username (default: admin). +CIDX_ORCH_PASSWORD Orchestrator password. REQUIRED. +CIDX_ORCH_MODEL Overrides the model cidx passes (default: cidx's analysis_model). +CIDX_ORCH_POLL_SECS Poll interval (default: 5). + +Enable with: + CIDX_CLI_INVOKER=cidx_orchestrator_invoker:make_invoker +(installing the package also registers it on the code_indexer.cli_invoker +entry point, so setting the env var is optional.) +""" + +from __future__ import annotations + +import json +import logging +import os +import re +import subprocess +import threading +import time +import urllib.error +import urllib.request +import uuid +from typing import Any, Dict, Optional + +# The seam's types and the core's repository source come from the SDK: a +# delegate depends on cidx-sdk only, never on the core (plugins-no-kernel). +from cidx_sdk.seams.cli_invoker import ( + REPOSITORY_SOURCE, + FailureClass, + InvocationResult, +) + +logger = logging.getLogger(__name__) + +DEFAULT_URL = "http://localhost:3001" +TERMINAL = {"completed", "failed", "cancelled", "error"} + +_URL_CREDENTIALS_RE = re.compile(r"(://)[^/@\s]+@") + +CLI_USED = "orchestrator" + +#: cidx's gate (cli_invoker_plugin.invoker_resolves_golden_repositories): this +#: invoker provisions a golden repository itself -- the orchestrator's agent +#: opens it from the registered remote -- and never reads the cwd it is handed, +#: so lifecycle/description analysis can run on a pod without the repository. +RESOLVES_GOLDEN_REPOSITORIES = True + + +class OrchestratorInvoker: + """IntelligenceCliInvoker backed by the orchestration layer. + + invoke(flow, cwd, prompt, timeout, max_turns) -> InvocationResult. + Never raises: the dispatcher expects a well-typed result, never an exception. + """ + + def __init__( + self, analysis_model: str = "opus", soft_timeout_seconds: Optional[int] = None + ) -> None: + self._model = os.environ.get("CIDX_ORCH_MODEL") or analysis_model + self._soft_timeout = soft_timeout_seconds + # The orchestrator caps concurrent jobs (MAX_CONCURRENT) and answers 429 + # with a retryAfterSeconds hint. cidx fans dep-map/lifecycle work across + # threads, so serialise submits to avoid stampeding into that cap. + self._submit_lock = threading.Lock() + self._token: Optional[str] = None + self._token_lock = threading.Lock() + + # ── HTTP ───────────────────────────────────────────────────────────────── + def _base_url(self) -> str: + return os.environ.get("CIDX_ORCH_URL", DEFAULT_URL).rstrip("/") + + def _request( + self, + path: str, + *, + method: str = "GET", + body: Optional[Dict[str, Any]] = None, + token: Optional[str] = None, + timeout: int = 30, + ) -> Dict[str, Any]: + headers = {"Content-Type": "application/json"} + if token: + headers["Authorization"] = "Bearer " + token + data = json.dumps(body).encode() if body is not None else None + req = urllib.request.Request( + self._base_url() + path, data=data, headers=headers, method=method + ) + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + return json.loads(raw) if raw else {} + + def _login(self, force: bool = False) -> str: + with self._token_lock: + if self._token and not force: + return self._token + password = os.environ.get("CIDX_ORCH_PASSWORD") + if not password: + raise _OrchError( + "CIDX_ORCH_PASSWORD is not set; cannot authenticate to the orchestrator" + ) + payload = self._request( + "/auth/login", + method="POST", + body={ + "username": os.environ.get("CIDX_ORCH_USER", "admin"), + "password": password, + }, + ) + token = payload.get("token") + if not token: + raise _OrchError("orchestrator /auth/login returned no token") + self._token = str(token) + return self._token + + @staticmethod + def _resolve_repo(cwd: str) -> Dict[str, Any]: + """The repository the orchestrator provisions for a job about *cwd*. + + On a pod without the repositories (cidx ``content_backend: + delegated``) *cwd* holds index state only: the repository is resolved + from cidx's golden registry (registered remote + branch) and the git service + (the commit cidx indexed) -- see :func:`_resolve_golden_repo`. Otherwise + it is read from the clone at *cwd*, as below. Which case applies is + the core's answer in ``cidx_sdk.seams.cli_invoker.REPOSITORY_SOURCE``; + with no core in the process (this plugin's own tests) *cwd* is a clone. + """ + source = REPOSITORY_SOURCE.get() + if source is not None and not source.holds_repositories(): + return _resolve_golden_repo(cwd) + return OrchestratorInvoker._resolve_local_repo(cwd) + + @staticmethod + def _resolve_local_repo(cwd: str) -> Dict[str, Any]: + """Resolve the git origin URL + current branch of the repo at cwd. + + cidx's dispatcher passes a LOCAL path (the golden-repo clone on the cidx + pod's volume). That path is NOT reachable from the orchestrator's + sandboxed worker, so without this the agent runs in an empty workspace + and analyzes nothing. We read the repo's origin here (cidx HAS the clone) + and hand the orchestrator a repoUrl + branch so it provisions the real + repo in its own sandbox (gitAware). Returns {} when cwd is not a git + repo with an origin -- the agent then runs against whatever prompt + context it was given, as before. + """ + try: + url = subprocess.run( + ["git", "-C", cwd, "config", "--get", "remote.origin.url"], + capture_output=True, + text=True, + timeout=10, + ) + if url.returncode != 0 or not url.stdout.strip(): + return {} + branch = subprocess.run( + ["git", "-C", cwd, "rev-parse", "--abbrev-ref", "HEAD"], + capture_output=True, + text=True, + timeout=10, + ) + raw_url = url.stdout.strip() + info: Dict[str, Any] = { + "repoUrl": _URL_CREDENTIALS_RE.sub(r"\1", raw_url), + } + b = branch.stdout.strip() + if branch.returncode == 0 and b and b != "HEAD": + info["branch"] = b + return info + except Exception as exc: # noqa: BLE001 - best-effort; fall back to no repo + logger.warning("could not resolve repo from cwd %s: %s", cwd, exc) + return {} + + # ── job lifecycle ──────────────────────────────────────────────────────── + def _submit(self, prompt: str, cwd: str, timeout: int) -> str: + job_id = str(uuid.uuid4()) + repo = self._resolve_repo(cwd) + options: Dict[str, Any] = { + "agentEngine": "claude", + "model": self._model, + "timeout": timeout, + # Return ONLY the agent's final message, matching plain `claude -p`. + # Without this the orchestrator returns the full rendered agentic + # transcript (tool-call trace + answer), and cidx's + # UnifiedResponseParser -- which takes the first `{` -- hits an early + # tool-call brace instead of the final structured answer. + # Requires agent-orchestrator master 2aef293 or later. + "outputMode": "result", + "cidxAware": False, + # gitAware provisions the repo in the orchestrator's sandbox (via + # the content service) from the top-level repoUrl/branch below. On when we + # resolved a URL (so the agent analyzes real content), off otherwise. + "gitAware": bool(repo), + } + + body: Dict[str, Any] = { + "jobId": job_id, + "prompt": prompt, + "options": options, + "metadata": {"source": "cidx", "cwd": cwd}, + } + # repoUrl/branch are TOP-LEVEL body fields (not options): the orchestrator + # reads them there to scope the job's the content service JWT to this repo and + # provision it into the agent's sandbox. + if repo: + body["repoUrl"] = repo["repoUrl"] + if "branch" in repo: + body["branch"] = repo["branch"] + if "commit" in repo: + # The orchestrator opens repoUrl@branch; the commit cidx indexed + # pins the analysis to what the index describes. + body["metadata"]["commit"] = repo["commit"] + body["systemPrompt"] = _pinned_commit_instructions(repo) + deadline = time.monotonic() + timeout + while True: + token = self._login() + try: + with self._submit_lock: + resp = self._request( + "/jobs/with-capabilities", + method="POST", + body=body, + token=token, + ) + return str(resp.get("jobId") or job_id) + except urllib.error.HTTPError as exc: + if exc.code == 401: + self._login(force=True) + continue + if exc.code == 429: + try: + wait = int( + json.loads(exc.read().decode("utf-8")).get( + "retryAfterSeconds", 10 + ) + ) + except Exception: # noqa: BLE001 - malformed body -> default + wait = 10 + if time.monotonic() + wait > deadline: + raise _OrchError( + "orchestrator at capacity (429) and the job budget expired" + ) from exc + logger.info( + "orchestrator at capacity; retrying submit in %ss", wait + ) + time.sleep(wait) + continue + raise _OrchError( + f"orchestrator rejected the job: HTTP {exc.code}" + ) from exc + + def _await(self, job_id: str, deadline: float, poll_secs: int) -> InvocationResult: + while True: + if time.monotonic() > deadline: + return _failure( + f"orchestrator job {job_id} did not finish before the timeout", + FailureClass.RETRYABLE_ON_SAME, + ) + try: + state = self._request(f"/jobs/{job_id}", token=self._login()) + except urllib.error.HTTPError as exc: + if exc.code == 401: + self._login(force=True) + continue + raise _OrchError( + f"orchestrator job {job_id}: poll failed HTTP {exc.code}" + ) from exc + + result = state.get("result") or {} + status = state.get("status") or result.get("status") + if status not in TERMINAL: + time.sleep(poll_secs) + continue + + output = result.get("output") or "" + if status == "completed" and int(result.get("exitCode", 0)) == 0: + return InvocationResult( + success=True, + output=output, + error="", + cli_used=CLI_USED, + was_failover=False, + ) + error = result.get("error") or output or "no error detail" + return _failure( + f"orchestrator job {job_id} {status}: {error}", + FailureClass.RETRYABLE_ON_OTHER, + ) + + # ── IntelligenceCliInvoker ─────────────────────────────────────────────── + def invoke( + self, flow: str, cwd: str, prompt: str, timeout: int, max_turns: int = 0 + ) -> InvocationResult: + try: + job_id = self._submit(prompt, cwd, timeout) + logger.info( + "orchestrator job %s submitted (flow=%s, cwd=%s)", job_id, flow, cwd + ) + poll_secs = int(os.environ.get("CIDX_ORCH_POLL_SECS", "5")) + res = self._await(job_id, time.monotonic() + timeout, poll_secs) + logger.info( + "orchestrator job %s finished success=%s (%d chars)", + job_id, + res.success, + len(res.output), + ) + return res + except _OrchError as exc: + logger.error("orchestrator invocation failed: %s", exc) + return _failure(str(exc), FailureClass.RETRYABLE_ON_SAME) + except Exception as exc: # noqa: BLE001 - must never escape into the dispatcher + logger.exception("orchestrator invocation crashed") + return _failure( + f"orchestrator invocation crashed: {exc}", + FailureClass.RETRYABLE_ON_OTHER, + ) + + +def _resolve_golden_repo(cwd: str) -> Dict[str, Any]: + """The golden repository behind *cwd* on a pod that does not hold it. + + ``{}`` when *cwd* is no golden repo (the job is about no repository). + Otherwise ``repoUrl`` (credentials stripped), ``branch`` and ``commit``. + A registry or the git service failure RAISES (GoldenRepoSourceError): handing the + agent no repository would publish a description of an empty tree. + """ + repository_source = REPOSITORY_SOURCE.get() + if repository_source is None: + raise _OrchError( + "no repository source is installed: cannot resolve the golden " + f"repository behind {cwd} on a pod that does not hold it" + ) + source = repository_source.golden_repository(cwd) + if source is None: + return {} + return { + "repoUrl": _URL_CREDENTIALS_RE.sub(r"\1", source["repoUrl"]), + "branch": source["branch"], + "commit": source["commit"], + } + + +def _pinned_commit_instructions(repo: Dict[str, Any]) -> str: + """System-prompt lines pinning the agent to the commit cidx indexed.""" + return ( + "## Repository under analysis\n" + f"Analyze {repo['repoUrl']} on branch {repo['branch']} at commit " + f"{repo['commit']} -- the commit cidx indexed. After opening the " + "repository, check out that commit in your workspace before reading any " + "file. Any absolute path named in the task is cidx's own path and is " + "not reachable from here: read the repository only through the opened " + "workspace.\n" + ) + + +class _OrchError(RuntimeError): + """Internal: orchestrator unreachable or refused the job.""" + + +def _failure(msg: str, fclass: FailureClass) -> InvocationResult: + return InvocationResult( + success=False, + output="", + error=msg, + cli_used=CLI_USED, + was_failover=False, + failure_class=fclass, + ) + + +def make_invoker( + analysis_model: str = "opus", soft_timeout_seconds: Optional[int] = None +) -> OrchestratorInvoker: + """Factory matching cidx's code_indexer.cli_invoker plugin contract.""" + return OrchestratorInvoker( + analysis_model=analysis_model, soft_timeout_seconds=soft_timeout_seconds + ) diff --git a/plugins/cidx_orchestrator_invoker/pyproject.toml b/plugins/cidx_orchestrator_invoker/pyproject.toml new file mode 100644 index 000000000..6ffb20dac --- /dev/null +++ b/plugins/cidx_orchestrator_invoker/pyproject.toml @@ -0,0 +1,24 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "cidx-orchestrator-invoker" +version = "0.1.0" +description = "Run cidx's LLM prompts as orchestration layer jobs instead of a local claude CLI subprocess" +requires-python = ">=3.10" +# A delegate depends on the SDK only (its seam types and the core's repository +# source), never on the core. By path, like every in-repo distribution. +dependencies = ["cidx-sdk @ {root:parent:parent:uri}/packages/cidx-sdk"] + +# Registers on cidx's code_indexer.cli_invoker seam, so the plugin is active as +# soon as it is installed. CIDX_CLI_INVOKER=cidx_orchestrator_invoker:make_invoker +# is an equivalent override and takes precedence. +[project.entry-points."code_indexer.cli_invoker"] +orchestrator = "cidx_orchestrator_invoker:make_invoker" + +[tool.hatch.metadata] +allow-direct-references = true + +[tool.hatch.build.targets.wheel] +packages = ["cidx_orchestrator_invoker"] diff --git a/plugins/cidx_orchestrator_invoker/test_cidx_orchestrator_invoker.py b/plugins/cidx_orchestrator_invoker/test_cidx_orchestrator_invoker.py new file mode 100644 index 000000000..e41329bfd --- /dev/null +++ b/plugins/cidx_orchestrator_invoker/test_cidx_orchestrator_invoker.py @@ -0,0 +1,309 @@ +""" +Tests for the orchestrator-backed IntelligenceCliInvoker. + +The dispatcher contract is unforgiving: invoke(...) must return an +InvocationResult and NEVER raise. This invoker runs inside a cidx background job +(golden-repo registration, dep-map); an escaping exception fails that job, which +is the exact failure mode -- exit 127 from a missing `claude` CLI -- the plugin +exists to cure. On failure it must classify the failure so the dispatcher's +retry/failover logic behaves. +""" + +from __future__ import annotations + +import io +import json +import urllib.error + +import pytest + +import cidx_orchestrator_invoker as plugin +from code_indexer.server.services.intelligence_cli_invoker import ( + FailureClass, + InvocationResult, +) + + +@pytest.fixture() +def invoker(monkeypatch): + monkeypatch.setenv("CIDX_ORCH_PASSWORD", "secret") + monkeypatch.setenv("CIDX_ORCH_POLL_SECS", "0") + return plugin.make_invoker("opus", 300) + + +def _http_error(code: int, body: dict | None = None) -> urllib.error.HTTPError: + payload = json.dumps(body or {}).encode() + return urllib.error.HTTPError( + url="http://orch", code=code, msg="err", hdrs=None, fp=io.BytesIO(payload) + ) + + +class TestContract: + def test_make_invoker_satisfies_the_protocol(self, invoker): + from code_indexer.server.services.intelligence_cli_invoker import ( + IntelligenceCliInvoker, + ) + + assert isinstance(invoker, IntelligenceCliInvoker) + + def test_model_override_env_wins(self, monkeypatch): + monkeypatch.setenv("CIDX_ORCH_PASSWORD", "x") + monkeypatch.setenv("CIDX_ORCH_MODEL", "sonnet") + inv = plugin.make_invoker("opus", 300) + assert inv._model == "sonnet" + + +class TestHappyPath: + def test_submits_polls_and_returns_output(self, invoker, monkeypatch): + seen = [] + + def fake_request(path, *, method="GET", body=None, token=None, timeout=30): + seen.append((method, path)) + if path == "/auth/login": + return {"token": "jwt"} + if path == "/jobs/with-capabilities": + assert body["prompt"] == "describe the repo" + assert body["options"]["model"] == "opus" + assert body["options"]["outputMode"] == "result" + return {"jobId": "job-1"} + return { + "status": "completed", + "result": {"status": "completed", "exitCode": 0, "output": "DESC"}, + } + + monkeypatch.setattr(invoker, "_request", fake_request) + + res = invoker.invoke("describe", "/repo", "describe the repo", 300) + + assert isinstance(res, InvocationResult) + assert res.success is True + assert res.output == "DESC" + assert res.cli_used == "orchestrator" + assert ("POST", "/jobs/with-capabilities") in seen + + def test_polls_until_terminal(self, invoker, monkeypatch): + states = iter( + [ + {"status": "queued"}, + {"status": "running"}, + { + "status": "completed", + "result": {"status": "completed", "exitCode": 0, "output": "ok"}, + }, + ] + ) + + def fake_request(path, *, method="GET", body=None, token=None, timeout=30): + if path == "/auth/login": + return {"token": "t"} + if path == "/jobs/with-capabilities": + return {"jobId": "j"} + return next(states) + + monkeypatch.setattr(invoker, "_request", fake_request) + assert invoker.invoke("f", "/r", "p", 300).success is True + + +class TestFailuresNeverRaise: + def test_agent_job_failed_is_retryable_on_other(self, invoker, monkeypatch): + def fake_request(path, *, method="GET", body=None, token=None, timeout=30): + if path == "/auth/login": + return {"token": "t"} + if path == "/jobs/with-capabilities": + return {"jobId": "j"} + return { + "status": "failed", + "result": {"status": "failed", "exitCode": 1, "error": "boom"}, + } + + monkeypatch.setattr(invoker, "_request", fake_request) + + res = invoker.invoke("f", "/r", "p", 300) + assert res.success is False + assert "boom" in res.error + assert res.failure_class == FailureClass.RETRYABLE_ON_OTHER + + def test_nonzero_exit_despite_completed_status_is_failure( + self, invoker, monkeypatch + ): + def fake_request(path, *, method="GET", body=None, token=None, timeout=30): + if path == "/auth/login": + return {"token": "t"} + if path == "/jobs/with-capabilities": + return {"jobId": "j"} + return { + "status": "completed", + "result": {"status": "completed", "exitCode": 3, "output": "partial"}, + } + + monkeypatch.setattr(invoker, "_request", fake_request) + assert invoker.invoke("f", "/r", "p", 300).success is False + + def test_missing_password_is_reported_not_raised(self, monkeypatch): + monkeypatch.delenv("CIDX_ORCH_PASSWORD", raising=False) + inv = plugin.make_invoker("opus", 300) + + res = inv.invoke("f", "/r", "p", 300) + assert res.success is False + assert "CIDX_ORCH_PASSWORD" in res.error + assert res.failure_class == FailureClass.RETRYABLE_ON_SAME + + def test_unexpected_crash_is_reported_not_raised(self, invoker, monkeypatch): + def boom(*a, **k): + raise RuntimeError("socket exploded") + + monkeypatch.setattr(invoker, "_request", boom) + + res = invoker.invoke("f", "/r", "p", 300) + assert res.success is False + assert "socket exploded" in res.error + + +class TestBackpressureAndAuth: + def test_429_is_retried_after_the_hinted_delay(self, invoker, monkeypatch): + slept = [] + monkeypatch.setattr(plugin.time, "sleep", lambda s: slept.append(s)) + calls = {"submit": 0} + + def fake_request(path, *, method="GET", body=None, token=None, timeout=30): + if path == "/auth/login": + return {"token": "t"} + if path == "/jobs/with-capabilities": + calls["submit"] += 1 + if calls["submit"] == 1: + raise _http_error(429, {"retryAfterSeconds": 7}) + return {"jobId": "j"} + return { + "status": "completed", + "result": {"status": "completed", "exitCode": 0, "output": "ok"}, + } + + monkeypatch.setattr(invoker, "_request", fake_request) + + res = invoker.invoke("f", "/r", "p", 300) + assert res.success is True + assert calls["submit"] == 2 + assert 7 in slept + + def test_expired_jwt_forces_one_reauth(self, invoker, monkeypatch): + calls = {"login": 0, "submit": 0} + + def fake_request(path, *, method="GET", body=None, token=None, timeout=30): + if path == "/auth/login": + calls["login"] += 1 + return {"token": f"jwt-{calls['login']}"} + if path == "/jobs/with-capabilities": + calls["submit"] += 1 + if calls["submit"] == 1: + raise _http_error(401) + return {"jobId": "j"} + return { + "status": "completed", + "result": {"status": "completed", "exitCode": 0, "output": "ok"}, + } + + monkeypatch.setattr(invoker, "_request", fake_request) + + assert invoker.invoke("f", "/r", "p", 300).success is True + assert calls["login"] >= 2 + + def test_token_cached_across_calls(self, invoker, monkeypatch): + calls = {"login": 0} + + def fake_request(path, *, method="GET", body=None, token=None, timeout=30): + if path == "/auth/login": + calls["login"] += 1 + return {"token": "t"} + if path == "/jobs/with-capabilities": + return {"jobId": "j"} + return { + "status": "completed", + "result": {"status": "completed", "exitCode": 0, "output": "ok"}, + } + + monkeypatch.setattr(invoker, "_request", fake_request) + invoker.invoke("f", "/r", "p", 300) + invoker.invoke("f", "/r", "p", 300) + assert calls["login"] == 1 + + +class TestRepoResolution: + def test_resolved_repo_sets_repourl_branch_and_gitaware(self, invoker, monkeypatch): + monkeypatch.setattr( + invoker, + "_resolve_repo", + lambda cwd: {"repoUrl": "https://example.com/r.git", "branch": "dev"}, + ) + captured = {} + + def fake_request(path, *, method="GET", body=None, token=None, timeout=30): + if path == "/auth/login": + return {"token": "t"} + if path == "/jobs/with-capabilities": + captured["body"] = body + return {"jobId": "j"} + return { + "status": "completed", + "result": {"status": "completed", "exitCode": 0, "output": "ok"}, + } + + monkeypatch.setattr(invoker, "_request", fake_request) + invoker.invoke("f", "/some/repo", "p", 300) + + assert captured["body"]["options"]["gitAware"] is True + assert captured["body"]["repoUrl"] == "https://example.com/r.git" + assert captured["body"]["branch"] == "dev" + + def test_resolve_repo_strips_embedded_credentials(self, invoker, monkeypatch): + def fake_run(cmd, **kwargs): + class R: + returncode = 0 + r = R() + if "config" in cmd: + r.stdout = "https://oauth2:glpat-XXXX@gitlab.com/org/repo.git\n" + else: + r.stdout = "main\n" + return r + + monkeypatch.setattr(plugin.subprocess, "run", fake_run) + info = invoker._resolve_repo("/some/clone") + assert info["repoUrl"] == "https://gitlab.com/org/repo.git" + assert "glpat" not in info["repoUrl"] + + def test_resolve_repo_passes_clean_urls_through(self, invoker, monkeypatch): + def fake_run(cmd, **kwargs): + class R: + returncode = 0 + r = R() + if "config" in cmd: + r.stdout = "https://gitlab.com/org/repo.git\n" + else: + r.stdout = "main\n" + return r + + monkeypatch.setattr(plugin.subprocess, "run", fake_run) + info = invoker._resolve_repo("/some/clone") + assert info["repoUrl"] == "https://gitlab.com/org/repo.git" + + def test_unresolved_repo_leaves_gitaware_off_and_no_repourl( + self, invoker, monkeypatch + ): + monkeypatch.setattr(invoker, "_resolve_repo", lambda cwd: {}) + captured = {} + + def fake_request(path, *, method="GET", body=None, token=None, timeout=30): + if path == "/auth/login": + return {"token": "t"} + if path == "/jobs/with-capabilities": + captured["body"] = body + return {"jobId": "j"} + return { + "status": "completed", + "result": {"status": "completed", "exitCode": 0, "output": "ok"}, + } + + monkeypatch.setattr(invoker, "_request", fake_request) + invoker.invoke("f", "/not/a/repo", "p", 300) + + assert captured["body"]["options"]["gitAware"] is False + assert "repoUrl" not in captured["body"] diff --git a/plugins/cidx_orchestrator_invoker/test_orchestrator_conformance.py b/plugins/cidx_orchestrator_invoker/test_orchestrator_conformance.py new file mode 100644 index 000000000..796c5ebe7 --- /dev/null +++ b/plugins/cidx_orchestrator_invoker/test_orchestrator_conformance.py @@ -0,0 +1,68 @@ +"""The orchestrator invoker passes the CLI invoker seam's conformance suite. + +Run against the testkit's fake orchestrator, a real HTTP server on the +loopback interface: the delegate is exercised over the wire exactly as +deployed, with nothing patched. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Iterator + +import pytest + +import cidx_orchestrator_invoker as plugin +from cidx_testkit.conformance.cli_invoker import ( + CliInvokerContract, + CliInvokerSubject, +) +from cidx_testkit.fakes.orchestrator import ( + FAKE_PASSWORD, + FakeOrchestrator, + orchestrator_subject, +) + + +@pytest.fixture +def fake_orchestrator(monkeypatch: pytest.MonkeyPatch) -> Iterator[FakeOrchestrator]: + with FakeOrchestrator() as service: + monkeypatch.setenv("CIDX_ORCH_URL", service.url) + monkeypatch.setenv("CIDX_ORCH_PASSWORD", FAKE_PASSWORD) + monkeypatch.setenv("CIDX_ORCH_POLL_SECS", "0") + monkeypatch.delenv("CIDX_ORCH_MODEL", raising=False) + yield service + + +class TestOrchestratorInvoker(CliInvokerContract): + @pytest.fixture + def cli_subject( + self, fake_orchestrator: FakeOrchestrator, tmp_path: Path + ) -> CliInvokerSubject: + return orchestrator_subject( + plugin.make_invoker(), fake_orchestrator, str(tmp_path) + ) + + +def test_capacity_is_waited_out_and_the_job_still_runs( + fake_orchestrator: FakeOrchestrator, tmp_path: Path +) -> None: + fake_orchestrator.capacity_rejections = 2 + fake_orchestrator.succeed_with("ok") + result = plugin.make_invoker().invoke("describe", str(tmp_path), "p", 60) + assert result.success, result.error + assert len(fake_orchestrator.submitted) == 1 + + +def test_a_revoked_token_forces_one_reauthentication( + fake_orchestrator: FakeOrchestrator, tmp_path: Path +) -> None: + invoker = plugin.make_invoker() + fake_orchestrator.succeed_with("first") + assert invoker.invoke("describe", str(tmp_path), "p", 60).success + fake_orchestrator.revoke_tokens() + fake_orchestrator.succeed_with("second") + result = invoker.invoke("describe", str(tmp_path), "p", 60) + assert result.success and result.output == "second" + logins = [r for r in fake_orchestrator.requests if r[1] == "/auth/login"] + assert len(logins) == 2