From e5c49144922318244b2bab8e8a825c464bf131f9 Mon Sep 17 00:00:00 2001 From: "lusendong.6789" Date: Sat, 14 Nov 2026 17:05:07 +0800 Subject: [PATCH] Fix MCP adapter runtime and lifecycle boundaries Signed-off-by: lusendong.6789 Signed-off-by: lusendong.6789 Co-authored-by: TRAE CLI --- docs/guides/kunluncode-adapter.zh-CN.html | 6 +- docs/guides/kunluncode-adapter.zh-CN.md | 12 +- docs/integrations/ego-source-reader.md | 2 +- docs/reference/local-delegation.md | 6 +- loopx/claude_goal_mode/hooks/goal_policy.py | 5 +- loopx/claude_goal_mode/scripts/connect.py | 5 +- .../claude_goal_mode/scripts/goalmode_cmd.py | 7 +- .../statusline/goal_status.py | 5 +- loopx/collaboration_mcp.py | 23 +-- loopx/command_invocation.py | 29 ++++ loopx/control_plane/turn_driver/codex_cli.py | 4 +- loopx/extensions/ego_source_reader.py | 23 ++- loopx/goal_mode_mcp.py | 6 +- loopx/kunluncode_goal_mode/README.md | 7 +- loopx/kunluncode_goal_mode/cli.py | 4 +- loopx/kunluncode_goal_mode/control_plane.py | 6 +- loopx/slash_command_install.py | 76 +++++---- packages/loopx-ark-turn/README.md | 5 +- .../src/loopx_ark_turn/mcp_tools.py | 5 +- .../tests/test_tools_lifetime.py | 101 +++++++++++ tests/test_collaboration_goal_instance.py | 44 +++++ tests/test_ego_source_reader.py | 33 +++- tests/test_goal_adapter_runtime_provenance.py | 158 ++++++++++++++++++ tests/test_loopx_turn_codex_cli.py | 46 +++-- tests/test_slash_command_install.py | 99 +++++++++++ 25 files changed, 600 insertions(+), 117 deletions(-) create mode 100644 packages/loopx-ark-turn/tests/test_tools_lifetime.py create mode 100644 tests/test_goal_adapter_runtime_provenance.py diff --git a/docs/guides/kunluncode-adapter.zh-CN.html b/docs/guides/kunluncode-adapter.zh-CN.html index 3fd433aa21..9fb83a40eb 100644 --- a/docs/guides/kunluncode-adapter.zh-CN.html +++ b/docs/guides/kunluncode-adapter.zh-CN.html @@ -379,7 +379,7 @@

三套命令空间:并不完全一致

LoopX shell CLIloopx ...
loopx-kunluncode ...LoopX 控制面连接、添加 todo、启动 native controller 和读取合并状态 KunlunCode TUI slash/goal、/goal-pro、/plan、/mcpKunlunCode session runtime仍由 TUI 解析;适配器通过等价 app-server API 激活 Goal - LoopX MCP toolsshould_run、claim_task、complete_taskLoopX MCP server交互/兼容模式使用;native run 期间写工具失败关闭 + LoopX MCP toolsshould_run、list_todos、claim_task、complete_task、review_task_visionLoopX MCP server交互/兼容模式使用;native run 期间写工具失败关闭 @@ -504,7 +504,7 @@

验证连接

kunluncode --cwd "$TARGET_PROJECT" mcp test loopx-kunluncode kunluncode config get mcp_servers -

状态应显示正确 goal 与 Agent;若安装 MCP,MCP test 应列出四个 LoopX 工具。源码贡献者还应运行 examples/kunluncode-app-server-goal-pro-smoke.py --require,证明 2026-07-27、mode=strict、status=complete、verification_passed=true 和跨进程同 thread 恢复。

+

状态应显示正确 goal 与 Agent;若安装 MCP,MCP test 应列出上述五个 LoopX 工具。review_task_vision 用于在原 Todo 完成后补齐遗漏的 vision 判断,不会重复完成 Todo 或扣减额度;native run 期间同样限制写入。源码贡献者还应运行 examples/kunluncode-app-server-goal-pro-smoke.py --require,证明 2026-07-27、mode=strict、status=complete、verification_passed=true 和跨进程同 thread 恢复。

@@ -639,7 +639,7 @@

完整验收清单

  • connect 返回成功,goal id 与 Agent id 正确。
  • .loopx/kunluncode.json 未被 Git 跟踪。
  • 已有 goal 的其他 registered agents 被保留。
  • -
  • 若安装 MCP,MCP test 显示四个工具。
  • +
  • 若安装 MCP,MCP test 显示上述五个工具。
  • status 显示 registered kunlun、host kunluncode、runtime profile kunluncode。
  • 真实 app-server smoke 证明 strict Goal、verifier PASS 与跨进程 resume。
  • 低风险 todo 只在 native Goal Pro verifier PASS 后完成 delivery/todo/quota writeback。
  • diff --git a/docs/guides/kunluncode-adapter.zh-CN.md b/docs/guides/kunluncode-adapter.zh-CN.md index 77a67e212c..07a20de983 100644 --- a/docs/guides/kunluncode-adapter.zh-CN.md +++ b/docs/guides/kunluncode-adapter.zh-CN.md @@ -41,7 +41,7 @@ KunlunCode 使用独立的 `.loopx/kunluncode.json` 绑定和注册身份。它 | --- | --- | --- | --- | | LoopX shell CLI | `loopx ...`、`loopx-kunluncode ...` | LoopX 控制面 | 连接、添加 todo、启动原生 Goal 控制器、读取合并状态 | | KunlunCode TUI slash | `/goal`、`/goal-pro`、`/plan`、`/mcp` | KunlunCode session runtime | 仍由 TUI 解析;适配器通过等价 app-server API 激活 Goal,不把 slash 文本塞进 prompt | -| LoopX MCP tools | `should_run`、`list_todos`、`claim_task`、`complete_task` | `loopx-kunluncode` MCP server | 供交互/兼容模式使用;native run 期间写工具会失败关闭,由外层控制器独占 writeback | +| LoopX MCP tools | `should_run`、`list_todos`、`claim_task`、`complete_task`、`review_task_vision` | `loopx-kunluncode` MCP server | 供交互/兼容模式使用;native run 期间写工具会失败关闭,由外层控制器独占 writeback | ### `/goal` 是 KunlunCode 原生 Goal @@ -270,15 +270,19 @@ kunluncode --cwd "$TARGET_PROJECT" mcp test loopx-kunluncode `status: complete` 和 `verification_passed: true`,且 resumed goal id 与首次运行一致。 这个 smoke 只保留摘要,不记录原始输出、trajectory、凭据或绝对路径。 -MCP 握手成功时应看到四个工具: +MCP 握手成功时应看到五个工具: ```text should_run list_todos claim_task complete_task +review_task_vision ``` +`review_task_vision` 用于在原 Todo 完成后补齐遗漏的 vision 判断,不会重复完成 +Todo 或扣减额度;native run 期间同样由外层控制器限制写入。 + 再读取 LoopX lane: ```bash @@ -503,7 +507,7 @@ uv pip install --python .venv/bin/python -e . 'mcp==1.28.1' 然后用绝对 `--python` 路径重新执行 `install`。 -### MCP test 无法连接或没有四个工具 +### MCP test 无法连接或缺少工具 依次检查: @@ -587,7 +591,7 @@ log 对账,并从缺失阶段继续。 - [ ] `connect` 返回 `ok: true`,goal id 和 Agent id 正确; - [ ] `.loopx/kunluncode.json` 未被 Git 跟踪; - [ ] 连接已有 goal 时其他 registered agents 仍存在; -- [ ] 若安装了 MCP,`kunluncode mcp test loopx-kunluncode` 显示四个工具; +- [ ] 若安装了 MCP,`kunluncode mcp test loopx-kunluncode` 显示上述五个工具; - [ ] `status` 显示 registered `kunlun`、host `kunluncode`、source `runtime_profile:kunluncode`; - [ ] `examples/kunluncode-app-server-goal-pro-smoke.py --require` 证明 strict Goal、verifier PASS diff --git a/docs/integrations/ego-source-reader.md b/docs/integrations/ego-source-reader.md index 2562013f74..12ce723c3f 100644 --- a/docs/integrations/ego-source-reader.md +++ b/docs/integrations/ego-source-reader.md @@ -181,7 +181,7 @@ Use a supported LoopX installation containing this module. Restart an idle host through its existing service path and resume the original Session. Do not change its sandbox, approval policy, workspace grants or authentication to make the tool work. The Python environment needs the optional `loopx[ego-source-reader]` -extra (`mcp==1.28.1`); the base LoopX CLI has no Python runtime dependencies. +extra (`mcp==1.30.0`); the base LoopX CLI has no Python runtime dependencies. Keep this environment outside PATH when another installation owns `loopx`. Disable by removing only this MCP entry and restarting that idle host. Keep a private configuration backup and the installed/source revision for rollback. diff --git a/docs/reference/local-delegation.md b/docs/reference/local-delegation.md index cbb2b8ca8d..be15a75450 100644 --- a/docs/reference/local-delegation.md +++ b/docs/reference/local-delegation.md @@ -1350,8 +1350,10 @@ python -m loopx.collaboration_mcp \ --execution-config "$DELEGATION_CONFIG" ``` -Without `--execution-config`, the original five collaboration tools are -unchanged and cannot launch workers. With it, the Agent can: +Without `--execution-config`, the scoped collaboration tools cannot launch +workers. Use MCP tool discovery for the current tool set; exact Goal-instance +bindings also expose `control_peer_request`. With execution configuration, the +Agent can: 1. Call `list_execution_bindings` to find its authorized work. 2. Call `start_delegation(binding_id, operation_id, brief, parent_request_id?)`. diff --git a/loopx/claude_goal_mode/hooks/goal_policy.py b/loopx/claude_goal_mode/hooks/goal_policy.py index a794800dca..28f3893da7 100644 --- a/loopx/claude_goal_mode/hooks/goal_policy.py +++ b/loopx/claude_goal_mode/hooks/goal_policy.py @@ -53,7 +53,6 @@ import json import os -import shutil import subprocess import sys from pathlib import Path @@ -63,6 +62,7 @@ # is the single source of truth; there is no separate active-state file. from goal_state import active_context from stdio_utf8 import pin_utf8_stdio +from loopx.command_invocation import pinned_python_module_command # Read-only tools are always allowed under goal-mode. Edit/Write are scoped to # write_scope; Bash is gated by a destructive-command denylist. (No OS sandbox in @@ -112,8 +112,7 @@ def _usable_cwd(value: str) -> bool: def _gh_prefix(): - _exe = shutil.which("loopx") - return [_exe] if _exe else [__import__("sys").executable, "-m", "loopx.cli"] + return pinned_python_module_command("loopx.cli") def emit(decision=None, reason=""): diff --git a/loopx/claude_goal_mode/scripts/connect.py b/loopx/claude_goal_mode/scripts/connect.py index dcf7d5f5d8..40bf432836 100644 --- a/loopx/claude_goal_mode/scripts/connect.py +++ b/loopx/claude_goal_mode/scripts/connect.py @@ -11,11 +11,11 @@ from __future__ import annotations import argparse -import shutil import subprocess import sys from pathlib import Path +from loopx.command_invocation import pinned_python_module_command from loopx.control_plane.projects.registry_codec import ( ProjectRegistryProtocolError, add_project_registry_backend, @@ -27,8 +27,7 @@ def _gh_prefix(): - exe = shutil.which("loopx") - return [exe] if exe else [sys.executable, "-m", "loopx.cli"] + return pinned_python_module_command("loopx.cli") def main(): diff --git a/loopx/claude_goal_mode/scripts/goalmode_cmd.py b/loopx/claude_goal_mode/scripts/goalmode_cmd.py index 23b97fdbe8..6a1e2ea693 100644 --- a/loopx/claude_goal_mode/scripts/goalmode_cmd.py +++ b/loopx/claude_goal_mode/scripts/goalmode_cmd.py @@ -26,7 +26,6 @@ import json import os import re -import shutil import subprocess import sys from pathlib import Path @@ -38,6 +37,7 @@ sys.path.insert(0, str(HERE.parent / "hooks")) from goal_state import goal_context, find_registry, loop_md_path # noqa: E402 from stdio_utf8 import pin_utf8_stdio # noqa: E402 +from loopx.command_invocation import pinned_python_module_command # noqa: E402 from loopx.control_plane.heartbeat.rules import ( # noqa: E402 HOST_LOOP_SAFETY_RULE, RUNTIME_REPAIR_ROUTING_RULE, @@ -47,9 +47,8 @@ def gh_prefix(): - """Cross-platform loopx invocation: the CLI shim if on PATH, else the module.""" - exe = shutil.which("loopx") - return [exe] if exe else [sys.executable, "-m", "loopx.cli"] + """Run the CLI from the same release as this host adapter.""" + return pinned_python_module_command("loopx.cli") def gh(args, cwd=None): diff --git a/loopx/claude_goal_mode/statusline/goal_status.py b/loopx/claude_goal_mode/statusline/goal_status.py index 88a65ae3f7..fb4c041ac6 100644 --- a/loopx/claude_goal_mode/statusline/goal_status.py +++ b/loopx/claude_goal_mode/statusline/goal_status.py @@ -26,12 +26,11 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hooks")) from goal_state import active_context from stdio_utf8 import pin_utf8_stdio +from loopx.command_invocation import pinned_python_module_command -import shutil as _shutil def _gh_prefix(): - _exe = _shutil.which("loopx") - return [_exe] if _exe else [__import__("sys").executable, "-m", "loopx.cli"] + return pinned_python_module_command("loopx.cli") def _clip(s, n: int) -> str: diff --git a/loopx/collaboration_mcp.py b/loopx/collaboration_mcp.py index 019b315801..804281e548 100644 --- a/loopx/collaboration_mcp.py +++ b/loopx/collaboration_mcp.py @@ -35,6 +35,7 @@ effect_runtime_request_scope, effect_runtime_result, EffectRuntimeRemoteError, ) from .control_plane.runtime.validation_command import noninteractive_validation +from .command_invocation import pinned_python_module_command from .control_plane.turn_driver.journal_store import ( load_turn_journal, turn_journal_path, @@ -82,15 +83,6 @@ ) -_PINNED_MODULE_LAUNCHER = ( - "import runpy,sys;" - "release_root,module=sys.argv[1:3];" - "sys.path.insert(0,release_root);" - "sys.argv=[module,*sys.argv[3:]];" - "runpy.run_module(module,run_name='__main__')" -) - - def _release_root() -> Path: return Path(__file__).resolve().parent.parent @@ -126,14 +118,9 @@ def _python_module_command(module: str) -> list[str]: def _pinned_module_command(module: str, *, interpreter: str | None = None) -> list[str]: """Build a self-contained module argv for hosts that sanitize env vars.""" - return [ - interpreter or sys.executable, - "-P", - "-c", - _PINNED_MODULE_LAUNCHER, - str(_release_root()), - module, - ] + return pinned_python_module_command( + module, interpreter=interpreter, release_root=_release_root(), + ) def _mcp_python_candidates() -> tuple[Path, ...]: @@ -979,6 +966,8 @@ def stop(self, operation_id: str, *, execute: bool) -> dict: with exclusive_file_lock(self._dispatch_lock(path)): row = _read(path) binding = self._bound(row) + if self._caller_goal_ref() is not None: + delegation_results.operation_brief(self, row) stop = self._read_stop(path) if stop is None: if row["status"] in DELEGATION_TERMINAL_STATUSES: diff --git a/loopx/command_invocation.py b/loopx/command_invocation.py index f2f3c3d7fa..1bfc0b46c5 100644 --- a/loopx/command_invocation.py +++ b/loopx/command_invocation.py @@ -12,6 +12,35 @@ _loopx_cli_bin: ContextVar[tuple[str, ...]] = ContextVar("loopx_cli_bin", default=("loopx",)) +_PINNED_MODULE_LAUNCHER = ( + "import runpy,sys;" + "release_root,module=sys.argv[1:3];" + "sys.path.insert(0,release_root);" + "sys.argv=[module,*sys.argv[3:]];" + "runpy.run_module(module,run_name='__main__')" +) + + +def pinned_python_module_command( + module: str, *, interpreter: str | None = None, release_root: Path | None = None, +) -> list[str]: + """Carry the loaded release into a child even when hosts sanitize its env. + + Source-backed adapters may run in an MCP-only Python and a foreign project. + Pin the import root in argv so neither PATH nor cwd/PYTHONPATH selects a + different LoopX. Keep the interpreter path intact to retain its venv. + This is Python process transport; it owns no control-plane decisions. + """ + return [ + interpreter or sys.executable, + "-P", + "-c", + _PINNED_MODULE_LAUNCHER, + str(release_root if release_root is not None else Path(__file__).resolve().parent.parent), + module, + ] + + def validate_cli_bin(value: str) -> str: """Accept one executable name/path, never a shell command or empty route.""" if not value.strip() or value.startswith("-") or any(ord(c) < 32 for c in value): diff --git a/loopx/control_plane/turn_driver/codex_cli.py b/loopx/control_plane/turn_driver/codex_cli.py index dd4d453b5e..5f6b9eb21f 100644 --- a/loopx/control_plane/turn_driver/codex_cli.py +++ b/loopx/control_plane/turn_driver/codex_cli.py @@ -184,8 +184,8 @@ def _codex_mcp_config_arguments( name = server["name"] command = server["command"] pairs = [ - f"mcp_servers.{name}.command={json.dumps(command[0])}", - f"mcp_servers.{name}.args={json.dumps(command[1:])}", + f"mcp_servers.{name}.command={json.dumps(command[0], ensure_ascii=False)}", + f"mcp_servers.{name}.args={json.dumps(command[1:], ensure_ascii=False)}", f"mcp_servers.{name}.enabled=true", f"mcp_servers.{name}.required=true", f'mcp_servers.{name}.default_tools_approval_mode="approve"', diff --git a/loopx/extensions/ego_source_reader.py b/loopx/extensions/ego_source_reader.py index b723fa4827..0c4774cd6b 100644 --- a/loopx/extensions/ego_source_reader.py +++ b/loopx/extensions/ego_source_reader.py @@ -282,6 +282,16 @@ def _url_fence(current: str, requested: str) -> str: ) +def _utf16_clip_script() -> str: + # Keep the existing JS code-unit budget without splitting a Unicode pair. + return ( + "const clip=(text,limit)=>{let end=Math.min(text.length,limit);" + "if(end=0xD800&&text.charCodeAt(end-1)<=0xDBFF" + "&&text.charCodeAt(end)>=0xDC00&&text.charCodeAt(end)<=0xDFFF)end--;" + "return text.slice(0,end);};" + ) + + def _script(config: ReaderConfig, url: str) -> str: # No caller-selected code, executable, browser, Page or CLI arguments. return ( @@ -292,11 +302,13 @@ def _script(config: ReaderConfig, url: str) -> str: # redirect returns no content, even within another authorized origin. _url_fence("current", "request.url") + "if(!request.ready)return {error:'source_content_not_ready'};" - "const text=document.body?.innerText||'';" + "const text=document.body?.innerText||'';" + + _utf16_clip_script() + + "const clipped=clip(text,request.limit);" "return {url:current.href,title:document.title," - "text:text.slice(0,request.limit),truncated:text.length>request.limit," + "text:clipped,truncated:clipped.length({index,alt:im.alt.slice(0,512)," + ".map((im,index)=>({index,alt:clip(im.alt,512)," "natural_width:im.naturalWidth,natural_height:im.naturalHeight}))};" f"}},{{url:target.href,limit:{MAX_TEXT_CHARS},ready:sourceReady}});" f"console.log({json.dumps(MARKER)}+JSON.stringify({{...r," @@ -406,8 +418,9 @@ def _image_script(config: ReaderConfig, url: str, index: int, path: str) -> str: _url_fence("u", "r.url") + "const im=document.images[r.index];const b=im.getBoundingClientRect();" "if(b.width<2||b.height<2||b.width>r.edge||b.height>r.edge)" - "return {error:'source_image_bounds_unsupported'};" - "return {url:u.href,index:r.index,alt:im.alt.slice(0,512),src:im.currentSrc," + "return {error:'source_image_bounds_unsupported'};" + + _utf16_clip_script() + + "return {url:u.href,index:r.index,alt:clip(im.alt,512),src:im.currentSrc," "clip:{x:b.left+scrollX,y:b.top+scrollY,width:b.width,height:b.height}};},request);" "if(before.error){console.log('LOOPX_PUBLIC_SOURCE:'+JSON.stringify({...before," "requested_url:requestedUrl,canonical_url:target.href}));}else{" diff --git a/loopx/goal_mode_mcp.py b/loopx/goal_mode_mcp.py index 02aeb55aec..356cb059c1 100644 --- a/loopx/goal_mode_mcp.py +++ b/loopx/goal_mode_mcp.py @@ -4,14 +4,13 @@ import inspect import json import os -import shutil import subprocess -import sys from collections.abc import Callable, Mapping from dataclasses import dataclass from pathlib import Path from typing import Any +from .command_invocation import pinned_python_module_command from .control_plane.host_adapter_settlement import ( HostTodoSettlementRequest, host_vision_request, @@ -91,8 +90,7 @@ def _allow_terminal_stride_path(self, goal_id: str, vision: dict[str, Any] | Non return (effective.get("execution_profile") or {}).get("stride_strategy") == "evidence_conditioned_v1" def command_prefix(self) -> list[str]: - executable = shutil.which("loopx") - return [executable] if executable else [sys.executable, "-m", "loopx.cli"] + return pinned_python_module_command("loopx.cli") @staticmethod def _runtime_profile_flag_is_unsupported( diff --git a/loopx/kunluncode_goal_mode/README.md b/loopx/kunluncode_goal_mode/README.md index dad4c77994..ba8ec68cbe 100644 --- a/loopx/kunluncode_goal_mode/README.md +++ b/loopx/kunluncode_goal_mode/README.md @@ -12,9 +12,14 @@ LoopX and KunlunCode do not share one command namespace: LoopX control plane; - `/goal`, `/goal-pro`, `/plan`, and `/mcp` are native KunlunCode TUI slash commands with KunlunCode session state; -- `should_run`, `list_todos`, `claim_task`, and `complete_task` are MCP tools +- `should_run`, `list_todos`, `claim_task`, `complete_task`, and + `review_task_vision` are MCP tools called by the model, not slash commands typed by the user. +`review_task_vision` repairs a missing vision decision for an already completed +Todo without repeating completion or spending again. Native runs also block +this write through the outer-controller guard. + Within KunlunCode's native Goal family, `/goal-pro` keeps `/goal`'s persistent objective lifecycle and adds a mandatory independent verifier before completion. Its Strict/Arrangement delegation rules are the execution mechanism for that diff --git a/loopx/kunluncode_goal_mode/cli.py b/loopx/kunluncode_goal_mode/cli.py index cff0cae4a7..e38a9849ca 100644 --- a/loopx/kunluncode_goal_mode/cli.py +++ b/loopx/kunluncode_goal_mode/cli.py @@ -12,6 +12,7 @@ from pathlib import Path from typing import Any +from loopx.command_invocation import pinned_python_module_command from loopx.control_plane.projects.registry_codec import ( load_project_registry, mutate_project_registry, @@ -61,8 +62,7 @@ def _run( def _loopx_prefix() -> list[str]: - executable = shutil.which("loopx") - return [executable] if executable else [sys.executable, "-m", "loopx.cli"] + return pinned_python_module_command("loopx.cli") def _venv_python(venv: Path) -> Path: diff --git a/loopx/kunluncode_goal_mode/control_plane.py b/loopx/kunluncode_goal_mode/control_plane.py index a61cae4d82..29f1d509b4 100644 --- a/loopx/kunluncode_goal_mode/control_plane.py +++ b/loopx/kunluncode_goal_mode/control_plane.py @@ -3,13 +3,12 @@ from __future__ import annotations import json -import shutil import subprocess -import sys from collections.abc import Callable, Mapping from pathlib import Path from typing import Any +from loopx.command_invocation import pinned_python_module_command from loopx.control_plane.agents.workspace_guard import capture_delivery_workspace @@ -25,8 +24,7 @@ class KunlunNativeGoalRuntimeError(RuntimeError): def _default_loopx_prefix() -> list[str]: - executable = shutil.which("loopx") - return [executable] if executable else [sys.executable, "-m", "loopx.cli"] + return pinned_python_module_command("loopx.cli") CommandRunner = Callable[..., subprocess.CompletedProcess[str]] diff --git a/loopx/slash_command_install.py b/loopx/slash_command_install.py index 7426fbd82a..fec6f55624 100644 --- a/loopx/slash_command_install.py +++ b/loopx/slash_command_install.py @@ -805,7 +805,8 @@ def _read_mcp_marker(marker_path: Path) -> dict[str, Any]: def _write_json_atomic(path: Path, payload: Any) -> None: - """Replace `path` in one step, so an interrupted run cannot truncate it.""" + """Replace the effective file in one step, preserving a user's symlink.""" + path = path.resolve() path.parent.mkdir(parents=True, exist_ok=True) mode = path.stat().st_mode if path.exists() else None handle, tmp_name = tempfile.mkstemp(dir=str(path.parent), prefix=f".{path.name}.") @@ -844,37 +845,40 @@ def _merge_managed_mcp_json( to the host's schema and must not carry an entry the host has to parse. """ marker_path = config_path.parent / CURSOR_MCP_MARKER_NAME - try: - text = config_path.read_text(encoding="utf-8") if config_path.exists() else "" - raw = json.loads(text) if text.strip() else {} - except (OSError, json.JSONDecodeError): - return invalid_status - if not isinstance(raw, dict): - return invalid_status - servers = raw.get("mcpServers") - if servers is None: - servers = {} - if not isinstance(servers, dict): - # A list-valued or scalar `mcpServers` is not something to overwrite: - # either the file follows a shape LoopX does not understand, or it is - # damaged. Both are the user's to resolve. - return invalid_status - - existing = servers.get(MANAGED_MCP_KEY) - recorded = _read_mcp_marker(marker_path).get(MANAGED_MCP_KEY) - # Ownership is only demonstrable when the entry still matches what LoopX - # recorded writing. A hand-edited entry counts as the user's from then on. - loopx_owned = existing is not None and existing == recorded - - # A marker that no longer describes reality is not just useless, it is - # dangerous: once the user deletes or edits the entry, the stale marker - # would still vouch for a future same-name entry and authorize deleting - # something LoopX never wrote. Ownership has to expire the moment it stops - # being demonstrable — and only in execute mode, so a dry run stays a - # read-only report. - if execute and recorded is not None and not loopx_owned: - marker_path.unlink(missing_ok=True) + def read_state() -> tuple[dict[str, object], dict[str, object], object, bool] | None: + try: + text = config_path.read_text(encoding="utf-8") if config_path.exists() else "" + raw = json.loads(text) if text.strip() else {} + except (OSError, json.JSONDecodeError): + return None + if not isinstance(raw, dict): + return None + servers = raw.get("mcpServers") + if servers is None: + servers = {} + if not isinstance(servers, dict): + # A list-valued or scalar `mcpServers` is not something to overwrite: + # either the file follows a shape LoopX does not understand, or it is + # damaged. Both are the user's to resolve. + return None + + existing = servers.get(MANAGED_MCP_KEY) + recorded = _read_mcp_marker(marker_path).get(MANAGED_MCP_KEY) + # Ownership is only demonstrable when the entry still matches what LoopX + # recorded writing. A hand-edited entry counts as the user's from then on. + loopx_owned = existing is not None and existing == recorded + + # A stale marker could vouch for a future same-name entry LoopX never + # wrote. Expire ownership when it stops matching, except in dry runs. + if execute and recorded is not None and not loopx_owned: + marker_path.unlink(missing_ok=True) + return raw, servers, existing, loopx_owned + + state = read_state() + if state is None: + return invalid_status + raw, servers, existing, loopx_owned = state if uninstall: if existing is None: return "absent" @@ -897,6 +901,16 @@ def _merge_managed_mcp_json( command = command_factory() if command is None: return "skipped_mcp_dependency_missing" + # Provisioning can take long enough for the user to edit the config or + # revoke ownership. Merge only into a fresh, revalidated snapshot. External + # writers can still race this final read/write; atomic replacement prevents + # truncation, not concurrent lost updates. + state = read_state() + if state is None: + return invalid_status + raw, servers, existing, loopx_owned = state + if existing is not None and not loopx_owned: + return "skipped_user_owned_mcp_entry" entry = {"command": command[0], "args": [command[1]]} if existing == entry: return "unchanged" diff --git a/packages/loopx-ark-turn/README.md b/packages/loopx-ark-turn/README.md index 73dcb467d3..1e70ee077f 100644 --- a/packages/loopx-ark-turn/README.md +++ b/packages/loopx-ark-turn/README.md @@ -9,7 +9,8 @@ This adapter does not activate a native Goal or add a second scheduler. Install both packages from the same integrated LoopX checkout containing `loopx.extensions.turn_host.extract_turn_work_identity` and -`assert_turn_host_request_version`. The shared decoder accepts complete-source +`assert_turn_host_request_version`, plus `supervised_stdio_command` for MCP. +The shared decoder accepts complete-source Host request v1 and historical v0; identity and provider permissions still use their existing owners. The package version alone does not establish that an older wheel contains this shared contract: @@ -72,6 +73,8 @@ Supply an operator-owned stdio MCP server with `--mcp-command-json` and an exact `--tool` selection for each exposed tool. Discovery reads every page, rejects duplicate names, and allows at most eight selected tools. One MCP process is bound to one Turn; models cannot change its command, selected tools or identity. +MCP uses LoopX's existing Node runtime and stdio supervisor to reap its process +when the Turn finishes, is cancelled, times out, or exits abruptly. The server receives host-bound `LOOPX_TURN_KEY`, `LOOPX_TURN_GOAL_ID`, `LOOPX_TURN_AGENT_ID`, `LOOPX_TURN_TODO_ID` and `LOOPX_TURN_WORKSPACE`. Use these diff --git a/packages/loopx-ark-turn/src/loopx_ark_turn/mcp_tools.py b/packages/loopx-ark-turn/src/loopx_ark_turn/mcp_tools.py index d573a5324d..6c4c37c4bf 100644 --- a/packages/loopx-ark-turn/src/loopx_ark_turn/mcp_tools.py +++ b/packages/loopx-ark-turn/src/loopx_ark_turn/mcp_tools.py @@ -11,6 +11,8 @@ from mcp import ClientSession, StdioServerParameters, types from mcp.client.stdio import stdio_client +from loopx.extensions.turn_host import supervised_stdio_command + from .config import AdapterError, Config, tool_environment @@ -48,8 +50,9 @@ async def connect(config: Config, identity: Mapping[str, str]) -> AsyncIterator[ if not config.mcp_command: yield Tools(None, [], config) return + command = supervised_stdio_command(config.mcp_command) server = StdioServerParameters( - command=config.mcp_command[0], args=list(config.mcp_command[1:]), + command=command[0], args=command[1:], env=tool_environment(config, identity), cwd=str(config.workspace), ) async with stdio_client(server) as (reader, writer): diff --git a/packages/loopx-ark-turn/tests/test_tools_lifetime.py b/packages/loopx-ark-turn/tests/test_tools_lifetime.py new file mode 100644 index 0000000000..b6c7bb57d0 --- /dev/null +++ b/packages/loopx-ark-turn/tests/test_tools_lifetime.py @@ -0,0 +1,101 @@ +"""Real Ark MCP stdio under the Turn supervisor, without model inference.""" +from __future__ import annotations + +import json +import os +import signal +import sys +import time + +import pytest + +from loopx.control_plane.turn_driver.host_process_transport import run_host_process + + +def process_present(pid: int) -> bool: + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + return True + + +@pytest.mark.skipif(os.name != "posix", reason="Windows process-tree cleanup remains best effort") +@pytest.mark.parametrize("stop", ["completed", "timeout", "cancel", "hard_parent_exit"]) +def test_real_mcp_is_gone_when_turn_supervision_returns(tmp_path, stop): + workspace = tmp_path / "workspace" + workspace.mkdir() + ready, release, late = (workspace / name for name in ("ready", "release", "late")) + server = tmp_path / "server.py" + server.write_text( + "from pathlib import Path\nimport os,time\n" + "os.environ['LOOPX_USAGE_PING']='0'\n" + "from mcp.server.fastmcp import FastMCP\n" + "server=FastMCP('process-lifetime-fixture')\n" + "@server.tool()\ndef delayed_effect(wait: bool) -> str:\n" + f" Path({str(ready)!r}).write_text(str(os.getpid()))\n" + " if not wait: return 'done'\n" + " deadline=time.monotonic()+30\n" + f" while not Path({str(release)!r}).exists() and time.monotonic() dict: } +def test_recreated_goal_cannot_stop_original_delegation_or_read_its_stop_receipt( + tmp_path, monkeypatch, +): + from loopx.collaboration_mcp import Delegations + from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime + + isolate_sqlite_runtime(tmp_path, monkeypatch) + registry = _create_source_registry(tmp_path) + config = tmp_path / "delegations.json" + config.write_text(json.dumps({ + "schema_version": "loopx_local_delegation_v0", + "bindings": [{ + "id": "review", "agent_id": "reviewer", "todo_id": "todo_probe", + "requesters": ["builder"], "workspace": str(tmp_path), + "timeout_seconds": 30, "output_refs": ["result.json"], + "host_args": ["--host", "generic-cli"], + }], + }), encoding="utf-8") + original = Delegations(tmp_path, registry, "delivery", "builder", config) + # The exact profile currently admits preparation, not native execution. + # Keep the real request/operation creation and lifetime transactions. + monkeypatch.setattr(original, "_spawn", lambda _operation_id: None) + original.start("review", "original-operation", _brief("Inspect the original Goal")) + path = original.path("original-operation") + before = path.read_bytes() + _recreate(registry) + replacement = Delegations(tmp_path, registry, "delivery", "builder", config) + + with pytest.raises(ValueError, match="captured Goal instance"): + replacement.stop("original-operation", execute=True) + assert path.read_bytes() == before + assert not original._stop_path(path).exists() + + # The original requester retains the ability to drain its historical work. + stopped = original.stop("original-operation", execute=True) + assert stopped["status"] == "stopped" + stopped_bytes = path.read_bytes() + receipt_bytes = original._stop_path(path).read_bytes() + with pytest.raises(ValueError, match="captured Goal instance"): + replacement.stop("original-operation", execute=True) + assert path.read_bytes() == stopped_bytes + assert original._stop_path(path).read_bytes() == receipt_bytes + + def _manager_request(root: Path, registry: Path, *, channel="manager", complete=True): store = ChatSessionStore(root) session = store.create_session( diff --git a/tests/test_ego_source_reader.py b/tests/test_ego_source_reader.py index 415e7dd2f7..34cfb3f151 100644 --- a/tests/test_ego_source_reader.py +++ b/tests/test_ego_source_reader.py @@ -724,7 +724,7 @@ def test_text_read_exposes_image_indices_without_claiming_visual_read(configured def run_generated_script(config, url, image, path, *, redirect=None, readiness=None, ownership="agent", - text="Source evidence"): + text="Source evidence", alt="figure"): """Execute the production script in Node, without the user's browser/Page.""" import shutil node = shutil.which("node") @@ -735,7 +735,7 @@ def run_generated_script(config, url, image, path, *, redirect=None, readiness=N harness = """ const vm=require('node:vm'),fs=require('node:fs'); let href='',domReads=0,captures=0,loaded=!readiness||readiness.startsWith('sidebar_busy')||readiness==='empty_sibling_article'; -const image={alt:'figure',currentSrc:'https://example.com/image.png', +const image={alt,currentSrc:'https://example.com/image.png', get complete(){return !readiness?.startsWith('image_')||loaded;}, naturalWidth:2,naturalHeight:2,scrollIntoView(){}, closest(){return null;}, @@ -806,6 +806,7 @@ def run_generated_script(config, url, image, path, *, redirect=None, readiness=N import base64 inputs = ("const source=" + json.dumps(script) + ";const redirect=" + json.dumps(redirect) + ";const readiness=" + json.dumps(readiness) + ";const text=" + json.dumps(text) + + ";const alt=" + json.dumps(alt) + ";const ownership=" + json.dumps(ownership) + ";const spaceId=" + json.dumps(config.task_space) + ";const pixels=" + json.dumps(base64.b64encode(png()).decode()) + ";") result = subprocess.run([node, "-e", inputs + harness], capture_output=True, @@ -817,6 +818,34 @@ def run_generated_script(config, url, image, path, *, redirect=None, readiness=N return decoded, json.loads(observed) +@pytest.mark.parametrize("prefix_size,expected_size", [(99998, 99999), (99999, 99999)]) +def test_text_limit_preserves_complete_unicode_characters( + configured, tmp_path, prefix_size, expected_size, +): + config = reader.ReaderConfig.from_environment() + text = "a" * prefix_size + "🙂tail" + result, _ = run_generated_script(config, URL, False, tmp_path / "image.png", text=text) + assert result["ok"] is True + assert result["text"] == text[:expected_size] + assert result["truncated"] is True + assert result["sha256"] == hashlib.sha256(result["text"].encode()).hexdigest() + + +@pytest.mark.parametrize("image", [False, True]) +def test_image_alt_limit_survives_mcp_serialization(configured, tmp_path, image): + from mcp.types import CallToolResult, TextContent + + config = reader.ReaderConfig.from_environment() + result, _ = run_generated_script( + config, URL, image, tmp_path / "image.png", alt="a" * 511 + "🙂tail", + ) + assert result["ok"] is True + alt = result["alt"] if image else result["images"][0]["alt"] + assert alt == "a" * 511 + content = TextContent(type="text", text=json.dumps(result, ensure_ascii=False)) + CallToolResult(content=[content]).model_dump_json().encode("utf-8") + + @pytest.mark.parametrize("image", [False, True]) @pytest.mark.parametrize("ownership", ["agentDelegatedToUser", "user", "inactive", "unassigned", "unknown"]) def test_live_user_control_stops_before_page_access_and_can_resume_without_chat( diff --git a/tests/test_goal_adapter_runtime_provenance.py b/tests/test_goal_adapter_runtime_provenance.py new file mode 100644 index 0000000000..f363a11495 --- /dev/null +++ b/tests/test_goal_adapter_runtime_provenance.py @@ -0,0 +1,158 @@ +"""Host adapters retain the imported release across real child processes.""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +import subprocess +import sys +import sysconfig +import textwrap +import venv + +import pytest + +from loopx import __version__ + + +REPO = Path(__file__).resolve().parents[1] +CLAUDE = REPO / "loopx" / "claude_goal_mode" +CALLERS = ( + "goal_mcp", + "kunlun_controller", + "kunlun_cli", + "scripts/goalmode_cmd.py", + "scripts/connect.py", + "hooks/goal_policy.py", + "statusline/goal_status.py", +) + + +@pytest.fixture(scope="module") +def mcp_only_python(tmp_path_factory): + runtime = tmp_path_factory.mktemp("mcp-only-python") + venv.EnvBuilder(with_pip=False).create(runtime) + interpreter = runtime / ("Scripts/python.exe" if os.name == "nt" else "bin/python") + probe = subprocess.run( + [str(interpreter), "-c", "import sysconfig; print(sysconfig.get_path('purelib'))"], + capture_output=True, text=True, check=True, timeout=30, + ) + # Reuse the test environment's MCP dependencies without processing its + # editable-install .pth files. The fixture must have no importable LoopX. + packages = Path(probe.stdout.strip()) + (packages / "mcp-test-dependencies.pth").write_text( + sysconfig.get_path("purelib") + "\n", encoding="utf-8", + ) + environment = {**os.environ, "PYTHONPATH": ""} + probe = subprocess.run( + [str(interpreter), "-P", "-c", + "from mcp.server.fastmcp import FastMCP; " + "import importlib.util; assert importlib.util.find_spec('loopx') is None"], + cwd=runtime, env=environment, capture_output=True, text=True, timeout=30, + ) + assert probe.returncode == 0, probe.stderr + return interpreter + + +def _host_invocation(interpreter: Path, project: Path, environment: dict[str, str], caller: str): + # The host imports the intended source release explicitly, as the managed + # MCP launcher does. This insertion deliberately does not reach children. + code = textwrap.dedent("""\ + import importlib.util, json, pathlib, subprocess, sys + from mcp.server.fastmcp import FastMCP + source, caller = sys.argv[1:3] + sys.path.insert(0, source) + if caller == "goal_mcp": + from loopx.goal_mode_mcp import GoalModeMCPConfig, GoalModeMCPControlPlane + control = GoalModeMCPControlPlane( + GoalModeMCPConfig("provenance", "claude_code", "claude_code"), lambda: {}) + print(control.run_cli(["version"])) + elif caller == "kunlun_controller": + from loopx.kunluncode_goal_mode.control_plane import LoopXControlPlane + control = LoopXControlPlane(pathlib.Path.cwd(), { + "registry": str(pathlib.Path.cwd() / "unused-registry.json"), + "goal_id": "provenance", "agent_id": "worker"}) + print(json.dumps(control._run_json(["version"]))) + elif caller == "kunlun_cli": + from loopx.kunluncode_goal_mode.cli import _loopx_prefix + result = subprocess.run([*_loopx_prefix(), "--format", "json", "version"], + capture_output=True, text=True, timeout=30) + sys.stdout.write(result.stdout) + sys.stderr.write(result.stderr) + sys.exit(result.returncode) + else: + adapter = pathlib.Path(source) / "loopx" / "claude_goal_mode" + sys.path.insert(0, str(adapter / "hooks")) + spec = importlib.util.spec_from_file_location("host_script", adapter / caller) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + prefix = module.gh_prefix if caller.endswith("goalmode_cmd.py") else module._gh_prefix + result = subprocess.run([*prefix(), "--format", "json", "version"], + capture_output=True, text=True, timeout=30) + sys.stdout.write(result.stdout) + sys.stderr.write(result.stderr) + sys.exit(result.returncode) + """) + return subprocess.run( + [str(interpreter), "-P", "-c", code, str(REPO), caller], + cwd=project, env=environment, capture_output=True, text=True, timeout=45, + ) + + +@pytest.mark.parametrize("caller,ambient", [ + *((caller, "no_loopx") for caller in CALLERS), + ("goal_mcp", "competing_cli"), + ("goal_mcp", "shadow_packages"), +]) +def test_host_children_keep_source_release(mcp_only_python, tmp_path, caller, ambient): + project = tmp_path / "foreign-project" + project.mkdir() + environment = {**os.environ, "PYTHONPATH": "", "PATH": ""} + invoked = tmp_path / "foreign-cli-invoked" + if ambient == "competing_cli": + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + trap = bin_dir / "foreign_cli.py" + trap.write_text( + f"from pathlib import Path\nPath({str(invoked)!r}).write_text('invoked')\n" + "print('{\"ok\": true, \"schema_version\": \"foreign_release\"}')\n", + encoding="utf-8", + ) + executable = bin_dir / ("loopx.cmd" if os.name == "nt" else "loopx") + if os.name == "nt": + executable.write_text(f'@"{sys.executable}" "{trap}" %*\n', encoding="utf-8") + else: + executable.write_text(f"#!{sys.executable}\n" + trap.read_text(), encoding="utf-8") + executable.chmod(0o755) + environment["PATH"] = str(bin_dir) + elif ambient == "shadow_packages": + inherited = tmp_path / "inherited-source" + for root in (project, inherited): + package = root / "loopx" + package.mkdir(parents=True) + (package / "__init__.py").write_text( + "raise RuntimeError('foreign LoopX package imported')\n", encoding="utf-8", + ) + environment["PYTHONPATH"] = str(inherited) + + result = _host_invocation(mcp_only_python, project, environment, caller) + + assert not invoked.exists(), "adapter invoked the competing PATH executable" + assert result.returncode == 0, result.stderr + payload = json.loads(result.stdout) + assert payload["ok"] is True + assert payload["schema_version"] == "loopx_version_v0" + assert payload["version"] == __version__ + + +def test_explicit_native_controller_command_override_is_preserved(tmp_path): + from loopx.kunluncode_goal_mode.control_plane import LoopXControlPlane + + launcher = tmp_path / "explicit.py" + launcher.write_text("print('{\"ok\": true, \"route\": \"explicit\"}')\n", encoding="utf-8") + control = LoopXControlPlane(tmp_path, { + "registry": str(tmp_path / "registry.json"), "goal_id": "g", "agent_id": "a", + }, command_prefix=[sys.executable, str(launcher)]) + + assert control._run_json(["version"]) == {"ok": True, "route": "explicit"} diff --git a/tests/test_loopx_turn_codex_cli.py b/tests/test_loopx_turn_codex_cli.py index d8be36dfc6..85f1756baf 100644 --- a/tests/test_loopx_turn_codex_cli.py +++ b/tests/test_loopx_turn_codex_cli.py @@ -8,6 +8,7 @@ import stat import subprocess import sys +import tomllib from pathlib import Path import pytest @@ -1124,9 +1125,15 @@ def test_codex_source_session_rejects_alias_only_descriptor( assert descriptor_path.read_bytes() == descriptor_before +@pytest.mark.parametrize("mcp_command", [ + [sys.executable, "-m", "loopx.collaboration_mcp", "--agent-id", "reviewer"], + ["/tmp/🔬/python", "/tmp/🧪/server.py", "--label=研究"], + [r"C:\Program Files\python.exe", r"C:\tools\server.py", 'quotes"\\\b\t\n\f\r\x01'], +]) def test_codex_cli_host_materializes_bound_mcp_tools_for_fresh_and_resume( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, + mcp_command: list[str], ) -> None: executable, log_path = _fake_codex(tmp_path) monkeypatch.setenv("FAKE_CODEX_LOG", str(log_path)) @@ -1136,13 +1143,7 @@ def test_codex_cli_host_materializes_bound_mcp_tools_for_fresh_and_resume( server = { "schema_version": CODEX_STDIO_MCP_SERVER_SCHEMA_VERSION, "name": "loopx_delegation", - "command": [ - sys.executable, - "-m", - "loopx.collaboration_mcp", - "--agent-id", - "reviewer", - ], + "command": mcp_command, } run_codex_cli_host( @@ -1171,23 +1172,20 @@ def test_codex_cli_host_materializes_bound_mcp_tools_for_fresh_and_resume( for index, value in enumerate(argv) if value == "-c" ] - assert ( - f'mcp_servers.loopx_delegation.command={json.dumps(sys.executable)}' - in config_values - ) - assert ( - "mcp_servers.loopx_delegation.args=" - + json.dumps(server["command"][1:]) - in config_values - ) - assert "mcp_servers.loopx_delegation.enabled=true" in config_values - assert "mcp_servers.loopx_delegation.required=true" in config_values - assert ( - 'mcp_servers.loopx_delegation.default_tools_approval_mode="approve"' - in config_values - ) - assert "mcp_servers.loopx_delegation.startup_timeout_sec=30" in config_values - assert "mcp_servers.loopx_delegation.tool_timeout_sec=60" in config_values + # Codex parses each override as TOML, not JSON. Decode with that grammar + # to prove argv values survive, including non-BMP paths and escapes. + overrides = tomllib.loads("\n".join( + value for value in config_values if value.startswith("mcp_servers.") + ))["mcp_servers"]["loopx_delegation"] + assert overrides == { + "command": mcp_command[0], + "args": mcp_command[1:], + "enabled": True, + "required": True, + "default_tools_approval_mode": "approve", + "startup_timeout_sec": 30, + "tool_timeout_sec": 60, + } def test_codex_cli_host_rejects_invalid_mcp_binding_before_launch( diff --git a/tests/test_slash_command_install.py b/tests/test_slash_command_install.py index 102f91f910..2d0b32255e 100644 --- a/tests/test_slash_command_install.py +++ b/tests/test_slash_command_install.py @@ -1275,6 +1275,105 @@ def test_cursor_mcp_writes_then_retires_only_its_own_entry( assert not (cursor_home / slash_command_install.CURSOR_MCP_MARKER_NAME).exists() +def test_cursor_mcp_preserves_edits_made_during_provisioning( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + entry = _stub_mcp_command(monkeypatch) + cursor_home = tmp_path / "cursor" + cursor_home.mkdir() + config = cursor_home / "mcp.json" + config.write_text(json.dumps({"mcpServers": {}}), encoding="utf-8") + edited = { + "mcpServers": {"other": {"command": "user-server"}}, + "settings": {"enabled": False}, + } + + def provision() -> tuple[str, str]: + config.write_text(json.dumps(edited), encoding="utf-8") + return str(entry["command"]), str(entry["args"][0]) + + monkeypatch.setattr(slash_command_install, "_loopx_mcp_command", provision) + payload = install_slash_commands( + execute=True, surfaces=["cursor"], cursor_home=str(cursor_home) + ) + + assert _row(payload, "cursor_mcp_server")["status"] == "written" + expected = {**edited, "mcpServers": {**edited["mcpServers"], "loopx": entry}} + assert json.loads(config.read_text(encoding="utf-8")) == expected + + +@pytest.mark.parametrize("change", ["entry", "marker", "invalid_json"]) +def test_cursor_mcp_revalidates_ownership_after_provisioning( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + change: str, +) -> None: + entry = _stub_mcp_command(monkeypatch) + cursor_home = tmp_path / "cursor" + install_slash_commands(execute=True, surfaces=["cursor"], cursor_home=str(cursor_home)) + config = cursor_home / "mcp.json" + marker = cursor_home / slash_command_install.CURSOR_MCP_MARKER_NAME + edited = config.read_text(encoding="utf-8") + if change == "entry": + edited = json.dumps({"mcpServers": {"loopx": {"command": "user-server"}}}) + elif change == "invalid_json": + edited = "{ incomplete user edit" + + def provision() -> tuple[str, str]: + config.write_text(edited, encoding="utf-8") + if change == "marker": + marker.unlink() + return str(entry["command"]), "/opt/loopx/mcp/upgraded_server.py" + + monkeypatch.setattr(slash_command_install, "_loopx_mcp_command", provision) + payload = install_slash_commands( + execute=True, surfaces=["cursor"], cursor_home=str(cursor_home) + ) + + expected_status = ( + "blocked_invalid_cursor_mcp_json" + if change.startswith("invalid_") + else "skipped_user_owned_mcp_entry" + ) + assert _row(payload, "cursor_mcp_server")["status"] == expected_status + assert config.read_text(encoding="utf-8") == edited + if change in {"entry", "marker"}: + assert not marker.exists() + + +def test_cursor_mcp_install_and_uninstall_preserve_config_symlink( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + entry = _stub_mcp_command(monkeypatch) + cursor_home = tmp_path / "cursor" + cursor_home.mkdir() + config = cursor_home / "mcp.json" + target = tmp_path / "dotfiles" / "cursor-mcp.json" + original = {"mcpServers": {"other": {"command": "user-server"}}} + target.parent.mkdir() + target.write_text(json.dumps(original), encoding="utf-8") + target.chmod(0o640) + config.symlink_to(Path("..") / "dotfiles" / target.name) + + payload = install_slash_commands( + execute=True, surfaces=["cursor"], cursor_home=str(cursor_home) + ) + assert _row(payload, "cursor_mcp_server")["status"] == "written" + assert config.is_symlink() + assert json.loads(target.read_text(encoding="utf-8"))["mcpServers"]["loopx"] == entry + assert target.stat().st_mode & 0o777 == 0o640 + + payload = install_slash_commands( + execute=True, uninstall=True, surfaces=["cursor"], cursor_home=str(cursor_home) + ) + assert _row(payload, "cursor_mcp_server")["status"] == "retired" + assert config.is_symlink() + assert json.loads(target.read_text(encoding="utf-8")) == original + assert target.stat().st_mode & 0o777 == 0o640 + + def test_cursor_mcp_hand_edited_entry_becomes_the_users( tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
    状态字段期望值