lean-ctx icon indicating copy to clipboard operation
lean-ctx copied to clipboard

bug: stdio server can inherit a stale session root from another checkout

Open JulienJBO opened this issue 7 months ago • 1 comments

lean-ctx version: 3.3.0 (installed global binary)

OS: macOS arm64

AI tool: Codex CLI in real usage, but the repro below talks directly to the lean-ctx MCP stdio server so it is client-agnostic

What happened:

When lean-ctx is started in a new checkout/worktree without an explicit project_root, the MCP server can inherit the latest persisted session root from another checkout.

After that, a normal tool call that targets an absolute path inside the current checkout is jailed against the previous checkout root and fails with:

path escapes project root: ... (root: <previous checkout>)

In practice this shows up when switching from one repo/worktree to another and then calling something like ctx_search with an absolute path.

The problem is not the ctx_search implementation itself. The stale root is already present before the tool call:

  • the stdio server starts from the global latest session
  • the active project_root still points to checkout A
  • a tool call in checkout B resolves against checkout A and is rejected by the path jail

What you expected:

A new stdio server started from checkout/worktree B should be rooted in B, or at least should not reuse checkout A as its active project_root.

More concretely, the startup behavior should be scoped to the current checkout/worktree instead of blindly reusing the global latest session root.

Steps to reproduce:

  1. Run the self-contained script below on a machine that has a global lean-ctx binary in PATH
  2. The script creates two temporary fake Git checkouts, starts lean-ctx from repo A, and then calls ctx_search on an absolute path in repo B through MCP stdio
  3. Observe the path escapes project root error where the reported root is repo A instead of repo B

Relevant output:

path escapes project root: /tmp/.../repo-b/internal/provider (root: /tmp/.../repo-a)

Self-contained reproduction script:

#!/usr/bin/env bash
set -euo pipefail

need_cmd() {
    if ! command -v "$1" >/dev/null 2>&1; then
        echo "Missing required command: $1" >&2
        exit 1
    fi
}

need_cmd python3

LEAN_CTX_BIN="${LEAN_CTX_BIN:-$(command -v lean-ctx || true)}"
if [[ -z "$LEAN_CTX_BIN" ]]; then
    echo "lean-ctx not found in PATH. Set LEAN_CTX_BIN=/absolute/path/to/lean-ctx and rerun." >&2
    exit 1
fi

TMP_ROOT="${TMPDIR:-/tmp}"
TMP_DIR="${LEAN_CTX_REPRO_TMP:-$(mktemp -d "$TMP_ROOT/lean-ctx-stale-root.XXXXXX")}"
KEEP_TMP="${KEEP_TMP:-0}"
DATA_DIR="$TMP_DIR/data"
REPO_A="$TMP_DIR/repo-a"
REPO_B="$TMP_DIR/repo-b"

cleanup() {
    local status=$?
    if [[ "$KEEP_TMP" == "1" ]]; then
        echo "Kept temp directory: $TMP_DIR" >&2
    else
        rm -rf "$TMP_DIR"
    fi
    exit "$status"
}
trap cleanup EXIT

mkdir -p "$DATA_DIR" "$REPO_A/.git" "$REPO_B/.git" "$REPO_B/internal/provider"
printf dummyn > "$REPO_B/internal/provider/dummy.txt"

REPO_A="$(cd "$REPO_A" && pwd -P)"
REPO_B="$(cd "$REPO_B" && pwd -P)"
DATA_DIR="$(cd "$DATA_DIR" && pwd -P)"

echo "Using lean-ctx binary: $LEAN_CTX_BIN"
"$LEAN_CTX_BIN" --version || true
echo "Temporary LEAN_CTX_DATA_DIR: $DATA_DIR"
echo "Repo A: $REPO_A"
echo "Repo B: $REPO_B"
echo
echo "Expected failure on the installed non-corrected binary:"
echo "  path escapes project root: $REPO_B/internal/provider (root: $REPO_A)"
echo

export LEAN_CTX_BIN
export LEAN_CTX_REPRO_DATA_DIR="$DATA_DIR"
export LEAN_CTX_REPRO_REPO_A="$REPO_A"
export LEAN_CTX_REPRO_REPO_B="$REPO_B"

python3 <<'PY'
import json
import os
import subprocess
import sys

lean_ctx_bin = os.environ["LEAN_CTX_BIN"]
data_dir = os.environ["LEAN_CTX_REPRO_DATA_DIR"]
repo_a = os.environ["LEAN_CTX_REPRO_REPO_A"]
repo_b = os.environ["LEAN_CTX_REPRO_REPO_B"]


def recv_json_line(stream):
    while True:
        line = stream.readline()
        if line == "":
            raise RuntimeError("lean-ctx terminated before returning a response")
        line = line.strip()
        if not line:
            continue
        return json.loads(line)


def request(proc, msg_id, method, params=None):
    payload = {"jsonrpc": "2.0", "id": msg_id, "method": method}
    if params is not None:
        payload["params"] = params
    proc.stdin.write(json.dumps(payload, separators=(",", ":")) + "\n")
    proc.stdin.flush()

    while True:
        response = recv_json_line(proc.stdout)
        if response.get("id") == msg_id:
            return response


env = os.environ.copy()
env["LEAN_CTX_DATA_DIR"] = data_dir
env.setdefault("RUST_LOG", "error")

proc = subprocess.Popen(
    [lean_ctx_bin],
    cwd=repo_a,
    env=env,
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    text=True,
)

try:
    init = request(
        proc,
        1,
        "initialize",
        {
            "protocolVersion": "2024-11-05",
            "capabilities": {},
            "clientInfo": {"name": "stale-root-repro", "version": "0.0.1"},
        },
    )
    if "error" in init:
        raise RuntimeError(f"initialize failed: {json.dumps(init, ensure_ascii=False)}")

    proc.stdin.write(
        json.dumps(
            {"jsonrpc": "2.0", "method": "notifications/initialized"},
            separators=(",", ":"),
        )
        + "\n"
    )
    proc.stdin.flush()

    result = request(
        proc,
        2,
        "tools/call",
        {
            "name": "ctx_search",
            "arguments": {
                "path": f"{repo_b}/internal/provider",
                "pattern": "dummy",
                "max_results": 20,
            },
        },
    )

    if "error" not in result:
        print("Unexpected success. Full response:", file=sys.stderr)
        print(json.dumps(result, indent=2, ensure_ascii=False), file=sys.stderr)
        sys.exit(1)

    message = result["error"].get("message", "")
    print(message)

    if "path escapes project root" not in message or repo_a not in message or repo_b not in message:
        print("\nUnexpected error payload:", file=sys.stderr)
        print(json.dumps(result, indent=2, ensure_ascii=False), file=sys.stderr)
        sys.exit(1)

    print("\nReproduction succeeded.")
finally:
    proc.kill()
    proc.wait(timeout=5)
PY

If useful, I also have a local fix plus regression tests for the startup/rooting behavior and can open a PR after alignment on the intended behavior.

JulienJBO avatar Apr 22 '26 07:04 JulienJBO

Fixed via PR #138 — startup now scopes session restore to the current checkout/worktree, preventing stale project_root inheritance across different projects.

yvgude avatar Apr 22 '26 09:04 yvgude