diff --git a/README.ja.md b/README.ja.md index 8382eccc47..cbf9484601 100644 --- a/README.ja.md +++ b/README.ja.md @@ -308,8 +308,8 @@ Todo として計画して、ホストの有効化をガイドします。アク [Getting Started](docs/guides/getting-started.md) にあります。ホスト連携では、 [Codex App のホストコマンドレジストリ契約](docs/reference/protocols/codex-app-host-command-registry-v0.md)、 [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)、 +[Claude Code アダプター](loopx/hosts/claude/README.md)、 +[KunlunCode のネイティブ Goal アダプター](loopx/hosts/kunluncode/README.md)、 [Kiro CLI の goal-mode アダプター](loopx/kiro_cli_goal_mode/README.md)、または [DeepSeek Harness のターンアダプター](loopx/dsh_goal_mode/README.md)を確認できます。 diff --git a/README.md b/README.md index 2a7a15f16e..6235c9ec88 100644 --- a/README.md +++ b/README.md @@ -322,8 +322,8 @@ The exact, copy-ready setup messages and host recovery paths live in [Getting Started](docs/guides/getting-started.md). Host integrations can inspect the [Codex App host command registry contract](docs/reference/protocols/codex-app-host-command-registry-v0.md), 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 +the [Claude Code adapter](loopx/hosts/claude/README.md), the +[KunlunCode native Goal adapter](loopx/hosts/kunluncode/README.md), the [Kiro CLI goal-mode adapter](loopx/kiro_cli_goal_mode/README.md), or the [DeepSeek Harness turn adapter](loopx/dsh_goal_mode/README.md). diff --git a/README.zh-CN.md b/README.zh-CN.md index ee67ed5cb2..c405fc67cd 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -270,7 +270,7 @@ LoopX 会复用项目已有状态或连接项目,把工作规划成 Todo,并 [Getting Started](docs/guides/getting-started.md)。Host 集成还可以查看 [Codex App host command registry](docs/reference/protocols/codex-app-host-command-registry-v0.md)、 [Codex CLI packaged install](docs/product/runtimes/codex-cli/codex-cli-packaged-install.md)和 -[Claude Code adapter](loopx/claude_goal_mode/README.md)、 +[Claude Code adapter](loopx/hosts/claude/README.md)、 [KunlunCode 原生 Goal adapter](docs/guides/kunluncode-adapter.zh-CN.md)、 [Kiro CLI goal-mode adapter](loopx/kiro_cli_goal_mode/README.md),以及 [DeepSeek Harness turn adapter](loopx/dsh_goal_mode/README.md)。 diff --git a/apps/presentation/dashboard/src/data/zcode-goal.ts b/apps/presentation/dashboard/src/data/zcode-goal.ts index b457590f49..ab5cd8df9e 100644 --- a/apps/presentation/dashboard/src/data/zcode-goal.ts +++ b/apps/presentation/dashboard/src/data/zcode-goal.ts @@ -1,4 +1,4 @@ -import { ZCODE_GOAL_ACTIONS, ZCODE_NATIVE_GOAL_STATUSES, ZCODE_IDENTITY_SCOPES, type ZCodeGoalAction, type ZCodeGoalReadback, type ZCodeModelSelection } from "../../../../../loopx/zcode_goal_mode/contract.js"; +import { ZCODE_GOAL_ACTIONS, ZCODE_NATIVE_GOAL_STATUSES, ZCODE_IDENTITY_SCOPES, type ZCodeGoalAction, type ZCodeGoalReadback, type ZCodeModelSelection } from "../../../../../loopx/hosts/zcode/contract.js"; import {z} from "zod"; import {requestJson} from "./chat.js"; diff --git a/apps/presentation/dashboard/src/features/personal-workspace/zcode-goal-control.tsx b/apps/presentation/dashboard/src/features/personal-workspace/zcode-goal-control.tsx index 9e6177e12f..b663d78c48 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/zcode-goal-control.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/zcode-goal-control.tsx @@ -2,7 +2,7 @@ import {CircleHelp} from "lucide-react"; import {ContextHelp} from "./context-help"; import { useCallback, useEffect, useRef, useState } from "react"; import { fetchZCodeGoal, updateZCodeGoal } from "../../data/zcode-goal"; -import type { ZCodeGoalAction, ZCodeGoalReadback, ZCodeModelSelection } from "../../../../../../loopx/zcode_goal_mode/contract.js"; +import type { ZCodeGoalAction, ZCodeGoalReadback, ZCodeModelSelection } from "../../../../../../loopx/hosts/zcode/contract.js"; import { useWorkspaceI18n, type WorkspaceTranslate } from "./i18n"; import type { WorkspaceGoal } from "./personal-workspace-model"; import "./zcode-goal-control.css"; diff --git a/docs/architecture/long-running-execution-exploration-and-correction.md b/docs/architecture/long-running-execution-exploration-and-correction.md index 87ffd4015c..1906e2a9d4 100644 --- a/docs/architecture/long-running-execution-exploration-and-correction.md +++ b/docs/architecture/long-running-execution-exploration-and-correction.md @@ -216,7 +216,7 @@ bypass it, quota settlement, permission, lease or revision checks. ### LoopX: an existing native-Goal provider and its recovery boundary -The [managed ZCode provider](../../loopx/zcode_goal_mode/README.md) is a concrete +The [managed ZCode provider](../../loopx/hosts/zcode/README.md) is a concrete example inside LoopX, not a fifth independent upstream runtime audit. Its current call chain separates binding, starting and resuming: @@ -233,8 +233,8 @@ CLI / Goal drawer -> bridge validates canonical Goal/Agent/project native completed -> observed only; no automatic Core completion or credit write ``` -[`zcode_goal_operation`](../../loopx/zcode_goal_mode/bridge.py) generates a new -canonical heartbeat task for bind/start. [`NativeGoalController`](../../loopx/zcode_goal_mode/runtime.ts) +[`zcode_goal_operation`](../../loopx/hosts/zcode/bridge.py) generates a new +canonical heartbeat task for bind/start. [`NativeGoalController`](../../loopx/hosts/zcode/runtime.ts) serializes operations and preserves the native session/target on resume. Its admission is validation → quota → validation. A lost `setGoal` reply is recoverable only when a durable admitted start intent and objective hash match; @@ -254,7 +254,7 @@ then observes the first new protected action. It must use current owning revisions, or remain pending/paused at an unsupported refresh boundary. Do not replace that evidence with a hash of the entire prompt or rewrite the old receipt. -The [broker](../../loopx/zcode_goal_mode/cli.ts) schedules another monitor about +The [broker](../../loopx/hosts/zcode/cli.ts) schedules another monitor about two seconds after a serialized check completes; its admission subprocesses each have a ten-second timeout. Online status can recheck quota and pause a target, so it is not a purely observational operation. Pause/stop also contend with the @@ -760,7 +760,7 @@ operation and current source revisions to join observations, not a new ledger. | Commit a result between final drain and idle; deliver duplicates and old wakes after stop, then a newly authorized input | Durable work remains discoverable; prior wakes cannot revive stopped execution; new input re-enters current admission through the same continuation owner | Existing [accepted-result wake](../../loopx/chat_loopx_mode.py) and Host continuation paths; qualify both no duplicate start and no lost work, not just a lock | | Deliver/retry an exact-Turn steer during tools, context preparation or finalization | Preserve text, ingress and target; show the actual pending/consumed/refused fact and permitted fallback; steering does not imply tool cancellation | [Steering tests](../../tests/test_chat_turn_steering.py) plus each Host's declared consumption boundary; no all-Host inference | | Lose the reply after native set; replay an old operation, then admit new recovery work | Recover only the target matching durable start intent; cold recovery pauses; old replay is idempotent while a new accountable Turn retains its settlement obligation | Native controller and [Turn recovery](../../loopx/control_plane/turn_driver/turn_journal.ts) are reused; inspect original-operation and new-Turn receipts separately | -| Delay validation/quota while requesting stop; reach the execution deadline and explicitly resume repeatedly | Measure request queueing, native cancellation and confirmed drain; preserve configured cumulative budgets and unknown usage across per-execution timers | [ZCode runtime/broker](../../loopx/zcode_goal_mode/cli.ts) supplies a measurement candidate, not a proved stop SLO or token-usage bound | +| Delay validation/quota while requesting stop; reach the execution deadline and explicitly resume repeatedly | Measure request queueing, native cancellation and confirmed drain; preserve configured cumulative budgets and unknown usage across per-execution timers | [ZCode runtime/broker](../../loopx/hosts/zcode/cli.ts) supplies a measurement candidate, not a proved stop SLO or token-usage bound | | Cite an omitted result via valid, forged, stale or foreign pages; add a positive finding under different conditions from an old refutation | Replay current source; keep counterevidence scoped and reachable; distinguish bad descriptors from unavailable source. Same-basis pages preserve admission identity; source drift can refresh basis within the original Turn | [Pagination tests](../../tests/control_plane_ts/stride_explore_pagination.test.ts) and Stride §7.6 own these rules; qualify actual omitted-evidence use | | Commit primary work, then lose Explore attachment/link confirmation | Preserve successful primary work; retry the attachment under the original operation without repeating work or declaring adoption | [Explore writeback tests](../../tests/control_plane/test_explore_result_writeback.py) supply the recovery seam; verify product retry/readback | | Exercise every enabled periodic-review exit, then disable strategy or omit direction declarations | Progress/successor/blocker/terminal exits retain their current duty; disabling preserves ordinary behavior/history; absent Direction M1 adds no projection or permission | [Stride tests](../../tests/control_plane_ts/stride_policy.test.ts) and [direction tests](../../tests/control_plane_ts/direction_baseline.test.ts); compaction, polling and UI refresh cannot discharge work obligations | diff --git a/docs/architecture/long-running-execution-exploration-and-correction.zh-CN.md b/docs/architecture/long-running-execution-exploration-and-correction.zh-CN.md index 7cfe08a4db..1b8b57c016 100644 --- a/docs/architecture/long-running-execution-exploration-and-correction.zh-CN.md +++ b/docs/architecture/long-running-execution-exploration-and-correction.zh-CN.md @@ -175,7 +175,7 @@ Explore 依据。它验证声明的来源与结构,不认证 Agent 解释为 ### LoopX:已有原生 Goal provider 及恢复边界 -[Managed ZCode provider](../../loopx/zcode_goal_mode/README.md)是 LoopX 内部的 +[Managed ZCode provider](../../loopx/hosts/zcode/README.md)是 LoopX 内部的 具体接入示例,不是第五个上游运行时的独立审计。当前调用链区分绑定、启动与恢复: ```text @@ -191,8 +191,8 @@ CLI / Goal drawer → bridge 验证 canonical Goal/Agent/project native completed → 仅观察,不自动写 Core 完成或额度扣减 ``` -[`zcode_goal_operation`](../../loopx/zcode_goal_mode/bridge.py)在 bind/start -生成新的规范 heartbeat 正文;[`NativeGoalController`](../../loopx/zcode_goal_mode/runtime.ts) +[`zcode_goal_operation`](../../loopx/hosts/zcode/bridge.py)在 bind/start +生成新的规范 heartbeat 正文;[`NativeGoalController`](../../loopx/hosts/zcode/runtime.ts) 串行执行操作,resume 保留原 native session/target,准入为 validation→quota→validation。 `setGoal` 回执丢失时,仅有持久获准 start intent 与匹配 objective hash 才能恢复; 冷恢复先暂停原 target,不自动续跑。[Controller 测试](../../tests/control_plane_ts/zcode_native_goal.test.ts) @@ -207,7 +207,7 @@ Agent 读取当前 Core 状态。待补组合验收应保持同一 Goal instance 无法支持该刷新边界时保持 pending/paused。不能用整段 prompt hash 代替这项证据, 也不能改写旧回执。 -[Broker](../../loopx/zcode_goal_mode/cli.ts)在一次串行检查结束后约两秒再安排下次 +[Broker](../../loopx/hosts/zcode/cli.ts)在一次串行检查结束后约两秒再安排下次 monitor,每个准入子进程有十秒 timeout。在线 status 可以重查 quota 并暂停 target, 不是对 Host 完全只读。Pause/stop 同样与串行队列竞争。每次执行的一小时安全期限 既不是整个 Goal 的 token 预算,也不是硬实时停机保证;native 用量仍未知。 @@ -618,7 +618,7 @@ Grok 的[第三方声明](https://github.com/xai-org/grok-build/blob/2bdd1d6a636 | 最后 drain 与 idle 之间提交结果;重复通知、停止后旧 wake,再加入新获准输入 | 持久工作可发现;旧 wake 不复活已停执行;新输入由原接续 owner 按当前准入处理 | 复用[已验收结果 wake](../../loopx/chat_loopx_mode.py) 和 Host 接续路径;同时验证不重复启动与不丢工作,不能只验证锁 | | 工具、上下文准备或终结期间投递/重试 exact-Turn steer | 文本、ingress、目标不变;如实显示 pending/consumed/refused 和许可 fallback;steering 不等于工具取消 | [Steering 测试](../../tests/test_chat_turn_steering.py) 加每个 Host 的声明消费边界,不推广为全部 Host 通过 | | Native set 已发生但回执丢失;重放旧操作后再准入新恢复工作 | 只恢复匹配持久 start intent 的 target;冷恢复暂停;旧重放幂等,新 accountable Turn 仍履行结算 | 复用原生控制器和 [Turn recovery](../../loopx/control_plane/turn_driver/turn_journal.ts),分别检查原操作与新 Turn 回执 | -| Validation/quota 变慢时请求停止;到单次 deadline 后多次显式恢复 | 分别测请求排队、原生取消与确认 drain;跨计时器保留配置的累计预算及 unknown 用量 | [ZCode runtime/broker](../../loopx/zcode_goal_mode/cli.ts) 是测量候选,不是已证明的停止 SLO 或 token 用量限制 | +| Validation/quota 变慢时请求停止;到单次 deadline 后多次显式恢复 | 分别测请求排队、原生取消与确认 drain;跨计时器保留配置的累计预算及 unknown 用量 | [ZCode runtime/broker](../../loopx/hosts/zcode/cli.ts) 是测量候选,不是已证明的停止 SLO 或 token 用量限制 | | 经合法/伪造/陈旧/跨消费者页引用省略结果;新增与旧反证条件不同的正 finding | 当前来源重放;反证保留适用范围及读取入口;坏页与来源不可用分开。同依据页保留准入身份,源漂移可在原 Turn 更新 basis | [分页测试](../../tests/control_plane_ts/stride_explore_pagination.test.ts) 与 Stride §7.6 已有合同;仍须验证实际采用省略证据 | | 主工作提交后丢失 Explore 附件/关联确认 | 主工作仍成功;原操作下补回附件,不重复工作、不宣称已采用 | [Explore 回写测试](../../tests/control_plane/test_explore_result_writeback.py) 提供恢复接缝,验证产品重试与回读 | | 遍历启用策略的周期复核出口,再关闭策略或不声明 direction | Progress/successor/blocker/terminal 保留现有义务;关闭保留普通行为/历史;未声明 Direction M1 不加投影或权限 | [Stride 测试](../../tests/control_plane_ts/stride_policy.test.ts) 与 [direction 测试](../../tests/control_plane_ts/direction_baseline.test.ts);压缩、轮询、UI 刷新不能解除工作义务 | diff --git a/docs/architecture/rfcs/agent-session-execution-modes-v0.md b/docs/architecture/rfcs/agent-session-execution-modes-v0.md index e2137538c3..8ce2d8894c 100644 --- a/docs/architecture/rfcs/agent-session-execution-modes-v0.md +++ b/docs/architecture/rfcs/agent-session-execution-modes-v0.md @@ -189,7 +189,7 @@ facts, not a qualification of every installed Host. | Runtime fencing | [`loopx/chat_runtime.py`](../../../loopx/chat_runtime.py) never starts a managed adapter for an attached session and fails closed with typed errors such as `attached_session_live_steering_unavailable`, `live_steering_requires_active_turn`, and `live_steering_session_not_attached`. | | CLI surface | `loopx worker-bridge attached-session-bind`, `-list`, `-claim`, and `-complete` exist in [`loopx/cli_commands/worker_bridge.py`](../../../loopx/cli_commands/worker_bridge.py), documented in the [broker guide](../../integrations/attached-agent-session-broker.md) and the [worker-bridge install contract](../../integrations/worker-bridge-install-contract.md). | | Existing-session delegation | [`loopx delegation`](../../reference/local-delegation.md#use-an-existing-agent-conversation-through-its-shell) exposes the same explicitly bound work as MCP to an existing shell-capable Agent. `operations` recovers requester-scoped work without remembered IDs, rechecks acceptance and exposes unavailable items and further pages. Newly tool-equipped Goal Chat consumes the same inventory; resumed native threads keep their original tool schema. It does not provision an Agent, migrate a host or install an automatic wake policy. | -| Managed native Goal | The opt-in [ZCode provider](../../../loopx/zcode_goal_mode/README.md) binds an idle session, starts under Core admission, retains session/target on resume and confirms pause on cold recovery. Native revisions and journaled start intent guard lost replies. Native completion writes no Core acceptance or credit debit; connected status can still pause denied execution. This is one provider, not generic native-Goal qualification. | +| Managed native Goal | The opt-in [ZCode provider](../../../loopx/hosts/zcode/README.md) binds an idle session, starts under Core admission, retains session/target on resume and confirms pause on cold recovery. Native revisions and journaled start intent guard lost replies. Native completion writes no Core acceptance or credit debit; connected status can still pause denied execution. This is one provider, not generic native-Goal qualification. | | Focused tests | [`tests/test_attached_session_cli.py`](../../../tests/test_attached_session_cli.py) and `tests/test_chat_codex_home.py::test_attached_session_uses_existing_host_not_managed_adapter` cover bind/claim/complete and the no-managed-adapter fence. | | Product-level proposal | The [Desktop execution frontends RFC](desktop-execution-frontends-v0.md) owns the Mode A/Mode B product comparison, the connector and event-source orthogonality, and the Desktop non-goals. | | Host-side loop guidance | [Codex CLI TUI loop](../../product/runtimes/codex-cli/codex-cli-tui-loop.md) documents session-attached automation and resume options for one visible host. | diff --git a/docs/architecture/rfcs/agent-session-execution-modes-v0.zh-CN.md b/docs/architecture/rfcs/agent-session-execution-modes-v0.zh-CN.md index 3e32a86110..6f2e8e411e 100644 --- a/docs/architecture/rfcs/agent-session-execution-modes-v0.zh-CN.md +++ b/docs/architecture/rfcs/agent-session-execution-modes-v0.zh-CN.md @@ -147,7 +147,7 @@ LoopX 启动,另一种已经属于其他宿主。当绑定没有说明自己 | 运行时围栏 | [`loopx/chat_runtime.py`](../../../loopx/chat_runtime.py) 绝不为挂接会话启动托管适配器,并以类型化错误失败关闭,例如 `attached_session_live_steering_unavailable`、`live_steering_requires_active_turn`、`live_steering_session_not_attached`。 | | CLI 面 | `loopx worker-bridge attached-session-bind`、`-list`、`-claim`、`-complete` 存在于 [`loopx/cli_commands/worker_bridge.py`](../../../loopx/cli_commands/worker_bridge.py),并在 [broker 指南](../../integrations/attached-agent-session-broker.md) 与 [worker-bridge 安装契约](../../integrations/worker-bridge-install-contract.md) 中记录。 | | 原会话委派 | [`loopx delegation`](../../reference/local-delegation.md#use-an-existing-agent-conversation-through-its-shell) 让有 shell 能力的原 Agent 使用与 MCP 相同的显式执行绑定;`operations` 无需记住 ID 即可找回自身委派,重新核验 accepted,明确单条不可用及剩余分页。新挂载工具的 Goal Chat 复用同一目录,已存在的原生线程恢复时保留原工具 schema;不创建 Agent、不迁移宿主,也不安装自动唤醒策略。 | -| Managed native Goal | 可选 [ZCode provider](../../../loopx/zcode_goal_mode/README.md) 绑定空闲会话,经 Core 准入启动,同 session/target 恢复,冷恢复确认暂停。Native revision 和已记录 start intent 保护丢失回执。原生完成不写 Core acceptance/credit debit,但在线 status 可暂停被拒绝的执行。这是单个 provider,不是通用 native Goal 资格。 | +| Managed native Goal | 可选 [ZCode provider](../../../loopx/hosts/zcode/README.md) 绑定空闲会话,经 Core 准入启动,同 session/target 恢复,冷恢复确认暂停。Native revision 和已记录 start intent 保护丢失回执。原生完成不写 Core acceptance/credit debit,但在线 status 可暂停被拒绝的执行。这是单个 provider,不是通用 native Goal 资格。 | | 聚焦测试 | [`tests/test_attached_session_cli.py`](../../../tests/test_attached_session_cli.py) 与 `tests/test_chat_codex_home.py::test_attached_session_uses_existing_host_not_managed_adapter` 覆盖 bind/claim/complete 与"不启动托管适配器"的围栏。 | | 产品级提案 | [桌面执行前端 RFC](desktop-execution-frontends-v0.zh-CN.md) 拥有 Mode A/Mode B 的产品对比、连接器与事件源正交性,以及桌面端非目标。 | | 宿主侧循环指引 | [Codex CLI TUI loop](../../product/runtimes/codex-cli/codex-cli-tui-loop.md) 记录了一个可见宿主的会话挂接自动化与恢复选项。 | diff --git a/docs/architecture/rfcs/loopx-overall-roadmap-v0.md b/docs/architecture/rfcs/loopx-overall-roadmap-v0.md index 142d0da206..f61e45f057 100644 --- a/docs/architecture/rfcs/loopx-overall-roadmap-v0.md +++ b/docs/architecture/rfcs/loopx-overall-roadmap-v0.md @@ -189,11 +189,11 @@ top-level packages: versus `FoldAndPrefetch` support, stdio/encoding requirements, and stop/pause 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 +- **Consolidating `loopx/*_goal_mode/` into `loopx/hosts/`:** migrate the + top-level `loopx/*_goal_mode/` packages (`3` migrated into `loopx/hosts/`: + `hosts/claude`, `hosts/kunluncode`, `hosts/zcode`; `6` remaining: + `agy_goal_mode`, `dsh_goal_mode`, `kiro_cli_goal_mode`, + `opencode2_goal_mode`, `opencode_goal_mode`, `pi_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), @@ -471,7 +471,7 @@ in the existing milestones; there is no parallel delivery program. The bounded S6/S8 source-reading slice provides a [read-only MCP adapter for an existing Ego Page](../../integrations/ego-source-reader.md): rendered text, image indices and one indexed rendered image region within configured origins and an exact URL fence. It creates no Session, material authority or browser service. Text/image navigation now has a bounded semantic-content readiness check scoped to primary semantic content rather than an ancillary sidebar article; navigation text alone cannot satisfy it, busy content ancestors still delay extraction, and image reads accept loaded visible pixels without requiring a caption. One native Bot text round read the observed article through its final paragraph and returned streamed progress and the answer in the original conversation; its first-answer latency remains unqualified. Native Bot single-image consumption has also been observed, but neither proves all images or the referenced primary post. Source capture, verification walls, truncation, unloaded images and optional provider setup keep their separate acceptance boundaries; this slice does not close the materials journey. -The bounded S4/S5/S7/S8/S12 [ZCode native CLI provider](../../../loopx/zcode_goal_mode/README.md) +The bounded S4/S5/S7/S8/S12 [ZCode native CLI provider](../../../loopx/hosts/zcode/README.md) adds explicit binding, model selection, start/pause/resume/stop and live readback through the existing CLI and Goal detail drawer. It reuses Core Goal/Agent identity and quota admission/revocation, isolates the managed session and keeps 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..aa38092afd 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` + 投影(已迁入 `3` 个:`hosts/claude`、`hosts/kunluncode`、`hosts/zcode`; + 待迁移 `6` 个:`agy_goal_mode`、`dsh_goal_mode`、`kiro_cli_goal_mode`、 + `opencode2_goal_mode`、`opencode_goal_mode`、`pi_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/semantic-vocabulary-convergence-v0.md b/docs/architecture/rfcs/semantic-vocabulary-convergence-v0.md index 3a7b92313d..b9c050c1c2 100644 --- a/docs/architecture/rfcs/semantic-vocabulary-convergence-v0.md +++ b/docs/architecture/rfcs/semantic-vocabulary-convergence-v0.md @@ -120,8 +120,8 @@ Concrete failures audited on the baseline: - Conflicting definitions with the same name: `DECISION_CONTEXT_CAPABILITY_ID` is `decision_context` in `capabilities/decision_context/packets.py:18` and `decision-context` in `extension_provider.py:24`; `MCP_REQUIREMENT` is - `mcp==1.28.1` in `kunluncode_goal_mode/cli.py:28` and `mcp<2` in - `claude_goal_mode/scripts/install.py:83`. Sixteen further names are generic + `mcp==1.28.1` in `hosts/kunluncode/cli.py:41` and `mcp<2` in + `hosts/claude/scripts/install.py:215`. Sixteen further names are generic module-local constants (`SCHEMA_VERSION`, `COMMAND`, `CAPABILITY_ID`) whose collision is harmless today and invisible tomorrow. - The Turn result kinds exist twice by hand: `LoopXTurnResultKind` in diff --git a/docs/architecture/rfcs/semantic-vocabulary-convergence-v0.zh-CN.md b/docs/architecture/rfcs/semantic-vocabulary-convergence-v0.zh-CN.md index 925cae2d34..120ed531fe 100644 --- a/docs/architecture/rfcs/semantic-vocabulary-convergence-v0.zh-CN.md +++ b/docs/architecture/rfcs/semantic-vocabulary-convergence-v0.zh-CN.md @@ -98,8 +98,8 @@ LoopX 由大量小型 agent 驱动的 PR 生长而成。每个 PR 在需要之 - 同名不同值:`DECISION_CONTEXT_CAPABILITY_ID` 在 `capabilities/decision_context/packets.py:18` 是 `decision_context`,在 `extension_provider.py:24` 是 `decision-context`;`MCP_REQUIREMENT` 在 - `kunluncode_goal_mode/cli.py:28` 是 `mcp==1.28.1`,在 - `claude_goal_mode/scripts/install.py:83` 是 `mcp<2`。另外 16 个名字是模块内 + `hosts/kunluncode/cli.py:41` 是 `mcp==1.28.1`,在 + `hosts/claude/scripts/install.py:215` 是 `mcp<2`。另外 16 个名字是模块内 通用常量(`SCHEMA_VERSION`、`COMMAND`、`CAPABILITY_ID`),今天的碰撞无害, 明天却不可见。 - Turn 结果种类靠手工维护了两份:`transaction.py:28` 的 `LoopXTurnResultKind` diff --git a/docs/book/chapters/00-reading-guide.md b/docs/book/chapters/00-reading-guide.md index 13a11cb43d..e46513447b 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/{claude,kunluncode,zcode}` 已迁入 `loopx/hosts/`,其余为 +`opencode_goal_mode`、`opencode2_goal_mode`、`pi_goal_mode`、`agy_goal_mode`、`dsh_goal_mode`、`kiro_cli_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..bcbaed0930 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/{claude,kunluncode,zcode}` consolidated under `loopx/hosts/`, alongside +`opencode_goal_mode`, `opencode2_goal_mode`, `pi_goal_mode`, `agy_goal_mode`, `dsh_goal_mode`, `kiro_cli_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/development/testing-and-quality.md b/docs/development/testing-and-quality.md index 5b96825926..1acdbeeea5 100644 --- a/docs/development/testing-and-quality.md +++ b/docs/development/testing-and-quality.md @@ -761,7 +761,7 @@ active users and recoverable dependency definitions. Keep this an explicit maint 目录较旧不能证明无人使用;清理应作为显式维护操作进行。 `npm run typecheck:control-plane` discovers all TypeScript sources under -`loopx/control_plane/` and `loopx/zcode_goal_mode/`, including standalone bridges +`loopx/control_plane/` and `loopx/hosts/zcode/`, including standalone bridges launched from Python and control-plane test drivers. New source files in these owners need no per-file compiler registration. Tests and examples retain their explicit compile entries; `npm run test:control-plane` separately discovers and executes diff --git a/examples/claude-goalmode-hook-policy-smoke.py b/examples/claude-goalmode-hook-policy-smoke.py index 13cfe9b17f..73d764a317 100644 --- a/examples/claude-goalmode-hook-policy-smoke.py +++ b/examples/claude-goalmode-hook-policy-smoke.py @@ -17,7 +17,7 @@ from pathlib import Path REPO_ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(REPO_ROOT / "loopx" / "claude_goal_mode" / "hooks")) +sys.path.insert(0, str(REPO_ROOT / "loopx" / "hosts" / "claude" / "hooks")) import goal_policy # noqa: E402 CTX = {"goal_id": "g", "registry": "/r", "agent_id": "cc", diff --git a/examples/claude-goalmode-lifecycle-smoke.py b/examples/claude-goalmode-lifecycle-smoke.py index 59b1af500c..639fa5c759 100644 --- a/examples/claude-goalmode-lifecycle-smoke.py +++ b/examples/claude-goalmode-lifecycle-smoke.py @@ -22,7 +22,7 @@ from pathlib import Path REPO_ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(REPO_ROOT / "loopx" / "claude_goal_mode" / "hooks")) +sys.path.insert(0, str(REPO_ROOT / "loopx" / "hosts" / "claude" / "hooks")) import goal_state # noqa: E402 from loopx import goal_mode_mcp # noqa: E402 from loopx.goal_mode_mcp import GoalModeMCPConfig, GoalModeMCPControlPlane # noqa: E402 diff --git a/examples/claude-install-no-system-mutation-smoke.py b/examples/claude-install-no-system-mutation-smoke.py index 4c50d399aa..8cdd7e320f 100644 --- a/examples/claude-install-no-system-mutation-smoke.py +++ b/examples/claude-install-no-system-mutation-smoke.py @@ -31,8 +31,8 @@ REPO_ROOT = Path(__file__).resolve().parents[1] if str(REPO_ROOT) not in sys.path: sys.path.insert(0, str(REPO_ROOT)) -INSTALLER = REPO_ROOT / "loopx" / "claude_goal_mode" / "scripts" / "install.py" -CONNECTOR = REPO_ROOT / "loopx" / "claude_goal_mode" / "scripts" / "connect.py" +INSTALLER = REPO_ROOT / "loopx" / "hosts" / "claude" / "scripts" / "install.py" +CONNECTOR = REPO_ROOT / "loopx" / "hosts" / "claude" / "scripts" / "connect.py" def load_install(): diff --git a/examples/claude-install-optin-smoke.py b/examples/claude-install-optin-smoke.py index 2fbc5e7163..68577e3760 100644 --- a/examples/claude-install-optin-smoke.py +++ b/examples/claude-install-optin-smoke.py @@ -26,7 +26,7 @@ REPO_ROOT = Path(__file__).resolve().parents[1] INSTALL_SH = REPO_ROOT / "scripts" / "install-local.sh" -INSTALLER = REPO_ROOT / "loopx" / "claude_goal_mode" / "scripts" / "install.py" +INSTALLER = REPO_ROOT / "loopx" / "hosts" / "claude" / "scripts" / "install.py" def _run(cmd, **kw): diff --git a/examples/kunluncode-app-server-goal-pro-smoke.py b/examples/kunluncode-app-server-goal-pro-smoke.py index 5e7df929c9..e663005d0d 100644 --- a/examples/kunluncode-app-server-goal-pro-smoke.py +++ b/examples/kunluncode-app-server-goal-pro-smoke.py @@ -15,7 +15,7 @@ if str(REPO_ROOT) not in sys.path: sys.path.insert(0, str(REPO_ROOT)) -from loopx.kunluncode_goal_mode.app_server import ( # noqa: E402 +from loopx.hosts.kunluncode.app_server import ( # noqa: E402 KUNLUN_APP_SERVER_PROTOCOL_VERSION, KunlunAppServerClient, build_app_server_command, diff --git a/examples/personal-workspace-browser/zcode-shared-off-probe.py b/examples/personal-workspace-browser/zcode-shared-off-probe.py index be6e72878c..d4ae72bfd8 100644 --- a/examples/personal-workspace-browser/zcode-shared-off-probe.py +++ b/examples/personal-workspace-browser/zcode-shared-off-probe.py @@ -48,7 +48,7 @@ if not any( isinstance(value, ast.Constant) and value.value - == "loopx.zcode_goal_mode.diagnostics.collect_zcode_host_diagnostics" + == "loopx.hosts.zcode.diagnostics.collect_zcode_host_diagnostics" for value in ast.walk(node) ) ] diff --git a/loopx/chat_server.py b/loopx/chat_server.py index 753b453b56..74e530496d 100644 --- a/loopx/chat_server.py +++ b/loopx/chat_server.py @@ -20,7 +20,7 @@ if TYPE_CHECKING: from .capabilities.native_chat.transports import ChatConversationTransports from .attached_session_api import AttachedSessionRequestMixin -from .zcode_goal_mode.api import ZCodeGoalRequestMixin +from .hosts.zcode.api import ZCodeGoalRequestMixin from .chat import TodoReviewPreviewConflict, redact_local_paths from .chat_agent import CodexChatAgentError from .capabilities.native_chat.project_context import ChatProjectContexts diff --git a/loopx/claude_goal_mode/scripts/install.py b/loopx/claude_goal_mode/scripts/install.py deleted file mode 100644 index 4aa8d8a5b9..0000000000 --- a/loopx/claude_goal_mode/scripts/install.py +++ /dev/null @@ -1,525 +0,0 @@ -#!/usr/bin/env python3 -"""Install the loopx Claude Code adapter — EXPLICIT, scoped, opt-in. - -This is NOT run by the default loopx installer. It is invoked deliberately -(`LOOPX_INSTALL_CLAUDE=1 scripts/install-local.sh`, or directly). It installs the -minimum: the loopx **MCP server** (the control-plane tools) + the **`/loopx`** -slash command. The run loop is Claude Code's native `/loop`; loopx only provides -the `should_run` protocol, so NO global hooks are wired by default. - - python install.py --scope project [--project DIR] # this project only (preferred) - python install.py --scope user # all your Claude Code projects - python install.py --scope ... --harden # ALSO add the optional - # PreToolUse should_run gate - # + statusline at that scope - -`--scope` is required (a deliberate choice). User scope is announced loudly. We -NEVER delete existing permission rules; legacy loopx entries get a printed -cleanup suggestion instead. -""" -from __future__ import annotations - -from typing import Any - -import argparse -import json -import os -import shlex -import shutil -import subprocess -import sys -from pathlib import Path - -PLUGIN_ROOT = Path(__file__).resolve().parents[1] -MCP_VENV = Path.home() / ".local" / "share" / "loopx" / "mcp-venv" - -# This script is run by path (`python /loopx/claude_goal_mode/scripts/ -# install.py`), so the package root is not on `sys.path` by default. -REPO_ROOT = Path(__file__).resolve().parents[3] -if str(REPO_ROOT) not in sys.path: - sys.path.insert(0, str(REPO_ROOT)) - -from loopx.file_lock import write_json_atomic # noqa: E402 - - -def _p(*parts: str) -> str: - return str(PLUGIN_ROOT.joinpath(*parts)).replace("\\", "/") - - -def _is_git_bash(path: str) -> bool: - """True when `path` is the MSYS/Cygwin bash Claude Code dispatches to. - - The WSL `bash.exe` that sits on some PATHs is a Linux shell, not the Git - Bash Claude Code spawns for a Windows command string, and its `uname` says - `Linux`; the System32 alias is rejected by name and everything else by - asking the candidate for its `uname`.""" - system32 = Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32" - resolved = os.path.normcase(os.path.realpath(path)) - system32_resolved = os.path.normcase(os.path.realpath(system32)) - if resolved == system32_resolved or resolved.startswith(system32_resolved + os.sep): - return False - try: - probe = subprocess.run([path, "-c", "uname -s"], capture_output=True, timeout=10) - except (OSError, subprocess.SubprocessError): - return False - return probe.returncode == 0 and probe.stdout.decode("utf-8", "replace").startswith( - ("MINGW", "MSYS", "CYGWIN") - ) - - -# Claude Code honors `CLAUDE_CODE_GIT_BASH_PATH` only when the file name is one -# of these (env-vars reference, 2.1.219+); any other name is ignored and Git -# Bash detection continues as if the variable were unset - even when the file -# exists and runs. -_GIT_BASH_OVERRIDE_NAMES = frozenset({"bash.exe", "sh.exe", "bash", "sh"}) - - -def _git_bash() -> str | None: - """The Git Bash Claude Code runs a shell-form command string with, if any. - - Claude Code passes a hook or statusline string to Git Bash on Windows when - Git Bash is installed, to PowerShell when it is not, and to `/bin/sh` on - macOS/Linux (Claude Code hooks reference, "Exec form and shell form"). It - finds Git Bash through its `CLAUDE_CODE_GIT_BASH_PATH` override, the Git - installation or a `bash` on PATH, or a default Git for Windows location; - this mirrors those sources so the encoding can follow the same choice. Like - that consumer, an override whose file name is not `bash.exe`, `sh.exe`, - `bash` or `sh` (compared case-insensitively) is ignored and detection - continues as if it were unset.""" - if sys.platform != "win32": - return None - candidates: list[str] = [] - override = os.environ.get("CLAUDE_CODE_GIT_BASH_PATH") - if override and Path(override).name.lower() in _GIT_BASH_OVERRIDE_NAMES: - candidates.append(override) - git = shutil.which("git") - if git: - root = Path(git).resolve().parent.parent - candidates += [str(root / "bin" / "bash.exe"), str(root / "usr" / "bin" / "bash.exe")] - on_path = shutil.which("bash") - if on_path: - candidates.append(on_path) - for base, sub in ( - (os.environ.get("ProgramFiles"), "Git"), - (os.environ.get("ProgramFiles(x86)"), "Git"), - (os.environ.get("LocalAppData"), "Programs/Git"), - ): - if base: - candidates.append(str(Path(base) / sub / "bin" / "bash.exe")) - for candidate in candidates: - if os.path.isfile(candidate) and _is_git_bash(candidate): - return candidate - return None - - -def _uses_powershell() -> bool: - """Whether Claude Code runs these command strings through PowerShell. - - A Windows host without Git Bash gets PowerShell for shell-form hooks and - the statusline; every other host runs `/bin/sh` or Git Bash.""" - return sys.platform == "win32" and _git_bash() is None - - -def _shell_literal(value: str, *, powershell: bool) -> str: - """Render `value` as one literal token the consumer shell reads back whole. - - Double quotes are not literal in either shell: `$NAME` expands inside them - and an inner `"` can close the token. Single quotes are literal in both, so - POSIX/Git Bash targets get `shlex.quote`'s form and PowerShell a `'...'` - string with its `''` escape. A bare Windows path would lose its - backslashes under Git Bash, so those are quoted too.""" - if powershell: - return "'" + value.replace("'", "''") + "'" - return shlex.quote(value) - - -def _shell_command(value: str, *, powershell: bool) -> str: - """`_shell_literal` in command position: PowerShell needs its `&` operator.""" - token = _shell_literal(value, powershell=powershell) - return f"& {token}" if powershell else token - - -def _launches_python(py: str) -> bool: - """True when running `py` starts a supported Python 3.11+ interpreter. - - `shutil.which` only proves a file is executable, not that it runs Python. On - Windows it can return the 0-byte `WindowsApps` App Execution Alias, which - never starts Python: on some hosts it exits non-zero (9009), on others - launching it raises OSError, and it writes nothing either way. Anything that - bakes that path (the PreToolUse hook, the statusline, `/loopx`) then - silently does nothing.""" - try: - return subprocess.run( - [py, "-c", "import sys; raise SystemExit(sys.version_info < (3, 11))"], - capture_output=True, - timeout=10, - ).returncode == 0 - except (OSError, subprocess.SubprocessError): - return False - - -def _python_cmd() -> str: - """Interpreter to bake into hook / statusline / command strings — robust where - only `python` (not `python3`) is registered, and where `python3` resolves to a - launcher that cannot run supported Python (including the Windows - `WindowsApps` alias and an older PATH interpreter).""" - for candidate in (shutil.which("python3"), shutil.which("python")): - if candidate and _launches_python(candidate): - return candidate - return sys.executable - - -def deep_merge(base: dict[str, Any], add: dict[str, Any]) -> dict[str, Any]: - for k, v in add.items(): - if isinstance(v, dict) and isinstance(base.get(k), dict): - deep_merge(base[k], v) - elif isinstance(v, list) and isinstance(base.get(k), list): - base[k] += [x for x in v if x not in base[k]] - else: - base[k] = v - return base - - -# ---- optional hardening (only with --harden) -------------------------------- - -def hardening_block() -> dict[str, Any]: - """The OPTIONAL per-tool gate + statusline. Not installed unless --harden.""" - powershell = _uses_powershell() - py = _shell_command(_python_cmd(), powershell=powershell) - gate = _shell_literal(_p("hooks", "goal_policy.py"), powershell=powershell) - status = _shell_literal(_p("statusline", "goal_status.py"), powershell=powershell) - return { - "hooks": { - "PreToolUse": [{"matcher": "*", "hooks": [ - {"type": "command", "command": f"{py} {gate}", "timeout": 10}]}], - }, - "statusLine": {"type": "command", "command": f"{py} {status}"}, - } - - -# ---- MCP dependency provisioning -------------------------------------------- - -def _venv_python(venv: Path) -> Path: - sub = "Scripts" if sys.platform == "win32" else "bin" - exe = "python.exe" if sys.platform == "win32" else "python" - return venv / sub / exe - - -# The server imports `mcp.server.fastmcp`, which MCP SDK 2.x no longer ships. -# Checking a bare `import mcp` accepts an interpreter that cannot actually run -# the server, so registration would write a config that fails to start — -# `cursor-agent mcp list` reports "Connection failed" and Claude silently drops -# the tools. Probe the module the server really needs. -MCP_PROBE = "import mcp.server.fastmcp" -# Upper bound for the same reason; drop it once loopx_mcp.py speaks the 2.x API. -MCP_REQUIREMENT = "mcp<2" - - -def _has_mcp(py: str | Path) -> bool: - try: - return subprocess.run([str(py), "-c", MCP_PROBE], capture_output=True).returncode == 0 - except (FileNotFoundError, OSError): - return False - - -def provision_mcp_python(dry: bool, allow_system_pip: bool = False) -> str: - """Return an interpreter that can `import mcp`, installing it into a dedicated - venv if needed (works under PEP 668 externally-managed pythons). - - We install `mcp` ONLY into a dedicated venv we own. We never silently mutate - the user's active/system interpreter (`pip install --break-system-packages`); - that is gated behind an explicit ``allow_system_pip`` opt-in.""" - if _has_mcp(sys.executable): - print(f"[deps] mcp already importable by {sys.executable}") - return sys.executable - vpy = _venv_python(MCP_VENV) - if _has_mcp(vpy): - print(f"[deps] reusing mcp venv {MCP_VENV}") - return str(vpy) - if dry: - print(f"[deps] (dry-run) would create venv {MCP_VENV} and pip install mcp") - return str(vpy) - print(f"[deps] creating mcp venv {MCP_VENV} …") - MCP_VENV.parent.mkdir(parents=True, exist_ok=True) - r = subprocess.run([sys.executable, "-m", "venv", str(MCP_VENV)], capture_output=True, text=True, encoding="utf-8", errors="replace",) - if r.returncode == 0: - subprocess.run([str(vpy), "-m", "pip", "install", "-q", "--upgrade", "pip"], capture_output=True, text=True, encoding="utf-8", errors="replace",) - pip = subprocess.run([str(vpy), "-m", "pip", "install", "-q", MCP_REQUIREMENT], capture_output=True, text=True, encoding="utf-8", errors="replace",) - if pip.returncode == 0 and _has_mcp(vpy): - print(f"[deps] mcp installed into {MCP_VENV}") - return str(vpy) - print("[deps] venv pip install failed:\n" + (pip.stdout + pip.stderr)[:300]) - else: - print("[deps] venv creation failed:\n" + (r.stdout + r.stderr)[:300]) - # The dedicated venv is the only place we install `mcp`. Do NOT touch the - # user's active/system interpreter unless they explicitly opted in. - if allow_system_pip: - print("[deps] --allow-system-pip: pip install --break-system-packages mcp") - subprocess.run([sys.executable, "-m", "pip", "install", "-q", "--break-system-packages", MCP_REQUIREMENT], - capture_output=True, text=True, encoding="utf-8", errors="replace",) - if _has_mcp(sys.executable): - return sys.executable - print("[deps] WARNING: could not provision `mcp` into a dedicated venv, and we will\n" - " NOT modify your system Python. The loopx MCP tools will not load until\n" - " you install `mcp` yourself, e.g.:\n" - f" {sys.executable} -m venv {MCP_VENV} && {vpy} -m pip install '{MCP_REQUIREMENT}'\n" - " (or re-run install.py with --allow-system-pip to use the active interpreter).") - return _python_cmd() - - -def install_mcp( - dry: bool, - py: str, - scope: str, - migrate_goal_harness: bool = False, - project_dir: Path | None = None, -) -> bool: - """Register the loopx MCP server at the chosen scope via `claude mcp add`. - - We replace only OUR `loopx` entry. A legacy/user-owned `goal-harness` MCP is - left untouched by default — we don't delete a server we don't own. If one - exists we print a manual cleanup hint; `--migrate-goal-harness` removes it. - - Returns whether the `loopx` entry is registered afterwards: True only when - `claude mcp add` reported success. A missing `claude` CLI and a failed add - both leave the server unregistered and print the manual command instead, so - a caller that narrates the install must read that receipt, not the attempt.""" - if scope == "project" and project_dir is None: - raise ValueError("project_dir is required for project-scoped MCP registration") - cwd_run = str(project_dir) if scope == "project" else None - claude = shutil.which("claude") - mcp_path = _p("mcp", "loopx_mcp.py") - add = ["mcp", "add", "--scope", scope, "loopx", "--", py, mcp_path] - if not claude: - print("[mcp] claude CLI not on PATH — add the MCP server manually:\n claude " + " ".join(add)) - return False - print(f"[mcp] claude mcp add --scope {scope} loopx -- {py} ") - if dry: - return False - subprocess.run( - [claude, "mcp", "remove", "--scope", scope, "loopx"], - capture_output=True, - text=True, encoding="utf-8", errors="replace", - cwd=cwd_run, - ) - has_gh = subprocess.run( - [claude, "mcp", "get", "goal-harness"], - capture_output=True, - text=True, encoding="utf-8", errors="replace", - cwd=cwd_run, - ).returncode == 0 - if has_gh: - if migrate_goal_harness: - print(f"[mcp] --migrate-goal-harness: removing legacy goal-harness MCP at {scope} scope") - subprocess.run( - [claude, "mcp", "remove", "--scope", scope, "goal-harness"], - capture_output=True, - text=True, encoding="utf-8", errors="replace", - cwd=cwd_run, - ) - else: - print("[mcp] note: a legacy `goal-harness` MCP entry exists — left untouched. Remove it " - f"yourself with `claude mcp remove --scope {scope} goal-harness`, or re-run with " - "--migrate-goal-harness.") - r = subprocess.run( - [claude, *add], - capture_output=True, - text=True, encoding="utf-8", errors="replace", - cwd=cwd_run, - ) - if r.returncode != 0: - print(" (mcp add failed; add manually:\n claude " + " ".join(add) + "\n " + (r.stdout + r.stderr)[:200] + ")") - return False - return True - - -# ---- /loopx command ---------------------------------------------------------- - -def command_md() -> str: - # The `!` line runs through the Bash tool - `sh`/Git Bash on every host - so - # it is always a POSIX literal, never the PowerShell form; a Windows host - # without Git Bash cannot run `!` lines at all (README). - entry = _shell_literal(_p("scripts", "goalmode_cmd.py"), powershell=False) - py = _shell_literal(_python_cmd(), powershell=False) - return ( - "---\n" - "description: loopx goal-mode setup. " - "`/loopx ` sets up a goal + writes .claude/loop.md; drive the loop with native /loop. " - "bare /loopx = arm; off | status.\n" - "argument-hint: | (no args = arm) | off | status\n" - f"allowed-tools: Bash({py}:*)\n" - "---\n\n" - "Run the loopx setup helper and read its output:\n\n" - f"!`{py} {entry} $ARGUMENTS`\n\n" - "The output is loopx control-plane SETUP / status info — it is the COMPLETE, user-facing " - "result. Show it to the user VERBATIM and STOP. Do NOT do any work, claim todos, write " - "files, or loop here: the WORK runs when the user types Claude Code's native `/loop` (which " - "executes `.claude/loop.md`). Do not summarize a multi-line `status` detail block into one line.\n\n" - "The run loop is native `/loop`; loopx provides the deterministic " - "`should_run` protocol.\n" - ) - - -def install_command(dry: bool, cmd_dir: Path) -> None: - path = cmd_dir / "loopx.md" - print(f"[command] /loopx -> {path}") - if dry: - return - cmd_dir.mkdir(parents=True, exist_ok=True) - old = cmd_dir / "goalmode.md" # migrate the legacy /goalmode entry name - if old.exists(): - old.unlink() - path.write_text(command_md(), encoding="utf-8") - - -class HardenSettingsUnreadable(RuntimeError): - """`--harden` refuses to rewrite a settings file it cannot read as JSON.""" - - -def add_hardening(dry: bool, settings_path: Path) -> None: - """Deep-merge the optional hook + statusline into settings_path, preserving - existing config. NEVER deletes permission rules. - - The merge rewrites the whole file, so a settings file that exists but does - not parse is refused instead of replaced: substituting `{}` for it would - drop every key the user owns - permission rules, `env`, `model`, other - hooks, MCP approvals - leaving only the loopx block, at exit status 0. The - file is user-owned (LoopX did not create it), which is why the sibling - merge in `loopx/slash_command_install.py` fails closed on the same input. - """ - cur = {} - if settings_path.exists(): - try: - cur = json.loads(settings_path.read_text(encoding="utf-8")) - except (OSError, ValueError) as exc: - raise HardenSettingsUnreadable( - f"{settings_path} exists but is not readable as JSON ({exc}); refusing to " - "rewrite it. Fix or move that file, then re-run with --harden." - ) from exc - if not isinstance(cur, dict): - raise HardenSettingsUnreadable( - f"{settings_path} exists but is not a JSON object; refusing to rewrite it. " - "Fix or move that file, then re-run with --harden." - ) - # prune prior loopx PreToolUse entries (avoid stacking on reinstall) - for grp in (cur.get("hooks", {}) or {}).get("PreToolUse", []) or []: - grp["hooks"] = [h for h in grp.get("hooks", []) if "goal_policy.py" not in str(h.get("command", ""))] - if isinstance(cur.get("hooks", {}).get("PreToolUse"), list): - cur["hooks"]["PreToolUse"] = [g for g in cur["hooks"]["PreToolUse"] if g.get("hooks")] - merged = deep_merge(cur, hardening_block()) - print(f"[harden] PreToolUse should_run gate + statusline -> {settings_path}") - if not dry: - # One replace, not a truncate-in-place: an interrupted install must not - # leave the user's settings.json as a partial document. The destination - # is resolved first so a dotfiles-managed symlink keeps pointing at its - # target instead of being replaced by the rename. - write_json_atomic(settings_path.resolve(), merged, preserve_mode=True) - - -def warn_legacy_perms(settings_path: Path) -> None: - """Detect a legacy loopx credential-deny and SUGGEST manual cleanup. Never mutate.""" - try: - cur = json.loads(settings_path.read_text(encoding="utf-8")) - except Exception: - return - deny = ((cur.get("permissions") or {}).get("deny")) or [] - legacy = [r for r in deny if r in ("Read(~/.ssh/**)", "Read(~/.aws/**)")] - if legacy: - print(f"[note] {settings_path} has loopx-era permission deny rules {legacy}. " - "We no longer add these and will NOT remove them automatically. " - "To drop them, edit that file's `permissions.deny` by hand.") - - -def main() -> int: - ap = argparse.ArgumentParser() - ap.add_argument("--scope", choices=["user", "project"], required=True, - help="user = ~/.claude (all projects); project = THIS project's .claude (preferred)") - ap.add_argument("--project", default=None, help="project dir for --scope project (default: cwd)") - ap.add_argument("--harden", action="store_true", - help="ALSO install the optional PreToolUse should_run gate + statusline") - ap.add_argument("--skip-mcp", action="store_true", - help="skip MCP venv provisioning + `claude mcp add` (for tests/CI)") - ap.add_argument("--allow-system-pip", action="store_true", - help="if the dedicated mcp venv can't be built, fall back to " - "`pip install --break-system-packages mcp` into the active interpreter " - "(off by default — we don't mutate your system Python)") - ap.add_argument("--migrate-goal-harness", action="store_true", - help="also remove a legacy `goal-harness` MCP entry at this scope " - "(off by default — we don't delete MCP servers we don't own)") - ap.add_argument("--dry-run", action="store_true") - a = ap.parse_args() - dry = a.dry_run - - project_dir = None - if a.scope == "project": - project_dir = Path(a.project).resolve() if a.project else Path.cwd() - claude_dir = project_dir / ".claude" - print(f"[scope] PROJECT — installs into {claude_dir} (this project only)") - else: - claude_dir = Path.home() / ".claude" - print("[scope] USER — installs into ~/.claude. The /loopx command and MCP become") - print(" available in ALL your Claude Code projects." + - (" --harden adds USER-LEVEL, matcher-wide hooks too." if a.harden else "")) - - mcp_registered = False - if a.skip_mcp: - print("[mcp] skipped (--skip-mcp)") - else: - mcp_python = provision_mcp_python(dry, a.allow_system_pip) - mcp_registered = install_mcp( - dry, - mcp_python, - a.scope, - a.migrate_goal_harness, - project_dir=project_dir, - ) - install_command(dry, claude_dir / "commands") - - settings_path = claude_dir / "settings.json" - if a.harden: - try: - add_hardening(dry, settings_path) - except HardenSettingsUnreadable as exc: - print(f"[harden] {exc}", file=sys.stderr) - outcome = ( - "nothing was written (dry-run)" - if dry - else "the settings file is unchanged" - ) - print( - f"[harden] the optional should_run gate + statusline were skipped; {outcome}.", - file=sys.stderr, - ) - if not dry: - # The rest of the install did run, so name only what happened: - # the /loopx command was written just above, and the MCP state is - # the registration receipt `install_mcp` returned - not the - # attempt. A missing CLI or a failed `claude mcp add` leaves the - # server unregistered, and reporting that attempt as an install - # would let a user skip the manual command printed above. - if a.skip_mcp: - mcp_state = "the MCP server was skipped (--skip-mcp)" - elif mcp_registered: - mcp_state = "the MCP server was registered" - else: - mcp_state = ("the MCP server was not registered — run the " - "`claude mcp add` command printed above") - print( - f"[harden] the /loopx command was installed; {mcp_state}.", - file=sys.stderr, - ) - return 2 - else: - print("[harden] skipped (default): no hooks/statusline installed. Add later with --harden.") - warn_legacy_perms(settings_path) - - print("\nloopx Claude adapter installed.") - print("Next: in a project with a goal, type `/loopx `, then drive it with native `/loop`.") - print("Restart any open Claude Code session so the command/MCP load.") - if dry: - print("(dry-run: nothing written)") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/loopx/cli_commands/slash_commands.py b/loopx/cli_commands/slash_commands.py index 60da0abbad..8d62ea679a 100644 --- a/loopx/cli_commands/slash_commands.py +++ b/loopx/cli_commands/slash_commands.py @@ -219,6 +219,11 @@ def handle_slash_commands_command( if agy_goal_id and getattr(args, "runtime_root", None) else None ) + resolved_runtime_root = ( + str(Path(args.runtime_root).expanduser().resolve()) + if getattr(args, "runtime_root", None) + else None + ) payload = install_slash_commands( execute=bool((args.install or args.uninstall) and not args.dry_run), uninstall=bool(args.uninstall), @@ -242,6 +247,8 @@ def handle_slash_commands_command( agy_registry=agy_registry, pi_project=args.pi_project, pi_scope=args.pi_scope, + registry_path=str(resolved_registry.resolve()) if resolved_registry is not None else None, + runtime_root=resolved_runtime_root, ) print_payload(payload, output_format(args), render_slash_command_install_markdown) return 0 if payload.get("ok") is True else 1 diff --git a/loopx/cli_commands/zcode_goal.py b/loopx/cli_commands/zcode_goal.py index 13ab665603..03b88aa5fe 100644 --- a/loopx/cli_commands/zcode_goal.py +++ b/loopx/cli_commands/zcode_goal.py @@ -4,7 +4,7 @@ from pathlib import Path from typing import Any, Callable -from ..zcode_goal_mode.bridge import ZCODE_GOAL_ACTIONS, zcode_goal_operation +from ..hosts.zcode.bridge import ZCODE_GOAL_ACTIONS, zcode_goal_operation AddFormat = Callable[[argparse.ArgumentParser], None] diff --git a/loopx/cli_runtime.py b/loopx/cli_runtime.py index ec485f3e31..d3d218e786 100644 --- a/loopx/cli_runtime.py +++ b/loopx/cli_runtime.py @@ -282,7 +282,7 @@ def resolve_cli_registry( def enforce_native_controller_guard(args: argparse.Namespace) -> int | None: if os.environ.get("LOOPX_KUNLUNCODE_OUTER_CONTROLLER") != "1": return None - from .kunluncode_goal_mode.guards import native_controller_cli_write_block + from .hosts.kunluncode.guards import native_controller_cli_write_block native_write_block = native_controller_cli_write_block(args) if native_write_block is None: diff --git a/loopx/control_plane/status/collection.py b/loopx/control_plane/status/collection.py index 46abee332a..d4b55bb427 100644 --- a/loopx/control_plane/status/collection.py +++ b/loopx/control_plane/status/collection.py @@ -223,7 +223,7 @@ def canonical_runtime_for_goal(current_goal_id: str) -> Path: zcode_eligibility: dict[str, list[str]] = {} source_goal_observer: Callable[[str, dict[str, Any] | None], None] | None = None if include_zcode_goal_eligibility: - from ...zcode_goal_mode.bridge import zcode_goal_eligible_agent_ids + from ...hosts.zcode.bridge import zcode_goal_eligible_agent_ids def observe_source_goal(current_goal_id: str, source_goal: dict[str, Any] | None) -> None: zcode_eligibility[current_goal_id] = ( diff --git a/loopx/doctor.py b/loopx/doctor.py index e8c9545c2b..7212a199c2 100644 --- a/loopx/doctor.py +++ b/loopx/doctor.py @@ -858,7 +858,7 @@ def collect_doctor( skill_roots: tuple[Path, ...] if canonical_agent_type == "zcode": from .slash_command_install import inspect_skill_facades - from .zcode_goal_mode import zcode_home + from .hosts.zcode import zcode_home selected_zcode_home = zcode_home() skill_roots = (selected_zcode_home / "skills",) @@ -1365,7 +1365,7 @@ def collect_doctor( ), } if canonical_agent_type == "zcode": - from .zcode_goal_mode.diagnostics import collect_zcode_host_diagnostics + from .hosts.zcode.diagnostics import collect_zcode_host_diagnostics payload["zcode"] = collect_zcode_host_diagnostics( cli_path=zcode_cli, desktop_path=zcode_desktop, source_root=zcode_source, @@ -1670,7 +1670,7 @@ def render_doctor_markdown(payload: dict[str, Any]) -> str: ]) zcode = payload.get("zcode") if isinstance(zcode, dict): - from .zcode_goal_mode.diagnostics import render_zcode_diagnostics_markdown + from .hosts.zcode.diagnostics import render_zcode_diagnostics_markdown lines.extend(render_zcode_diagnostics_markdown(zcode)) restart = payload.get("effect_runtime_restart") diff --git a/loopx/goal_mode_mcp.py b/loopx/goal_mode_mcp.py index 4fef4af90a..f64887f2e3 100644 --- a/loopx/goal_mode_mcp.py +++ b/loopx/goal_mode_mcp.py @@ -157,7 +157,7 @@ def list_todos(self) -> str: return self.should_run() def host_prompt(self) -> str: - from .claude_goal_mode.scripts.goalmode_cmd import loop_execution_content + from .hosts.claude.scripts.goalmode_cmd import loop_execution_content state = self.state() goal_id, agent_id = state.get("goal_id"), state.get("agent_id") if not goal_id or not agent_id: diff --git a/loopx/host_loop_activation.py b/loopx/host_loop_activation.py index 2c00da83cd..793db9b128 100644 --- a/loopx/host_loop_activation.py +++ b/loopx/host_loop_activation.py @@ -3,7 +3,7 @@ from typing import Any import shlex -from .zcode_goal_mode import native_goal_activation +from .hosts.zcode import native_goal_activation from .agent_registry import normalize_registered_agents from .agy_goal_mode import ( AGY_ACCEPTED_INPUTS, diff --git a/loopx/claude_goal_mode/.claude-plugin/plugin.json b/loopx/hosts/claude/.claude-plugin/plugin.json similarity index 100% rename from loopx/claude_goal_mode/.claude-plugin/plugin.json rename to loopx/hosts/claude/.claude-plugin/plugin.json diff --git a/loopx/claude_goal_mode/README.md b/loopx/hosts/claude/README.md similarity index 94% rename from loopx/claude_goal_mode/README.md rename to loopx/hosts/claude/README.md index 107e5a694f..c8753b097c 100644 --- a/loopx/claude_goal_mode/README.md +++ b/loopx/hosts/claude/README.md @@ -33,13 +33,13 @@ Without `LOOPX_INSTALL_CLAUDE=1` the installer skips the adapter entirely. ```bash # this project only (recommended) -python3 loopx/claude_goal_mode/scripts/install.py --scope project --project /path/to/project +python3 loopx/hosts/claude/scripts/install.py --scope project --project /path/to/project # all your Claude Code projects (announced at install time) -python3 loopx/claude_goal_mode/scripts/install.py --scope user +python3 loopx/hosts/claude/scripts/install.py --scope user # preview without writing anything -python3 loopx/claude_goal_mode/scripts/install.py --scope project --project /path/to/project --dry-run +python3 loopx/hosts/claude/scripts/install.py --scope project --project /path/to/project --dry-run ``` ### Optional hardening (`--harden`) @@ -103,7 +103,7 @@ hook, statusline and `/loopx` commands through the selected shell for a plain path, an ordinary spaced path and literal `$`/quote paths. ```bash -python3 loopx/claude_goal_mode/scripts/install.py --scope project --project /path/to/project --harden +python3 loopx/hosts/claude/scripts/install.py --scope project --project /path/to/project --harden ``` The installer **never** deletes existing permission rules: a legacy LoopX @@ -113,7 +113,7 @@ manual-cleanup suggestion instead of being removed. ### One-shot connect (set up a goal + project-scoped install) ```bash -python3 loopx/claude_goal_mode/scripts/connect.py \ +python3 loopx/hosts/claude/scripts/connect.py \ --project /path/to/project --goal-id GOAL [--objective "..."] [--harden] ``` diff --git a/loopx/claude_goal_mode/__init__.py b/loopx/hosts/claude/__init__.py similarity index 100% rename from loopx/claude_goal_mode/__init__.py rename to loopx/hosts/claude/__init__.py diff --git a/loopx/claude_goal_mode/commands/loopx.md b/loopx/hosts/claude/commands/loopx.md similarity index 100% rename from loopx/claude_goal_mode/commands/loopx.md rename to loopx/hosts/claude/commands/loopx.md diff --git a/loopx/claude_goal_mode/hooks/goal_policy.py b/loopx/hosts/claude/hooks/goal_policy.py similarity index 100% rename from loopx/claude_goal_mode/hooks/goal_policy.py rename to loopx/hosts/claude/hooks/goal_policy.py diff --git a/loopx/claude_goal_mode/hooks/goal_state.py b/loopx/hosts/claude/hooks/goal_state.py similarity index 98% rename from loopx/claude_goal_mode/hooks/goal_state.py rename to loopx/hosts/claude/hooks/goal_state.py index 1d0668422d..f87d0aa341 100644 --- a/loopx/claude_goal_mode/hooks/goal_state.py +++ b/loopx/hosts/claude/hooks/goal_state.py @@ -21,7 +21,7 @@ import sys from pathlib import Path -REPO_ROOT = Path(__file__).resolve().parents[3] +REPO_ROOT = Path(__file__).resolve().parents[4] if str(REPO_ROOT) not in sys.path: sys.path.insert(0, str(REPO_ROOT)) diff --git a/loopx/claude_goal_mode/hooks/hooks.json b/loopx/hosts/claude/hooks/hooks.json similarity index 100% rename from loopx/claude_goal_mode/hooks/hooks.json rename to loopx/hosts/claude/hooks/hooks.json diff --git a/loopx/claude_goal_mode/hooks/stdio_utf8.py b/loopx/hosts/claude/hooks/stdio_utf8.py similarity index 100% rename from loopx/claude_goal_mode/hooks/stdio_utf8.py rename to loopx/hosts/claude/hooks/stdio_utf8.py diff --git a/loopx/claude_goal_mode/mcp/loopx_mcp.py b/loopx/hosts/claude/mcp/loopx_mcp.py similarity index 95% rename from loopx/claude_goal_mode/mcp/loopx_mcp.py rename to loopx/hosts/claude/mcp/loopx_mcp.py index 57627e2199..604488c206 100644 --- a/loopx/claude_goal_mode/mcp/loopx_mcp.py +++ b/loopx/hosts/claude/mcp/loopx_mcp.py @@ -6,7 +6,7 @@ from pathlib import Path -REPO_ROOT = Path(__file__).resolve().parents[3] +REPO_ROOT = Path(__file__).resolve().parents[4] if str(REPO_ROOT) not in sys.path: sys.path.insert(0, str(REPO_ROOT)) diff --git a/loopx/claude_goal_mode/scripts/connect.py b/loopx/hosts/claude/scripts/connect.py similarity index 95% rename from loopx/claude_goal_mode/scripts/connect.py rename to loopx/hosts/claude/scripts/connect.py index dcf7d5f5d8..8bfca84cc2 100644 --- a/loopx/claude_goal_mode/scripts/connect.py +++ b/loopx/hosts/claude/scripts/connect.py @@ -16,15 +16,18 @@ import sys from pathlib import Path -from loopx.control_plane.projects.registry_codec import ( +PLUGIN_ROOT = Path(__file__).resolve().parents[1] +REPO_ROOT = Path(__file__).resolve().parents[4] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from loopx.control_plane.projects.registry_codec import ( # noqa: E402 ProjectRegistryProtocolError, add_project_registry_backend, load_project_registry, require_runtime_compatible_project_registry, ) -PLUGIN_ROOT = Path(__file__).resolve().parents[1] - def _gh_prefix(): exe = shutil.which("loopx") diff --git a/loopx/claude_goal_mode/scripts/goalmode_cmd.py b/loopx/hosts/claude/scripts/goalmode_cmd.py similarity index 100% rename from loopx/claude_goal_mode/scripts/goalmode_cmd.py rename to loopx/hosts/claude/scripts/goalmode_cmd.py diff --git a/loopx/hosts/claude/scripts/install.py b/loopx/hosts/claude/scripts/install.py new file mode 100644 index 0000000000..24acfbc3c0 --- /dev/null +++ b/loopx/hosts/claude/scripts/install.py @@ -0,0 +1,1373 @@ +#!/usr/bin/env python3 +"""Install the loopx Claude Code adapter — EXPLICIT, scoped, opt-in. + +This is NOT run by the default loopx installer. It is invoked deliberately +(`LOOPX_INSTALL_CLAUDE=1 scripts/install-local.sh`, or directly). It installs the +minimum: the loopx **MCP server** (the control-plane tools) + the **`/loopx`** +slash command. The run loop is Claude Code's native `/loop`; loopx only provides +the `should_run` protocol, so NO global hooks are wired by default. + + python install.py --scope project [--project DIR] # this project only (preferred) + python install.py --scope user # all your Claude Code projects + python install.py --scope ... --harden # ALSO add the optional + # PreToolUse should_run gate + # + statusline at that scope + +`--scope` is required (a deliberate choice). User scope is announced loudly. We +NEVER delete existing permission rules; legacy loopx entries get a printed +cleanup suggestion instead. +""" +from __future__ import annotations + +from typing import Any, NamedTuple + +import argparse +import json +import os +import re +import shlex +import shutil +import subprocess +import sys +from pathlib import Path + +PLUGIN_ROOT = Path(__file__).resolve().parents[1] +MCP_VENV = Path.home() / ".local" / "share" / "loopx" / "mcp-venv" + +# This script is run by path (`python /loopx/hosts/claude/scripts/ +# install.py`), so the package root is not on `sys.path` by default. +REPO_ROOT = Path(__file__).resolve().parents[4] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from loopx.file_lock import write_bytes_atomic, write_json_atomic # noqa: E402 + + +def _p(*parts: str) -> str: + return str(PLUGIN_ROOT.joinpath(*parts)).replace("\\", "/") + + +def _is_git_bash(path: str) -> bool: + """True when `path` is the MSYS/Cygwin bash Claude Code dispatches to. + + The WSL `bash.exe` that sits on some PATHs is a Linux shell, not the Git + Bash Claude Code spawns for a Windows command string, and its `uname` says + `Linux`; the System32 alias is rejected by name and everything else by + asking the candidate for its `uname`.""" + system32 = Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32" + resolved = os.path.normcase(os.path.realpath(path)) + system32_resolved = os.path.normcase(os.path.realpath(system32)) + if resolved == system32_resolved or resolved.startswith(system32_resolved + os.sep): + return False + try: + probe = subprocess.run([path, "-c", "uname -s"], capture_output=True, timeout=10) + except (OSError, subprocess.SubprocessError): + return False + return probe.returncode == 0 and probe.stdout.decode("utf-8", "replace").startswith( + ("MINGW", "MSYS", "CYGWIN") + ) + + +# Claude Code honors `CLAUDE_CODE_GIT_BASH_PATH` only when the file name is one +# of these (env-vars reference, 2.1.219+); any other name is ignored and Git +# Bash detection continues as if the variable were unset - even when the file +# exists and runs. +_GIT_BASH_OVERRIDE_NAMES = frozenset({"bash.exe", "sh.exe", "bash", "sh"}) + + +def _git_bash() -> str | None: + """The Git Bash Claude Code runs a shell-form command string with, if any. + + Claude Code passes a hook or statusline string to Git Bash on Windows when + Git Bash is installed, to PowerShell when it is not, and to `/bin/sh` on + macOS/Linux (Claude Code hooks reference, "Exec form and shell form"). It + finds Git Bash through its `CLAUDE_CODE_GIT_BASH_PATH` override, the Git + installation or a `bash` on PATH, or a default Git for Windows location; + this mirrors those sources so the encoding can follow the same choice. Like + that consumer, an override whose file name is not `bash.exe`, `sh.exe`, + `bash` or `sh` (compared case-insensitively) is ignored and detection + continues as if it were unset.""" + if sys.platform != "win32": + return None + candidates: list[str] = [] + override = os.environ.get("CLAUDE_CODE_GIT_BASH_PATH") + if override and Path(override).name.lower() in _GIT_BASH_OVERRIDE_NAMES: + candidates.append(override) + git = shutil.which("git") + if git: + root = Path(git).resolve().parent.parent + candidates += [str(root / "bin" / "bash.exe"), str(root / "usr" / "bin" / "bash.exe")] + on_path = shutil.which("bash") + if on_path: + candidates.append(on_path) + for base, sub in ( + (os.environ.get("ProgramFiles"), "Git"), + (os.environ.get("ProgramFiles(x86)"), "Git"), + (os.environ.get("LocalAppData"), "Programs/Git"), + ): + if base: + candidates.append(str(Path(base) / sub / "bin" / "bash.exe")) + for candidate in candidates: + if os.path.isfile(candidate) and _is_git_bash(candidate): + return candidate + return None + + +def _uses_powershell() -> bool: + """Whether Claude Code runs these command strings through PowerShell. + + A Windows host without Git Bash gets PowerShell for shell-form hooks and + the statusline; every other host runs `/bin/sh` or Git Bash.""" + return sys.platform == "win32" and _git_bash() is None + + +def _shell_literal(value: str, *, powershell: bool) -> str: + """Render `value` as one literal token the consumer shell reads back whole. + + Double quotes are not literal in either shell: `$NAME` expands inside them + and an inner `"` can close the token. Single quotes are literal in both, so + POSIX/Git Bash targets get `shlex.quote`'s form and PowerShell a `'...'` + string with its `''` escape. A bare Windows path would lose its + backslashes under Git Bash, so those are quoted too.""" + if powershell: + return "'" + value.replace("'", "''") + "'" + return shlex.quote(value) + + +def _shell_command(value: str, *, powershell: bool) -> str: + """`_shell_literal` in command position: PowerShell needs its `&` operator.""" + token = _shell_literal(value, powershell=powershell) + return f"& {token}" if powershell else token + + +def _launches_python(py: str) -> bool: + """True when running `py` starts a supported Python 3.11+ interpreter. + + `shutil.which` only proves a file is executable, not that it runs Python. On + Windows it can return the 0-byte `WindowsApps` App Execution Alias, which + never starts Python: on some hosts it exits non-zero (9009), on others + launching it raises OSError, and it writes nothing either way. Anything that + bakes that path (the PreToolUse hook, the statusline, `/loopx`) then + silently does nothing.""" + try: + return subprocess.run( + [py, "-c", "import sys; raise SystemExit(sys.version_info < (3, 11))"], + capture_output=True, + timeout=10, + ).returncode == 0 + except (OSError, subprocess.SubprocessError): + return False + + +def _python_cmd() -> str: + """Interpreter to bake into hook / statusline / command strings — robust where + only `python` (not `python3`) is registered, and where `python3` resolves to a + launcher that cannot run supported Python (including the Windows + `WindowsApps` alias and an older PATH interpreter).""" + for candidate in (shutil.which("python3"), shutil.which("python")): + if candidate and _launches_python(candidate): + return candidate + return sys.executable + + +def deep_merge(base: dict[str, Any], add: dict[str, Any]) -> dict[str, Any]: + for k, v in add.items(): + if isinstance(v, dict) and isinstance(base.get(k), dict): + deep_merge(base[k], v) + elif isinstance(v, list) and isinstance(base.get(k), list): + base[k] += [x for x in v if x not in base[k]] + else: + base[k] = v + return base + + +# ---- optional hardening (only with --harden) -------------------------------- + +def hardening_block() -> dict[str, Any]: + """The OPTIONAL per-tool gate + statusline. Not installed unless --harden.""" + powershell = _uses_powershell() + py = _shell_command(_python_cmd(), powershell=powershell) + gate = _shell_literal(_p("hooks", "goal_policy.py"), powershell=powershell) + status = _shell_literal(_p("statusline", "goal_status.py"), powershell=powershell) + return { + "hooks": { + "PreToolUse": [{"matcher": "*", "hooks": [ + {"type": "command", "command": f"{py} {gate}", "timeout": 10}]}], + }, + "statusLine": {"type": "command", "command": f"{py} {status}"}, + } + + +# ---- MCP dependency provisioning -------------------------------------------- + +def _venv_python(venv: Path) -> Path: + sub = "Scripts" if sys.platform == "win32" else "bin" + exe = "python.exe" if sys.platform == "win32" else "python" + return venv / sub / exe + + +# The server imports `mcp.server.fastmcp`, which MCP SDK 2.x no longer ships. +# Checking a bare `import mcp` accepts an interpreter that cannot actually run +# the server, so registration would write a config that fails to start — +# `cursor-agent mcp list` reports "Connection failed" and Claude silently drops +# the tools. Probe the module the server really needs. +MCP_PROBE = "import mcp.server.fastmcp" +# Upper bound for the same reason; drop it once loopx_mcp.py speaks the 2.x API. +MCP_REQUIREMENT = "mcp<2" + + +def _has_mcp(py: str | Path) -> bool: + try: + return subprocess.run([str(py), "-c", MCP_PROBE], capture_output=True).returncode == 0 + except (FileNotFoundError, OSError): + return False + + +def provision_mcp_python(dry: bool, allow_system_pip: bool = False) -> str: + """Return an interpreter that can `import mcp`, installing it into a dedicated + venv if needed (works under PEP 668 externally-managed pythons). + + We install `mcp` ONLY into a dedicated venv we own. We never silently mutate + the user's active/system interpreter (`pip install --break-system-packages`); + that is gated behind an explicit ``allow_system_pip`` opt-in.""" + if _has_mcp(sys.executable): + print(f"[deps] mcp already importable by {sys.executable}") + return sys.executable + vpy = _venv_python(MCP_VENV) + if _has_mcp(vpy): + print(f"[deps] reusing mcp venv {MCP_VENV}") + return str(vpy) + if dry: + print(f"[deps] (dry-run) would create venv {MCP_VENV} and pip install mcp") + return str(vpy) + print(f"[deps] creating mcp venv {MCP_VENV} …") + MCP_VENV.parent.mkdir(parents=True, exist_ok=True) + r = subprocess.run([sys.executable, "-m", "venv", str(MCP_VENV)], capture_output=True, text=True, encoding="utf-8", errors="replace",) + if r.returncode == 0: + subprocess.run([str(vpy), "-m", "pip", "install", "-q", "--upgrade", "pip"], capture_output=True, text=True, encoding="utf-8", errors="replace",) + pip = subprocess.run([str(vpy), "-m", "pip", "install", "-q", MCP_REQUIREMENT], capture_output=True, text=True, encoding="utf-8", errors="replace",) + if pip.returncode == 0 and _has_mcp(vpy): + print(f"[deps] mcp installed into {MCP_VENV}") + return str(vpy) + print("[deps] venv pip install failed:\n" + (pip.stdout + pip.stderr)[:300]) + else: + print("[deps] venv creation failed:\n" + (r.stdout + r.stderr)[:300]) + # The dedicated venv is the only place we install `mcp`. Do NOT touch the + # user's active/system interpreter unless they explicitly opted in. + if allow_system_pip: + print("[deps] --allow-system-pip: pip install --break-system-packages mcp") + subprocess.run([sys.executable, "-m", "pip", "install", "-q", "--break-system-packages", MCP_REQUIREMENT], + capture_output=True, text=True, encoding="utf-8", errors="replace",) + if _has_mcp(sys.executable): + return sys.executable + print("[deps] WARNING: could not provision `mcp` into a dedicated venv, and we will\n" + " NOT modify your system Python. The loopx MCP tools will not load until\n" + " you install `mcp` yourself, e.g.:\n" + f" {sys.executable} -m venv {MCP_VENV} && {vpy} -m pip install '{MCP_REQUIREMENT}'\n" + " (or re-run install.py with --allow-system-pip to use the active interpreter).") + return _python_cmd() + + +def install_mcp( + dry: bool, + py: str, + scope: str, + migrate_goal_harness: bool = False, + project_dir: Path | None = None, +) -> bool: + """Register the loopx MCP server at the chosen scope via `claude mcp add`. + + We replace only OUR `loopx` entry. A legacy/user-owned `goal-harness` MCP is + left untouched by default — we don't delete a server we don't own. If one + exists we print a manual cleanup hint; `--migrate-goal-harness` removes it. + + Returns whether the `loopx` entry is registered afterwards: True only when + `claude mcp add` reported success. A missing `claude` CLI and a failed add + both leave the server unregistered and print the manual command instead, so + a caller that narrates the install must read that receipt, not the attempt.""" + if scope == "project" and project_dir is None: + raise ValueError("project_dir is required for project-scoped MCP registration") + cwd_run = str(project_dir) if scope == "project" else None + claude = shutil.which("claude") + mcp_path = _p("mcp", "loopx_mcp.py") + add = ["mcp", "add", "--scope", scope, "loopx", "--", py, mcp_path] + if not claude: + print("[mcp] claude CLI not on PATH — add the MCP server manually:\n claude " + " ".join(add)) + return False + print(f"[mcp] claude mcp add --scope {scope} loopx -- {py} ") + if dry: + return False + subprocess.run( + [claude, "mcp", "remove", "--scope", scope, "loopx"], + capture_output=True, + text=True, encoding="utf-8", errors="replace", + cwd=cwd_run, + ) + has_gh = subprocess.run( + [claude, "mcp", "get", "goal-harness"], + capture_output=True, + text=True, encoding="utf-8", errors="replace", + cwd=cwd_run, + ).returncode == 0 + if has_gh: + if migrate_goal_harness: + print(f"[mcp] --migrate-goal-harness: removing legacy goal-harness MCP at {scope} scope") + subprocess.run( + [claude, "mcp", "remove", "--scope", scope, "goal-harness"], + capture_output=True, + text=True, encoding="utf-8", errors="replace", + cwd=cwd_run, + ) + else: + print("[mcp] note: a legacy `goal-harness` MCP entry exists — left untouched. Remove it " + f"yourself with `claude mcp remove --scope {scope} goal-harness`, or re-run with " + "--migrate-goal-harness.") + r = subprocess.run( + [claude, *add], + capture_output=True, + text=True, encoding="utf-8", errors="replace", + cwd=cwd_run, + ) + if r.returncode != 0: + print(" (mcp add failed; add manually:\n claude " + " ".join(add) + "\n " + (r.stdout + r.stderr)[:200] + ")") + return False + return True + + +# ---- /loopx command ---------------------------------------------------------- + +def command_md() -> str: + # The `!` line runs through the Bash tool - `sh`/Git Bash on every host - so + # it is always a POSIX literal, never the PowerShell form; a Windows host + # without Git Bash cannot run `!` lines at all (README). + entry = _shell_literal(_p("scripts", "goalmode_cmd.py"), powershell=False) + py = _shell_literal(_python_cmd(), powershell=False) + return ( + "---\n" + "description: loopx goal-mode setup. " + "`/loopx ` sets up a goal + writes .claude/loop.md; drive the loop with native /loop. " + "bare /loopx = arm; off | status.\n" + "argument-hint: | (no args = arm) | off | status\n" + f"allowed-tools: Bash({py}:*)\n" + "---\n\n" + "Run the loopx setup helper and read its output:\n\n" + f"!`{py} {entry} $ARGUMENTS`\n\n" + "The output is loopx control-plane SETUP / status info — it is the COMPLETE, user-facing " + "result. Show it to the user VERBATIM and STOP. Do NOT do any work, claim todos, write " + "files, or loop here: the WORK runs when the user types Claude Code's native `/loop` (which " + "executes `.claude/loop.md`). Do not summarize a multi-line `status` detail block into one line.\n\n" + "The run loop is native `/loop`; loopx provides the deterministic " + "`should_run` protocol.\n" + ) + + +def install_command(dry: bool, cmd_dir: Path) -> None: + path = cmd_dir / "loopx.md" + print(f"[command] /loopx -> {path}") + if dry: + return + cmd_dir.mkdir(parents=True, exist_ok=True) + old = cmd_dir / "goalmode.md" # migrate the legacy /goalmode entry name + if old.exists(): + old.unlink() + path.write_text(command_md(), encoding="utf-8") + + +class HardenSettingsUnreadable(RuntimeError): + """`--harden` refuses to rewrite a settings file it cannot read as JSON.""" + + +def add_hardening(dry: bool, settings_path: Path) -> None: + """Deep-merge the optional hook + statusline into settings_path, preserving + existing config. NEVER deletes permission rules. + + The merge rewrites the whole file, so a settings file that exists but does + not parse is refused instead of replaced: substituting `{}` for it would + drop every key the user owns - permission rules, `env`, `model`, other + hooks, MCP approvals - leaving only the loopx block, at exit status 0. The + file is user-owned (LoopX did not create it), which is why the sibling + merge in `loopx/slash_command_install.py` fails closed on the same input. + """ + cur = {} + if settings_path.exists(): + try: + cur = json.loads(settings_path.read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + raise HardenSettingsUnreadable( + f"{settings_path} exists but is not readable as JSON ({exc}); refusing to " + "rewrite it. Fix or move that file, then re-run with --harden." + ) from exc + if not isinstance(cur, dict): + raise HardenSettingsUnreadable( + f"{settings_path} exists but is not a JSON object; refusing to rewrite it. " + "Fix or move that file, then re-run with --harden." + ) + # prune prior loopx PreToolUse entries (avoid stacking on reinstall) + for grp in (cur.get("hooks", {}) or {}).get("PreToolUse", []) or []: + grp["hooks"] = [h for h in grp.get("hooks", []) if "goal_policy.py" not in str(h.get("command", ""))] + if isinstance(cur.get("hooks", {}).get("PreToolUse"), list): + cur["hooks"]["PreToolUse"] = [g for g in cur["hooks"]["PreToolUse"] if g.get("hooks")] + merged = deep_merge(cur, hardening_block()) + print(f"[harden] PreToolUse should_run gate + statusline -> {settings_path}") + if not dry: + # One replace, not a truncate-in-place: an interrupted install must not + # leave the user's settings.json as a partial document. The destination + # is resolved first so a dotfiles-managed symlink keeps pointing at its + # target instead of being replaced by the rename. + write_json_atomic(settings_path.resolve(), merged, preserve_mode=True) + + +def warn_legacy_perms(settings_path: Path) -> None: + """Detect a legacy loopx credential-deny and SUGGEST manual cleanup. Never mutate.""" + try: + cur = json.loads(settings_path.read_text(encoding="utf-8")) + except Exception: + return + deny = ((cur.get("permissions") or {}).get("deny")) or [] + legacy = [r for r in deny if r in ("Read(~/.ssh/**)", "Read(~/.aws/**)")] + if legacy: + print(f"[note] {settings_path} has loopx-era permission deny rules {legacy}. " + "We no longer add these and will NOT remove them automatically. " + "To drop them, edit that file's `permissions.deny` by hand.") + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--scope", choices=["user", "project"], required=True, + help="user = ~/.claude (all projects); project = THIS project's .claude (preferred)") + ap.add_argument("--project", default=None, help="project dir for --scope project (default: cwd)") + ap.add_argument("--harden", action="store_true", + help="ALSO install the optional PreToolUse should_run gate + statusline") + ap.add_argument("--skip-mcp", action="store_true", + help="skip MCP venv provisioning + `claude mcp add` (for tests/CI)") + ap.add_argument("--allow-system-pip", action="store_true", + help="if the dedicated mcp venv can't be built, fall back to " + "`pip install --break-system-packages mcp` into the active interpreter " + "(off by default — we don't mutate your system Python)") + ap.add_argument("--migrate-goal-harness", action="store_true", + help="also remove a legacy `goal-harness` MCP entry at this scope " + "(off by default — we don't delete MCP servers we don't own)") + ap.add_argument("--dry-run", action="store_true") + a = ap.parse_args() + dry = a.dry_run + + project_dir = None + if a.scope == "project": + project_dir = Path(a.project).resolve() if a.project else Path.cwd() + claude_dir = project_dir / ".claude" + print(f"[scope] PROJECT — installs into {claude_dir} (this project only)") + else: + claude_dir = Path.home() / ".claude" + print("[scope] USER — installs into ~/.claude. The /loopx command and MCP become") + print(" available in ALL your Claude Code projects." + + (" --harden adds USER-LEVEL, matcher-wide hooks too." if a.harden else "")) + + mcp_registered = False + if a.skip_mcp: + print("[mcp] skipped (--skip-mcp)") + else: + mcp_python = provision_mcp_python(dry, a.allow_system_pip) + mcp_registered = install_mcp( + dry, + mcp_python, + a.scope, + a.migrate_goal_harness, + project_dir=project_dir, + ) + install_command(dry, claude_dir / "commands") + + settings_path = claude_dir / "settings.json" + if a.harden: + try: + add_hardening(dry, settings_path) + except HardenSettingsUnreadable as exc: + print(f"[harden] {exc}", file=sys.stderr) + outcome = ( + "nothing was written (dry-run)" + if dry + else "the settings file is unchanged" + ) + print( + f"[harden] the optional should_run gate + statusline were skipped; {outcome}.", + file=sys.stderr, + ) + if not dry: + # The rest of the install did run, so name only what happened: + # the /loopx command was written just above, and the MCP state is + # the registration receipt `install_mcp` returned - not the + # attempt. A missing CLI or a failed `claude mcp add` leaves the + # server unregistered, and reporting that attempt as an install + # would let a user skip the manual command printed above. + if a.skip_mcp: + mcp_state = "the MCP server was skipped (--skip-mcp)" + elif mcp_registered: + mcp_state = "the MCP server was registered" + else: + mcp_state = ("the MCP server was not registered — run the " + "`claude mcp add` command printed above") + print( + f"[harden] the /loopx command was installed; {mcp_state}.", + file=sys.stderr, + ) + return 2 + else: + print("[harden] skipped (default): no hooks/statusline installed. Add later with --harden.") + warn_legacy_perms(settings_path) + + print("\nloopx Claude adapter installed.") + print("Next: in a project with a goal, type `/loopx `, then drive it with native `/loop`.") + print("Restart any open Claude Code session so the command/MCP load.") + if dry: + print("(dry-run: nothing written)") + return 0 + + +_LEGACY_COMMAND_SCRIPT_SUFFIX = "/loopx/claude_goal_mode/scripts/goalmode_cmd.py" +_LEGACY_POLICY_HOOK_SUFFIX = "/loopx/claude_goal_mode/hooks/goal_policy.py" +_LEGACY_STATUSLINE_SCRIPT_SUFFIX = "/loopx/claude_goal_mode/statusline/goal_status.py" +_LEGACY_MCP_SCRIPT_SUFFIX = "/loopx/claude_goal_mode/mcp/loopx_mcp.py" +_LEGACY_COMMAND_LINE_RE = re.compile( + r"^!`[^`\r\n]*/loopx/claude_goal_mode/scripts/goalmode_cmd\.py[^`\r\n]*`\s*$" +) +_ALLOWED_TOOLS_BASH_RE = re.compile(r"^allowed-tools:\s*Bash\([^\r\n]*\)\s*$") + + +def _migration_python_cmd() -> str: + """Prefer the running LoopX Python interpreter so upgraded venv commands resolve `loopx`.""" + if sys.executable and _launches_python(sys.executable): + return sys.executable + return _python_cmd() + + +def _migrated_command_md_text(raw: str, *, py_exe: str) -> str | None: + if _LEGACY_COMMAND_SCRIPT_SUFFIX not in raw.replace("\\", "/"): + return None + if "description: loopx goal-mode setup" not in raw: + return None + lines = raw.splitlines(keepends=True) + command_index: int | None = None + allowed_index: int | None = None + for index, line in enumerate(lines): + bare = line.rstrip("\r\n") + if _LEGACY_COMMAND_LINE_RE.match(bare.replace("\\", "/")): + command_index = index + elif allowed_index is None and _ALLOWED_TOOLS_BASH_RE.match(bare): + allowed_index = index + if command_index is None: + return None + py = _shell_literal(py_exe, powershell=False) + entry = _shell_literal(_p("scripts", "goalmode_cmd.py"), powershell=False) + cmd_nl = "\r\n" if lines[command_index].endswith("\r\n") else "\n" + lines[command_index] = f"!`{py} {entry} $ARGUMENTS`{cmd_nl}" + if allowed_index is not None: + allowed_nl = "\r\n" if lines[allowed_index].endswith("\r\n") else "\n" + lines[allowed_index] = f"allowed-tools: Bash({py}:*){allowed_nl}" + updated = "".join(lines) + return updated if updated != raw else None + + +_PYTHON_EXE_NAME_RE = re.compile( + r"^(?:pypy3?|python(?:w|3(?:\.\d+)?)?)(?:\.exe)?$" +) +_PYTHON_PASSTHROUGH_FLAGS = frozenset( + {"-B", "-E", "-I", "-O", "-OO", "-P", "-S", "-s", "-u", "-v", "-q"} +) +_PYTHON_SHORT_FLAG_CHARS = frozenset("BbEdiIOPqRsSuvx") +_PYTHON_VALUE_FLAGS = frozenset({"-W", "-X", "--check-hash-based-pycs"}) +_PYTHON_TERMINAL_FLAGS = frozenset({"-c", "-m", "-"}) +_SHELL_OPERATORS_ORDERED = ( + "<<-", + "<<<", + ";;&", + "&&", + "||", + "|&", + ";;", + ";&", + ">>", + ">&", + "<&", + "<<", + "<>", + ";", + "|", + "&", + "(", + ")", + "<", + ">", + "\n", +) +_SHELL_OPERATOR_CHARS = frozenset(";|&()<>\n") +_REDIRECTION_OPS = frozenset({"<<-", "<<<", ">>", ">&", "<&", "<<", "<>", "<", ">"}) +_ENV_ASSIGN_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=.*") +_ENV_VALUE_FLAGS = frozenset({"-u", "--unset", "-C", "--chdir", "-P", "-a", "--argv0"}) +_TIMEOUT_VALUE_FLAGS = frozenset({"-k", "--kill-after", "-s", "--signal"}) +_SHELL_NAMES = frozenset({"sh", "bash", "zsh", "dash", "ash", "ksh"}) +_CLAUSE_STARTERS = frozenset({"if", "elif", "then", "else", "while", "until", "do", "{"}) +_CLAUSE_HEADERS_NON_COMMAND = frozenset({"for", "select", "case"}) + + +class _ShellToken(NamedTuple): + start: int + end: int + unquoted: str + is_operator: bool = False + + +def _consume_heredoc_bodies( + raw_command: str, i: int, pending_heredocs: list[tuple[str, bool]] +) -> int | None: + """Skip pending POSIX here-document bodies and delimiters starting after `\\n`.""" + n = len(raw_command) + for delim, strip_tabs in pending_heredocs: + closed = False + while i < n: + line_end = raw_command.find("\n", i) + if line_end == -1: + line_end = n + line_text = raw_command[i:line_end].rstrip("\r") + candidate = line_text.lstrip("\t") if strip_tabs else line_text + i = line_end + 1 if line_end < n else n + if candidate == delim: + closed = True + break + if not closed: + return None + return i + + +def _tokenize_shell_spans( + raw_command: str, *, powershell: bool +) -> list[_ShellToken] | None: + """Return word/operator tokens with original offsets, or ``None`` on shell syntax failure.""" + n = len(raw_command) + i = 0 + tokens: list[_ShellToken] = [] + awaiting_heredoc: bool | None = None + pending_heredocs: list[tuple[str, bool]] = [] + while i < n: + while i < n and raw_command[i] in " \t\r\v\f": + i += 1 + if i >= n: + break + matched_op: str | None = None + if raw_command[i] in _SHELL_OPERATOR_CHARS: + for candidate in _SHELL_OPERATORS_ORDERED: + if raw_command.startswith(candidate, i): + matched_op = candidate + break + if matched_op is not None: + if awaiting_heredoc is not None: + return None + tokens.append(_ShellToken(i, i + len(matched_op), matched_op, is_operator=True)) + i += len(matched_op) + if not powershell and matched_op in {"<<", "<<-"}: + awaiting_heredoc = matched_op == "<<-" + elif not powershell and matched_op == "\n" and pending_heredocs: + next_i = _consume_heredoc_bodies(raw_command, i, pending_heredocs) + if next_i is None: + return None + pending_heredocs.clear() + i = next_i + continue + + start = i + buf: list[str] = [] + while i < n and raw_command[i] not in " \t\r\v\f" and raw_command[i] not in _SHELL_OPERATOR_CHARS: + ch = raw_command[i] + if ch == "'": + i += 1 + closed = False + while i < n: + if raw_command[i] == "'": + if powershell and i + 1 < n and raw_command[i + 1] == "'": + buf.append("'") + i += 2 + continue + i += 1 + closed = True + break + buf.append(raw_command[i]) + i += 1 + if not closed: + return None + elif ch == '"': + i += 1 + while i < n and raw_command[i] != '"': + if ( + raw_command[i] == "\\" + and i + 1 < n + and raw_command[i + 1] == '"' + ): + buf.append('"') + i += 2 + continue + buf.append(raw_command[i]) + i += 1 + if i >= n: + return None + i += 1 + elif ( + ch == "\\" + and not powershell + and i + 1 < n + and ( + awaiting_heredoc is not None + or raw_command[i + 1].isspace() + or raw_command[i + 1] in {"'", '"', "\\", "|", "&", ";", "(", ")", "<", ">"} + ) + ): + if awaiting_heredoc is not None and raw_command[i + 1] == "\n": + return None + i += 1 + buf.append(raw_command[i]) + i += 1 + else: + buf.append(ch) + i += 1 + unquoted_word = "".join(buf) + tokens.append(_ShellToken(start, i, unquoted_word)) + if awaiting_heredoc is not None: + pending_heredocs.append((unquoted_word, awaiting_heredoc)) + awaiting_heredoc = None + if awaiting_heredoc is not None or pending_heredocs: + return None + return tokens + + +def _looks_like_python_token(unquoted: str) -> bool: + if "=" in unquoted: + return False + name = Path(unquoted.replace("\\", "/")).name.lower() + return bool(_PYTHON_EXE_NAME_RE.fullmatch(name)) + + +def _is_unquoted_env_assignment(token: _ShellToken, *, raw_command: str) -> bool: + if not _ENV_ASSIGN_RE.fullmatch(token.unquoted): + return False + eq_pos = raw_command.find("=", token.start, token.end) + if eq_pos <= token.start: + return False + prefix = raw_command[token.start : eq_pos] + return bool(re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", prefix)) + + +def _split_command_segments( + tokens: list[_ShellToken], *, raw_command: str, powershell: bool +) -> list[tuple[list[_ShellToken], bool]]: + segments: list[tuple[list[_ShellToken], bool]] = [] + words: list[_ShellToken] = [] + has_ps_call = False + in_case_header = False + case_depth = 0 + expect_case_pattern = False + idx = 0 + while idx < len(tokens): + tok = tokens[idx] + if tok.is_operator: + if tok.unquoted in _REDIRECTION_OPS: + if words and words[-1].end == tok.start and words[-1].unquoted.isdigit(): + words.pop() + if idx + 1 < len(tokens) and not tokens[idx + 1].is_operator: + idx += 2 + else: + idx += 1 + continue + if tok.unquoted == "&" and powershell and not words and not has_ps_call: + has_ps_call = True + idx += 1 + continue + if case_depth > 0 and expect_case_pattern: + if tok.unquoted == ")": + expect_case_pattern = False + words = [] + has_ps_call = False + idx += 1 + continue + if words: + segments.append((words, has_ps_call)) + words = [] + has_ps_call = False + in_case_header = False + if case_depth > 0 and tok.unquoted in {";;", ";&", ";;&"}: + expect_case_pattern = True + idx += 1 + continue + + raw_slice = raw_command[tok.start : tok.end] + if not powershell: + if case_depth > 0 and expect_case_pattern: + if not words and raw_slice == "esac": + case_depth -= 1 + expect_case_pattern = False + idx += 1 + continue + idx += 1 + continue + if case_depth > 0 and not words and raw_slice == "esac": + case_depth -= 1 + idx += 1 + continue + if in_case_header and raw_slice == "in": + in_case_header = False + case_depth += 1 + expect_case_pattern = True + words = [] + idx += 1 + continue + if not words and raw_slice == "case": + in_case_header = True + + words.append(tok) + idx += 1 + if words and not (case_depth > 0 and expect_case_pattern): + segments.append((words, has_ps_call)) + return segments + + +def _advance_command_wrappers( + words: list[_ShellToken], + *, + raw_command: str, + legacy_suffix: str, + powershell: bool, +) -> tuple[int | None, str | None]: + idx = 0 + while idx < len(words): + if not powershell: + tok = words[idx] + raw_slice = raw_command[tok.start : tok.end] + if raw_slice == tok.unquoted and tok.unquoted in _CLAUSE_STARTERS: + idx += 1 + continue + if raw_slice == tok.unquoted and tok.unquoted in _CLAUSE_HEADERS_NON_COMMAND: + return (None, None) + if _is_unquoted_env_assignment(tok, raw_command=raw_command): + idx += 1 + continue + if tok.unquoted == "!" and raw_slice == "!": + idx += 1 + continue + if powershell: + break + + cmd_word = words[idx].unquoted + cmd_name = Path(cmd_word.replace("\\", "/")).name.lower() + has_legacy_tail = any( + legacy_suffix in w.unquoted.replace("\\", "/") for w in words[idx:] + ) + probe = idx + 1 + if cmd_name == "env": + while probe < len(words): + arg = words[probe].unquoted + if arg == "--": + probe += 1 + break + if arg in {"-S", "--split-string"} or arg.startswith(("-S", "--split-string=")): + return ( + None, + "unsupported `env -S` wrapper around legacy Claude command" + if has_legacy_tail + else None, + ) + if arg in _ENV_VALUE_FLAGS: + probe += 2 + continue + if arg.startswith("-") or _ENV_ASSIGN_RE.fullmatch(arg): + probe += 1 + continue + break + if probe > len(words): + return (None, None) + idx = probe + continue + if cmd_word == "command": + while probe < len(words) and words[probe].unquoted.startswith("-") and words[probe].unquoted != "--": + flag = words[probe].unquoted + if "v" in flag or "V" in flag: + return (None, None) + if flag != "-p": + return ( + None, + f"unsupported `command {flag}` option around legacy Claude command" + if has_legacy_tail + else None, + ) + probe += 1 + if probe < len(words) and words[probe].unquoted == "--": + probe += 1 + idx = probe + continue + if cmd_word == "exec": + while probe < len(words) and words[probe].unquoted.startswith("-"): + flag = words[probe].unquoted + if flag == "--": + probe += 1 + break + if flag == "-a": + probe += 2 + elif len(flag) > 1 and set(flag[1:]) <= {"c", "l"}: + probe += 1 + else: + return ( + None, + f"unsupported `exec {flag}` option around legacy Claude command" + if has_legacy_tail + else None, + ) + if probe > len(words): + return (None, None) + idx = probe + continue + if cmd_word in {"nohup", "time"} or cmd_name == "nice": + if cmd_word == "time" and probe < len(words) and words[probe].unquoted == "-p": + probe += 1 + elif cmd_name == "nice" and probe < len(words): + arg = words[probe].unquoted + if arg in {"-n", "--adjustment"}: + probe += 2 + elif arg.startswith("--adjustment=") or ( + arg.startswith("-") and arg[1:].lstrip("+-").isdigit() + ): + probe += 1 + if probe > len(words): + return (None, None) + idx = probe + continue + if cmd_name == "timeout": + while probe < len(words) and words[probe].unquoted.startswith("-"): + arg = words[probe].unquoted + if arg == "--": + probe += 1 + break + if arg in _TIMEOUT_VALUE_FLAGS: + probe += 2 + elif arg.startswith(("--kill-after=", "--signal=")) or arg in { + "-v", + "--verbose", + "--foreground", + "--preserve-status", + }: + probe += 1 + else: + return ( + None, + f"unsupported `timeout {arg}` option around legacy Claude command" + if has_legacy_tail + else None, + ) + if probe >= len(words): + return (None, None) + dur = words[probe].unquoted + if dur.startswith("-") or dur.replace("\\", "/").endswith(legacy_suffix): + return (None, None) + idx = probe + 1 + continue + break + return (idx, None) if idx < len(words) else (None, None) + + +def _segment_edits( + words: list[_ShellToken], + *, + has_ps_call: bool, + raw_command: str, + legacy_suffix: str, + new_script: str, + py_exe: str, + powershell: bool, +) -> tuple[list[tuple[int, int, str]], str | None]: + cmd_idx, wrapper_reason = _advance_command_wrappers( + words, + raw_command=raw_command, + legacy_suffix=legacy_suffix, + powershell=powershell, + ) + if cmd_idx is None: + return ([], wrapper_reason) + + cmd_tok = words[cmd_idx] + cmd_name = Path(cmd_tok.unquoted.replace("\\", "/")).name.lower() + if not powershell and cmd_tok.unquoted == "eval": + if any(legacy_suffix in w.unquoted.replace("\\", "/") for w in words[cmd_idx + 1 :]): + return ([], "dynamic `eval` command references legacy Claude launcher") + return ([], None) + + if cmd_name.removesuffix(".exe") in _SHELL_NAMES and not cmd_tok.unquoted.startswith("-"): + probe = cmd_idx + 1 + saw_dash_c = False + while probe < len(words): + arg = words[probe].unquoted + if arg == "--": + probe += 1 + break + if not arg.startswith("-") and not (arg.startswith("+") and len(arg) > 1): + break + if arg in {"-o", "+o"}: + probe += 2 + continue + if arg.startswith("-") and not arg.startswith("--") and "c" in arg[1:]: + saw_dash_c = True + probe += 1 + break + probe += 1 + if not saw_dash_c or probe >= len(words): + return ([], None) + inner_tok = words[probe] + if legacy_suffix not in inner_tok.unquoted.replace("\\", "/"): + return ([], None) + inner, inner_reason = _inspect_legacy_claude_command( + inner_tok.unquoted, + legacy_suffix=legacy_suffix, + new_script=new_script, + py_exe=py_exe, + powershell=False, + ) + if inner is None: + return ([], inner_reason) + return ([(inner_tok.start, inner_tok.end, _shell_literal(inner, powershell=powershell))], inner_reason) + + needs_ps_call = powershell and not (has_ps_call and cmd_idx == 0) + py_replacement = ( + _shell_command(py_exe, powershell=True) + if needs_ps_call + else _shell_literal(py_exe, powershell=powershell) + ) + script_literal = _shell_literal(new_script, powershell=powershell) + + if _looks_like_python_token(cmd_tok.unquoted): + probe = cmd_idx + 1 + while probe < len(words): + arg = words[probe].unquoted + if arg in _PYTHON_TERMINAL_FLAGS or arg.startswith(("-c", "-m")): + return ([], None) + if arg in _PYTHON_VALUE_FLAGS: + probe += 2 + if probe > len(words): + return ([], None) + continue + if arg.startswith(("-W", "-X", "--check-hash-based-pycs=")): + probe += 1 + continue + if arg in _PYTHON_PASSTHROUGH_FLAGS or ( + len(arg) > 1 + and arg[0] == "-" + and not arg.startswith("--") + and set(arg[1:]) <= _PYTHON_SHORT_FLAG_CHARS + ): + probe += 1 + continue + if arg.startswith("-"): + has_legacy_tail = any( + legacy_suffix in w.unquoted.replace("\\", "/") for w in words[probe + 1 :] + ) + return ( + [], + f"unsupported Python option `{arg}` around legacy Claude launcher" + if has_legacy_tail + else None, + ) + break + if probe >= len(words): + return ([], None) + script_tok = words[probe] + normalized = script_tok.unquoted.replace("\\", "/") + if not normalized.startswith("-") and normalized.endswith(legacy_suffix): + return ( + [ + (script_tok.start, script_tok.end, script_literal), + (cmd_tok.start, cmd_tok.end, py_replacement), + ], + None, + ) + return ([], None) + + normalized_cmd = cmd_tok.unquoted.replace("\\", "/") + if ( + not normalized_cmd.startswith("-") + and not _ENV_ASSIGN_RE.fullmatch(normalized_cmd) + and normalized_cmd.endswith(legacy_suffix) + ): + return ([(cmd_tok.start, cmd_tok.end, f"{py_replacement} {script_literal}")], None) + return ([], None) + + +def _inspect_legacy_claude_command( + raw_command: str, + *, + legacy_suffix: str, + new_script: str, + py_exe: str, + powershell: bool, +) -> tuple[str | None, str | None]: + """Upgrade certified executed legacy commands and report uncertifiable dynamic legacy references.""" + if legacy_suffix not in raw_command.replace("\\", "/"): + return (None, None) + tokens = _tokenize_shell_spans(raw_command, powershell=powershell) + if tokens is None: + return (None, "unterminated shell quote or here-document around legacy Claude command") + if not tokens: + return (None, None) + + edits: list[tuple[int, int, str]] = [] + manual_reasons: list[str] = [] + for words, has_ps_call in _split_command_segments( + tokens, raw_command=raw_command, powershell=powershell + ): + seg_edits, seg_reason = _segment_edits( + words, + has_ps_call=has_ps_call, + raw_command=raw_command, + legacy_suffix=legacy_suffix, + new_script=new_script, + py_exe=py_exe, + powershell=powershell, + ) + edits.extend(seg_edits) + if seg_reason and seg_reason not in manual_reasons: + manual_reasons.append(seg_reason) + manual_reason = "; ".join(manual_reasons) if manual_reasons else None + if not edits: + return (None, manual_reason) + + edits.sort(key=lambda item: item[0], reverse=True) + updated = raw_command + last_start = len(raw_command) + 1 + for start, end, replacement in edits: + if end > last_start: + return (None, "overlapping shell spans prevent safe automatic migration") + updated = updated[:start] + replacement + updated[end:] + last_start = start + return (updated if updated != raw_command else None, manual_reason) + + +def _rewrite_legacy_claude_command( + raw_command: str, + *, + legacy_suffix: str, + new_script: str, + py_exe: str, + powershell: bool, +) -> str | None: + """Upgrade executed legacy Claude hook/statusline commands while keeping wrappers and data args.""" + updated, _ = _inspect_legacy_claude_command( + raw_command, + legacy_suffix=legacy_suffix, + new_script=new_script, + py_exe=py_exe, + powershell=powershell, + ) + return updated + + +def _inspect_settings_migration( + raw_data: dict[str, Any], *, py_exe: str +) -> tuple[dict[str, Any] | None, list[str]]: + powershell = _uses_powershell() + gate_script = _p("hooks", "goal_policy.py") + status_script = _p("statusline", "goal_status.py") + updated: dict[str, Any] = dict(raw_data) + changed = False + manual_reasons: list[str] = [] + + hooks_obj = raw_data.get("hooks") + if isinstance(hooks_obj, dict): + pre_obj = hooks_obj.get("PreToolUse") + if isinstance(pre_obj, list): + new_pre: list[Any] = [] + pre_changed = False + for group in pre_obj: + if not isinstance(group, dict): + new_pre.append(group) + continue + group_hooks = group.get("hooks") + if not isinstance(group_hooks, list): + new_pre.append(group) + continue + new_group_hooks: list[Any] = [] + group_changed = False + for item in group_hooks: + if isinstance(item, dict) and isinstance(item.get("command"), str): + migrated_cmd, manual_reason = _inspect_legacy_claude_command( + item["command"], + legacy_suffix=_LEGACY_POLICY_HOOK_SUFFIX, + new_script=gate_script, + py_exe=py_exe, + powershell=powershell, + ) + if manual_reason and manual_reason not in manual_reasons: + manual_reasons.append(manual_reason) + if migrated_cmd is not None: + new_item = dict(item) + new_item["command"] = migrated_cmd + new_group_hooks.append(new_item) + group_changed = True + continue + new_group_hooks.append(item) + if group_changed: + new_group = dict(group) + new_group["hooks"] = new_group_hooks + new_pre.append(new_group) + pre_changed = True + else: + new_pre.append(group) + if pre_changed: + new_hooks = dict(hooks_obj) + new_hooks["PreToolUse"] = new_pre + updated["hooks"] = new_hooks + changed = True + + sl_obj = raw_data.get("statusLine") + if isinstance(sl_obj, dict) and isinstance(sl_obj.get("command"), str): + migrated_sl, sl_reason = _inspect_legacy_claude_command( + sl_obj["command"], + legacy_suffix=_LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=status_script, + py_exe=py_exe, + powershell=powershell, + ) + if sl_reason and sl_reason not in manual_reasons: + manual_reasons.append(sl_reason) + if migrated_sl is not None: + new_sl = dict(sl_obj) + new_sl["command"] = migrated_sl + updated["statusLine"] = new_sl + changed = True + + return (updated if changed else None, manual_reasons) + + +def _migrated_settings_payload(raw_data: dict[str, Any], *, py_exe: str) -> dict[str, Any] | None: + updated, _ = _inspect_settings_migration(raw_data, py_exe=py_exe) + return updated + + +def _migrated_mcp_json_payload(raw_data: dict[str, Any]) -> dict[str, Any] | None: + servers = raw_data.get("mcpServers") + if not isinstance(servers, dict): + return None + loopx_entry = servers.get("loopx") + if not isinstance(loopx_entry, dict): + return None + args = loopx_entry.get("args") + if not isinstance(args, list): + return None + new_mcp_script = _p("mcp", "loopx_mcp.py") + updated_args: list[Any] = [] + changed = False + for arg in args: + if isinstance(arg, str) and _LEGACY_MCP_SCRIPT_SUFFIX in arg.replace("\\", "/"): + updated_args.append(new_mcp_script) + changed = True + else: + updated_args.append(arg) + if not changed: + return None + updated_entry = dict(loopx_entry) + updated_entry["args"] = updated_args + updated_servers = dict(servers) + updated_servers["loopx"] = updated_entry + updated = dict(raw_data) + updated["mcpServers"] = updated_servers + return updated + + +def _read_json_dict_fail_closed(path: Path) -> dict[str, Any] | None: + try: + raw_obj: object = json.loads(path.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, ValueError): + return None + return raw_obj if isinstance(raw_obj, dict) else None + + +def migrate_legacy_claude_dir( + claude_dir: Path, + *, + project_dir: Path | None = None, + execute: bool, +) -> list[dict[str, str]]: + """Migrate provably LoopX-owned legacy `loopx/claude_goal_mode/` entries in `claude_dir`. + + Leaves user-owned rules/hooks/statusline/commands and unreadable JSON/non-UTF-8 files untouched. + """ + results: list[dict[str, str]] = [] + py_exe: str | None = None + + def resolve_py() -> str: + nonlocal py_exe + if py_exe is None: + py_exe = _migration_python_cmd() + return py_exe + + cmd_path = claude_dir / "commands" / "loopx.md" + if cmd_path.is_file(): + try: + raw_cmd = cmd_path.read_text(encoding="utf-8") + except (OSError, UnicodeDecodeError): + raw_cmd = "" + updated_cmd = _migrated_command_md_text(raw_cmd, py_exe=resolve_py()) if raw_cmd else None + if updated_cmd is not None: + if execute: + write_bytes_atomic( + cmd_path.resolve(), + updated_cmd.encode("utf-8"), + preserve_mode=True, + ) + results.append({"path": str(cmd_path), "status": "updated" if execute else "would_write"}) + + settings_path = claude_dir / "settings.json" + if settings_path.is_file(): + raw_settings = _read_json_dict_fail_closed(settings_path) + updated_settings, manual_reasons = ( + _inspect_settings_migration(raw_settings, py_exe=resolve_py()) + if raw_settings is not None + else (None, []) + ) + if updated_settings is not None: + if execute: + write_json_atomic( + settings_path.resolve(), + updated_settings, + preserve_mode=True, + ) + results.append({"path": str(settings_path), "status": "updated" if execute else "would_write"}) + if manual_reasons: + scope_args = ( + f"--scope project --project {shlex.quote(str(project_dir))} --harden" + if project_dir is not None + else "--scope user --harden" + ) + recovery_cmd = f"{_shell_literal(resolve_py(), powershell=_uses_powershell())} {_shell_literal(str(Path(__file__).resolve()), powershell=_uses_powershell())} {scope_args}" + results.append( + { + "path": str(settings_path), + "status": "manual_migration_required", + "reason": "; ".join(manual_reasons), + "recovery": recovery_cmd, + "note": ( + f"Manual Claude migration required for {settings_path} " + f"({'; '.join(manual_reasons)}). Recover with: {recovery_cmd}" + ), + } + ) + + if project_dir is not None: + mcp_path = project_dir / ".mcp.json" + if mcp_path.is_file(): + raw_mcp = _read_json_dict_fail_closed(mcp_path) + updated_mcp = _migrated_mcp_json_payload(raw_mcp) if raw_mcp is not None else None + if updated_mcp is not None: + if execute: + write_json_atomic( + mcp_path.resolve(), + updated_mcp, + preserve_mode=True, + ) + results.append({"path": str(mcp_path), "status": "updated" if execute else "would_write"}) + + return results + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/loopx/claude_goal_mode/settings.example.json b/loopx/hosts/claude/settings.example.json similarity index 81% rename from loopx/claude_goal_mode/settings.example.json rename to loopx/hosts/claude/settings.example.json index 21f246fd26..b04d670acc 100644 --- a/loopx/claude_goal_mode/settings.example.json +++ b/loopx/hosts/claude/settings.example.json @@ -1,5 +1,5 @@ { - "_comment": "OPTIONAL manual hardening for loopx on Claude Code. The loopx adapter's runtime is Claude Code's native /loop + the loopx MCP server (added via `claude mcp add` or install.py) + the /loopx command — NONE of which live in settings.json. This file is ONLY the optional should_run PreToolUse gate + statusline. Merge it into a PROJECT's .claude/settings.json (preferred) or ~/.claude/settings.json. Replace with the absolute path to loopx/claude_goal_mode; if your machine has `python` but not `python3`, replace `python3` accordingly. For strong isolation, run Claude Code inside a dev container / VM.", + "_comment": "OPTIONAL manual hardening for loopx on Claude Code. The loopx adapter's runtime is Claude Code's native /loop + the loopx MCP server (added via `claude mcp add` or install.py) + the /loopx command — NONE of which live in settings.json. This file is ONLY the optional should_run PreToolUse gate + statusline. Merge it into a PROJECT's .claude/settings.json (preferred) or ~/.claude/settings.json. Replace with the absolute path to loopx/hosts/claude; if your machine has `python` but not `python3`, replace `python3` accordingly. For strong isolation, run Claude Code inside a dev container / VM.", "hooks": { "PreToolUse": [ { diff --git a/loopx/claude_goal_mode/statusline/goal_status.py b/loopx/hosts/claude/statusline/goal_status.py similarity index 100% rename from loopx/claude_goal_mode/statusline/goal_status.py rename to loopx/hosts/claude/statusline/goal_status.py diff --git a/loopx/kunluncode_goal_mode/README.md b/loopx/hosts/kunluncode/README.md similarity index 100% rename from loopx/kunluncode_goal_mode/README.md rename to loopx/hosts/kunluncode/README.md diff --git a/loopx/kunluncode_goal_mode/__init__.py b/loopx/hosts/kunluncode/__init__.py similarity index 100% rename from loopx/kunluncode_goal_mode/__init__.py rename to loopx/hosts/kunluncode/__init__.py diff --git a/loopx/kunluncode_goal_mode/app_server.py b/loopx/hosts/kunluncode/app_server.py similarity index 100% rename from loopx/kunluncode_goal_mode/app_server.py rename to loopx/hosts/kunluncode/app_server.py diff --git a/loopx/kunluncode_goal_mode/cli.py b/loopx/hosts/kunluncode/cli.py similarity index 97% rename from loopx/kunluncode_goal_mode/cli.py rename to loopx/hosts/kunluncode/cli.py index 37d09161d7..6052ea5c1b 100644 --- a/loopx/kunluncode_goal_mode/cli.py +++ b/loopx/hosts/kunluncode/cli.py @@ -18,10 +18,10 @@ require_runtime_compatible_project_registry, ) from loopx.goal_mode_context import registered_agent_ids -from loopx.kunluncode_goal_mode import DEFAULT_AGENT_ID, MCP_SERVER_NAME -from loopx.kunluncode_goal_mode.app_server import build_app_server_command -from loopx.kunluncode_goal_mode.context import goal_context, write_binding -from loopx.kunluncode_goal_mode.runtime import ( +from loopx.hosts.kunluncode import DEFAULT_AGENT_ID, MCP_SERVER_NAME +from loopx.hosts.kunluncode.app_server import build_app_server_command +from loopx.hosts.kunluncode.context import goal_context, write_binding +from loopx.hosts.kunluncode.runtime import ( compact_runtime_state, read_runtime_state, run_native_goal, @@ -32,7 +32,7 @@ # loopx/goal_mode_mcp.py imports `mcp.server.fastmcp`, which the MCP SDK 2.x # line no longer ships, and the pin is a deliberate security pin (892faa2c9 # "fix(security): upgrade the MCP SDK pin"). It belongs to the KunlunCode -# adapter venv only; loopx/claude_goal_mode/scripts/install.py provisions its +# adapter venv only; loopx/hosts/claude/scripts/install.py provisions its # own venv and spells the same dependency as a range ("mcp<2"). The two are # separate packaging boundaries, so they are not required to agree on a # spelling. Bump MCP_SDK_VERSION alone; the probe and the user-facing message @@ -77,7 +77,7 @@ def _compatible_python(value: str | Path) -> bool: ( "from importlib.metadata import version; " "from mcp.server.fastmcp import FastMCP; " - "import loopx.kunluncode_goal_mode.server; " + "import loopx.hosts.kunluncode.server; " f"assert version('mcp') == '{MCP_SDK_VERSION}'" ), ], @@ -87,7 +87,7 @@ def _compatible_python(value: str | Path) -> bool: def _source_root() -> Path | None: - candidate = Path(__file__).resolve().parents[2] + candidate = Path(__file__).resolve().parents[3] return candidate if (candidate / "pyproject.toml").is_file() else None @@ -144,6 +144,12 @@ def _configured_mcp_servers(kunluncode: str) -> list[dict[str, Any]]: return [item for item in payload if isinstance(item, dict)] +_MANAGED_MCP_SCRIPT_SUFFIXES = ( + "/loopx/hosts/kunluncode/server.py", + "/loopx/kunluncode_goal_mode/server.py", +) + + def _is_managed_server(entry: dict[str, Any]) -> bool: args = list(entry.get("args") or []) return ( @@ -151,7 +157,7 @@ def _is_managed_server(entry: dict[str, Any]) -> bool: and len(args) == 1 and str(args[0]) .replace("\\", "/") - .endswith("/loopx/kunluncode_goal_mode/server.py") + .endswith(_MANAGED_MCP_SCRIPT_SUFFIXES) ) diff --git a/loopx/kunluncode_goal_mode/context.py b/loopx/hosts/kunluncode/context.py similarity index 100% rename from loopx/kunluncode_goal_mode/context.py rename to loopx/hosts/kunluncode/context.py diff --git a/loopx/kunluncode_goal_mode/control_plane.py b/loopx/hosts/kunluncode/control_plane.py similarity index 100% rename from loopx/kunluncode_goal_mode/control_plane.py rename to loopx/hosts/kunluncode/control_plane.py diff --git a/loopx/kunluncode_goal_mode/guards.py b/loopx/hosts/kunluncode/guards.py similarity index 100% rename from loopx/kunluncode_goal_mode/guards.py rename to loopx/hosts/kunluncode/guards.py diff --git a/loopx/kunluncode_goal_mode/runtime.py b/loopx/hosts/kunluncode/runtime.py similarity index 99% rename from loopx/kunluncode_goal_mode/runtime.py rename to loopx/hosts/kunluncode/runtime.py index ce9b38dfd2..f4938ee558 100644 --- a/loopx/kunluncode_goal_mode/runtime.py +++ b/loopx/hosts/kunluncode/runtime.py @@ -16,7 +16,7 @@ FirstPartyHostGoalAdmission, capture_first_party_host_goal_ref, ) -from loopx.kunluncode_goal_mode.app_server import ( +from loopx.hosts.kunluncode.app_server import ( NATIVE_GOAL_MODES, KunlunAppServerClient, KunlunAppServerError, @@ -25,12 +25,12 @@ native_goal_success, stable_text_digest, ) -from loopx.kunluncode_goal_mode.control_plane import ( +from loopx.hosts.kunluncode.control_plane import ( VERIFIED_CLASSIFICATIONS, KunlunNativeGoalRuntimeError, LoopXControlPlane, ) -from loopx.kunluncode_goal_mode.guards import ( +from loopx.hosts.kunluncode.guards import ( NATIVE_CONTROLLER_AGENT_ENV, NATIVE_CONTROLLER_ENV, NATIVE_CONTROLLER_GOAL_ENV, diff --git a/loopx/kunluncode_goal_mode/server.py b/loopx/hosts/kunluncode/server.py similarity index 80% rename from loopx/kunluncode_goal_mode/server.py rename to loopx/hosts/kunluncode/server.py index 18e629e197..484636c3ac 100644 --- a/loopx/kunluncode_goal_mode/server.py +++ b/loopx/hosts/kunluncode/server.py @@ -5,8 +5,8 @@ from pathlib import Path from loopx.goal_mode_mcp import GoalModeMCPConfig, create_fastmcp_server -from loopx.kunluncode_goal_mode.context import goal_context -from loopx.kunluncode_goal_mode.guards import guard_native_controller_writeback +from loopx.hosts.kunluncode.context import goal_context +from loopx.hosts.kunluncode.guards import guard_native_controller_writeback CONFIG = GoalModeMCPConfig( diff --git a/loopx/hosts/skill_facade.py b/loopx/hosts/skill_facade.py index bef38874b3..2e25a1393a 100644 --- a/loopx/hosts/skill_facade.py +++ b/loopx/hosts/skill_facade.py @@ -27,7 +27,7 @@ SKILLS_ROOT_LABEL as KIRO_CLI_SKILLS_ROOT_LABEL, kiro_cli_activation_extras, ) -from ..zcode_goal_mode import ( +from .zcode import ( SKILLS_ROOT_LABEL as ZCODE_SKILLS_ROOT_LABEL, ZCODE_INSTALL_SURFACE, ) diff --git a/loopx/zcode_goal_mode/README.md b/loopx/hosts/zcode/README.md similarity index 100% rename from loopx/zcode_goal_mode/README.md rename to loopx/hosts/zcode/README.md diff --git a/loopx/zcode_goal_mode/__init__.py b/loopx/hosts/zcode/__init__.py similarity index 100% rename from loopx/zcode_goal_mode/__init__.py rename to loopx/hosts/zcode/__init__.py diff --git a/loopx/zcode_goal_mode/api.py b/loopx/hosts/zcode/api.py similarity index 98% rename from loopx/zcode_goal_mode/api.py rename to loopx/hosts/zcode/api.py index 6aeb2ad49a..f58e4b5f26 100644 --- a/loopx/zcode_goal_mode/api.py +++ b/loopx/hosts/zcode/api.py @@ -4,8 +4,8 @@ from typing import Any from urllib.parse import unquote, urlparse -from ..chat import redact_local_paths -from ..status_server import is_loopback_host +from ...chat import redact_local_paths +from ...status_server import is_loopback_host from .bridge import ZCodeGoalBridgeError, zcode_goal_operation diff --git a/loopx/zcode_goal_mode/app-server.ts b/loopx/hosts/zcode/app-server.ts similarity index 100% rename from loopx/zcode_goal_mode/app-server.ts rename to loopx/hosts/zcode/app-server.ts diff --git a/loopx/zcode_goal_mode/bridge.py b/loopx/hosts/zcode/bridge.py similarity index 95% rename from loopx/zcode_goal_mode/bridge.py rename to loopx/hosts/zcode/bridge.py index 8147578f02..6c415425c4 100644 --- a/loopx/zcode_goal_mode/bridge.py +++ b/loopx/hosts/zcode/bridge.py @@ -11,16 +11,16 @@ import sys from typing import Any -from ..agent_registry import agent_profile_for_goal, load_goal_from_registry, registered_agent_ids_for_goal, require_registered_agent_id -from ..control_plane.coordination.local_authority import local_authority_is_promoted -from ..control_plane.goals.acceptance import inspect_goal_acceptance -from ..control_plane.goals.activation import goal_is_stopped -from ..control_plane.goals.goal_ref_validation import exact_goal_ref, require_goal_id -from ..control_plane.runtime.goal_project_route import resolve_goal_project_route -from ..control_plane.runtime.node_probe import node_typescript_flags -from ..control_plane.projects.registry_codec import load_registry -from ..host_loop_activation import normalize_agent_type -from ..registry import registry_goals +from ...agent_registry import agent_profile_for_goal, load_goal_from_registry, registered_agent_ids_for_goal, require_registered_agent_id +from ...control_plane.coordination.local_authority import local_authority_is_promoted +from ...control_plane.goals.acceptance import inspect_goal_acceptance +from ...control_plane.goals.activation import goal_is_stopped +from ...control_plane.goals.goal_ref_validation import exact_goal_ref, require_goal_id +from ...control_plane.runtime.goal_project_route import resolve_goal_project_route +from ...control_plane.runtime.node_probe import node_typescript_flags +from ...control_plane.projects.registry_codec import load_registry +from ...host_loop_activation import normalize_agent_type +from ...registry import registry_goals # The bundled provider contract is the single action vocabulary for Python and TS. ZCODE_GOAL_ACTIONS: tuple[str, ...] = tuple( @@ -109,7 +109,7 @@ def validate_zcode_binding( def _node_command() -> str: - from ..control_plane.effect_runtime import _node_executable, EffectRuntimeStartupError + from ...control_plane.effect_runtime import _node_executable, EffectRuntimeStartupError try: return _node_executable() except EffectRuntimeStartupError as exc: @@ -264,7 +264,7 @@ def zcode_goal_operation( "action": action, **{key: binding[key] for key in ("project", "registry", "goal_id", "goal_ref", "goal_creation_operation_id", "identity_scope", "agent_id")}, "state_path": str(state_root / "zcode-goal" / f"{state_key}.json"), "loopx_command": loopx_command, - "validation_command": [sys.executable, "-m", "loopx.zcode_goal_mode.bridge", "--validate-binding"], + "validation_command": [sys.executable, "-m", "loopx.hosts.zcode.bridge", "--validate-binding"], } if model_selection is not None: request["model_selection"] = model_selection diff --git a/loopx/zcode_goal_mode/cli.ts b/loopx/hosts/zcode/cli.ts similarity index 98% rename from loopx/zcode_goal_mode/cli.ts rename to loopx/hosts/zcode/cli.ts index 29b837504f..9ea578fb2e 100644 --- a/loopx/zcode_goal_mode/cli.ts +++ b/loopx/hosts/zcode/cli.ts @@ -3,15 +3,15 @@ import {spawn, execFile} from "node:child_process"; import {randomBytes} from "node:crypto"; import {createServer, request as httpRequest} from "node:http"; import {mkdir, readFile, unlink} from "node:fs/promises"; -import type {JsonObject} from "../control_plane/effect_program.ts"; -import {BARE_SHA256_PATTERN} from "../control_plane/content_digest.ts"; +import type {JsonObject} from "../../control_plane/effect_program.ts"; +import {BARE_SHA256_PATTERN} from "../../control_plane/content_digest.ts"; import {isAbsolute, join} from "node:path"; import {fileURLToPath} from "node:url"; import {ZCODE_GOAL_ACTIONS, isGoalBasis, sameBinding, ZCodeGoalError, safeFailure, type NativeRequest, type ZCodeGoalReadback} from "./contract.ts"; import {NativeGoalController, readState, atomicState, type BindingState} from "./runtime.ts"; import {ZCodeAppServer} from "./app-server.ts"; -import {acquireFileMutationLock, releaseFileMutationLock, durableWriteJson} from "../control_plane/effect_runtime_io.ts"; -import {nodeTypescriptFlags} from "../control_plane/runtime/node_version.ts"; +import {acquireFileMutationLock, releaseFileMutationLock, durableWriteJson} from "../../control_plane/effect_runtime_io.ts"; +import {nodeTypescriptFlags} from "../../control_plane/runtime/node_version.ts"; const MAX_INPUT = 64 * 1024; const MAX_RESPONSE = 1024 * 1024; diff --git a/loopx/zcode_goal_mode/contract.json b/loopx/hosts/zcode/contract.json similarity index 100% rename from loopx/zcode_goal_mode/contract.json rename to loopx/hosts/zcode/contract.json diff --git a/loopx/zcode_goal_mode/contract.ts b/loopx/hosts/zcode/contract.ts similarity index 100% rename from loopx/zcode_goal_mode/contract.ts rename to loopx/hosts/zcode/contract.ts diff --git a/loopx/zcode_goal_mode/diagnostics.py b/loopx/hosts/zcode/diagnostics.py similarity index 100% rename from loopx/zcode_goal_mode/diagnostics.py rename to loopx/hosts/zcode/diagnostics.py diff --git a/loopx/zcode_goal_mode/guard.ts b/loopx/hosts/zcode/guard.ts similarity index 100% rename from loopx/zcode_goal_mode/guard.ts rename to loopx/hosts/zcode/guard.ts diff --git a/loopx/zcode_goal_mode/images/native-error-mobile.png b/loopx/hosts/zcode/images/native-error-mobile.png similarity index 100% rename from loopx/zcode_goal_mode/images/native-error-mobile.png rename to loopx/hosts/zcode/images/native-error-mobile.png diff --git a/loopx/zcode_goal_mode/images/native-quota-desktop.png b/loopx/hosts/zcode/images/native-quota-desktop.png similarity index 100% rename from loopx/zcode_goal_mode/images/native-quota-desktop.png rename to loopx/hosts/zcode/images/native-quota-desktop.png diff --git a/loopx/zcode_goal_mode/runtime.ts b/loopx/hosts/zcode/runtime.ts similarity index 98% rename from loopx/zcode_goal_mode/runtime.ts rename to loopx/hosts/zcode/runtime.ts index 8471c321cf..0dde78b2b9 100644 --- a/loopx/zcode_goal_mode/runtime.ts +++ b/loopx/hosts/zcode/runtime.ts @@ -1,9 +1,9 @@ /** One native session owner. Quota admission and revocation reuse Core CLI decisions. */ import {createHash} from "node:crypto"; import {readFile} from "node:fs/promises"; -import {durableWriteJson} from "../control_plane/effect_runtime_io.ts"; -import {BARE_SHA256_PATTERN} from "../control_plane/content_digest.ts"; -import type {JsonObject} from "../control_plane/effect_program.ts"; +import {durableWriteJson} from "../../control_plane/effect_runtime_io.ts"; +import {BARE_SHA256_PATTERN} from "../../control_plane/content_digest.ts"; +import type {JsonObject} from "../../control_plane/effect_program.ts"; import type {GoalBasis, NativeObservation, NativeRequest, QuotaObservation, ZCodeModelSelection, ZCodeGoalAction, ZCodeGoalReadback} from "./contract.ts"; import {isGoalBasis, sameBinding, sameGoalBasis, ZCodeGoalError, safeFailure} from "./contract.ts"; diff --git a/loopx/presentation/chat_bundle.py b/loopx/presentation/chat_bundle.py index 991234e01b..cacfce2dd6 100644 --- a/loopx/presentation/chat_bundle.py +++ b/loopx/presentation/chat_bundle.py @@ -24,8 +24,8 @@ "apps/presentation/dashboard/package-lock.json", "apps/presentation/dashboard/vite.chat.config.ts", "apps/presentation/dashboard/tsconfig.json", - "loopx/zcode_goal_mode/contract.ts", - "loopx/zcode_goal_mode/contract.json", + "loopx/hosts/zcode/contract.ts", + "loopx/hosts/zcode/contract.json", ) BUILD_HELP = "Run npm ci and npm run build:chat in apps/presentation/dashboard (or reinstall a complete LoopX package)." diff --git a/loopx/semantics/goal_instance_binding_inventory_v1.json b/loopx/semantics/goal_instance_binding_inventory_v1.json index bcc5108083..6a89834d01 100644 --- a/loopx/semantics/goal_instance_binding_inventory_v1.json +++ b/loopx/semantics/goal_instance_binding_inventory_v1.json @@ -67,7 +67,7 @@ "loopx/control_plane/turn_driver/settlement.py::TurnSettlementJournalAdapter.hold_tail", "loopx/control_plane/turn_driver/settlement.py::TurnSettlementJournalAdapter.release_tail", "loopx/dsh_goal_mode/turn_host_adapter.py::run_dsh_host", - "loopx/kunluncode_goal_mode/runtime.py::run_native_goal" + "loopx/hosts/kunluncode/runtime.py::run_native_goal" ], "effect_boundary": "loopx/control_plane/goals/source_session_turn_effects.py::prepare_source_turn_effect", "authority_role": "host_execution_binding", diff --git a/loopx/slash_command_install.py b/loopx/slash_command_install.py index cad48f0b37..13636fd911 100644 --- a/loopx/slash_command_install.py +++ b/loopx/slash_command_install.py @@ -7,6 +7,7 @@ from collections.abc import Callable, Mapping from enum import Enum from pathlib import Path +from typing import cast from .agy_goal_mode import ( ANTIGRAVITY_HOOKS_CONFIG_FILENAME, @@ -48,7 +49,7 @@ target_status as _target_status, ) from .slash_commands import build_slash_command_catalog -from .zcode_goal_mode import zcode_home as _zcode_home +from .hosts.zcode import zcode_home as _zcode_home SCHEMA_VERSION = "loopx_slash_command_install_v0" OPENCODE_GOAL_DEPENDENCIES = { @@ -601,7 +602,7 @@ def _provisioned_mcp_interpreter() -> str | None: dedicated venv and one `mcp` dependency. """ try: - from loopx.claude_goal_mode.scripts import install as claude_install + from loopx.hosts.claude.scripts import install as claude_install except ImportError: return None try: @@ -636,12 +637,165 @@ def _mcp_command_for_script(script: Path) -> tuple[str, str] | None: def _loopx_mcp_command() -> tuple[str, str] | None: """The shared Claude-profile server Cursor registers.""" try: - from loopx.claude_goal_mode.scripts import install as claude_install + from loopx.hosts.claude.scripts import install as claude_install except ImportError: return None return _mcp_command_for_script(Path(claude_install._p("mcp", "loopx_mcp.py"))) +def _is_within(path: Path, parent: Path) -> bool: + try: + path.expanduser().resolve().relative_to(parent.expanduser().resolve()) + return True + except (OSError, ValueError): + return False + + +def _projects_from_registry_file(registry_file: Path) -> list[Path]: + """Read project directories from one registry JSON file without creating or mutating state.""" + if not registry_file.is_file(): + return [] + try: + from .control_plane.projects.registry_codec import ( + read_activation_upgrade_registry, + ) + + payload_obj: object = read_activation_upgrade_registry(registry_file) + except (OSError, UnicodeDecodeError, ValueError): + return [] + if not isinstance(payload_obj, dict): + return [] + goals_obj = cast(dict[str, object], payload_obj).get("goals") + if not isinstance(goals_obj, list): + return [] + projects: list[Path] = [] + for item in goals_obj: + if not isinstance(item, dict): + continue + goal = cast(dict[str, object], item) + repo_val = goal.get("repo") + if isinstance(repo_val, str) and repo_val.strip(): + projects.append(Path(repo_val).expanduser()) + source_val = goal.get("source_registry") + if isinstance(source_val, str) and source_val.strip(): + src_path = Path(source_val).expanduser() + if src_path.parent.name in {".loopx", ".goal-harness"}: + projects.append(src_path.parent.parent) + return projects + + +def _discover_claude_migration_targets( + *, + claude_root: Path, + claude_home_overridden: bool, + registry_path: str | None, + runtime_root: str | None, +) -> list[tuple[Path, Path | None]]: + """Return unique `(claude_dir, project_dir)` targets to inspect for legacy migration.""" + targets: list[tuple[Path, Path | None]] = [(claude_root, None)] + env_config_dir = os.environ.get("CLAUDE_CONFIG_DIR") if not claude_home_overridden else None + if env_config_dir and env_config_dir.strip(): + targets.append((Path(env_config_dir).expanduser(), None)) + + project_roots: list[Path] = [] + cwd = Path.cwd() + project_roots.append(cwd) + for parent in (cwd, *cwd.parents): + if any((parent / marker / "registry.json").is_file() for marker in (".loopx", ".goal-harness")): + project_roots.append(parent) + break + + registry_files: list[Path] = [] + if registry_path and registry_path.strip(): + registry_files.append(Path(registry_path).expanduser()) + for marker in (".loopx", ".goal-harness"): + local_reg = cwd / marker / "registry.json" + if local_reg.is_file(): + registry_files.append(local_reg) + + explicit_runtime = runtime_root or os.environ.get("LOOPX_RUNTIME_ROOT") + if explicit_runtime and explicit_runtime.strip(): + rt = Path(explicit_runtime).expanduser() + registry_files.extend([rt / "registry.global.json", rt / "registry.json"]) + if not claude_home_overridden or _is_within(claude_root, Path.home()): + home = Path.home() + for rt in (home / ".loopx", home / ".codex" / "loopx"): + registry_files.extend([rt / "registry.global.json", rt / "registry.json"]) + + for reg_file in registry_files: + project_roots.extend(_projects_from_registry_file(reg_file)) + + for proj in project_roots: + targets.append((proj / ".claude", proj)) + + deduped: list[tuple[Path, Path | None]] = [] + seen_dirs: set[Path] = set() + for claude_dir, proj_dir in targets: + try: + key = claude_dir.expanduser().resolve() + except OSError: + key = claude_dir + if key in seen_dirs: + continue + seen_dirs.add(key) + if claude_dir.is_dir() or (proj_dir is not None and (proj_dir / ".mcp.json").is_file()): + deduped.append((claude_dir, proj_dir)) + return deduped + + +def _migrate_legacy_claude_configs( + *, + installed: list[dict[str, object]], + claude_root: Path, + claude_home_overridden: bool, + registry_path: str | None, + runtime_root: str | None, + execute: bool, + extra_notes: list[str] | None = None, +) -> None: + try: + from loopx.hosts.claude.scripts import install as claude_install + except ImportError: + return + for claude_dir, proj_dir in _discover_claude_migration_targets( + claude_root=claude_root, + claude_home_overridden=claude_home_overridden, + registry_path=registry_path, + runtime_root=runtime_root, + ): + for row in claude_install.migrate_legacy_claude_dir( + claude_dir, + project_dir=proj_dir, + execute=execute, + ): + if row.get("note") and extra_notes is not None: + extra_notes.append(str(row["note"])) + if row.get("reason") or row.get("recovery"): + installed.append( + _installed_entry( + surface="claude-code", + host_surfaces=["claude-code"], + mechanism="claude_goal_mode_legacy_migration", + command="/loopx", + path=Path(row["path"]), + status=row["status"], + reason=row.get("reason"), + recovery=row.get("recovery"), + ) + ) + else: + installed.append( + _installed_entry( + surface="claude-code", + host_surfaces=["claude-code"], + mechanism="claude_goal_mode_legacy_migration", + command="/loopx", + path=Path(row["path"]), + status=row["status"], + ) + ) + + def _kiro_cli_mcp_command() -> tuple[str, str] | None: """The Kiro CLI server: same control plane, Kiro runtime profile and session-bound identity.""" @@ -837,6 +991,8 @@ def install_slash_commands( pi_project: str | None = None, pi_scope: str = "project", pi_user_home: str | None = None, + registry_path: str | None = None, + runtime_root: str | None = None, ) -> dict[str, object]: facade_specs = _command_prompt_specs(cli_bin=cli_bin, include_legacy_aliases=True) agy_facade_specs = _command_prompt_specs( @@ -864,6 +1020,7 @@ def install_slash_commands( pi_project_root, scope=pi_scope, agent_dir=_pi_agent_dir(pi_user_home) ) installed: list[dict[str, object]] = [] + migration_notes: list[str] = [] if with_goal_bridge and "opencode" not in effective_surfaces: installed.append( @@ -907,6 +1064,16 @@ def install_slash_commands( uninstall=uninstall, invoke_prefix="/", ) + if not uninstall: + _migrate_legacy_claude_configs( + installed=installed, + claude_root=claude_root, + claude_home_overridden=claude_home is not None, + registry_path=registry_path, + runtime_root=runtime_root, + execute=execute, + extra_notes=migration_notes, + ) if "gemini" in effective_surfaces: # Gemini CLI discovers user skills from GEMINI_HOME/skills. Files are @@ -1180,6 +1347,7 @@ def install_slash_commands( "The OpenCode goal bridge uses Bun-managed config-directory dependencies and must replace any direct goal-plugin registration.", "OpenCode bridge uninstall preserves package.json dependencies because they may be shared by user-owned local plugins.", "Uninstall is fail-closed: it retires only files carrying the LoopX managed marker and leaves user-owned files in place.", + *migration_notes, ], } diff --git a/packages/dsh-loopx-plugin/src/managed-runtime.ts b/packages/dsh-loopx-plugin/src/managed-runtime.ts index b43f8ec096..1f90ab44ba 100644 --- a/packages/dsh-loopx-plugin/src/managed-runtime.ts +++ b/packages/dsh-loopx-plugin/src/managed-runtime.ts @@ -50,7 +50,7 @@ export function pluginPythonCandidates( // Windows install registers `python.exe`, and the host's `python3` name can be // the WindowsApps alias that never starts Python. The same fallback pair is // used by the Claude Code adapter installer - // (loopx/claude_goal_mode/scripts/install.py), and the callers above still + // (loopx/hosts/claude/scripts/install.py), and the callers above still // reject an interpreter that fails the version/pip probe. const discoveredNames = [...discovered] .sort(([nameA, minorA], [nameB, minorB]) => minorB - minorA || nameA.localeCompare(nameB)) diff --git a/pyproject.toml b/pyproject.toml index 072b27d926..44bb7aa1d4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -68,7 +68,7 @@ test = [ [project.scripts] loopx = "loopx.entrypoint:main" -loopx-kunluncode = "loopx.kunluncode_goal_mode.cli:main" +loopx-kunluncode = "loopx.hosts.kunluncode.cli:main" loopx-lark-provider = "loopx.extensions.lark.provider:main" loopx-openviking-history-export = "loopx.extensions.openviking_semantic_preference.history_export:main" loopx-openviking-semantic-preference = "loopx.extensions.openviking_semantic_preference.provider:main" @@ -107,8 +107,9 @@ include = ["loopx*"] "loopx.opencode_goal_mode" = ["*.js", "*.mjs", "README.md"] "loopx.opencode2_goal_mode" = ["*.mjs", "README.md"] "loopx.pi_goal_mode" = ["*.ts", "*.mjs", "README.md"] -"loopx.kunluncode_goal_mode" = ["README.md"] -"loopx.zcode_goal_mode" = ["README.md", "*.ts", "contract.json", "images/*.png"] +"loopx.hosts.claude" = ["README.md", ".claude-plugin/*.json", "commands/*.md", "hooks/*.json", "settings.example.json"] +"loopx.hosts.kunluncode" = ["README.md"] +"loopx.hosts.zcode" = ["README.md", "*.ts", "contract.json", "images/*.png"] [tool.setuptools.data-files] "share/loopx/skills/loopx-material" = [ diff --git a/scripts/ci/test_impact_plan.py b/scripts/ci/test_impact_plan.py index bb6b553aef..6bca8179fd 100644 --- a/scripts/ci/test_impact_plan.py +++ b/scripts/ci/test_impact_plan.py @@ -50,7 +50,7 @@ def test_root_readme_locales_are_documents(self): def test_backend_mixed_and_full_risk_tiering(self): for path in ("loopx/cli.py", "loopx/control_plane/goals/vision_checkpoint.ts", - "loopx/claude_goal_mode/commands/loopx.md", "tests/test_ui.py", + "loopx/hosts/claude/commands/loopx.md", "tests/test_ui.py", "AGENTS.md", "docs/build.py", "packages/dsh-loopx-plugin/src/cli.ts", "packages/loopx-ark-turn/tests/test_cli.py", "packages/dsh-loopx-plugin/smoke/dsh-legacy-host.package.json", diff --git a/scripts/install-local.sh b/scripts/install-local.sh index 9681fbf640..2101a11fb9 100755 --- a/scripts/install-local.sh +++ b/scripts/install-local.sh @@ -1015,8 +1015,8 @@ fi # LOOPX_INSTALL_CLAUDE=1 (installs at USER scope: MCP + /loopx command). Add # the optional should_run gate later with `install.py --scope # --harden`. Prefer PROJECT scope: -# `python /loopx/claude_goal_mode/scripts/install.py --scope project`. -claude_installer="$release_dir/loopx/claude_goal_mode/scripts/install.py" +# `python /loopx/hosts/claude/scripts/install.py --scope project`. +claude_installer="$release_dir/loopx/hosts/claude/scripts/install.py" install_claude="${LOOPX_INSTALL_CLAUDE:-0}" claude_line="- loopx Claude adapter: skipped (opt-in; LOOPX_INSTALL_CLAUDE=1, or run install.py --scope project|user)" if [[ "$install_claude" != "0" && -f "$claude_installer" ]]; then diff --git a/scripts/qualify-claude-goal-release.py b/scripts/qualify-claude-goal-release.py index 20a3bcdb4f..fc731bae76 100644 --- a/scripts/qualify-claude-goal-release.py +++ b/scripts/qualify-claude-goal-release.py @@ -121,13 +121,13 @@ def verify_mcp_completions(events: list[dict], expected_todos: set[str] | None = def exercise_host(root: Path, project: Path, launcher: Path, claude: str, timeout: int) -> list[dict]: - from loopx.claude_goal_mode.scripts.goalmode_cmd import write_loop_md + from loopx.hosts.claude.scripts.goalmode_cmd import write_loop_md write_loop_md(project, shared.GOAL, shared.AGENT) config = root / "mcp.json" config.write_text(json.dumps({"mcpServers": {"loopx": { "command": sys.executable, - "args": [str(REPO / "loopx/claude_goal_mode/mcp/loopx_mcp.py")], + "args": [str(REPO / "loopx/hosts/claude/mcp/loopx_mcp.py")], }}})) command = [ claude, "--bare", "--setting-sources", "", "--no-session-persistence", diff --git a/tests/architecture/test_source_session_registry_denial.py b/tests/architecture/test_source_session_registry_denial.py index fb9163403b..2a94fd53ba 100644 --- a/tests/architecture/test_source_session_registry_denial.py +++ b/tests/architecture/test_source_session_registry_denial.py @@ -24,7 +24,7 @@ "loopx/capabilities/manager_context/roundtrip.py", "loopx/capabilities/issue_fix/correction_settlement.py", "loopx/capabilities/native_chat/project_context.py", - "loopx/claude_goal_mode/scripts/connect.py", + "loopx/hosts/claude/scripts/connect.py", "loopx/cli_runtime.py", "loopx/cli_commands/coordination_shadow.py", "loopx/cli_commands/manager_inbox.py", @@ -46,7 +46,7 @@ "loopx/control_plane/projects/registry.py", "loopx/control_plane/quota/execution_preparation.py", "loopx/control_plane/turn_driver/codex_sessions.py", - "loopx/kunluncode_goal_mode/cli.py", + "loopx/hosts/kunluncode/cli.py", "loopx/state_migration.py", "loopx/hosts/managed_service_runtime.py", } diff --git a/tests/cli_commands/test_source_session_lifetime.py b/tests/cli_commands/test_source_session_lifetime.py index c3b48b6e38..2379bd3ee6 100644 --- a/tests/cli_commands/test_source_session_lifetime.py +++ b/tests/cli_commands/test_source_session_lifetime.py @@ -11,7 +11,7 @@ import pytest from loopx.cli import main -from loopx.claude_goal_mode.scripts import connect as claude_connect +from loopx.hosts.claude.scripts import connect as claude_connect from loopx.control_plane.goals import ( source_session_recreation, source_session_registration, diff --git a/tests/control_plane/test_machine_guard_context_contract.py b/tests/control_plane/test_machine_guard_context_contract.py index c700de872a..acbcd9fd4c 100644 --- a/tests/control_plane/test_machine_guard_context_contract.py +++ b/tests/control_plane/test_machine_guard_context_contract.py @@ -10,9 +10,9 @@ import pytest -from loopx.claude_goal_mode.scripts import goalmode_cmd -from loopx.claude_goal_mode.statusline import goal_status -from loopx.claude_goal_mode.hooks import goal_policy +from loopx.hosts.claude.scripts import goalmode_cmd +from loopx.hosts.claude.statusline import goal_status +from loopx.hosts.claude.hooks import goal_policy from loopx.control_plane.host_adapter_settlement import HostTodoSettlementRequest, _prepare from loopx.goal_mode_mcp import GoalModeMCPConfig, GoalModeMCPControlPlane from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime diff --git a/tests/control_plane/test_replan_context_evidence.py b/tests/control_plane/test_replan_context_evidence.py index 4ea36c8a60..7f8405274a 100644 --- a/tests/control_plane/test_replan_context_evidence.py +++ b/tests/control_plane/test_replan_context_evidence.py @@ -445,7 +445,7 @@ def test_unscoped_replan_assignment_ignores_evidence_and_presentation_changes(): def test_native_recovery_reads_its_event_source_without_the_removed_cli(tmp_path: Path): - from loopx.kunluncode_goal_mode.control_plane import LoopXControlPlane + from loopx.hosts.kunluncode.control_plane import LoopXControlPlane runtime = tmp_path / "runtime" registry = tmp_path / "registry.json" diff --git a/tests/control_plane_ts/content_digest_single_owner.test.ts b/tests/control_plane_ts/content_digest_single_owner.test.ts index 7bedfcc5b3..2895b3c57d 100644 --- a/tests/control_plane_ts/content_digest_single_owner.test.ts +++ b/tests/control_plane_ts/content_digest_single_owner.test.ts @@ -196,8 +196,8 @@ const CANONICAL_CONSUMERS = [ "control_plane/work_items/task_lease_lifecycle_request.ts", "control_plane/work_items/task_lease_workspace.ts", "control_plane/work_items/yardstick_decision.ts", - "zcode_goal_mode/cli.ts", - "zcode_goal_mode/runtime.ts", + "hosts/zcode/cli.ts", + "hosts/zcode/runtime.ts", ]; function packageFiles(dir: string, base = ""): string[] { diff --git a/tests/control_plane_ts/zcode_app_server.test.ts b/tests/control_plane_ts/zcode_app_server.test.ts index b289ed170d..456d72084f 100644 --- a/tests/control_plane_ts/zcode_app_server.test.ts +++ b/tests/control_plane_ts/zcode_app_server.test.ts @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; import { createHash } from "node:crypto"; -import { ZCodeAppServer, ZCodeProtocolError } from "../../loopx/zcode_goal_mode/app-server.ts"; +import { ZCodeAppServer, ZCodeProtocolError } from "../../loopx/hosts/zcode/app-server.ts"; // An independent native host fixture, with strict CAS and a self-running Goal. const HOST = String.raw` diff --git a/tests/control_plane_ts/zcode_guard.test.ts b/tests/control_plane_ts/zcode_guard.test.ts index 8ed7bf7b02..8719cfd12a 100644 --- a/tests/control_plane_ts/zcode_guard.test.ts +++ b/tests/control_plane_ts/zcode_guard.test.ts @@ -5,8 +5,8 @@ import {mkdtemp, readFile, rm} from "node:fs/promises"; import {tmpdir} from "node:os"; import {join, resolve, sep} from "node:path"; import {fileURLToPath} from "node:url"; -import {ZCodeAppServer, terminateOwnedProcess} from "../../loopx/zcode_goal_mode/app-server.ts"; -const guardian = fileURLToPath(new URL("../../loopx/zcode_goal_mode/guard.ts",import.meta.url)); +import {ZCodeAppServer, terminateOwnedProcess} from "../../loopx/hosts/zcode/app-server.ts"; +const guardian = fileURLToPath(new URL("../../loopx/hosts/zcode/guard.ts",import.meta.url)); const writer = String.raw`const fs=require('node:fs');const path=process.argv[1];let n=0;setInterval(()=>fs.writeFileSync(path,String(++n)),20);`; const cli = String.raw`const cp=require('node:child_process'),fs=require('node:fs');const path=process.argv[1];let n=0;const owned=cp.spawn(process.execPath,['-e',process.argv[2],path+'.child'],{stdio:'ignore',windowsHide:true});setInterval(()=>fs.writeFileSync(path,String(++n)),20);process.stdout.write(JSON.stringify({childPid:owned.pid})+'\n');process.stdin.resume();`; async function pulse(path:string):Promise{try{return await readFile(path,"utf8");}catch{return null;}} diff --git a/tests/control_plane_ts/zcode_native_goal.test.ts b/tests/control_plane_ts/zcode_native_goal.test.ts index c2aa9c72f0..1ff0823d03 100644 --- a/tests/control_plane_ts/zcode_native_goal.test.ts +++ b/tests/control_plane_ts/zcode_native_goal.test.ts @@ -1,8 +1,8 @@ import test from "node:test"; import assert from "node:assert/strict"; import {createHash} from "node:crypto"; -import {NativeGoalController, type BindingState, type NativeHost} from "../../loopx/zcode_goal_mode/runtime.ts"; -import type {NativeObservation, NativeRequest} from "../../loopx/zcode_goal_mode/contract.ts"; +import {NativeGoalController, type BindingState, type NativeHost} from "../../loopx/hosts/zcode/runtime.ts"; +import type {NativeObservation, NativeRequest} from "../../loopx/hosts/zcode/contract.ts"; function fixture() { const request: NativeRequest = {action: "bind", project: "/project", registry: "/registry", @@ -326,7 +326,7 @@ test("a legacy journal file is read back byte for byte and left unchanged by a r const {mkdtemp, readFile, rm} = await import("node:fs/promises"); const {join} = await import("node:path"); const {tmpdir} = await import("node:os"); - const {atomicState, readState} = await import("../../loopx/zcode_goal_mode/runtime.ts"); + const {atomicState, readState} = await import("../../loopx/hosts/zcode/runtime.ts"); const dir = await mkdtemp(join(tmpdir(), "zcode-legacy-")); try { const path = join(dir, "binding.json"); @@ -374,7 +374,7 @@ test("a malformed recorded basis is an unsupported binding", async () => { const {writeFile, mkdtemp, rm} = await import("node:fs/promises"); const {join} = await import("node:path"); const {tmpdir} = await import("node:os"); - const {readState} = await import("../../loopx/zcode_goal_mode/runtime.ts"); + const {readState} = await import("../../loopx/hosts/zcode/runtime.ts"); const dir = await mkdtemp(join(tmpdir(), "zcode-basis-")); try { const path = join(dir, "binding.json"); diff --git a/tests/presentation/test_chat_bundle.py b/tests/presentation/test_chat_bundle.py index d4b5f0a2b3..a6fd07d28d 100644 --- a/tests/presentation/test_chat_bundle.py +++ b/tests/presentation/test_chat_bundle.py @@ -398,7 +398,7 @@ def test_frontend_source_inputs_ignore_placeholder_checkout_line_endings(tmp_pat @pytest.mark.parametrize("name", ["contract.ts", "contract.json"]) def test_provider_contract_update_invalidates_packaged_frontend(source, tmp_path, name): # A changed caller contract must not ship with previously built controls. - contract = tmp_path / "loopx/zcode_goal_mode" / name + contract = tmp_path / "loopx/hosts/zcode" / name contract.parent.mkdir(parents=True) contract.write_text("original contract", encoding="utf-8") builder.build(None) diff --git a/tests/test_atomic_write_modes.py b/tests/test_atomic_write_modes.py index 16ac26173e..acd108da88 100644 --- a/tests/test_atomic_write_modes.py +++ b/tests/test_atomic_write_modes.py @@ -18,7 +18,7 @@ from loopx import chat_store, file_lock from loopx.chat import endpoints as chat_endpoints from loopx.extensions.lark import private_json -from loopx.kunluncode_goal_mode.context import read_binding, write_binding +from loopx.hosts.kunluncode.context import read_binding, write_binding from loopx.registry import atomic_write_json diff --git a/tests/test_audit_cli_and_runtime_fixes.py b/tests/test_audit_cli_and_runtime_fixes.py index 488a9eaa5f..c7d300dac9 100644 --- a/tests/test_audit_cli_and_runtime_fixes.py +++ b/tests/test_audit_cli_and_runtime_fixes.py @@ -214,7 +214,7 @@ def raise_rpc(*_a, **_k): def test_claude_goal_policy_fail_closed_empty_path_and_resolves_relative_cwd( tmp_path: Path, monkeypatch ) -> None: - hooks_dir = str(REPO_ROOT / "loopx" / "claude_goal_mode" / "hooks") + hooks_dir = str(REPO_ROOT / "loopx" / "hosts" / "claude" / "hooks") if hooks_dir not in sys.path: sys.path.insert(0, hooks_dir) import goal_policy diff --git a/tests/test_claude_goal_harden_settings_preservation.py b/tests/test_claude_goal_harden_settings_preservation.py index 2f98b1e881..b57ef0d1fd 100644 --- a/tests/test_claude_goal_harden_settings_preservation.py +++ b/tests/test_claude_goal_harden_settings_preservation.py @@ -24,7 +24,7 @@ import pytest -from loopx.claude_goal_mode.scripts import install as claude_install +from loopx.hosts.claude.scripts import install as claude_install # Each entry is an ordinary on-disk state of a user-owned settings file that # `json.loads` rejects. The last one is what an interrupted write leaves behind. diff --git a/tests/test_claude_goal_install_python_launcher.py b/tests/test_claude_goal_install_python_launcher.py index 57ff86bf93..2ee287f2d6 100644 --- a/tests/test_claude_goal_install_python_launcher.py +++ b/tests/test_claude_goal_install_python_launcher.py @@ -44,7 +44,7 @@ import pytest -from loopx.claude_goal_mode.scripts import install as claude_install +from loopx.hosts.claude.scripts import install as claude_install def _dead_python3_alias(tmp_path: Path) -> Path: diff --git a/tests/test_claude_goal_mode_hook_fail_closed.py b/tests/test_claude_goal_mode_hook_fail_closed.py index 1427965849..8c38772440 100644 --- a/tests/test_claude_goal_mode_hook_fail_closed.py +++ b/tests/test_claude_goal_mode_hook_fail_closed.py @@ -42,7 +42,7 @@ import pytest REPO_ROOT = Path(__file__).resolve().parents[1] -HOOK = REPO_ROOT / "loopx/claude_goal_mode/hooks/goal_policy.py" +HOOK = REPO_ROOT / "loopx/hosts/claude/hooks/goal_policy.py" GOAL_ID = "hook-fail-closed-goal" @@ -310,7 +310,7 @@ def test_unreadable_event_value_is_refused_with_an_explicit_deny( def hook_policy(): """The shipped hook module, imported in-process for ``decide`` cases.""" - hooks_dir = REPO_ROOT / "loopx" / "claude_goal_mode" / "hooks" + hooks_dir = REPO_ROOT / "loopx" / "hosts" / "claude" / "hooks" if str(hooks_dir) not in sys.path: sys.path.insert(0, str(hooks_dir)) import goal_policy diff --git a/tests/test_claude_goal_mode_stdio_utf8.py b/tests/test_claude_goal_mode_stdio_utf8.py index 264e89c799..9c6a4d45dd 100644 --- a/tests/test_claude_goal_mode_stdio_utf8.py +++ b/tests/test_claude_goal_mode_stdio_utf8.py @@ -32,9 +32,9 @@ from pathlib import Path REPO_ROOT = Path(__file__).resolve().parents[1] -HOOK = REPO_ROOT / "loopx/claude_goal_mode/hooks/goal_policy.py" -STATUSLINE = REPO_ROOT / "loopx/claude_goal_mode/statusline/goal_status.py" -GOALMODE = REPO_ROOT / "loopx/claude_goal_mode/scripts/goalmode_cmd.py" +HOOK = REPO_ROOT / "loopx/hosts/claude/hooks/goal_policy.py" +STATUSLINE = REPO_ROOT / "loopx/hosts/claude/statusline/goal_status.py" +GOALMODE = REPO_ROOT / "loopx/hosts/claude/scripts/goalmode_cmd.py" # A codec the scripts must not fall back to. `gbk` cannot encode the statusline # glyphs and decodes the UTF-8 project path below into mojibake, so a missing pin diff --git a/tests/test_claude_goal_release_qualification.py b/tests/test_claude_goal_release_qualification.py index 26effac000..b7cd9426ef 100644 --- a/tests/test_claude_goal_release_qualification.py +++ b/tests/test_claude_goal_release_qualification.py @@ -71,7 +71,7 @@ def test_child_environment_allowlist_drops_unrelated_secrets_and_operator_home(m def test_claude_loop_uses_current_contract_not_segment_or_empty_list_stop(): - from loopx.claude_goal_mode.scripts.goalmode_cmd import loop_execution_content, loop_md_content + from loopx.hosts.claude.scripts.goalmode_cmd import loop_execution_content, loop_md_content from loopx.control_plane.heartbeat.rules import SCOPE_BOUNDED_WORK_RULE bootstrap = loop_md_content("goal-a", "agent-a") @@ -130,7 +130,7 @@ def test_real_claude_stdio_mcp_binding_and_identity_gate(tmp_path): pytest.importorskip("mcp.server.fastmcp") from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client - from loopx.claude_goal_mode.scripts.goalmode_cmd import write_loop_md + from loopx.hosts.claude.scripts.goalmode_cmd import write_loop_md project, _, launcher = runner.shared.setup(tmp_path) write_loop_md(project, runner.shared.GOAL, runner.shared.AGENT) @@ -138,7 +138,7 @@ def test_real_claude_stdio_mcp_binding_and_identity_gate(tmp_path): before = state.read_bytes() params = StdioServerParameters( command=sys.executable, - args=[str(REPO / "loopx/claude_goal_mode/mcp/loopx_mcp.py")], + args=[str(REPO / "loopx/hosts/claude/mcp/loopx_mcp.py")], cwd=str(project), env=runner.shared.host_environment(tmp_path, launcher), ) async def exercise(): diff --git a/tests/test_host_vision_recovery.py b/tests/test_host_vision_recovery.py index 338ae2c4c0..bdf3b4079d 100644 --- a/tests/test_host_vision_recovery.py +++ b/tests/test_host_vision_recovery.py @@ -322,7 +322,7 @@ def response_lost(args, **kwargs): def test_native_outer_controller_owns_new_vision_tool(monkeypatch): - from loopx.kunluncode_goal_mode.guards import guard_native_controller_writeback + from loopx.hosts.kunluncode.guards import guard_native_controller_writeback from types import SimpleNamespace monkeypatch.setenv("LOOPX_KUNLUNCODE_OUTER_CONTROLLER", "1") diff --git a/tests/test_hosts_goal_mode_batch2_consolidation.py b/tests/test_hosts_goal_mode_batch2_consolidation.py new file mode 100644 index 0000000000..0c05ae4826 --- /dev/null +++ b/tests/test_hosts_goal_mode_batch2_consolidation.py @@ -0,0 +1,83 @@ +"""Contracts protecting Batch 2 host consolidation under loopx/hosts/.""" + +from __future__ import annotations + +import os +from pathlib import Path +import subprocess +import sys + +from loopx.hosts.kunluncode import cli as kunlun_cli + +REPO_ROOT = Path(__file__).resolve().parents[1] + + +def test_batch2_retired_goal_mode_packages_live_under_hosts() -> None: + for retired in ( + "claude_goal_mode", + "kunluncode_goal_mode", + "zcode_goal_mode", + ): + assert not (REPO_ROOT / "loopx" / retired).exists(), retired + + for host_dir in ("claude", "kunluncode", "zcode"): + assert (REPO_ROOT / "loopx" / "hosts" / host_dir / "__init__.py").is_file() + assert (REPO_ROOT / "loopx" / "hosts" / host_dir / "README.md").is_file() + + for asset in ( + "claude/.claude-plugin/plugin.json", + "claude/commands/loopx.md", + "claude/hooks/hooks.json", + "claude/settings.example.json", + "zcode/contract.json", + "zcode/contract.ts", + "zcode/images/native-error-mobile.png", + "zcode/images/native-quota-desktop.png", + ): + assert (REPO_ROOT / "loopx" / "hosts" / asset).is_file(), asset + + +def test_kunluncode_source_root_resolves_repository_root() -> None: + assert kunlun_cli._source_root() == REPO_ROOT + + +def test_claude_direct_scripts_resolve_repo_and_plugin_root_without_pythonpath( + tmp_path: Path, +) -> None: + env = { + key: value + for key, value in os.environ.items() + if key != "PYTHONPATH" + } + expected_plugin = REPO_ROOT / "loopx" / "hosts" / "claude" + + for rel, check_plugin in ( + ("hooks/goal_state.py", False), + ("mcp/loopx_mcp.py", False), + ("scripts/install.py", True), + ("scripts/connect.py", True), + ): + script = expected_plugin / rel + assert script.is_file(), script + checks = [ + "import importlib.util", + "from pathlib import Path", + f"spec = importlib.util.spec_from_file_location('claude_probe', {str(script)!r})", + "assert spec is not None and spec.loader is not None", + "mod = importlib.util.module_from_spec(spec)", + "spec.loader.exec_module(mod)", + f"assert mod.REPO_ROOT.resolve() == Path({str(REPO_ROOT)!r}).resolve()", + ] + if check_plugin: + checks.append( + f"assert mod.PLUGIN_ROOT.resolve() == Path({str(expected_plugin)!r}).resolve()" + ) + completed = subprocess.run( + [sys.executable, "-c", "\n".join(checks)], + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + check=False, + ) + assert completed.returncode == 0, f"{rel}: {completed.stderr}{completed.stdout}" diff --git a/tests/test_kunluncode_goal_mode.py b/tests/test_kunluncode_goal_mode.py index afac67688a..d1b349da74 100644 --- a/tests/test_kunluncode_goal_mode.py +++ b/tests/test_kunluncode_goal_mode.py @@ -11,7 +11,7 @@ from loopx import goal_mode_mcp from loopx import cli as loopx_cli -from loopx.claude_goal_mode.hooks.goal_state import goal_context as claude_context +from loopx.hosts.claude.hooks.goal_state import goal_context as claude_context from loopx.goal_mode_mcp import ( GoalModeMCPConfig, GoalModeMCPControlPlane, @@ -26,26 +26,26 @@ source_session_registry_transaction, ) from loopx.file_lock import exclusive_cross_runtime_file_lock -from loopx.kunluncode_goal_mode import cli -from loopx.kunluncode_goal_mode.app_server import ( +from loopx.hosts.kunluncode import cli +from loopx.hosts.kunluncode.app_server import ( NATIVE_GOAL_MODES, KunlunAppServerError, native_goal_success, stable_text_digest, ) -from loopx.kunluncode_goal_mode.context import ( +from loopx.hosts.kunluncode.context import ( goal_context as kunluncode_context, write_binding, ) -from loopx.kunluncode_goal_mode.control_plane import LoopXControlPlane -from loopx.kunluncode_goal_mode.guards import ( +from loopx.hosts.kunluncode.control_plane import LoopXControlPlane +from loopx.hosts.kunluncode.guards import ( NATIVE_CONTROLLER_AGENT_ENV, NATIVE_CONTROLLER_ENV, NATIVE_CONTROLLER_GOAL_ENV, guard_native_controller_writeback, native_controller_cli_write_block, ) -from loopx.kunluncode_goal_mode.runtime import ( +from loopx.hosts.kunluncode.runtime import ( RUNTIME_STATE_SCHEMA_VERSION, KunlunNativeGoalRuntimeError, build_native_goal_objective, @@ -1178,7 +1178,7 @@ def _native_todo(*, claimed: bool = False) -> dict[str, object]: "todo_id": "todo-native-1", "text": "Implement and verify the native Goal Pro adapter.", "claimed_by": "kunlun" if claimed else "", - "required_write_scopes": ["loopx/kunluncode_goal_mode/**"], + "required_write_scopes": ["loopx/hosts/kunluncode/**"], } @@ -1829,3 +1829,89 @@ def test_mcp_pin_has_one_source_of_truth() -> None: assert cli.MCP_REQUIREMENT.startswith("mcp==") assert cli.MCP_SDK_VERSION not in probe_source assert "MCP_SDK_VERSION" in probe_source + + +@pytest.mark.parametrize( + "legacy_script", + ( + "/opt/loopx/loopx/kunluncode_goal_mode/server.py", + r"C:\loopx\loopx\kunluncode_goal_mode\server.py", + ), +) +def test_install_connect_and_uninstall_accept_legacy_kunluncode_goal_mode_server( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + legacy_script: str, +) -> None: + registry = _registry(tmp_path) + calls: list[list[str]] = [] + configured = [ + { + "name": cli.MCP_SERVER_NAME, + "command": "/old/python", + "args": [legacy_script], + } + ] + monkeypatch.setattr(cli.shutil, "which", lambda name: f"/usr/bin/{name}") + monkeypatch.setattr(cli, "_compatible_python", lambda _python: True) + monkeypatch.setattr(cli, "_configured_mcp_servers", lambda _binary: configured) + monkeypatch.setattr(cli, "_loopx_prefix", lambda: ["loopx"]) + + def capture(command: list[str], **_kwargs) -> subprocess.CompletedProcess[str]: + calls.append(command) + return subprocess.CompletedProcess(command, 0, '{"ok": true}', "") + + monkeypatch.setattr(cli, "_run", capture) + + selected = cli.install_mcp( + python="/managed/.venv/bin/python", + dry_run=False, + replace=False, + ) + assert selected == "/managed/.venv/bin/python" + assert calls[0] == ["/usr/bin/kunluncode", "mcp", "remove", cli.MCP_SERVER_NAME] + assert calls[1][-1] == str(cli.MCP_SCRIPT) + + calls.clear() + connected = cli.connect_project( + project=tmp_path, + goal_id="shared-goal", + agent_id="kunlun", + objective=None, + python="/managed/.venv/bin/python", + skip_mcp=False, + replace=False, + dry_run=False, + ) + assert connected["mcp_python"] == "/managed/.venv/bin/python" + assert any( + cmd[:3] == ["/usr/bin/kunluncode", "mcp", "remove"] for cmd in calls + ) + assert json.loads(registry.read_text(encoding="utf-8"))["agent_backends"] == [ + "kunluncode" + ] + + calls.clear() + removed = cli.uninstall_mcp(dry_run=False) + assert removed is True + assert calls == [["/usr/bin/kunluncode", "mcp", "remove", cli.MCP_SERVER_NAME]] + + +def test_uninstall_mcp_still_refuses_user_owned_server( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(cli.shutil, "which", lambda name: f"/usr/bin/{name}") + monkeypatch.setattr( + cli, + "_configured_mcp_servers", + lambda _binary: [ + { + "name": cli.MCP_SERVER_NAME, + "command": "/usr/bin/python3", + "args": ["/home/user/custom/server.py"], + } + ], + ) + + with pytest.raises(RuntimeError, match="user-owned"): + cli.uninstall_mcp(dry_run=False) diff --git a/tests/test_runtime_subprocess_utf8.py b/tests/test_runtime_subprocess_utf8.py index e10400df2c..10e5666d23 100644 --- a/tests/test_runtime_subprocess_utf8.py +++ b/tests/test_runtime_subprocess_utf8.py @@ -16,7 +16,7 @@ from pathlib import Path from loopx.capabilities.change_quality import scope -from loopx.claude_goal_mode.scripts import goalmode_cmd +from loopx.hosts.claude.scripts import goalmode_cmd REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_slash_command_install.py b/tests/test_slash_command_install.py index 6523d5c8b0..596b722c39 100644 --- a/tests/test_slash_command_install.py +++ b/tests/test_slash_command_install.py @@ -1388,3 +1388,889 @@ def test_antigravity_resident_guidance_is_isolated_to_antigravity_surfaces(tmp_p codex_text = (codex_home / "skills" / "loopx" / "SKILL.md").read_text(encoding="utf-8") assert "Antigravity App fixed resident session" not in codex_text assert "--with-agy-hooks" not in codex_text + + +def _seed_legacy_claude_dir( + claude_dir: Path, + *, + legacy_root: str = "/opt/old-loopx/loopx/claude_goal_mode", + include_custom_statusline: bool = False, +) -> tuple[Path, Path]: + cmd_dir = claude_dir / "commands" + cmd_dir.mkdir(parents=True, exist_ok=True) + cmd_path = cmd_dir / "loopx.md" + cmd_path.write_text( + "---\n" + "description: loopx goal-mode setup. `/loopx ` sets up a goal + writes .claude/loop.md; " + "drive the loop with native /loop. bare /loopx = arm; off | status.\n" + "argument-hint: | (no args = arm) | off | status\n" + "allowed-tools: Bash('/old/python3':*)\n" + "---\n\n" + "Run the loopx setup helper and read its output:\n\n" + f"!`'/old/python3' '{legacy_root}/scripts/goalmode_cmd.py' $ARGUMENTS`\n\n" + "Show it to the user VERBATIM and STOP.\n", + encoding="utf-8", + ) + settings_path = claude_dir / "settings.json" + settings_payload: dict[str, object] = { + "permissions": {"allow": ["Bash(ls:*)"], "deny": ["Read(~/.ssh/**)"]}, + "env": {"CUSTOM_FLAG": "keep"}, + "model": "sonnet", + "hooks": { + "PreToolUse": [ + { + "matcher": "Bash", + "hooks": [{"type": "command", "command": "echo user-owned-hook"}], + }, + { + "matcher": "*", + "hooks": [ + { + "type": "command", + "command": f"/old/python3 '{legacy_root}/hooks/goal_policy.py'", + "timeout": 10, + } + ], + }, + ] + }, + "statusLine": ( + {"type": "command", "command": "custom-user-statusline.sh"} + if include_custom_statusline + else { + "type": "command", + "command": f"/old/python3 '{legacy_root}/statusline/goal_status.py'", + } + ), + } + settings_path.write_text(json.dumps(settings_payload, indent=2), encoding="utf-8") + return cmd_path, settings_path + + +def test_default_install_migrates_legacy_claude_project_and_user_preserving_config( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + import shlex + import subprocess + import sys + + home = tmp_path / "home" + user_claude = home / ".claude" + proj = tmp_path / "proj" + proj_claude = proj / ".claude" + (proj / ".loopx").mkdir(parents=True) + (proj / ".loopx" / "registry.json").write_text( + json.dumps( + { + "schema_version": "0.1", + "goals": [ + { + "id": "cc-proj", + "repo": str(proj), + "coordination": {"agent_model": "peer_v1", "registered_agents": ["cc"]}, + } + ], + } + ), + encoding="utf-8", + ) + runtime_root = home / ".loopx" + runtime_root.mkdir(parents=True) + (runtime_root / "registry.global.json").write_text( + json.dumps( + { + "schema_version": "0.1", + "goals": [ + { + "id": "cc-proj", + "repo": str(proj), + "source_registry": str(proj / ".loopx" / "registry.json"), + } + ], + } + ), + encoding="utf-8", + ) + + user_cmd, user_settings = _seed_legacy_claude_dir(user_claude, include_custom_statusline=True) + proj_cmd, proj_settings = _seed_legacy_claude_dir(proj_claude, include_custom_statusline=False) + proj_mcp = proj / ".mcp.json" + proj_mcp.write_text( + json.dumps( + { + "mcpServers": { + "other": {"command": "other-bin", "args": ["--serve"]}, + "loopx": { + "command": "/old/python3", + "args": ["/opt/old-loopx/loopx/claude_goal_mode/mcp/loopx_mcp.py"], + }, + } + } + ), + encoding="utf-8", + ) + + # Dry-run reports planned migrations without writing any file. + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("CLAUDE_HOME", str(user_claude)) + monkeypatch.delenv("LOOPX_RUNTIME_ROOT", raising=False) + monkeypatch.chdir(tmp_path) + + before_proj_cmd = proj_cmd.read_text(encoding="utf-8") + before_proj_settings = proj_settings.read_text(encoding="utf-8") + dry_payload = install_slash_commands( + execute=False, + codex_home=str(home / ".codex"), + opencode_home=str(home / ".config" / "opencode"), + ) + assert dry_payload["ok"] is True + assert proj_cmd.read_text(encoding="utf-8") == before_proj_cmd + assert proj_settings.read_text(encoding="utf-8") == before_proj_settings + migrated_dry = [ + row + for row in dry_payload["installed"] # type: ignore[attr-defined] + if isinstance(row, dict) and row.get("mechanism") == "claude_goal_mode_legacy_migration" + ] + assert {row["status"] for row in migrated_dry} == {"would_write"} + assert len(migrated_dry) == 5 + + # Default install migrates both user and project entries cleanly while preserving user config. + applied = install_slash_commands( + execute=True, + codex_home=str(home / ".codex"), + opencode_home=str(home / ".config" / "opencode"), + ) + assert applied["ok"] is True + migrated = [ + row + for row in applied["installed"] # type: ignore[attr-defined] + if isinstance(row, dict) and row.get("mechanism") == "claude_goal_mode_legacy_migration" + ] + assert {row["status"] for row in migrated} == {"updated"} + assert len(migrated) == 5 + + # Idempotent on repeated default install. + second = install_slash_commands( + execute=True, + codex_home=str(home / ".codex"), + opencode_home=str(home / ".config" / "opencode"), + ) + assert not any( + isinstance(row, dict) and row.get("mechanism") == "claude_goal_mode_legacy_migration" + for row in second["installed"] # type: ignore[attr-defined] + ) + + user_settings_data = json.loads(user_settings.read_text(encoding="utf-8")) + assert user_settings_data["statusLine"] == {"type": "command", "command": "custom-user-statusline.sh"} + assert "/loopx/hosts/claude/commands/" not in user_cmd.read_text(encoding="utf-8") + assert "/loopx/hosts/claude/scripts/goalmode_cmd.py" in user_cmd.read_text(encoding="utf-8") + + proj_settings_data = json.loads(proj_settings.read_text(encoding="utf-8")) + assert proj_settings_data["permissions"] == {"allow": ["Bash(ls:*)"], "deny": ["Read(~/.ssh/**)"]} + assert proj_settings_data["env"] == {"CUSTOM_FLAG": "keep"} + assert proj_settings_data["model"] == "sonnet" + hooks_cmds = [ + h["command"] + for g in proj_settings_data["hooks"]["PreToolUse"] + for h in g["hooks"] + ] + assert "echo user-owned-hook" in hooks_cmds + assert any("/loopx/hosts/claude/hooks/goal_policy.py" in c for c in hooks_cmds) + assert "/loopx/hosts/claude/statusline/goal_status.py" in proj_settings_data["statusLine"]["command"] + + mcp_data = json.loads(proj_mcp.read_text(encoding="utf-8")) + assert mcp_data["mcpServers"]["other"] == {"command": "other-bin", "args": ["--serve"]} + assert mcp_data["mcpServers"]["loopx"]["args"][0].endswith("/loopx/hosts/claude/mcp/loopx_mcp.py") + + # Execute the migrated /loopx status command and statusLine command verbatim against proj. + cmd_lines = [ + line.strip() + for line in proj_cmd.read_text(encoding="utf-8").splitlines() + if line.strip().startswith("!`") and line.strip().endswith("`") + ] + assert len(cmd_lines) == 1 + status_tokens = shlex.split(cmd_lines[0][2:-1].replace("$ARGUMENTS", "status")) + status_run = subprocess.run( + status_tokens, + cwd=str(proj), + capture_output=True, + text=True, + env={**slash_command_install.os.environ, "HOME": str(home), "PYTHONPATH": str(Path(__file__).resolve().parents[1])}, + check=False, + ) + assert status_run.returncode == 0, status_run.stderr + status_run.stdout + assert "goal : cc-proj" in status_run.stdout + + sl_tokens = shlex.split(proj_settings_data["statusLine"]["command"]) + sl_run = subprocess.run( + sl_tokens, + input=json.dumps({"cwd": str(proj)}), + capture_output=True, + text=True, + env={**slash_command_install.os.environ, "HOME": str(home), "PYTHONPATH": str(Path(__file__).resolve().parents[1])}, + check=False, + ) + assert sl_run.returncode == 0, sl_run.stderr + sl_run.stdout + assert sys.executable + + +def test_claude_legacy_migration_skips_targeted_uninstall_and_unowned_or_corrupt_files( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + home = tmp_path / "home" + user_claude = home / ".claude" + _seed_legacy_claude_dir(user_claude) + user_cmd = user_claude / "commands" / "loopx.md" + user_settings = user_claude / "settings.json" + before_cmd = user_cmd.read_bytes() + before_settings = user_settings.read_bytes() + + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("CLAUDE_HOME", str(user_claude)) + monkeypatch.chdir(tmp_path) + + # 1. Explicit --surface codex never probes or modifies Claude configs. + monkeypatch.setattr( + slash_command_install, + "_migrate_legacy_claude_configs", + lambda **_kw: pytest.fail("explicit --surface codex must not probe legacy Claude configs"), + ) + codex_payload = install_slash_commands( + execute=True, + surfaces=["codex"], + codex_home=str(home / ".codex"), + ) + assert codex_payload["ok"] is True + assert user_cmd.read_bytes() == before_cmd + assert user_settings.read_bytes() == before_settings + + # 2. --uninstall never migrates legacy Claude configs. + monkeypatch.undo() + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("CLAUDE_HOME", str(user_claude)) + monkeypatch.chdir(tmp_path) + uninstall_payload = install_slash_commands( + execute=True, + uninstall=True, + codex_home=str(home / ".codex"), + opencode_home=str(home / ".config" / "opencode"), + ) + assert uninstall_payload["ok"] is True + assert user_cmd.read_bytes() == before_cmd + assert user_settings.read_bytes() == before_settings + + # 3. Unowned commands/loopx.md and non-UTF-8 settings.json / global registry fail closed cleanly. + user_cmd.write_text("---\ndescription: user custom loopx\n---\n!`echo custom`\n", encoding="utf-8") + custom_cmd_bytes = user_cmd.read_bytes() + user_settings.write_bytes(b"\xff\xfe\x00not-utf8-settings") + corrupt_settings_bytes = user_settings.read_bytes() + (home / ".loopx").mkdir(parents=True, exist_ok=True) + (home / ".loopx" / "registry.global.json").write_bytes(b"\xff\xfe\x00bad-registry") + + default_payload = install_slash_commands( + execute=True, + codex_home=str(home / ".codex"), + opencode_home=str(home / ".config" / "opencode"), + ) + assert default_payload["ok"] is True + assert user_cmd.read_bytes() == custom_cmd_bytes + assert user_settings.read_bytes() == corrupt_settings_bytes + + +def test_claude_legacy_migration_preserves_wrapped_commands_and_reads_v2_envelope( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + import hashlib + import sys + + from loopx.control_plane.projects.registry_codec import ( + SOURCE_SESSION_PROFILE_ID, + SOURCE_SESSION_SCHEMA_VERSION, + SOURCE_SESSION_WRITER_PROTOCOL, + ) + from loopx.hosts.claude.scripts import install as claude_install + + home = tmp_path / "home" + user_claude = home / ".claude" + user_claude.mkdir(parents=True) + proj = tmp_path / "proj-v2" + (proj / ".loopx").mkdir(parents=True) + payload = { + "schema_version": "0.1", + "profile_id": SOURCE_SESSION_PROFILE_ID, + "goals": [{"id": "cc-v2", "repo": str(proj)}], + } + digest = "sha256:" + hashlib.sha256( + json.dumps( + payload, + ensure_ascii=False, + allow_nan=False, + sort_keys=True, + separators=(",", ":"), + ).encode("utf-8") + ).hexdigest() + (proj / ".loopx" / "registry.json").write_text( + json.dumps( + [ + { + "schema_version": SOURCE_SESSION_SCHEMA_VERSION, + "minimum_writer_protocol": SOURCE_SESSION_WRITER_PROTOCOL, + "payload_sha256": digest, + }, + payload, + ], + ensure_ascii=False, + allow_nan=False, + indent=2, + ) + + "\n", + encoding="utf-8", + ) + + proj_claude = proj / ".claude" + proj_claude.mkdir(parents=True) + proj_settings = proj_claude / "settings.json" + proj_settings.write_text( + json.dumps( + { + "hooks": { + "PreToolUse": [ + { + "matcher": "*", + "hooks": [ + { + "type": "command", + "command": ( + "env FOO=bar /old/python3 " + "/opt/old/loopx/claude_goal_mode/hooks/goal_policy.py --flag" + ), + "timeout": 10, + }, + { + "type": "command", + "command": ( + "sh -c 'BAR=\"a b\" /old/python3 -I " + "\"/opt/old/loopx/claude_goal_mode/hooks/goal_policy.py\" --inner'" + ), + }, + ], + } + ] + }, + "statusLine": { + "type": "command", + "command": ( + "env BAZ='x y' /old/python3 -u " + "\"/opt/old/loopx/claude_goal_mode/statusline/goal_status.py\" --compact" + ), + }, + } + ), + encoding="utf-8", + ) + + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("CLAUDE_HOME", str(user_claude)) + monkeypatch.delenv("LOOPX_RUNTIME_ROOT", raising=False) + elsewhere = tmp_path / "elsewhere" + elsewhere.mkdir() + monkeypatch.chdir(elsewhere) + + assert slash_command_install._projects_from_registry_file(proj / ".loopx" / "registry.json") == [proj] + + result = install_slash_commands( + execute=True, + registry_path=str(proj / ".loopx" / "registry.json"), + codex_home=str(home / ".codex"), + opencode_home=str(home / ".config" / "opencode"), + ) + assert result["ok"] is True + + migrated = json.loads(proj_settings.read_text(encoding="utf-8")) + hook_cmds = [h["command"] for h in migrated["hooks"]["PreToolUse"][0]["hooks"]] + assert hook_cmds[0].startswith("env FOO=bar ") + assert "/old/python3" not in hook_cmds[0] + assert sys.executable in hook_cmds[0] + assert "/loopx/hosts/claude/hooks/goal_policy.py" in hook_cmds[0] + assert hook_cmds[0].endswith(" --flag") + + assert "BAR=\"a b\"" in hook_cmds[1] + assert "/loopx/hosts/claude/hooks/goal_policy.py" in hook_cmds[1] + assert hook_cmds[1].endswith("--inner'") + + sl_cmd = migrated["statusLine"]["command"] + assert sl_cmd.startswith("env BAZ='x y' ") + assert " -u " in sl_cmd + assert "/loopx/hosts/claude/statusline/goal_status.py" in sl_cmd + assert sl_cmd.endswith(" --compact") + + # Idempotent after migration. + assert claude_install._migrated_settings_payload(migrated, py_exe=sys.executable) is None + + # PowerShell wrapped command preserves `&`, prefix, and flags. + ps_migrated = claude_install._rewrite_legacy_claude_command( + "& 'C:\\old\\python.exe' 'C:\\old\\loopx\\claude_goal_mode\\hooks\\goal_policy.py' --flag", + legacy_suffix=claude_install._LEGACY_POLICY_HOOK_SUFFIX, + new_script=claude_install._p("hooks", "goal_policy.py"), + py_exe="/new/python.exe", + powershell=True, + ) + assert ps_migrated is not None + assert ps_migrated.startswith("& '/new/python.exe' ") + assert ps_migrated.endswith(" --flag") + assert "& &" not in ps_migrated + + +def test_claude_legacy_migration_command_position_and_operator_boundaries( + tmp_path: Path, +) -> None: + import shlex + import subprocess + import sys + + from loopx.hosts.claude.scripts import install as claude_install + + home = tmp_path / "home" + user_claude = home / ".claude" + user_claude.mkdir(parents=True) + proj = tmp_path / "proj-cmd-pos" + (proj / ".loopx").mkdir(parents=True) + (proj / ".loopx" / "registry.json").write_text( + json.dumps( + { + "schema_version": "0.1", + "goals": [ + { + "id": "cc-pos", + "repo": str(proj), + "coordination": {"agent_model": "peer_v1", "registered_agents": ["cc"]}, + } + ], + } + ), + encoding="utf-8", + ) + runtime_root = home / ".loopx" + runtime_root.mkdir(parents=True) + (runtime_root / "registry.global.json").write_text( + json.dumps( + { + "schema_version": "0.1", + "goals": [ + { + "id": "cc-pos", + "repo": str(proj), + "source_registry": str(proj / ".loopx" / "registry.json"), + } + ], + } + ), + encoding="utf-8", + ) + + legacy_status = "/opt/old dir/loopx/claude_goal_mode/statusline/goal_status.py" + legacy_hook = "/opt/old/loopx/claude_goal_mode/hooks/goal_policy.py" + new_status = claude_install._p("statusline", "goal_status.py") + new_hook = claude_install._p("hooks", "goal_policy.py") + + # Data-argument, query, redirection, and non-script Python invocations stay untouched. + untouched_commands = [ + f"printf '%s\\n' {shlex.quote(legacy_status)}", + f"echo {shlex.quote(legacy_status)}", + f"FOO=1 env BAR=2 printf '%s\\n' {shlex.quote(legacy_status)}", + f"command -v {shlex.quote(legacy_status)}", + f"cat <{shlex.quote(legacy_status)}", + f"echo hi>{shlex.quote(legacy_status)}", + f"/old/python3 -c \"print('{legacy_status}')\"", + f"/old/python3 -m user_tool {shlex.quote(legacy_status)}", + f"/old/python3 /user/custom_tool.py {shlex.quote(legacy_status)}", + f"sh -c 'printf \"%s\\n\" \"{legacy_status}\"'", + f"FOO={shlex.quote(legacy_status)} printf '%s\\n' ok", + ] + for raw in untouched_commands: + assert ( + claude_install._rewrite_legacy_claude_command( + raw, + legacy_suffix=claude_install._LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=new_status, + py_exe=sys.executable, + powershell=False, + ) + is None + ), raw + + # Executed commands right before adjacent unquoted shell operators migrate cleanly. + adjacent_status = f"/old/python3 -u {shlex.quote(legacy_status)}&&echo AFTER_STATUS" + migrated_adj = claude_install._rewrite_legacy_claude_command( + adjacent_status, + legacy_suffix=claude_install._LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=new_status, + py_exe=sys.executable, + powershell=False, + ) + assert migrated_adj is not None + assert migrated_adj.endswith("&&echo AFTER_STATUS") + assert "/old/python3" not in migrated_adj + assert " -u " in migrated_adj + assert new_status in migrated_adj + + # Direct adjacent operator with no interpreter prefix and pipe/semicolon/or-else boundaries. + for sep in ("&&", "||", ";", "|"): + direct_cmd = f"/opt/old{legacy_hook.removeprefix('/opt/old')}{sep}cat" + migrated_direct = claude_install._rewrite_legacy_claude_command( + direct_cmd, + legacy_suffix=claude_install._LEGACY_POLICY_HOOK_SUFFIX, + new_script=new_hook, + py_exe=sys.executable, + powershell=False, + ) + assert migrated_direct is not None, sep + assert migrated_direct.endswith(f"{sep}cat") + assert new_hook in migrated_direct + assert "/claude_goal_mode/" not in migrated_direct + + # Mixed print-then-execute leaves the printed data arg intact and upgrades only the launcher. + print_then_run_adj = f"printf '%s\\n' {shlex.quote(legacy_status)}&&/old/python3 {shlex.quote(legacy_status)}" + migrated_mix = claude_install._rewrite_legacy_claude_command( + print_then_run_adj, + legacy_suffix=claude_install._LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=new_status, + py_exe=sys.executable, + powershell=False, + ) + assert migrated_mix is not None + head_part, tail_part = migrated_mix.split("&&", 1) + assert head_part == f"printf '%s\\n' {shlex.quote(legacy_status)}" + assert "/old/python3" not in tail_part + assert new_status in tail_part + + # Nested sh -c with both print-data segment and adjacent executed launcher. + nested_mix = f"env WRAP=1 sh -ec 'printf \"%s\\n\" \"{legacy_status}\"&&/old/python3 \"{legacy_status}\"'" + migrated_nested = claude_install._rewrite_legacy_claude_command( + nested_mix, + legacy_suffix=claude_install._LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=new_status, + py_exe=sys.executable, + powershell=False, + ) + assert migrated_nested is not None + assert legacy_status in migrated_nested + assert new_status in migrated_nested + assert "/old/python3" not in migrated_nested + + # PowerShell mixed literal arg + executed command keeps literal arg and `&`. + ps_mix = ( + "printf '%s' 'C:\\old\\loopx\\claude_goal_mode\\statusline\\goal_status.py'; " + "& 'C:\\old\\python.exe' 'C:\\old\\loopx\\claude_goal_mode\\statusline\\goal_status.py'" + ) + migrated_ps_mix = claude_install._rewrite_legacy_claude_command( + ps_mix, + legacy_suffix=claude_install._LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=new_status, + py_exe="/new/python.exe", + powershell=True, + ) + assert migrated_ps_mix is not None + assert migrated_ps_mix.startswith( + "printf '%s' 'C:\\old\\loopx\\claude_goal_mode\\statusline\\goal_status.py'; & '/new/python.exe' " + ) + + # Full migrate_legacy_claude_dir + actual /bin/sh execution for print-only, adjacent-&&, and print-then-launch. + env_exec = { + **slash_command_install.os.environ, + "HOME": str(home), + "LOOPX_RUNTIME_ROOT": str(runtime_root), + "LOOPX_GOAL_FORCE": "1", + "PYTHONPATH": str(Path(__file__).resolve().parents[1]), + "PATH": f"{Path(sys.executable).parent}:{slash_command_install.os.environ.get('PATH', '')}", + } + proj_claude = proj / ".claude" + proj_claude.mkdir(parents=True) + (proj_claude / "loop.md").write_text("\n", encoding="utf-8") + proj_settings = proj_claude / "settings.json" + cases = [ + ("print_only", f"printf '%s\\n' {shlex.quote(legacy_status)}", legacy_status, False), + ("adjacent_and", f"/old/python3 {shlex.quote(legacy_status)}&&echo CHAIN_OK", "CHAIN_OK", True), + ( + "print_then_launch", + f"printf '%s\\n' {shlex.quote(legacy_status)}&&/old/python3 {shlex.quote(legacy_status)}", + legacy_status, + True, + ), + ] + for name, raw_cmd, expected_line, expect_status_output in cases: + proj_settings.write_text( + json.dumps({"statusLine": {"type": "command", "command": raw_cmd}}), + encoding="utf-8", + ) + res = claude_install.migrate_legacy_claude_dir(proj_claude, project_dir=proj, execute=True) + if expect_status_output: + assert res == [{"path": str(proj_settings), "status": "updated"}], name + else: + assert res == [], name + updated_cmd = json.loads(proj_settings.read_text(encoding="utf-8"))["statusLine"]["command"] + proc = subprocess.run( + ["/bin/sh", "-c", updated_cmd], + input=json.dumps({"cwd": str(proj)}), + capture_output=True, + text=True, + env=env_exec, + check=False, + ) + assert proc.returncode == 0, f"{name}: {proc.stderr} {proc.stdout}" + assert expected_line in proc.stdout, (name, proc.stdout) + if expect_status_output: + assert "cc-pos" in proc.stdout, (name, proc.stdout) + # Idempotent on repeat run. + assert claude_install.migrate_legacy_claude_dir(proj_claude, project_dir=proj, execute=True) == [] + + +def test_claude_legacy_migration_heredocs_compound_clauses_and_manual_diagnostics( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + import shlex + import subprocess + import sys + + from loopx.hosts.claude.scripts import install as claude_install + + home = tmp_path / "home" + user_claude = home / ".claude" + user_claude.mkdir(parents=True) + proj = tmp_path / "proj-compound" + (proj / ".loopx").mkdir(parents=True) + (proj / ".loopx" / "registry.json").write_text( + json.dumps( + { + "schema_version": "0.1", + "goals": [ + { + "id": "cc-comp", + "repo": str(proj), + "coordination": {"agent_model": "peer_v1", "registered_agents": ["cc"]}, + } + ], + } + ), + encoding="utf-8", + ) + runtime_root = home / ".loopx" + runtime_root.mkdir(parents=True) + (runtime_root / "registry.global.json").write_text( + json.dumps( + { + "schema_version": "0.1", + "goals": [ + { + "id": "cc-comp", + "repo": str(proj), + "source_registry": str(proj / ".loopx" / "registry.json"), + } + ], + } + ), + encoding="utf-8", + ) + + legacy_status = "/opt/old dir/loopx/claude_goal_mode/statusline/goal_status.py" + legacy_hook = "/opt/old/loopx/claude_goal_mode/hooks/goal_policy.py" + new_status = claude_install._p("statusline", "goal_status.py") + new_hook = claude_install._p("hooks", "goal_policy.py") + + # 1. Quoted/tab-stripped here-document bodies remain byte-verbatim (even with unmatched quotes), + # while executable launchers on the header line or after the closing delimiter migrate. + heredoc_only = f"cat <<'EOF'\n{legacy_status}\nEOF" + assert claude_install._inspect_legacy_claude_command( + heredoc_only, + legacy_suffix=claude_install._LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=new_status, + py_exe=sys.executable, + powershell=False, + ) == (None, None) + + heredoc_and_post = ( + f"cat <<'EOF'\n{legacy_status}\nit's raw text\nEOF\n" + f"/old/python3 {shlex.quote(legacy_status)}" + ) + migrated_hd, hd_reason = claude_install._inspect_legacy_claude_command( + heredoc_and_post, + legacy_suffix=claude_install._LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=new_status, + py_exe=sys.executable, + powershell=False, + ) + assert hd_reason is None + assert migrated_hd is not None + hd_prefix, hd_tail = migrated_hd.split("\nEOF\n", 1) + assert hd_prefix == f"cat <<'EOF'\n{legacy_status}\nit's raw text" + assert "/old/python3" not in hd_tail + assert new_status in hd_tail + + tab_heredoc = ( + f"cat <<-EOF && echo ok\n\t{legacy_status}\n\tEOF\n" + f"{legacy_hook}" + ) + migrated_tab = claude_install._rewrite_legacy_claude_command( + tab_heredoc, + legacy_suffix=claude_install._LEGACY_POLICY_HOOK_SUFFIX, + new_script=new_hook, + py_exe=sys.executable, + powershell=False, + ) + assert migrated_tab is not None + assert migrated_tab.startswith(f"cat <<-EOF && echo ok\n\t{legacy_status}\n\tEOF\n") + assert migrated_tab.endswith(shlex.quote(new_hook)) + + # 2. Compound POSIX control clauses migrate executed positions while skipping loop lists, + # case patterns, and quoted keyword literals. + if_cmd = f"if [ -n \"$HOME\" ]; then /old/python3 {shlex.quote(legacy_status)}; fi" + migrated_if = claude_install._rewrite_legacy_claude_command( + if_cmd, + legacy_suffix=claude_install._LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=new_status, + py_exe=sys.executable, + powershell=False, + ) + assert migrated_if is not None + assert migrated_if.startswith("if [ -n \"$HOME\" ]; then ") + assert migrated_if.endswith("; fi") + assert new_status in migrated_if and "/old/python3" not in migrated_if + + elif_else_cmd = ( + f"if {legacy_hook}; then echo a; elif {legacy_hook}; then echo b; " + f"else /old/python3 {legacy_hook}; fi" + ) + migrated_branch = claude_install._rewrite_legacy_claude_command( + elif_else_cmd, + legacy_suffix=claude_install._LEGACY_POLICY_HOOK_SUFFIX, + new_script=new_hook, + py_exe=sys.executable, + powershell=False, + ) + assert migrated_branch is not None + assert "/claude_goal_mode/" not in migrated_branch + assert migrated_branch.count(new_hook) == 3 + + brace_subshell_while = ( + f"while {legacy_hook}; do {{ /old/python3 {legacy_hook}; }}; done && ( {legacy_hook} )" + ) + migrated_complex = claude_install._rewrite_legacy_claude_command( + brace_subshell_while, + legacy_suffix=claude_install._LEGACY_POLICY_HOOK_SUFFIX, + new_script=new_hook, + py_exe=sys.executable, + powershell=False, + ) + assert migrated_complex is not None + assert "/claude_goal_mode/" not in migrated_complex + assert migrated_complex.count(new_hook) == 3 + + # Non-command positions in for/case/quoted-'then' stay intact; case arm body updates. + for_non_exec = f"for s in {shlex.quote(legacy_status)}; do echo \"$s\"; done" + assert claude_install._rewrite_legacy_claude_command( + for_non_exec, + legacy_suffix=claude_install._LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=new_status, + py_exe=sys.executable, + powershell=False, + ) is None + assert claude_install._rewrite_legacy_claude_command( + f"'then' {shlex.quote(legacy_status)}", + legacy_suffix=claude_install._LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=new_status, + py_exe=sys.executable, + powershell=False, + ) is None + + case_cmd = ( + f"case \"$MODE\" in {shlex.quote(legacy_status)}) echo pat;; " + f"run) /old/python3 {shlex.quote(legacy_status)};; esac" + ) + migrated_case = claude_install._rewrite_legacy_claude_command( + case_cmd, + legacy_suffix=claude_install._LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=new_status, + py_exe=sys.executable, + powershell=False, + ) + assert migrated_case is not None + first_arm, second_arm = migrated_case.split(";;", 1) + assert shlex.quote(legacy_status) in first_arm + assert new_status in second_arm and "/old/python3" not in second_arm + + # 3. Execute real migrated heredoc-then-launch and if/then statusLine commands via /bin/sh. + env_exec = { + **slash_command_install.os.environ, + "HOME": str(home), + "LOOPX_RUNTIME_ROOT": str(runtime_root), + "LOOPX_GOAL_FORCE": "1", + "PYTHONPATH": str(Path(__file__).resolve().parents[1]), + "PATH": f"{Path(sys.executable).parent}:{slash_command_install.os.environ.get('PATH', '')}", + } + proj_claude = proj / ".claude" + proj_claude.mkdir(parents=True) + (proj_claude / "loop.md").write_text("\n", encoding="utf-8") + proj_settings = proj_claude / "settings.json" + for label, raw_cmd, expected_verbatim in ( + ("heredoc_then_launch", heredoc_and_post, f"{legacy_status}\nit's raw text\n"), + ("if_then_branch", if_cmd, ""), + ): + proj_settings.write_text( + json.dumps({"statusLine": {"type": "command", "command": raw_cmd}}), + encoding="utf-8", + ) + mig = claude_install.migrate_legacy_claude_dir(proj_claude, project_dir=proj, execute=True) + assert mig == [{"path": str(proj_settings), "status": "updated"}], label + updated_cmd = json.loads(proj_settings.read_text(encoding="utf-8"))["statusLine"]["command"] + proc = subprocess.run( + ["/bin/sh", "-c", updated_cmd], + input=json.dumps({"cwd": str(proj)}), + capture_output=True, + text=True, + env=env_exec, + check=False, + ) + assert proc.returncode == 0, f"{label}: {proc.stderr} {proc.stdout}" + if expected_verbatim: + assert proc.stdout.startswith(expected_verbatim), (label, proc.stdout) + assert "cc-comp" in proc.stdout, (label, proc.stdout) + + # 4. Uncertifiable dynamic syntax (`eval` / `env -S` / unterminated heredoc) stays untouched + # and reports `manual_migration_required` with explicit recovery guidance through install_slash_commands. + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("CLAUDE_HOME", str(user_claude)) + monkeypatch.setenv("LOOPX_RUNTIME_ROOT", str(runtime_root)) + monkeypatch.chdir(tmp_path) + + for bad_cmd in ( + f"eval '/old/python3 {shlex.quote(legacy_status)}'", + f"env -S '/old/python3 {shlex.quote(legacy_status)}'", + f"cat < Path: lambda _: {"apps": [], "status": "not_installed"}, ) monkeypatch.setattr( - "loopx.zcode_goal_mode.diagnostics.collect_zcode_host_diagnostics", + "loopx.hosts.zcode.diagnostics.collect_zcode_host_diagnostics", lambda **kwargs: { "cli": {"status": "not_discovered"}, "desktop": {"status": "not_discovered"}, @@ -230,7 +230,7 @@ def test_selected_host_paths_reach_only_the_zcode_diagnostic_owner( def collect(**kwargs): captured.update(kwargs) return {"synthetic_host_probe": True} - monkeypatch.setattr("loopx.zcode_goal_mode.diagnostics.collect_zcode_host_diagnostics", collect) + monkeypatch.setattr("loopx.hosts.zcode.diagnostics.collect_zcode_host_diagnostics", collect) payload = doctor.collect_doctor( agent_type="z-code", zcode_cli="fixture-cli", zcode_desktop="fixture-desktop", zcode_source="fixture-source", ) diff --git a/tests/test_zcode_goal_bridge.py b/tests/test_zcode_goal_bridge.py index fe32b0a7d3..4d9caeb246 100644 --- a/tests/test_zcode_goal_bridge.py +++ b/tests/test_zcode_goal_bridge.py @@ -9,8 +9,8 @@ import pytest from loopx.control_plane.goals.activation import build_goal_activation -from loopx.zcode_goal_mode import bridge -from loopx.zcode_goal_mode.api import ZCodeGoalRequestMixin, public_zcode_goal_readback +from loopx.hosts.zcode import bridge +from loopx.hosts.zcode.api import ZCodeGoalRequestMixin, public_zcode_goal_readback INSTANCE_A = "ginst_" + "a" * 32 INSTANCE_B = "ginst_" + "b" * 32 @@ -281,7 +281,7 @@ def test_cli_bridge_pins_interpreter_and_scopes_runtime_state(authority, monkeyp assert "--thin" in heartbeat_command assert heartbeat_command[heartbeat_command.index("--runtime-profile") + 1] == "generic_cli" assert native_request["loopx_command"] == [sys.executable, "-m", "loopx.cli"] - assert native_request["validation_command"] == [sys.executable, "-m", "loopx.zcode_goal_mode.bridge", "--validate-binding"] + assert native_request["validation_command"] == [sys.executable, "-m", "loopx.hosts.zcode.bridge", "--validate-binding"] assert native_request["cli_command"] == ["qualified-node", str(cli.resolve()), "app-server"] assert native_request["cli_path"] == str(cli.resolve()) assert Path(native_request["state_path"]).parent == tmp_path / "runtime" / "zcode-goal" @@ -321,7 +321,7 @@ def test_foreign_provider_readback_is_rejected(authority, monkeypatch): def test_internal_binding_guard_runs_on_selected_interpreter(authority): registry, project, payload = authority request = {"action": "start", "registry": str(registry), "project": str(project), "goal_id": "delivery", "agent_id": "zcode-worker", "goal_ref": {"goal_id": "delivery", "goal_instance_id": INSTANCE_A}} - command = [sys.executable, "-X", "utf8", "-B", "-m", "loopx.zcode_goal_mode.bridge", "--validate-binding"] + command = [sys.executable, "-X", "utf8", "-B", "-m", "loopx.hosts.zcode.bridge", "--validate-binding"] valid = subprocess.run(command, input=json.dumps(request), encoding="utf-8", capture_output=True, timeout=15) assert valid.returncode == 0, valid.stderr assert json.loads(valid.stdout)["goal_ref"] == request["goal_ref"] @@ -373,7 +373,7 @@ def test_api_public_projection_keeps_same_session_evidence(): @pytest.mark.parametrize("case", ["remote_server", "foreign_origin", "project_injection", "missing_action", "invalid_cli", "query"]) def test_api_rejects_outside_authority_before_provider(authority, monkeypatch, case): - from loopx.zcode_goal_mode import api + from loopx.hosts.zcode import api registry, _, _ = authority handler = Handler(registry, host="0.0.0.0" if case == "remote_server" else "127.0.0.1", allowed=case != "foreign_origin", body={"action": "bind"}) if case == "project_injection": @@ -413,7 +413,7 @@ def test_api_cannot_borrow_ordinary_project_chat_authority(authority, monkeypatc def test_api_get_and_post_share_canonical_bridge(authority, monkeypatch): - from loopx.zcode_goal_mode import api + from loopx.hosts.zcode import api registry, _, _ = authority seen = [] def operation(**kwargs): @@ -449,7 +449,7 @@ def test_real_chat_http_route_preserves_scoped_readback(authority, monkeypatch): from urllib.request import Request, urlopen from urllib.error import HTTPError from loopx.chat_server import ChatRequestHandler - from loopx.zcode_goal_mode import api + from loopx.hosts.zcode import api registry, _, _ = authority seen = [] def operation(**kwargs): @@ -622,7 +622,7 @@ def test_internal_guard_requires_known_action_and_validates_inactive_cleanup(aut ) registry.write_text(json.dumps(payload), encoding="utf-8") request = {"registry": str(registry), "project": str(project), "goal_id": "delivery", "agent_id": "zcode-worker", "goal_ref": {"goal_id": "delivery", "goal_instance_id": INSTANCE_A}} - command = [sys.executable, "-X", "utf8", "-B", "-m", "loopx.zcode_goal_mode.bridge", "--validate-binding"] + command = [sys.executable, "-X", "utf8", "-B", "-m", "loopx.hosts.zcode.bridge", "--validate-binding"] def invoke(action): body = dict(request) if action is not None: @@ -673,7 +673,7 @@ def test_stale_expected_binding_rejects_before_any_provider_effect(authority, mo def test_api_mutations_require_readback_expectation(authority, monkeypatch): - from loopx.zcode_goal_mode import api + from loopx.hosts.zcode import api registry, _, _ = authority handler = Handler(registry, body={"action": "start"}) monkeypatch.setattr(api, "zcode_goal_operation", lambda **kwargs: pytest.fail("missing expectation reached provider")) diff --git a/tests/test_zcode_host_diagnostics.py b/tests/test_zcode_host_diagnostics.py index 1ec43cb9fe..1dba919eca 100644 --- a/tests/test_zcode_host_diagnostics.py +++ b/tests/test_zcode_host_diagnostics.py @@ -9,7 +9,7 @@ import pytest -from loopx.zcode_goal_mode import diagnostics +from loopx.hosts.zcode import diagnostics # Independent syntax examples, not a snapshot of one installed release. diff --git a/tests/test_zcode_host_surface.py b/tests/test_zcode_host_surface.py index a08633f938..21044fe0a2 100644 --- a/tests/test_zcode_host_surface.py +++ b/tests/test_zcode_host_surface.py @@ -28,7 +28,7 @@ scheduler_command_binding_for_agent_type, ) from loopx.slash_command_install import install_slash_commands -from loopx.zcode_goal_mode import ZCODE_HOME_ENV, zcode_home +from loopx.hosts.zcode import ZCODE_HOME_ENV, zcode_home HOST_SURFACE = "zcode" diff --git a/tsconfig.control-plane.json b/tsconfig.control-plane.json index dc1b69abfb..9a45ec3d07 100644 --- a/tsconfig.control-plane.json +++ b/tsconfig.control-plane.json @@ -16,7 +16,7 @@ "loopx/control_plane/**/*.ts", "tests/control_plane_ts/session_binding.test.ts", "tests/control_plane_ts/host_failure_policy.test.ts", - "loopx/zcode_goal_mode/**/*.ts", + "loopx/hosts/zcode/**/*.ts", "tests/control_plane_ts/background_services.test.ts", "tests/control_plane_ts/explore_research.test.ts", "tests/control_plane_ts/explore_research_execution.test.ts",