From 9ab003bc15f5c48c8bd652e29012bdcdd8bfc899 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:02:46 +0800 Subject: [PATCH 1/3] refactor(hosts): consolidate kiro_cli, opencode, opencode2, and pi under loopx/hosts Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- README.ja.md | 2 +- README.md | 2 +- README.zh-CN.md | 2 +- apps/presentation/dashboard/README.md | 2 +- .../rfcs/desktop-execution-frontends-v0.md | 2 +- .../desktop-execution-frontends-v0.zh-CN.md | 2 +- .../rfcs/loopx-overall-roadmap-v0.md | 9 +-- .../rfcs/loopx-overall-roadmap-v0.zh-CN.md | 10 +-- ...shared-goal-authority-state-provider-v0.md | 2 +- ...-goal-authority-state-provider-v0.zh-CN.md | 2 +- docs/book/chapters/00-reading-guide.md | 4 +- docs/book/en/chapters/00-reading-guide.md | 4 +- docs/guides/getting-started.md | 2 +- .../kiro-cli-goal-command-contract-probe.py | 4 +- examples/loopx-chat-acp-adapter-smoke.py | 2 +- loopx/agent_onboarding.py | 4 +- loopx/chat/endpoint_catalog.py | 2 +- loopx/chat/endpoints.py | 2 +- loopx/chat/session_open.py | 2 +- loopx/chat_actions.py | 2 +- loopx/chat_runtime.py | 2 +- loopx/chat_server.py | 2 +- loopx/cli_commands/opencode2_goal_worker.py | 2 +- loopx/cli_commands/slash_commands.py | 2 +- loopx/cli_commands/support_control.py | 2 +- loopx/cli_commands/support_control_chat.py | 2 +- loopx/dashboard_launcher.py | 2 +- loopx/host_loop_activation.py | 2 +- loopx/hosts/__init__.py | 11 +++ .../kiro_cli}/README.md | 2 +- .../kiro_cli}/__init__.py | 0 .../kiro_cli}/mcp_server.py | 6 +- .../opencode}/README.md | 2 +- loopx/hosts/opencode/__init__.py | 11 +++ .../opencode}/goal-bridge-runtime.mjs | 0 .../opencode}/loopx-goal.js | 0 .../opencode2}/README.md | 0 loopx/hosts/opencode2/__init__.py | 7 ++ .../opencode2}/opencode2-goal-worker.mjs | 0 loopx/{pi_goal_mode => hosts/pi}/README.md | 0 loopx/hosts/pi/__init__.py | 11 +++ .../pi}/installation.py | 2 +- .../{pi_goal_mode => hosts/pi}/loopx-goal.ts | 0 .../pi}/pi-goal-loop-runtime.mjs | 0 loopx/hosts/skill_facade.py | 6 +- loopx/hosts/slash_command_surfaces.py | 2 +- loopx/opencode2_goal_mode/__init__.py | 9 --- loopx/opencode_goal_mode/__init__.py | 13 ---- loopx/pi_goal_mode/__init__.py | 13 ---- loopx/slash_command_install.py | 10 +-- pyproject.toml | 7 +- ...test_managed_slash_command_marker_owner.py | 8 +- tests/control_plane/test_pi_adapter_start.py | 2 +- tests/opencode2_goal_worker.test.mjs | 6 +- tests/opencode_goal_bridge_runtime.test.mjs | 6 +- tests/pi_goal_adapter_authority.test.mjs | 2 +- tests/pi_goal_adapter_input.test.mjs | 4 +- tests/pi_goal_loop_runtime.test.mjs | 2 +- tests/test_host_loop_runtime_parity.py | 2 +- tests/test_hosts_goal_mode_consolidation.py | 78 +++++++++++++++++++ tests/test_kiro_cli_host_surface.py | 4 +- tests/test_kiro_cli_mcp.py | 4 +- tests/test_pi_goal_mode.py | 2 +- tests/test_slash_command_install.py | 2 +- .../test_slash_command_install_equivalence.py | 11 ++- 65 files changed, 208 insertions(+), 116 deletions(-) rename loopx/{kiro_cli_goal_mode => hosts/kiro_cli}/README.md (99%) rename loopx/{kiro_cli_goal_mode => hosts/kiro_cli}/__init__.py (100%) rename loopx/{kiro_cli_goal_mode => hosts/kiro_cli}/mcp_server.py (94%) rename loopx/{opencode_goal_mode => hosts/opencode}/README.md (99%) create mode 100644 loopx/hosts/opencode/__init__.py rename loopx/{opencode_goal_mode => hosts/opencode}/goal-bridge-runtime.mjs (100%) rename loopx/{opencode_goal_mode => hosts/opencode}/loopx-goal.js (100%) rename loopx/{opencode2_goal_mode => hosts/opencode2}/README.md (100%) create mode 100644 loopx/hosts/opencode2/__init__.py rename loopx/{opencode2_goal_mode => hosts/opencode2}/opencode2-goal-worker.mjs (100%) rename loopx/{pi_goal_mode => hosts/pi}/README.md (100%) create mode 100644 loopx/hosts/pi/__init__.py rename loopx/{pi_goal_mode => hosts/pi}/installation.py (98%) rename loopx/{pi_goal_mode => hosts/pi}/loopx-goal.ts (100%) rename loopx/{pi_goal_mode => hosts/pi}/pi-goal-loop-runtime.mjs (100%) delete mode 100644 loopx/opencode2_goal_mode/__init__.py delete mode 100644 loopx/opencode_goal_mode/__init__.py delete mode 100644 loopx/pi_goal_mode/__init__.py create mode 100644 tests/test_hosts_goal_mode_consolidation.py diff --git a/README.ja.md b/README.ja.md index 8382eccc47..2dd2fa9e4d 100644 --- a/README.ja.md +++ b/README.ja.md @@ -310,7 +310,7 @@ Todo として計画して、ホストの有効化をガイドします。アク [Codex CLI のパッケージインストール手順](docs/product/runtimes/codex-cli/codex-cli-packaged-install.md)、 [Claude Code アダプター](loopx/claude_goal_mode/README.md)、 [KunlunCode のネイティブ Goal アダプター](loopx/kunluncode_goal_mode/README.md)、 -[Kiro CLI の goal-mode アダプター](loopx/kiro_cli_goal_mode/README.md)、または +[Kiro CLI の goal-mode アダプター](loopx/hosts/kiro_cli/README.md)、または [DeepSeek Harness のターンアダプター](loopx/dsh_goal_mode/README.md)を確認できます。 ネイティブな手順については、[60 秒の DSH × LoopX Replan の録画と再現可能な diff --git a/README.md b/README.md index 2a7a15f16e..d675549ec2 100644 --- a/README.md +++ b/README.md @@ -324,7 +324,7 @@ the [Codex App host command registry contract](docs/reference/protocols/codex-ap the [Codex CLI packaged install path](docs/product/runtimes/codex-cli/codex-cli-packaged-install.md), the [Claude Code adapter](loopx/claude_goal_mode/README.md), the [KunlunCode native Goal adapter](loopx/kunluncode_goal_mode/README.md), the -[Kiro CLI goal-mode adapter](loopx/kiro_cli_goal_mode/README.md), or the +[Kiro CLI goal-mode adapter](loopx/hosts/kiro_cli/README.md), or the [DeepSeek Harness turn adapter](loopx/dsh_goal_mode/README.md). See the [60-second DSH × LoopX Replan recording and reproducible diff --git a/README.zh-CN.md b/README.zh-CN.md index ee67ed5cb2..8a04460caf 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -272,7 +272,7 @@ LoopX 会复用项目已有状态或连接项目,把工作规划成 Todo,并 [Codex CLI packaged install](docs/product/runtimes/codex-cli/codex-cli-packaged-install.md)和 [Claude Code adapter](loopx/claude_goal_mode/README.md)、 [KunlunCode 原生 Goal adapter](docs/guides/kunluncode-adapter.zh-CN.md)、 -[Kiro CLI goal-mode adapter](loopx/kiro_cli_goal_mode/README.md),以及 +[Kiro CLI goal-mode adapter](loopx/hosts/kiro_cli/README.md),以及 [DeepSeek Harness turn adapter](loopx/dsh_goal_mode/README.md)。 可查看 [60 秒 DSH × LoopX Replan 真实录屏和可复现 diff --git a/apps/presentation/dashboard/README.md b/apps/presentation/dashboard/README.md index 326e16e8e8..e48e95be79 100644 --- a/apps/presentation/dashboard/README.md +++ b/apps/presentation/dashboard/README.md @@ -150,7 +150,7 @@ so a Kiro tool call that needs approval is refused rather than auto-approved. LoopX passes no `--trust-all-tools`. Reaching the host this way drives one read-only Chat session; it is not the governed `/goal` loop, which is entered from a Kiro CLI session through the -[Kiro CLI goal-mode adapter](../../../loopx/kiro_cli_goal_mode/README.md). +[Kiro CLI goal-mode adapter](../../../loopx/hosts/kiro_cli/README.md). Source-checkout development is a separate mode: diff --git a/docs/architecture/rfcs/desktop-execution-frontends-v0.md b/docs/architecture/rfcs/desktop-execution-frontends-v0.md index 74267fcc19..d15de1c633 100644 --- a/docs/architecture/rfcs/desktop-execution-frontends-v0.md +++ b/docs/architecture/rfcs/desktop-execution-frontends-v0.md @@ -1261,7 +1261,7 @@ checkout or passing helper test does not qualify this native process boundary. - [Extensions](../../reference/extensions.md) - [LoopX Turn v0](../../reference/protocols/loopx-turn-v0.md) - [DeepSeek Harness connector](../../integrations/deepseek-harness-connector.md) -- [Pi Goal mode](../../../loopx/pi_goal_mode/README.md) +- [Pi Goal mode](../../../loopx/hosts/pi/README.md) - [Goal Channel collaboration v0](goal-channel-collaboration-v0.md) - [Volcengine Ark Agent Plan documentation](https://www.volcengine.com/docs/82379/1928262) - [Volcengine Ark API overview](https://api.volcengine.com/api-docs/view?serviceCode=ark&version=2024-01-01) diff --git a/docs/architecture/rfcs/desktop-execution-frontends-v0.zh-CN.md b/docs/architecture/rfcs/desktop-execution-frontends-v0.zh-CN.md index 9cd1326499..1470cfd76a 100644 --- a/docs/architecture/rfcs/desktop-execution-frontends-v0.zh-CN.md +++ b/docs/architecture/rfcs/desktop-execution-frontends-v0.zh-CN.md @@ -1021,7 +1021,7 @@ provider 新增忙碌回合输入能力。 - [Extensions](../../reference/extensions.md) - [LoopX Turn v0](../../reference/protocols/loopx-turn-v0.md) - [DeepSeek Harness connector](../../integrations/deepseek-harness-connector.md) -- [Pi Goal mode](../../../loopx/pi_goal_mode/README.md) +- [Pi Goal mode](../../../loopx/hosts/pi/README.md) - [Goal Channel collaboration v0](goal-channel-collaboration-v0.md) - [Volcengine Ark Agent Plan documentation](https://www.volcengine.com/docs/82379/1928262) - [Volcengine Ark API overview](https://api.volcengine.com/api-docs/view?serviceCode=ark&version=2024-01-01) diff --git a/docs/architecture/rfcs/loopx-overall-roadmap-v0.md b/docs/architecture/rfcs/loopx-overall-roadmap-v0.md index 142d0da206..f3f4def252 100644 --- a/docs/architecture/rfcs/loopx-overall-roadmap-v0.md +++ b/docs/architecture/rfcs/loopx-overall-roadmap-v0.md @@ -190,11 +190,10 @@ top-level packages: fence fidelity—never claiming autonomous execution or budget enforcement a host cannot verify. - **Consolidating `loopx/*_goal_mode/` into `loopx/hosts/`:** migrate the `9` - remaining top-level `loopx/*_goal_mode/` packages (`agy_goal_mode`, - `claude_goal_mode`, `dsh_goal_mode`, `kiro_cli_goal_mode`, - `kunluncode_goal_mode`, `opencode2_goal_mode`, `opencode_goal_mode`, - `pi_goal_mode`, `zcode_goal_mode`) into `loopx/hosts/` under shared - `HostHarnessCapabilities` projections per + top-level `loopx/*_goal_mode/` packages (`4` migrated into `loopx/hosts/`: + `hosts/kiro_cli`, `hosts/opencode`, `hosts/opencode2`, `hosts/pi`; `5` remaining: + `agy_goal_mode`, `claude_goal_mode`, `dsh_goal_mode`, `kunluncode_goal_mode`, + `zcode_goal_mode`) under shared `HostHarnessCapabilities` projections per [the unified contract's retirement gate](controller-executor-unified-contract-v0.md#3-normative-retirement-backlog-and-ratchet-rules) and [`top_level_module_budget.json`](../../../tests/architecture/top_level_module_budget.json), keeping CLI compatibility aliases strictly until caller cutover completes. diff --git a/docs/architecture/rfcs/loopx-overall-roadmap-v0.zh-CN.md b/docs/architecture/rfcs/loopx-overall-roadmap-v0.zh-CN.md index f8640cbfec..4dabc41b5b 100644 --- a/docs/architecture/rfcs/loopx-overall-roadmap-v0.zh-CN.md +++ b/docs/architecture/rfcs/loopx-overall-roadmap-v0.zh-CN.md @@ -144,11 +144,11 @@ LoopX 的权威与决策基座(`AuthorityStore`、`CAS`、`claim/lease`、`Tur 围栏保真度),绝不伪造宿主无法执行的自治承诺或预算强约束。 - **把 `loopx/*_goal_mode/` 收敛至 `loopx/hosts/`:** 按 [统一契约的退役门禁](controller-executor-unified-contract-v0.zh-CN.md#3-具名退役清单与棘轮规则)与 - [`top_level_module_budget.json`](../../../tests/architecture/top_level_module_budget.json),将现存 - `9` 个顶层 `loopx/*_goal_mode/` 包(`agy_goal_mode`、`claude_goal_mode`、`dsh_goal_mode`、 - `kiro_cli_goal_mode`、`kunluncode_goal_mode`、`opencode2_goal_mode`、`opencode_goal_mode`、 - `pi_goal_mode`、`zcode_goal_mode`)迁入 `loopx/hosts/` 并收敛至共享 `HostHarnessCapabilities` - 投影,仅在调用方切换完成前保留 CLI 兼容别名。 + [`top_level_module_budget.json`](../../../tests/architecture/top_level_module_budget.json),将 + `9` 个顶层 `loopx/*_goal_mode/` 包迁入 `loopx/hosts/` 并收敛至共享 `HostHarnessCapabilities` + 投影(已迁入 `4` 个:`hosts/kiro_cli`、`hosts/opencode`、`hosts/opencode2`、`hosts/pi`; + 待迁移 `5` 个:`agy_goal_mode`、`claude_goal_mode`、`dsh_goal_mode`、`kunluncode_goal_mode`、 + `zcode_goal_mode`),仅在调用方切换完成前保留 CLI 兼容别名。 - **漏斗验证门禁:** `BoundaryCLI`、`OrchestratedApp` 与 `InTree` 的协同优化(`Quiet-Turn`、 `EpochReset`、`Subagent Scope`、`FoldAndPrefetch`)在通过[四层漏斗验证协议](long-horizon-harness-benchmark-research-program-v0.zh-CN.md#55-四层漏斗验证协议)前均为架构与设计目标,不直接等同已测收益或默认切换。 diff --git a/docs/architecture/rfcs/shared-goal-authority-state-provider-v0.md b/docs/architecture/rfcs/shared-goal-authority-state-provider-v0.md index d52d780fe1..ecdf530d37 100644 --- a/docs/architecture/rfcs/shared-goal-authority-state-provider-v0.md +++ b/docs/architecture/rfcs/shared-goal-authority-state-provider-v0.md @@ -634,7 +634,7 @@ Source anchors for the classifications include `loopx/global_registry.py`, and the host state in `loopx/control_plane/scheduler/state.py`, `loopx/control_plane/turn_driver/codex_cli.py`, -and `loopx/pi_goal_mode/pi-goal-loop-runtime.mjs`. +and `loopx/hosts/pi/pi-goal-loop-runtime.mjs`. ## 4. What Goes Into This Coordination Ledger diff --git a/docs/architecture/rfcs/shared-goal-authority-state-provider-v0.zh-CN.md b/docs/architecture/rfcs/shared-goal-authority-state-provider-v0.zh-CN.md index 487aef8cc5..96b9d63886 100644 --- a/docs/architecture/rfcs/shared-goal-authority-state-provider-v0.zh-CN.md +++ b/docs/architecture/rfcs/shared-goal-authority-state-provider-v0.zh-CN.md @@ -514,7 +514,7 @@ owner,新 host 或 extension 也可以新增本地 artifact,而无需修改 `loopx/global_registry.py`,以及这些 host state: `loopx/control_plane/scheduler/state.py`、 `loopx/control_plane/turn_driver/codex_cli.py` 和 -`loopx/pi_goal_mode/pi-goal-loop-runtime.mjs`。 +`loopx/hosts/pi/pi-goal-loop-runtime.mjs`。 ## 4. 这本协调账里到底放什么 diff --git a/docs/book/chapters/00-reading-guide.md b/docs/book/chapters/00-reading-guide.md index 13a11cb43d..34062ff3f5 100644 --- a/docs/book/chapters/00-reading-guide.md +++ b/docs/book/chapters/00-reading-guide.md @@ -257,7 +257,7 @@ live operation 不进入当前主线。需要这些能力时,应回到官方 接入主线只以 Codex App 与 Codex CLI 为例,因为这两条路径可以端到端复现。LoopX 的 agent type 覆盖面更宽:`loopx/host_loop_activation.py` 的 `SUPPORTED_AGENT_TYPES` 列出 21 个类型,其中 9 个 -另有独立的 goal-mode 适配包(`claude_goal_mode`、`kunluncode_goal_mode`、`opencode_goal_mode`、 -`pi_goal_mode`、`zcode_goal_mode`、`agy_goal_mode`、`dsh_goal_mode`、`kiro_cli_goal_mode` 等)。 +另有目标模式适配包(`hosts/{kiro_cli,opencode,opencode2,pi}` 已迁入 `loopx/hosts/`,其余为 `claude_goal_mode`、 +`kunluncode_goal_mode`、`zcode_goal_mode`、`agy_goal_mode`、`dsh_goal_mode` 等)。 路线选择是教学取舍:其余 harness 的接入差异,以各自适配包和 [协议文档](/loopx/docs/reference/protocols/) 为准。 diff --git a/docs/book/en/chapters/00-reading-guide.md b/docs/book/en/chapters/00-reading-guide.md index a88d06eab7..a274bd1ed0 100644 --- a/docs/book/en/chapters/00-reading-guide.md +++ b/docs/book/en/chapters/00-reading-guide.md @@ -286,7 +286,7 @@ workflows. The onboarding path uses Codex App and Codex CLI as its worked examples, because those two routes can be reproduced end to end. LoopX's agent type coverage is wider: `SUPPORTED_AGENT_TYPES` in `loopx/host_loop_activation.py` lists 21 types, and 9 of them have a dedicated goal-mode adapter package -(`claude_goal_mode`, `kunluncode_goal_mode`, `opencode_goal_mode`, `pi_goal_mode`, `zcode_goal_mode`, -`agy_goal_mode`, `dsh_goal_mode`, `kiro_cli_goal_mode`, and others). Choosing two routes is a teaching +(`hosts/{kiro_cli,opencode,opencode2,pi}` consolidated under `loopx/hosts/`, alongside `claude_goal_mode`, +`kunluncode_goal_mode`, `zcode_goal_mode`, `agy_goal_mode`, `dsh_goal_mode`, and others). Choosing two routes is a teaching tradeoff, not a capability boundary: for another harness, follow its own adapter package and the [protocol documentation](/loopx/docs/reference/protocols/). diff --git a/docs/guides/getting-started.md b/docs/guides/getting-started.md index e0184aef21..c5de990cf2 100644 --- a/docs/guides/getting-started.md +++ b/docs/guides/getting-started.md @@ -100,7 +100,7 @@ can discover user-installed skills: loop runs through the persistent `loopx opencode2-goal-worker` process, which drives the session over the OpenCode 2 HTTP API and owns the loop timers, so long runs survive TUI close. OpenCode 1 plugins do not run under - OpenCode 2; see `loopx/opencode2_goal_mode/README.md`. + OpenCode 2; see `loopx/hosts/opencode2/README.md`. - Pi: the self-contained goal extension exposes `/loopx` after `/reload` or a restart and runs the quota-gated goal loop through `loopx_goal_activate`. `loopx slash-commands --install --surface pi` installs it for the current diff --git a/examples/kiro-cli-goal-command-contract-probe.py b/examples/kiro-cli-goal-command-contract-probe.py index 495e7dbee1..99d7631d2e 100644 --- a/examples/kiro-cli-goal-command-contract-probe.py +++ b/examples/kiro-cli-goal-command-contract-probe.py @@ -8,7 +8,7 @@ This probe is replayable and public-safe: it starts the host as an ACP stdio agent, reads the advertised `/goal` entry, and compares it with what -`loopx.kiro_cli_goal_mode` projects. It exits 0 and reports `skipped` when the +`loopx.hosts.kiro_cli` projects. It exits 0 and reports `skipped` when the binary is absent, so it is safe in environments without the host. python3 examples/kiro-cli-goal-command-contract-probe.py @@ -28,7 +28,7 @@ REPO_ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(REPO_ROOT)) -from loopx.kiro_cli_goal_mode import ( # noqa: E402 +from loopx.hosts.kiro_cli import ( # noqa: E402 KIRO_CLI_GOAL_CLEAR_COMMAND, KIRO_CLI_GOAL_COMMAND, KIRO_CLI_GOAL_MAX_FLAG, diff --git a/examples/loopx-chat-acp-adapter-smoke.py b/examples/loopx-chat-acp-adapter-smoke.py index 933bc62188..c3f78b1ffd 100644 --- a/examples/loopx-chat-acp-adapter-smoke.py +++ b/examples/loopx-chat-acp-adapter-smoke.py @@ -19,7 +19,7 @@ from loopx.chat.endpoints import AgentEndpointRegistry # noqa: E402 from loopx.chat_runtime import ChatRuntimeController # noqa: E402 from loopx.chat_store import ChatSessionStore # noqa: E402 -from loopx.kiro_cli_goal_mode import KIRO_CLI_CHAT_AGENT_ID # noqa: E402 +from loopx.hosts.kiro_cli import KIRO_CLI_CHAT_AGENT_ID # noqa: E402 FAKE_ACP = r'''#!/usr/bin/env python3 diff --git a/loopx/agent_onboarding.py b/loopx/agent_onboarding.py index bb4c8fe38c..50bddbb209 100644 --- a/loopx/agent_onboarding.py +++ b/loopx/agent_onboarding.py @@ -19,13 +19,13 @@ ) from .history import load_registry from .install_contract import NO_CLONE_INSTALL_URL -from .kiro_cli_goal_mode import ( +from .hosts.kiro_cli import ( KIRO_CLI_GOAL_CLEAR_COMMAND, KIRO_CLI_GOAL_COMPLETION_TOOL, KIRO_CLI_GOAL_DEFAULT_MAX_ITERATIONS, kiro_cli_goal_invocation, ) -from .kiro_cli_goal_mode import ( +from .hosts.kiro_cli import ( SKILLS_ROOT_LABEL as KIRO_CLI_SKILLS_ROOT_LABEL, ) from .project_prompt import ( diff --git a/loopx/chat/endpoint_catalog.py b/loopx/chat/endpoint_catalog.py index 85a60f0151..18fafdf582 100644 --- a/loopx/chat/endpoint_catalog.py +++ b/loopx/chat/endpoint_catalog.py @@ -23,7 +23,7 @@ MANAGED_TURN_HOST, managed_executor_binding, ) -from ..kiro_cli_goal_mode import ( +from ..hosts.kiro_cli import ( KIRO_CLI_CHAT_ADAPTER_KIND, KIRO_CLI_CHAT_AGENT_ID, KIRO_CLI_CHAT_DISPLAY_NAME, diff --git a/loopx/chat/endpoints.py b/loopx/chat/endpoints.py index 8a8fc8a399..70ca1e0a12 100644 --- a/loopx/chat/endpoints.py +++ b/loopx/chat/endpoints.py @@ -12,7 +12,7 @@ from ..chat_store import utc_now from ..file_lock import exclusive_file_lock, write_json_atomic -from ..kiro_cli_goal_mode import KIRO_CLI_CHAT_AGENT_ID +from ..hosts.kiro_cli import KIRO_CLI_CHAT_AGENT_ID CHAT_ENDPOINT_REGISTRY_SCHEMA_VERSION = "loopx_chat_endpoint_registry_v1" diff --git a/loopx/chat/session_open.py b/loopx/chat/session_open.py index 7a8121eb3c..00774e999e 100644 --- a/loopx/chat/session_open.py +++ b/loopx/chat/session_open.py @@ -71,7 +71,7 @@ from ..control_plane.turn_driver.execution_profile import managed_execution_profile from ..control_plane.turn_driver.host_binding import MANAGED_TURN_HOST from ..file_lock import exclusive_cross_runtime_file_lock -from ..kiro_cli_goal_mode import KIRO_CLI_CHAT_AGENT_ID, kiro_cli_chat_command +from ..hosts.kiro_cli import KIRO_CLI_CHAT_AGENT_ID, kiro_cli_chat_command from .coordination import PROJECT_CONTEXT_VERSION if TYPE_CHECKING: diff --git a/loopx/chat_actions.py b/loopx/chat_actions.py index 8f261714ef..c8d6d9fc59 100644 --- a/loopx/chat_actions.py +++ b/loopx/chat_actions.py @@ -40,7 +40,7 @@ from .control_plane.todos.contract import TODO_DECISION_OUTCOME_VALUES from .history import load_registry from .host_loop_activation import build_host_loop_activation_packet -from .kiro_cli_goal_mode import KIRO_CLI_CHAT_AGENT_ID +from .hosts.kiro_cli import KIRO_CLI_CHAT_AGENT_ID from .paths import resolve_runtime_root from .public_safe_text import OPAQUE_ID_PATTERN as _OPAQUE_ID from .quota import build_quota_should_run diff --git a/loopx/chat_runtime.py b/loopx/chat_runtime.py index fabe593765..4e967fa6d3 100644 --- a/loopx/chat_runtime.py +++ b/loopx/chat_runtime.py @@ -56,7 +56,7 @@ LOCK_HOLDER_DEAD, LOCK_HOLDER_LIVE, LOCK_HOLDER_RELEASED, LockAcquireTimeoutError, _lock_id, lock_holder_host_label, lock_holder_liveness, process_is_alive, try_exclusive_file_lock, ) -from .kiro_cli_goal_mode import KIRO_CLI_BIN +from .hosts.kiro_cli import KIRO_CLI_BIN from .chat_store import ( CHAT_SESSION_MODE_ATTACHED, CHAT_SESSION_MODE_MANAGED, diff --git a/loopx/chat_server.py b/loopx/chat_server.py index 4c16ae2043..de27fa7364 100644 --- a/loopx/chat_server.py +++ b/loopx/chat_server.py @@ -108,7 +108,7 @@ from .presentation.research_analysis_api import RESEARCH_ANALYSIS_PATH, ResearchAnalysisRequestMixin from .presentation.goal_source_routing import GOAL_SOURCE_LINKS_PATH, GOAL_SOURCE_STRATEGIES_PATH, GOAL_SOURCE_DOCUMENT_PATH, GoalSourceRequestMixin from .chat.todo_detail import TodoDetailRequestMixin -from .kiro_cli_goal_mode import KIRO_CLI_BIN +from .hosts.kiro_cli import KIRO_CLI_BIN from .paths import resolve_runtime_root from .release_manifest import release_runtime_identity from .control_plane.projects.registry_codec import load_registry diff --git a/loopx/cli_commands/opencode2_goal_worker.py b/loopx/cli_commands/opencode2_goal_worker.py index 48fe613318..0164ce90c9 100644 --- a/loopx/cli_commands/opencode2_goal_worker.py +++ b/loopx/cli_commands/opencode2_goal_worker.py @@ -10,7 +10,7 @@ from pathlib import Path from collections.abc import Callable, Iterable -from ..opencode2_goal_mode import worker_source +from ..hosts.opencode2 import worker_source PrintPayload = Callable[ [dict[str, object], str, Callable[[dict[str, object]], str]], diff --git a/loopx/cli_commands/slash_commands.py b/loopx/cli_commands/slash_commands.py index 60da0abbad..b304e96af0 100644 --- a/loopx/cli_commands/slash_commands.py +++ b/loopx/cli_commands/slash_commands.py @@ -5,7 +5,7 @@ import os from pathlib import Path -from ..pi_goal_mode.installation import inspect_pi_installations, render_pi_installation_markdown +from ..hosts.pi.installation import inspect_pi_installations, render_pi_installation_markdown from ..slash_command_install import install_slash_commands, render_slash_command_install_markdown from ..slash_commands import build_slash_command_catalog, render_slash_command_catalog_markdown diff --git a/loopx/cli_commands/support_control.py b/loopx/cli_commands/support_control.py index db4b049b24..b4795134f8 100644 --- a/loopx/cli_commands/support_control.py +++ b/loopx/cli_commands/support_control.py @@ -19,7 +19,7 @@ render_heartbeat_pre_quota_markdown, run_heartbeat_pre_quota, ) -from ..kiro_cli_goal_mode import KIRO_CLI_BIN +from ..hosts.kiro_cli import KIRO_CLI_BIN from ..paths import default_public_scan_root from ..registry import ( inspect_registry, diff --git a/loopx/cli_commands/support_control_chat.py b/loopx/cli_commands/support_control_chat.py index c8bb0dcde8..9e8ec16749 100644 --- a/loopx/cli_commands/support_control_chat.py +++ b/loopx/cli_commands/support_control_chat.py @@ -13,7 +13,7 @@ from typing import Any from ..chat_server import DEFAULT_CHAT_HOST, DEFAULT_CHAT_PORT -from ..kiro_cli_goal_mode import KIRO_CLI_BIN +from ..hosts.kiro_cli import KIRO_CLI_BIN from ..paths import default_public_scan_root from .support_control_agent_runtime import ( ensure_agent_runtime_path, diff --git a/loopx/dashboard_launcher.py b/loopx/dashboard_launcher.py index 9415cc25e0..0052a6c0fa 100644 --- a/loopx/dashboard_launcher.py +++ b/loopx/dashboard_launcher.py @@ -13,7 +13,7 @@ import webbrowser from .cli_commands.support_control_agent_runtime import ensure_agent_runtime_path -from .kiro_cli_goal_mode import KIRO_CLI_BIN +from .hosts.kiro_cli import KIRO_CLI_BIN from .release_manifest import release_runtime_identity diff --git a/loopx/host_loop_activation.py b/loopx/host_loop_activation.py index 2c00da83cd..0745d5d90d 100644 --- a/loopx/host_loop_activation.py +++ b/loopx/host_loop_activation.py @@ -18,7 +18,7 @@ kiro_cli_activation, zcode_activation, ) -from .kiro_cli_goal_mode import KIRO_CLI_AGENT_TYPE_CATALOG_ENTRY +from .hosts.kiro_cli import KIRO_CLI_AGENT_TYPE_CATALOG_ENTRY from .control_plane.todos.contract import ( normalize_required_capabilities, normalize_todo_claimed_by, diff --git a/loopx/hosts/__init__.py b/loopx/hosts/__init__.py index 4cd5d7b926..0c22931636 100644 --- a/loopx/hosts/__init__.py +++ b/loopx/hosts/__init__.py @@ -1 +1,12 @@ """Internal host activation projections and adapters.""" + +from __future__ import annotations + +from importlib import resources + + +def read_host_asset(package: str | None, filename: str) -> str: + """Load one packaged text asset relative to a host adapter subpackage.""" + if not package: + raise RuntimeError(f"host asset package is unavailable for {filename}") + return resources.files(package).joinpath(filename).read_text(encoding="utf-8") diff --git a/loopx/kiro_cli_goal_mode/README.md b/loopx/hosts/kiro_cli/README.md similarity index 99% rename from loopx/kiro_cli_goal_mode/README.md rename to loopx/hosts/kiro_cli/README.md index 827219a3c8..cf4796cbf2 100644 --- a/loopx/kiro_cli_goal_mode/README.md +++ b/loopx/hosts/kiro_cli/README.md @@ -127,7 +127,7 @@ native-goal body and its blocked-state rules do not apply to Kiro. ## MCP control plane -The kiro-cli surface registers `loopx/kiro_cli_goal_mode/mcp_server.py` in +The kiro-cli surface registers `loopx/hosts/kiro_cli/mcp_server.py` in `/settings/mcp.json`, which Kiro's default agent loads, so the session that runs `/loopx` also gets the typed `should_run`, `list_todos`, `claim_task`, `complete_task` and `review_task_vision` tools. It is the shared diff --git a/loopx/kiro_cli_goal_mode/__init__.py b/loopx/hosts/kiro_cli/__init__.py similarity index 100% rename from loopx/kiro_cli_goal_mode/__init__.py rename to loopx/hosts/kiro_cli/__init__.py diff --git a/loopx/kiro_cli_goal_mode/mcp_server.py b/loopx/hosts/kiro_cli/mcp_server.py similarity index 94% rename from loopx/kiro_cli_goal_mode/mcp_server.py rename to loopx/hosts/kiro_cli/mcp_server.py index cadb53ef86..7e67c3c786 100644 --- a/loopx/kiro_cli_goal_mode/mcp_server.py +++ b/loopx/hosts/kiro_cli/mcp_server.py @@ -22,14 +22,14 @@ from typing import Any # The provisioned MCP interpreter does not have LoopX installed; the package -# root is two levels above this file in both a checkout and a wheel install. -PACKAGE_PARENT = Path(__file__).resolve().parents[2] +# root is three levels above this file in both a checkout and a wheel install. +PACKAGE_PARENT = Path(__file__).resolve().parents[3] if str(PACKAGE_PARENT) not in sys.path: sys.path.insert(0, str(PACKAGE_PARENT)) from loopx.goal_mode_context import find_registry, resolve_goal_context # noqa: E402 from loopx.goal_mode_mcp import GoalModeMCPConfig, create_fastmcp_server # noqa: E402 -from loopx.kiro_cli_goal_mode import ( # noqa: E402 +from loopx.hosts.kiro_cli import ( # noqa: E402 KIRO_CLI_AGENT_TYPE, KIRO_CLI_SESSION_ID_ENV, ) diff --git a/loopx/opencode_goal_mode/README.md b/loopx/hosts/opencode/README.md similarity index 99% rename from loopx/opencode_goal_mode/README.md rename to loopx/hosts/opencode/README.md index 6ca175bbfa..b6491bd934 100644 --- a/loopx/opencode_goal_mode/README.md +++ b/loopx/hosts/opencode/README.md @@ -71,7 +71,7 @@ Bindings are private per-session JSON files under and use mode `0600`. OpenCode's one-shot `opencode run` process cannot own timers after exit; recurring operation requires the visible TUI or a persistent OpenCode server. OpenCode 2 runs a persistent goal worker instead; -see `loopx/opencode2_goal_mode/README.md`. +see `loopx/hosts/opencode2/README.md`. Quota probes carry `--record-host-poll`, so LoopX writes a compact poll receipt beside the goal state file and `loopx global-risks` can flag a loop diff --git a/loopx/hosts/opencode/__init__.py b/loopx/hosts/opencode/__init__.py new file mode 100644 index 0000000000..ddb443ea01 --- /dev/null +++ b/loopx/hosts/opencode/__init__.py @@ -0,0 +1,11 @@ +from __future__ import annotations + +from .. import read_host_asset + + +def plugin_source() -> str: + return read_host_asset(__package__, "loopx-goal.js") + + +def runtime_source() -> str: + return read_host_asset(__package__, "goal-bridge-runtime.mjs") diff --git a/loopx/opencode_goal_mode/goal-bridge-runtime.mjs b/loopx/hosts/opencode/goal-bridge-runtime.mjs similarity index 100% rename from loopx/opencode_goal_mode/goal-bridge-runtime.mjs rename to loopx/hosts/opencode/goal-bridge-runtime.mjs diff --git a/loopx/opencode_goal_mode/loopx-goal.js b/loopx/hosts/opencode/loopx-goal.js similarity index 100% rename from loopx/opencode_goal_mode/loopx-goal.js rename to loopx/hosts/opencode/loopx-goal.js diff --git a/loopx/opencode2_goal_mode/README.md b/loopx/hosts/opencode2/README.md similarity index 100% rename from loopx/opencode2_goal_mode/README.md rename to loopx/hosts/opencode2/README.md diff --git a/loopx/hosts/opencode2/__init__.py b/loopx/hosts/opencode2/__init__.py new file mode 100644 index 0000000000..32de772c76 --- /dev/null +++ b/loopx/hosts/opencode2/__init__.py @@ -0,0 +1,7 @@ +from __future__ import annotations + +from .. import read_host_asset + + +def worker_source() -> str: + return read_host_asset(__package__, "opencode2-goal-worker.mjs") diff --git a/loopx/opencode2_goal_mode/opencode2-goal-worker.mjs b/loopx/hosts/opencode2/opencode2-goal-worker.mjs similarity index 100% rename from loopx/opencode2_goal_mode/opencode2-goal-worker.mjs rename to loopx/hosts/opencode2/opencode2-goal-worker.mjs diff --git a/loopx/pi_goal_mode/README.md b/loopx/hosts/pi/README.md similarity index 100% rename from loopx/pi_goal_mode/README.md rename to loopx/hosts/pi/README.md diff --git a/loopx/hosts/pi/__init__.py b/loopx/hosts/pi/__init__.py new file mode 100644 index 0000000000..f40cb8b72c --- /dev/null +++ b/loopx/hosts/pi/__init__.py @@ -0,0 +1,11 @@ +from __future__ import annotations + +from .. import read_host_asset + + +def extension_source() -> str: + return read_host_asset(__package__, "loopx-goal.ts") + + +def runtime_source() -> str: + return read_host_asset(__package__, "pi-goal-loop-runtime.mjs") diff --git a/loopx/pi_goal_mode/installation.py b/loopx/hosts/pi/installation.py similarity index 98% rename from loopx/pi_goal_mode/installation.py rename to loopx/hosts/pi/installation.py index c33f270419..c785bf7a86 100644 --- a/loopx/pi_goal_mode/installation.py +++ b/loopx/hosts/pi/installation.py @@ -6,7 +6,7 @@ from pathlib import Path from typing import Any -from ..slash_command_files import managed_marker as _managed_marker +from ...slash_command_files import managed_marker as _managed_marker from . import extension_source as pi_extension_source from . import runtime_source as pi_runtime_source diff --git a/loopx/pi_goal_mode/loopx-goal.ts b/loopx/hosts/pi/loopx-goal.ts similarity index 100% rename from loopx/pi_goal_mode/loopx-goal.ts rename to loopx/hosts/pi/loopx-goal.ts diff --git a/loopx/pi_goal_mode/pi-goal-loop-runtime.mjs b/loopx/hosts/pi/pi-goal-loop-runtime.mjs similarity index 100% rename from loopx/pi_goal_mode/pi-goal-loop-runtime.mjs rename to loopx/hosts/pi/pi-goal-loop-runtime.mjs diff --git a/loopx/hosts/skill_facade.py b/loopx/hosts/skill_facade.py index bef38874b3..0307e81f0a 100644 --- a/loopx/hosts/skill_facade.py +++ b/loopx/hosts/skill_facade.py @@ -8,8 +8,8 @@ live together here instead of each growing `host_loop_activation.py`, whose module budget is already spent on the agent-type catalog and identity rules. -Each host's facts stay in its own `*_goal_mode` package; this module only -binds them to the shared packet shape. +Each host's facts stay in its host adapter module (`loopx/hosts/*` or remaining +`*_goal_mode` packages); this module only binds them to the shared packet shape. """ from __future__ import annotations @@ -22,7 +22,7 @@ agy_activation_extras, antigravity_app_activation_extras, ) -from ..kiro_cli_goal_mode import ( +from .kiro_cli import ( KIRO_CLI_INSTALL_SURFACE, SKILLS_ROOT_LABEL as KIRO_CLI_SKILLS_ROOT_LABEL, kiro_cli_activation_extras, diff --git a/loopx/hosts/slash_command_surfaces.py b/loopx/hosts/slash_command_surfaces.py index 75a753e81b..8b1ad967f1 100644 --- a/loopx/hosts/slash_command_surfaces.py +++ b/loopx/hosts/slash_command_surfaces.py @@ -6,7 +6,7 @@ from pathlib import Path from typing import Protocol -from ..opencode_goal_mode import plugin_source, runtime_source +from .opencode import plugin_source, runtime_source from ..skill_install_readback import retire_duplicate_managed_skills from ..slash_command_files import ( CommandFacadeSpec, diff --git a/loopx/opencode2_goal_mode/__init__.py b/loopx/opencode2_goal_mode/__init__.py deleted file mode 100644 index cbeb4eaeac..0000000000 --- a/loopx/opencode2_goal_mode/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -from __future__ import annotations - -from importlib import resources - - -def worker_source() -> str: - return resources.files(__package__).joinpath("opencode2-goal-worker.mjs").read_text( - encoding="utf-8" - ) diff --git a/loopx/opencode_goal_mode/__init__.py b/loopx/opencode_goal_mode/__init__.py deleted file mode 100644 index ef6c155730..0000000000 --- a/loopx/opencode_goal_mode/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -from __future__ import annotations - -from importlib import resources - - -def plugin_source() -> str: - return resources.files(__package__).joinpath("loopx-goal.js").read_text(encoding="utf-8") - - -def runtime_source() -> str: - return resources.files(__package__).joinpath("goal-bridge-runtime.mjs").read_text( - encoding="utf-8" - ) diff --git a/loopx/pi_goal_mode/__init__.py b/loopx/pi_goal_mode/__init__.py deleted file mode 100644 index e5aae0894a..0000000000 --- a/loopx/pi_goal_mode/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -from __future__ import annotations - -from importlib import resources - - -def extension_source() -> str: - return resources.files(__package__).joinpath("loopx-goal.ts").read_text(encoding="utf-8") - - -def runtime_source() -> str: - return resources.files(__package__).joinpath("pi-goal-loop-runtime.mjs").read_text( - encoding="utf-8" - ) diff --git a/loopx/slash_command_install.py b/loopx/slash_command_install.py index cad48f0b37..36b2e241b9 100644 --- a/loopx/slash_command_install.py +++ b/loopx/slash_command_install.py @@ -24,14 +24,14 @@ install_pi_surface as _install_pi_surface, installed_entry as _installed_entry, ) -from .kiro_cli_goal_mode import ( +from .hosts.kiro_cli import ( KIRO_CLI_MCP_CONFIG_SUBPATH as _KIRO_MCP_CONFIG_SUBPATH, SKILLS_ROOT_LABEL as _KIRO_SKILLS_ROOT_LABEL, kiro_home as _kiro_home, ) -from .pi_goal_mode import extension_source as pi_extension_source -from .pi_goal_mode import runtime_source as pi_runtime_source -from .pi_goal_mode.installation import ( +from .hosts.pi import extension_source as pi_extension_source +from .hosts.pi import runtime_source as pi_runtime_source +from .hosts.pi.installation import ( _pi_agent_dir, _pi_extension_path, _pi_extension_root, @@ -645,7 +645,7 @@ def _loopx_mcp_command() -> tuple[str, str] | None: def _kiro_cli_mcp_command() -> tuple[str, str] | None: """The Kiro CLI server: same control plane, Kiro runtime profile and session-bound identity.""" - from .kiro_cli_goal_mode import mcp_server_script + from .hosts.kiro_cli import mcp_server_script return _mcp_command_for_script(mcp_server_script()) diff --git a/pyproject.toml b/pyproject.toml index 072b27d926..ce4337575f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -104,9 +104,10 @@ include = ["loopx*"] "loopx.extensions.openviking_periodic_report" = ["extension.toml"] "loopx.extensions.openviking_semantic_preference" = ["extension.toml"] "loopx.dsh_goal_mode" = ["README.md"] -"loopx.opencode_goal_mode" = ["*.js", "*.mjs", "README.md"] -"loopx.opencode2_goal_mode" = ["*.mjs", "README.md"] -"loopx.pi_goal_mode" = ["*.ts", "*.mjs", "README.md"] +"loopx.hosts.kiro_cli" = ["README.md"] +"loopx.hosts.opencode" = ["*.js", "*.mjs", "README.md"] +"loopx.hosts.opencode2" = ["*.mjs", "README.md"] +"loopx.hosts.pi" = ["*.ts", "*.mjs", "README.md"] "loopx.kunluncode_goal_mode" = ["README.md"] "loopx.zcode_goal_mode" = ["README.md", "*.ts", "contract.json", "images/*.png"] diff --git a/tests/architecture/test_managed_slash_command_marker_owner.py b/tests/architecture/test_managed_slash_command_marker_owner.py index 9eb6b0731a..523dc3af50 100644 --- a/tests/architecture/test_managed_slash_command_marker_owner.py +++ b/tests/architecture/test_managed_slash_command_marker_owner.py @@ -22,10 +22,10 @@ OWNER_MODULE = "loopx/slash_command_files.py" ASSET_HEADERS = ( - "loopx/opencode_goal_mode/goal-bridge-runtime.mjs", - "loopx/opencode_goal_mode/loopx-goal.js", - "loopx/pi_goal_mode/loopx-goal.ts", - "loopx/pi_goal_mode/pi-goal-loop-runtime.mjs", + "loopx/hosts/opencode/goal-bridge-runtime.mjs", + "loopx/hosts/opencode/loopx-goal.js", + "loopx/hosts/pi/loopx-goal.ts", + "loopx/hosts/pi/pi-goal-loop-runtime.mjs", ) # Surfaces a generated facade may be written for; each one has to survive the diff --git a/tests/control_plane/test_pi_adapter_start.py b/tests/control_plane/test_pi_adapter_start.py index c33afc6179..c4b7b6bf1b 100644 --- a/tests/control_plane/test_pi_adapter_start.py +++ b/tests/control_plane/test_pi_adapter_start.py @@ -132,7 +132,7 @@ def test_pi_start_preserves_native_identity_authority(tmp_path, monkeypatch, cas monkeypatch.setenv("LOOPX_BIN", str(launcher)) completed = subprocess.run([ node, "--input-type=module", "-e", HOST, - str(REPO / "loopx" / "pi_goal_mode" / "loopx-goal.ts"), + str(REPO / "loopx" / "hosts" / "pi" / "loopx-goal.ts"), str(project), "" if case == "ephemeral" else str(session), preview_command, ], capture_output=True, text=True, timeout=90, env=os.environ.copy()) diff --git a/tests/opencode2_goal_worker.test.mjs b/tests/opencode2_goal_worker.test.mjs index e4d6dc222f..b1747dd673 100644 --- a/tests/opencode2_goal_worker.test.mjs +++ b/tests/opencode2_goal_worker.test.mjs @@ -21,7 +21,7 @@ import { shouldRunNow, turnVerdict, waitPlan, -} from "../loopx/opencode2_goal_mode/opencode2-goal-worker.mjs" +} from "../loopx/hosts/opencode2/opencode2-goal-worker.mjs" const execFile = promisify(execFileCallback) @@ -686,7 +686,7 @@ test("createApiTransport surfaces a wait failure that is not a missing route", a test("worker entry runs main() even when argv[1] goes through a symlinked path", async () => { const workerFile = path.resolve( - path.join(import.meta.dirname, "..", "loopx", "opencode2_goal_mode", "opencode2-goal-worker.mjs"), + path.join(import.meta.dirname, "..", "loopx", "hosts", "opencode2", "opencode2-goal-worker.mjs"), ) const linkDir = path.join(os.tmpdir(), `loopx-worker-entry-${process.pid}`) const stateDir = await fs.mkdtemp(path.join(os.tmpdir(), "loopx-worker-entry-state-")) @@ -744,7 +744,7 @@ test("parseWorkerArgs maps repeated capabilities and rejects unknown flags", () test("createQuotaProbe reads a denied decision that exits non-zero", async () => { - const { createQuotaProbe } = await import("../loopx/opencode2_goal_mode/opencode2-goal-worker.mjs") + const { createQuotaProbe } = await import("../loopx/hosts/opencode2/opencode2-goal-worker.mjs") const denied = JSON.stringify({ ok: false, should_run: false, diff --git a/tests/opencode_goal_bridge_runtime.test.mjs b/tests/opencode_goal_bridge_runtime.test.mjs index b37b4515f8..8bd1801c92 100644 --- a/tests/opencode_goal_bridge_runtime.test.mjs +++ b/tests/opencode_goal_bridge_runtime.test.mjs @@ -10,7 +10,7 @@ import { createFileLockStore, pidIsAlive, waitPlan, -} from "../loopx/opencode_goal_mode/goal-bridge-runtime.mjs" +} from "../loopx/hosts/opencode/goal-bridge-runtime.mjs" function fakeTool(spec) { @@ -704,7 +704,7 @@ test("user messages keep the loop running and clear after the resume probe", asy test("probeLoopxQuota reads a denied decision that exits non-zero", async () => { - const { probeLoopxQuota } = await import("../loopx/opencode_goal_mode/goal-bridge-runtime.mjs") + const { probeLoopxQuota } = await import("../loopx/hosts/opencode/goal-bridge-runtime.mjs") const denied = JSON.stringify({ ok: false, should_run: false, @@ -726,7 +726,7 @@ test("probeLoopxQuota reads a denied decision that exits non-zero", async () => test("probeLoopxQuota fails closed when a non-zero exit carries no payload", async () => { - const { probeLoopxQuota } = await import("../loopx/opencode_goal_mode/goal-bridge-runtime.mjs") + const { probeLoopxQuota } = await import("../loopx/hosts/opencode/goal-bridge-runtime.mjs") const execFileImpl = async () => { const error = new Error("Command failed: loopx ...") error.stdout = "" diff --git a/tests/pi_goal_adapter_authority.test.mjs b/tests/pi_goal_adapter_authority.test.mjs index 3885df1132..9862caa2ca 100644 --- a/tests/pi_goal_adapter_authority.test.mjs +++ b/tests/pi_goal_adapter_authority.test.mjs @@ -29,7 +29,7 @@ childProcess.execFile = Object.assign(() => {}, { }), }); syncBuiltinESMExports(); -const { default: extension } = await import("../loopx/pi_goal_mode/loopx-goal.ts"); +const { default: extension } = await import("../loopx/hosts/pi/loopx-goal.ts"); function packet(capabilities = ["task_lease_v0"]) { return { diff --git a/tests/pi_goal_adapter_input.test.mjs b/tests/pi_goal_adapter_input.test.mjs index e844d41091..bef64ef5cb 100644 --- a/tests/pi_goal_adapter_input.test.mjs +++ b/tests/pi_goal_adapter_input.test.mjs @@ -5,7 +5,7 @@ import { createRequire, registerHooks, syncBuiltinESMExports } from "node:module import os from "node:os"; import path from "node:path"; import test from "node:test"; -import { createBindingStore, sessionKey } from "../loopx/pi_goal_mode/pi-goal-loop-runtime.mjs"; +import { createBindingStore, sessionKey } from "../loopx/hosts/pi/pi-goal-loop-runtime.mjs"; // Actual adapter and durable binding; SDK/UI and CLI admission are synthetic. // Pi's input contract delivers queued steer/followUp without before_agent_start. @@ -31,7 +31,7 @@ childProcess.execFile = Object.assign(() => {}, { }), }); syncBuiltinESMExports(); -const { default: extension } = await import("../loopx/pi_goal_mode/loopx-goal.ts"); +const { default: extension } = await import("../loopx/hosts/pi/loopx-goal.ts"); async function harness(t, { prime = true } = {}) { const directory = await mkdtemp(path.join(os.tmpdir(), "pi-owner-input-")); diff --git a/tests/pi_goal_loop_runtime.test.mjs b/tests/pi_goal_loop_runtime.test.mjs index c3c2936b4b..c629d31164 100644 --- a/tests/pi_goal_loop_runtime.test.mjs +++ b/tests/pi_goal_loop_runtime.test.mjs @@ -18,7 +18,7 @@ import { sanitizedKey, sessionKey, waitPlan, -} from "../loopx/pi_goal_mode/pi-goal-loop-runtime.mjs" +} from "../loopx/hosts/pi/pi-goal-loop-runtime.mjs" test("Pi thread identity is private, stable and distinguishes colliding basenames", () => { const file = path.join(os.tmpdir(), "project-a", "session.jsonl") diff --git a/tests/test_host_loop_runtime_parity.py b/tests/test_host_loop_runtime_parity.py index 8f07238571..bd4742f23f 100644 --- a/tests/test_host_loop_runtime_parity.py +++ b/tests/test_host_loop_runtime_parity.py @@ -150,7 +150,7 @@ def _pi_plan( node = shutil.which("node") if node is None: pytest.skip("node is required for Pi scheduler-consumer parity") - runtime_uri = (REPO_ROOT / "loopx/pi_goal_mode/pi-goal-loop-runtime.mjs").as_uri() + runtime_uri = (REPO_ROOT / "loopx/hosts/pi/pi-goal-loop-runtime.mjs").as_uri() probe = f""" import {{ waitPlan }} from {json.dumps(runtime_uri)} let raw = "" diff --git a/tests/test_hosts_goal_mode_consolidation.py b/tests/test_hosts_goal_mode_consolidation.py new file mode 100644 index 0000000000..d9946da058 --- /dev/null +++ b/tests/test_hosts_goal_mode_consolidation.py @@ -0,0 +1,78 @@ +"""Contracts protecting the consolidation of host adapters under loopx/hosts/.""" + +from __future__ import annotations + +import os +from pathlib import Path +import subprocess +import sys + +import pytest + +from loopx.hosts import read_host_asset +from loopx.hosts.kiro_cli import mcp_server_script +from loopx.hosts.opencode import plugin_source as opencode_plugin_source +from loopx.hosts.opencode import runtime_source as opencode_runtime_source +from loopx.hosts.opencode2 import worker_source as opencode2_worker_source +from loopx.hosts.pi import extension_source as pi_extension_source +from loopx.hosts.pi import runtime_source as pi_runtime_source + +REPO_ROOT = Path(__file__).resolve().parents[1] + + +def test_retired_goal_mode_packages_live_under_hosts() -> None: + for retired in ( + "kiro_cli_goal_mode", + "opencode_goal_mode", + "opencode2_goal_mode", + "pi_goal_mode", + ): + assert not (REPO_ROOT / "loopx" / retired).exists(), retired + + for host_dir in ("kiro_cli", "opencode", "opencode2", "pi"): + assert (REPO_ROOT / "loopx" / "hosts" / host_dir / "__init__.py").is_file() + assert (REPO_ROOT / "loopx" / "hosts" / host_dir / "README.md").is_file() + + +def test_shared_host_asset_loader_reads_consolidated_assets_and_fails_closed() -> None: + assert "LoopXGoalPlugin" in opencode_plugin_source() + assert "createLoopxGoalPlugin" in opencode_runtime_source() + assert "STATE_SCHEMA_VERSION" in opencode2_worker_source() + assert "loopx_goal_activate" in pi_extension_source() + assert "createGoalLoop" in pi_runtime_source() + + with pytest.raises(RuntimeError, match="host asset package is unavailable"): + read_host_asset(None, "loopx-goal.ts") + + +def test_kiro_mcp_server_resolves_package_parent_without_pythonpath( + tmp_path: Path, +) -> None: + script = mcp_server_script() + assert script == REPO_ROOT / "loopx" / "hosts" / "kiro_cli" / "mcp_server.py" + assert script.is_file() + + env = { + key: value + for key, value in os.environ.items() + if key != "PYTHONPATH" + } + probe = ( + "import importlib.util\n" + f"spec = importlib.util.spec_from_file_location('kiro_mcp_probe', {str(script)!r})\n" + "assert spec is not None and spec.loader is not None\n" + "mod = importlib.util.module_from_spec(spec)\n" + "spec.loader.exec_module(mod)\n" + "assert mod.PACKAGE_PARENT.resolve() == __import__('pathlib').Path(" + f"{str(REPO_ROOT)!r}).resolve()\n" + "assert mod.KIRO_CLI_RUNTIME_PROFILE == 'kiro_cli'\n" + ) + completed = subprocess.run( + [sys.executable, "-c", probe], + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + check=False, + ) + assert completed.returncode == 0, completed.stderr + completed.stdout diff --git a/tests/test_kiro_cli_host_surface.py b/tests/test_kiro_cli_host_surface.py index 9eac681460..681f99b3fb 100644 --- a/tests/test_kiro_cli_host_surface.py +++ b/tests/test_kiro_cli_host_surface.py @@ -42,7 +42,7 @@ normalize_agent_type, scheduler_command_binding_for_agent_type, ) -from loopx.kiro_cli_goal_mode import ( +from loopx.hosts.kiro_cli import ( KIRO_CLI_CHAT_AGENT_ID, KIRO_CLI_GOAL_CLEAR_COMMAND, KIRO_CLI_GOAL_COMMAND, @@ -219,7 +219,7 @@ def test_every_actionable_consumer_renders_the_complete_goal_command() -> None: # Public docs are consumers too: a reader copies the row, not the module. for doc in ( - "loopx/kiro_cli_goal_mode/README.md", + "loopx/hosts/kiro_cli/README.md", "README.md", "README.zh-CN.md", ): diff --git a/tests/test_kiro_cli_mcp.py b/tests/test_kiro_cli_mcp.py index 7163aa54e6..bb777f8020 100644 --- a/tests/test_kiro_cli_mcp.py +++ b/tests/test_kiro_cli_mcp.py @@ -25,12 +25,12 @@ initialize_goal_storage_target, ) from loopx.goal_mode_mcp import GoalModeMCPControlPlane -from loopx.kiro_cli_goal_mode import ( +from loopx.hosts.kiro_cli import ( KIRO_CLI_MCP_CONFIG_SUBPATH, KIRO_CLI_SESSION_ID_ENV, mcp_server_script, ) -from loopx.kiro_cli_goal_mode.mcp_server import CONFIG, goal_context +from loopx.hosts.kiro_cli.mcp_server import CONFIG, goal_context from loopx.slash_command_install import install_slash_commands from loopx.status import parse_active_state_todos from loopx.todos import add_goal_todo diff --git a/tests/test_pi_goal_mode.py b/tests/test_pi_goal_mode.py index 0f71714242..0cb05df0a2 100644 --- a/tests/test_pi_goal_mode.py +++ b/tests/test_pi_goal_mode.py @@ -6,7 +6,7 @@ import pytest -from loopx.pi_goal_mode import extension_source, runtime_source +from loopx.hosts.pi import extension_source, runtime_source def test_pi_extension_source_is_managed_and_self_contained() -> None: diff --git a/tests/test_slash_command_install.py b/tests/test_slash_command_install.py index 6523d5c8b0..aa0962a575 100644 --- a/tests/test_slash_command_install.py +++ b/tests/test_slash_command_install.py @@ -5,7 +5,7 @@ from loopx.entrypoint import main as loopx_main from loopx import slash_command_install -from loopx.pi_goal_mode.installation import inspect_pi_installations +from loopx.hosts.pi.installation import inspect_pi_installations from loopx.slash_command_install import ( install_slash_commands, materialize_loopx_entry_skill, diff --git a/tests/test_slash_command_install_equivalence.py b/tests/test_slash_command_install_equivalence.py index 136afe5833..59bfdb7481 100644 --- a/tests/test_slash_command_install_equivalence.py +++ b/tests/test_slash_command_install_equivalence.py @@ -46,8 +46,17 @@ def _load_baseline_module( module = ModuleType("loopx._baseline_slash_command_install") module.__file__ = str(REPOSITORY_ROOT / relpath) module.__package__ = "loopx" + # Historical commit e5d5945f6 imported kiro_cli_goal_mode, opencode_goal_mode, + # and pi_goal_mode before those packages moved under loopx/hosts/. + compiled_source = ( + source.replace("from .kiro_cli_goal_mode", "from .hosts.kiro_cli") + .replace("from .opencode_goal_mode", "from .hosts.opencode") + .replace("from .pi_goal_mode", "from .hosts.pi") + if source_override is None + else source + ) try: - code = compile(source, f"{commit}:{relpath}", "exec") + code = compile(compiled_source, f"{commit}:{relpath}", "exec") exec(code, module.__dict__) except Exception as exc: raise RuntimeError( From aa38b92613f9bfebd12b161cb956266745d2c05d Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:47:48 +0800 Subject: [PATCH 2/3] fix(hosts): migrate managed Kiro MCP config on default slash-commands install Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/hosts/slash_command_config_io.py | 38 +++++ loopx/slash_command_install.py | 57 ++++++- tests/test_kiro_cli_mcp.py | 199 +++++++++++++++++++++++++ 3 files changed, 290 insertions(+), 4 deletions(-) diff --git a/loopx/hosts/slash_command_config_io.py b/loopx/hosts/slash_command_config_io.py index 2ce04de79d..7fc4a33150 100644 --- a/loopx/hosts/slash_command_config_io.py +++ b/loopx/hosts/slash_command_config_io.py @@ -208,6 +208,44 @@ def read_json_marker_section(marker_path: Path, section: str) -> dict[str, objec return cast(dict[str, object], entries_obj) if isinstance(entries_obj, dict) else {} +def read_managed_json_entry( + *, + config_path: Path, + marker_path: Path, + marker_section: str, + marker_schema_version: str, + entry_key: str, + container_key: str | None, +) -> dict[str, object] | None: + """Return the existing entry when proven LoopX-managed by its sidecar, else ``None``.""" + try: + marker_obj: object = json.loads(marker_path.read_text(encoding="utf-8")) + config_obj: object = json.loads(config_path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return None + if not isinstance(marker_obj, dict) or not isinstance(config_obj, dict): + return None + marker = cast(dict[str, object], marker_obj) + if marker.get("schema_version") != marker_schema_version: + return None + section = marker.get(marker_section) + if not isinstance(section, dict): + return None + recorded = cast(dict[str, object], section).get(entry_key) + config = cast(dict[str, object], config_obj) + container_obj: object = config if container_key is None else config.get(container_key) + if not isinstance(container_obj, dict): + return None + existing = cast(dict[str, object], container_obj).get(entry_key) + if ( + not isinstance(recorded, dict) + or not isinstance(existing, dict) + or existing != recorded + ): + return None + return cast(dict[str, object], existing) + + def merge_managed_json_entry( *, config_path: Path, diff --git a/loopx/slash_command_install.py b/loopx/slash_command_install.py index 36b2e241b9..11af04225a 100644 --- a/loopx/slash_command_install.py +++ b/loopx/slash_command_install.py @@ -17,6 +17,7 @@ ) from .hosts.slash_command_config_io import ( merge_managed_json_entry as _merge_managed_json_entry, + read_managed_json_entry as _read_managed_json_entry, ) from .hosts.slash_command_surfaces import ( install_codex_surface as _install_codex_surface, @@ -28,6 +29,7 @@ KIRO_CLI_MCP_CONFIG_SUBPATH as _KIRO_MCP_CONFIG_SUBPATH, SKILLS_ROOT_LABEL as _KIRO_SKILLS_ROOT_LABEL, kiro_home as _kiro_home, + mcp_server_script as _kiro_mcp_server_script, ) from .hosts.pi import extension_source as pi_extension_source from .hosts.pi import runtime_source as pi_runtime_source @@ -645,9 +647,22 @@ def _loopx_mcp_command() -> tuple[str, str] | None: def _kiro_cli_mcp_command() -> tuple[str, str] | None: """The Kiro CLI server: same control plane, Kiro runtime profile and session-bound identity.""" - from .hosts.kiro_cli import mcp_server_script + return _mcp_command_for_script(_kiro_mcp_server_script()) - return _mcp_command_for_script(mcp_server_script()) + +def _managed_kiro_mcp_needs_migration(config_path: Path) -> bool: + """Return True when a sidecar-verified LoopX entry points away from the current Kiro script.""" + existing = _read_managed_json_entry( + config_path=config_path, + marker_path=config_path.parent / CURSOR_MCP_MARKER_NAME, + marker_section="servers", + marker_schema_version=KIRO_CLI_MCP_MARKER_SCHEMA_VERSION, + entry_key=MANAGED_MCP_KEY, + container_key="mcpServers", + ) + if existing is None: + return False + return existing.get("args") != [str(_kiro_mcp_server_script())] def _merge_managed_mcp_json( @@ -1009,6 +1024,8 @@ def install_slash_commands( ) ) + kiro_mcp_config_path = kiro_root / _KIRO_MCP_CONFIG_SUBPATH + kiro_mcp_migrated = False if "kiro-cli" in effective_surfaces: _install_skill_facade( specs=facade_specs, @@ -1026,13 +1043,41 @@ def install_slash_commands( surface="kiro-cli", host_surfaces=["kiro-cli"], mechanism="kiro_cli_mcp_server", - config_path=kiro_root / _KIRO_MCP_CONFIG_SUBPATH, + config_path=kiro_mcp_config_path, marker_schema_version=KIRO_CLI_MCP_MARKER_SCHEMA_VERSION, invalid_status="blocked_invalid_kiro_cli_mcp_json", command_factory=lambda: _kiro_cli_mcp_command(), uninstall=uninstall, execute=execute, ) + elif not uninstall and _managed_kiro_mcp_needs_migration(kiro_mcp_config_path): + # Updater runs default `--install` (`surfaces=all`, without `kiro-cli`); + # migrate proven managed Kiro MCP entries whose server path moved. + kiro_mcp_migrated = True + if execute: + _install_managed_mcp_surface( + installed=installed, + surface="kiro-cli", + host_surfaces=["kiro-cli"], + mechanism="kiro_cli_mcp_server", + config_path=kiro_mcp_config_path, + marker_schema_version=KIRO_CLI_MCP_MARKER_SCHEMA_VERSION, + invalid_status="blocked_invalid_kiro_cli_mcp_json", + command_factory=lambda: _kiro_cli_mcp_command(), + uninstall=False, + execute=True, + ) + else: + installed.append( + _installed_entry( + surface="kiro-cli", + host_surfaces=["kiro-cli"], + mechanism="kiro_cli_mcp_server", + command="loopx", + path=kiro_mcp_config_path, + status="would_write", + ) + ) if "cursor" in effective_surfaces: _install_skill_facade( @@ -1147,7 +1192,11 @@ def install_slash_commands( else None ), "kiro_cli_skill_dir": str(kiro_root / "skills") if "kiro-cli" in effective_surfaces else None, - "kiro_cli_mcp_path": str(kiro_root / _KIRO_MCP_CONFIG_SUBPATH) if "kiro-cli" in effective_surfaces else None, + "kiro_cli_mcp_path": ( + str(kiro_mcp_config_path) + if ("kiro-cli" in effective_surfaces or kiro_mcp_migrated) + else None + ), "opencode_skill_dir": str(opencode_root / "skills") if "opencode" in effective_surfaces else None, "opencode_command_dir": str(opencode_root / "commands") if "opencode" in effective_surfaces else None, "opencode_plugin_path": str(opencode_root / "plugins" / "loopx-goal.js") if "opencode" in effective_surfaces and with_goal_bridge else None, diff --git a/tests/test_kiro_cli_mcp.py b/tests/test_kiro_cli_mcp.py index bb777f8020..295443c6b0 100644 --- a/tests/test_kiro_cli_mcp.py +++ b/tests/test_kiro_cli_mcp.py @@ -13,6 +13,7 @@ from __future__ import annotations +from typing import cast import json import subprocess import sys @@ -382,3 +383,201 @@ def test_install_reports_a_malformed_config_instead_of_rewriting_it( ) assert _mcp_row(payload)["status"] == "blocked_invalid_kiro_cli_mcp_json" assert config.read_text(encoding="utf-8") == '{"mcpServers": ["not", "a", "map"]}' + + +def test_default_install_migrates_stale_managed_kiro_mcp_and_preserves_other_entries( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Default `slash-commands --install` (`surfaces=all`, what `self-update` runs) + migrates a sidecar-verified Kiro MCP registration whose server path moved.""" + from loopx.claude_goal_mode.scripts import install as claude_install + + provision_calls = 0 + + def fake_provision(*, dry: bool = False) -> Path: + nonlocal provision_calls + if not dry: + provision_calls += 1 + return Path(sys.executable) + + monkeypatch.setattr(claude_install, "provision_mcp_python", fake_provision) + monkeypatch.setattr(claude_install, "_has_mcp", lambda _interp: True) + monkeypatch.setenv("HOME", str(tmp_path / "home")) + + kiro_home = tmp_path / "kiro-home" + config = kiro_home / KIRO_CLI_MCP_CONFIG_SUBPATH + marker = config.parent / slash_command_install.CURSOR_MCP_MARKER_NAME + config.parent.mkdir(parents=True) + stale_script = tmp_path / "removed-wheel" / "loopx" / "kiro_cli_goal_mode" / "mcp_server.py" + stale_entry = {"command": "/stale/mcp-venv/bin/python", "args": [str(stale_script)]} + other = {"command": "codegraph", "args": ["serve", "--mcp"]} + config.write_text(json.dumps({"mcpServers": {"codegraph": other, "loopx": stale_entry}}), encoding="utf-8") + marker.write_text( + json.dumps( + { + "schema_version": slash_command_install.KIRO_CLI_MCP_MARKER_SCHEMA_VERSION, + "servers": {"loopx": stale_entry}, + } + ), + encoding="utf-8", + ) + + codex_home = str(tmp_path / "codex") + claude_home = str(tmp_path / "claude") + opencode_home = str(tmp_path / "opencode") + kiro_home_arg = str(kiro_home) + + preview = install_slash_commands( + execute=False, + codex_home=codex_home, + claude_home=claude_home, + opencode_home=opencode_home, + kiro_home=kiro_home_arg, + ) + assert preview["effective_surfaces"] == ["codex", "claude-code", "opencode"] + assert provision_calls == 0 + assert _mcp_row(preview)["status"] == "would_write" + assert json.loads(config.read_text(encoding="utf-8"))["mcpServers"]["loopx"] == stale_entry + assert not (kiro_home / "skills").exists() + + # The stale removed script fails before migration. + stale_run = subprocess.run([sys.executable, str(stale_script)], capture_output=True, text=True, check=False) + assert stale_run.returncode == 2 + + migrated = install_slash_commands( + execute=True, + codex_home=codex_home, + claude_home=claude_home, + opencode_home=opencode_home, + kiro_home=kiro_home_arg, + ) + assert provision_calls == 1 + assert _mcp_row(migrated)["status"] == "written" + migrated_summary = cast(dict[str, object], migrated["summary"]) + assert migrated_summary["kiro_cli_mcp_path"] == str(config) + assert migrated_summary["kiro_cli_skill_dir"] is None + assert not (kiro_home / "skills").exists() + + expected_entry = {"command": sys.executable, "args": [str(mcp_server_script())]} + assert json.loads(config.read_text(encoding="utf-8")) == { + "mcpServers": {"codegraph": other, "loopx": expected_entry} + } + assert json.loads(marker.read_text(encoding="utf-8")) == { + "schema_version": slash_command_install.KIRO_CLI_MCP_MARKER_SCHEMA_VERSION, + "servers": {"loopx": expected_entry}, + } + + # Verify the migrated entry imports cleanly as a standalone script. + probe = subprocess.run( + [ + sys.executable, + "-c", + "import runpy; ns = runpy.run_path(__import__('sys').argv[1], run_name='probe'); print(ns['CONFIG'].runtime_profile)", + str(mcp_server_script()), + ], + capture_output=True, + text=True, + cwd="/", + check=False, + ) + assert probe.returncode == 0, probe.stderr + assert probe.stdout.strip() == "kiro_cli" + + # Re-running default install is a clean no-op with zero extra provisioning. + second = install_slash_commands( + execute=True, + codex_home=codex_home, + claude_home=claude_home, + opencode_home=opencode_home, + kiro_home=kiro_home_arg, + ) + assert provision_calls == 1 + second_summary = cast(dict[str, object], second["summary"]) + second_installed = cast(list[dict[str, object]], second["installed"]) + assert second_summary["kiro_cli_mcp_path"] is None + assert all(row["surface"] != "kiro-cli" for row in second_installed) + + # Explicit kiro-cli uninstall still retires only the migrated LoopX entry. + default_uninstall = install_slash_commands( + execute=True, + uninstall=True, + codex_home=codex_home, + claude_home=claude_home, + opencode_home=opencode_home, + kiro_home=kiro_home_arg, + ) + default_uninstall_rows = cast(list[dict[str, object]], default_uninstall["installed"]) + assert all(row["surface"] != "kiro-cli" for row in default_uninstall_rows) + assert "loopx" in json.loads(config.read_text(encoding="utf-8"))["mcpServers"] + + kiro_uninstall = install_slash_commands( + execute=True, uninstall=True, surfaces=["kiro-cli"], kiro_home=str(kiro_home) + ) + assert _mcp_row(kiro_uninstall)["status"] == "retired" + assert json.loads(config.read_text(encoding="utf-8")) == {"mcpServers": {"codegraph": other}} + + +@pytest.mark.parametrize("case", ("no_sidecar", "user_edited_entry", "wrong_schema", "malformed_config")) +def test_default_install_leaves_unverified_or_user_owned_kiro_mcp_untouched( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + case: str, +) -> None: + monkeypatch.setattr( + slash_command_install, + "_kiro_cli_mcp_command", + lambda: pytest.fail("must not provision or rewrite unverified Kiro MCP"), + ) + monkeypatch.setenv("HOME", str(tmp_path / "home")) + kiro_home = tmp_path / "kiro-home" + config = kiro_home / KIRO_CLI_MCP_CONFIG_SUBPATH + marker = config.parent / slash_command_install.CURSOR_MCP_MARKER_NAME + config.parent.mkdir(parents=True) + + mine = {"command": "my-custom-loopx", "args": ["--custom"]} + other = {"command": "codegraph", "args": ["serve"]} + if case == "malformed_config": + raw_config = "{not-valid-json" + config.write_text(raw_config, encoding="utf-8") + marker.write_text( + json.dumps( + { + "schema_version": slash_command_install.KIRO_CLI_MCP_MARKER_SCHEMA_VERSION, + "servers": {"loopx": {"command": "/old/python", "args": ["/old/mcp_server.py"]}}, + } + ), + encoding="utf-8", + ) + else: + raw_config = json.dumps({"mcpServers": {"other": other, "loopx": mine}}) + config.write_text(raw_config, encoding="utf-8") + if case == "user_edited_entry": + marker.write_text( + json.dumps( + { + "schema_version": slash_command_install.KIRO_CLI_MCP_MARKER_SCHEMA_VERSION, + "servers": {"loopx": {"command": "/old/python", "args": ["/old/mcp_server.py"]}}, + } + ), + encoding="utf-8", + ) + elif case == "wrong_schema": + marker.write_text( + json.dumps({"schema_version": "other_schema_v0", "servers": {"loopx": mine}}), + encoding="utf-8", + ) + + payload = install_slash_commands( + execute=True, + codex_home=str(tmp_path / "codex"), + claude_home=str(tmp_path / "claude"), + opencode_home=str(tmp_path / "opencode"), + kiro_home=str(kiro_home), + ) + assert payload["ok"] is True + payload_summary = cast(dict[str, object], payload["summary"]) + payload_installed = cast(list[dict[str, object]], payload["installed"]) + assert payload_summary["kiro_cli_mcp_path"] is None + assert all(row["surface"] != "kiro-cli" for row in payload_installed) + assert config.read_text(encoding="utf-8") == raw_config From e955cc6ee592350acdf34debbffa751b115a121c Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:30:46 +0800 Subject: [PATCH 3/3] fix(hosts): scope Kiro MCP migration to default all and handle non-UTF-8 sidecars Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/hosts/slash_command_config_io.py | 10 +- loopx/slash_command_install.py | 12 ++- tests/test_kiro_cli_mcp.py | 129 +++++++++++++++++++++++++ 3 files changed, 145 insertions(+), 6 deletions(-) diff --git a/loopx/hosts/slash_command_config_io.py b/loopx/hosts/slash_command_config_io.py index 7fc4a33150..2e6510becf 100644 --- a/loopx/hosts/slash_command_config_io.py +++ b/loopx/hosts/slash_command_config_io.py @@ -111,7 +111,7 @@ def opencode_direct_goal_plugin_conflicts( if path.suffix == ".jsonc": content = strip_jsonc_trailing_commas(strip_jsonc_comments(content)) payload_obj: object = json.loads(content) - except (json.JSONDecodeError, OSError): + except (OSError, UnicodeDecodeError, json.JSONDecodeError): invalid.append(str(path)) continue if not isinstance(payload_obj, dict): @@ -150,7 +150,7 @@ def target_package_dependencies( if path.exists(): try: payload_obj: object = json.loads(path.read_text(encoding="utf-8")) - except (json.JSONDecodeError, OSError): + except (OSError, UnicodeDecodeError, json.JSONDecodeError): return "blocked_invalid_user_package_json" if not isinstance(payload_obj, dict): return "blocked_invalid_user_package_json" @@ -200,7 +200,7 @@ def read_json_marker_section(marker_path: Path, section: str) -> dict[str, objec """Read one mapping section from a LoopX ownership marker, failing closed to ``{}``.""" try: payload_obj: object = json.loads(marker_path.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError): + except (OSError, UnicodeDecodeError, json.JSONDecodeError): return {} if not isinstance(payload_obj, dict): return {} @@ -221,7 +221,7 @@ def read_managed_json_entry( try: marker_obj: object = json.loads(marker_path.read_text(encoding="utf-8")) config_obj: object = json.loads(config_path.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError): + except (OSError, UnicodeDecodeError, json.JSONDecodeError): return None if not isinstance(marker_obj, dict) or not isinstance(config_obj, dict): return None @@ -267,7 +267,7 @@ def merge_managed_json_entry( try: text = config_path.read_text(encoding="utf-8") if config_path.exists() else "" raw_obj: object = json.loads(text) if text.strip() else {} - except (OSError, json.JSONDecodeError): + except (OSError, UnicodeDecodeError, json.JSONDecodeError): return invalid_status if not isinstance(raw_obj, dict): return invalid_status diff --git a/loopx/slash_command_install.py b/loopx/slash_command_install.py index 11af04225a..463b48eb54 100644 --- a/loopx/slash_command_install.py +++ b/loopx/slash_command_install.py @@ -582,6 +582,12 @@ def _normalize_surfaces(surfaces: list[str] | None) -> list[str]: return normalized +def _requests_default_all_surfaces(surfaces: list[str] | None) -> bool: + """Only default/``all`` installs migrate stale Kiro MCP entries; targeted selections skip Kiro.""" + requested = surfaces or ["all"] + return any(item.strip().casefold() == "all" for item in requested) + + # Every surface that registers the LoopX stdio server shares one key, one # ownership marker file name and one merge rule; only the config location, the # host-specific server script and the reported status names differ. @@ -1050,7 +1056,11 @@ def install_slash_commands( uninstall=uninstall, execute=execute, ) - elif not uninstall and _managed_kiro_mcp_needs_migration(kiro_mcp_config_path): + elif ( + not uninstall + and _requests_default_all_surfaces(surfaces) + and _managed_kiro_mcp_needs_migration(kiro_mcp_config_path) + ): # Updater runs default `--install` (`surfaces=all`, without `kiro-cli`); # migrate proven managed Kiro MCP entries whose server path moved. kiro_mcp_migrated = True diff --git a/tests/test_kiro_cli_mcp.py b/tests/test_kiro_cli_mcp.py index 295443c6b0..59e5fbdabf 100644 --- a/tests/test_kiro_cli_mcp.py +++ b/tests/test_kiro_cli_mcp.py @@ -15,6 +15,7 @@ from typing import cast import json +import os import subprocess import sys from pathlib import Path @@ -581,3 +582,131 @@ def test_default_install_leaves_unverified_or_user_owned_kiro_mcp_untouched( assert payload_summary["kiro_cli_mcp_path"] is None assert all(row["surface"] != "kiro-cli" for row in payload_installed) assert config.read_text(encoding="utf-8") == raw_config + + +@pytest.mark.parametrize("sidecar_kind", ("stale_managed", "non_utf8_sidecar")) +def test_explicit_codex_surface_skips_kiro_mcp_probe_and_migration( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + sidecar_kind: str, +) -> None: + monkeypatch.setattr( + slash_command_install, + "_managed_kiro_mcp_needs_migration", + lambda _path: pytest.fail("explicit --surface codex must not probe Kiro sidecar"), + ) + monkeypatch.setattr( + slash_command_install, + "_kiro_cli_mcp_command", + lambda: pytest.fail("explicit --surface codex must not provision Kiro MCP"), + ) + monkeypatch.setenv("HOME", str(tmp_path / "home")) + + kiro_home = tmp_path / "kiro-home" + config = kiro_home / KIRO_CLI_MCP_CONFIG_SUBPATH + marker = config.parent / slash_command_install.CURSOR_MCP_MARKER_NAME + config.parent.mkdir(parents=True) + stale_entry = {"command": "/stale/python", "args": ["/stale/mcp_server.py"]} + config_bytes = json.dumps({"mcpServers": {"loopx": stale_entry}}).encode("utf-8") + config.write_bytes(config_bytes) + if sidecar_kind == "stale_managed": + marker_bytes = json.dumps( + { + "schema_version": slash_command_install.KIRO_CLI_MCP_MARKER_SCHEMA_VERSION, + "servers": {"loopx": stale_entry}, + } + ).encode("utf-8") + else: + marker_bytes = b"\xff\xfe\x00not-utf8-sidecar" + marker.write_bytes(marker_bytes) + + codex_home = str(tmp_path / "codex") + for execute in (False, True): + payload = install_slash_commands( + execute=execute, + surfaces=["codex"], + codex_home=codex_home, + kiro_home=str(kiro_home), + ) + assert payload["ok"] is True + assert payload["effective_surfaces"] == ["codex"] + summary = cast(dict[str, object], payload["summary"]) + installed = cast(list[dict[str, object]], payload["installed"]) + assert summary["kiro_cli_mcp_path"] is None + assert summary["kiro_cli_skill_dir"] is None + assert all(row["surface"] != "kiro-cli" for row in installed) + assert config.read_bytes() == config_bytes + assert marker.read_bytes() == marker_bytes + assert not (kiro_home / "skills").exists() + + +def test_real_cli_handles_non_utf8_kiro_sidecar_and_selective_codex_cleanly( + tmp_path: Path, +) -> None: + repo_root = Path(__file__).resolve().parents[1] + kiro_home = tmp_path / "kiro-home" + config = kiro_home / KIRO_CLI_MCP_CONFIG_SUBPATH + marker = config.parent / slash_command_install.CURSOR_MCP_MARKER_NAME + config.parent.mkdir(parents=True) + preserved_entry = {"command": "/existing/python", "args": ["/existing/mcp_server.py"]} + config_bytes = json.dumps({"mcpServers": {"loopx": preserved_entry}}).encode("utf-8") + corrupt_sidecar_bytes = b"\xff\xfe\x00\x80corrupt-kiro-sidecar" + config.write_bytes(config_bytes) + marker.write_bytes(corrupt_sidecar_bytes) + + env = { + **os.environ, + "HOME": str(tmp_path / "home"), + "KIRO_HOME": str(kiro_home), + "CODEX_HOME": str(tmp_path / "codex"), + "CLAUDE_HOME": str(tmp_path / "claude"), + "OPENCODE_CONFIG_DIR": str(tmp_path / "opencode"), + "XDG_CONFIG_HOME": str(tmp_path / "xdg"), + "PYTHONPATH": str(repo_root), + } + + def run_cli(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-m", "loopx.cli_runtime", "slash-commands", *args, "--format", "json"], + capture_output=True, + text=True, + env=env, + cwd=str(tmp_path), + check=False, + ) + + codex_only = run_cli("--install", "--surface", "codex") + assert codex_only.returncode == 0, codex_only.stderr + codex_payload = json.loads(codex_only.stdout) + assert codex_payload["ok"] is True + assert codex_payload["effective_surfaces"] == ["codex"] + assert codex_payload["summary"]["kiro_cli_mcp_path"] is None + assert config.read_bytes() == config_bytes + assert marker.read_bytes() == corrupt_sidecar_bytes + + default_all = run_cli("--install") + assert default_all.returncode == 0, default_all.stderr + default_payload = json.loads(default_all.stdout) + assert default_payload["ok"] is True + assert default_payload["effective_surfaces"] == ["codex", "claude-code", "opencode"] + assert default_payload["summary"]["kiro_cli_mcp_path"] is None + assert all(row["surface"] != "kiro-cli" for row in default_payload["installed"]) + assert config.read_bytes() == config_bytes + assert marker.read_bytes() == corrupt_sidecar_bytes + + kiro_selected = run_cli("--install", "--surface", "kiro-cli") + assert kiro_selected.returncode == 0, kiro_selected.stderr + kiro_payload = json.loads(kiro_selected.stdout) + assert kiro_payload["ok"] is True + assert _mcp_row(kiro_payload)["status"] == "skipped_user_owned_mcp_entry" + assert config.read_bytes() == config_bytes + assert marker.read_bytes() == corrupt_sidecar_bytes + + # Non-UTF-8 mcp.json itself also fails closed structurally rather than raising UnicodeDecodeError. + config.write_bytes(corrupt_sidecar_bytes) + bad_config = run_cli("--install", "--surface", "kiro-cli") + assert bad_config.returncode == 1, bad_config.stderr + bad_payload = json.loads(bad_config.stdout) + assert bad_payload["ok"] is False + assert _mcp_row(bad_payload)["status"] == "blocked_invalid_kiro_cli_mcp_json" + assert config.read_bytes() == corrupt_sidecar_bytes