From 581d7d1bc4444e9de7b0e3ea730bf6c4c60a2ea6 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:20:45 +0800 Subject: [PATCH 1/5] refactor(hosts): consolidate claude, kunluncode, and zcode packages under loopx/hosts Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- README.ja.md | 4 +- README.md | 4 +- README.zh-CN.md | 2 +- .../dashboard/src/data/zcode-goal.ts | 2 +- .../personal-workspace/zcode-goal-control.tsx | 2 +- ...ng-execution-exploration-and-correction.md | 10 +-- ...cution-exploration-and-correction.zh-CN.md | 10 +-- .../rfcs/agent-session-execution-modes-v0.md | 2 +- .../agent-session-execution-modes-v0.zh-CN.md | 2 +- .../rfcs/loopx-overall-roadmap-v0.md | 12 +-- .../rfcs/loopx-overall-roadmap-v0.zh-CN.md | 10 +-- .../semantic-vocabulary-convergence-v0.md | 4 +- ...emantic-vocabulary-convergence-v0.zh-CN.md | 4 +- docs/book/chapters/00-reading-guide.md | 4 +- docs/book/en/chapters/00-reading-guide.md | 4 +- docs/development/testing-and-quality.md | 2 +- examples/claude-goalmode-hook-policy-smoke.py | 2 +- examples/claude-goalmode-lifecycle-smoke.py | 2 +- ...claude-install-no-system-mutation-smoke.py | 4 +- examples/claude-install-optin-smoke.py | 2 +- .../kunluncode-app-server-goal-pro-smoke.py | 2 +- .../zcode-shared-off-probe.py | 2 +- loopx/chat_server.py | 2 +- loopx/cli_commands/zcode_goal.py | 2 +- loopx/cli_runtime.py | 2 +- loopx/control_plane/status/collection.py | 2 +- loopx/doctor.py | 6 +- loopx/goal_mode_mcp.py | 2 +- loopx/host_loop_activation.py | 2 +- .../claude}/.claude-plugin/plugin.json | 0 .../claude}/README.md | 10 +-- .../claude}/__init__.py | 0 .../claude}/commands/loopx.md | 0 .../claude}/hooks/goal_policy.py | 0 .../claude}/hooks/goal_state.py | 2 +- .../claude}/hooks/hooks.json | 0 .../claude}/hooks/stdio_utf8.py | 0 .../claude}/mcp/loopx_mcp.py | 2 +- .../claude}/scripts/connect.py | 9 +- .../claude}/scripts/goalmode_cmd.py | 0 .../claude}/scripts/install.py | 4 +- .../claude}/settings.example.json | 2 +- .../claude}/statusline/goal_status.py | 0 .../kunluncode}/README.md | 0 .../kunluncode}/__init__.py | 0 .../kunluncode}/app_server.py | 0 .../kunluncode}/cli.py | 16 ++-- .../kunluncode}/context.py | 0 .../kunluncode}/control_plane.py | 0 .../kunluncode}/guards.py | 0 .../kunluncode}/runtime.py | 6 +- .../kunluncode}/server.py | 4 +- loopx/hosts/skill_facade.py | 2 +- .../zcode}/README.md | 0 .../zcode}/__init__.py | 0 loopx/{zcode_goal_mode => hosts/zcode}/api.py | 4 +- .../zcode}/app-server.ts | 0 .../zcode}/bridge.py | 24 ++--- loopx/{zcode_goal_mode => hosts/zcode}/cli.ts | 8 +- .../zcode}/contract.json | 0 .../zcode}/contract.ts | 0 .../zcode}/diagnostics.py | 0 .../{zcode_goal_mode => hosts/zcode}/guard.ts | 0 .../zcode}/images/native-error-mobile.png | Bin .../zcode}/images/native-quota-desktop.png | Bin .../zcode}/runtime.ts | 6 +- loopx/presentation/chat_bundle.py | 4 +- .../goal_instance_binding_inventory_v1.json | 2 +- loopx/slash_command_install.py | 6 +- .../dsh-loopx-plugin/src/managed-runtime.ts | 2 +- pyproject.toml | 7 +- scripts/ci/test_impact_plan.py | 3 +- scripts/install-local.sh | 4 +- scripts/qualify-claude-goal-release.py | 4 +- .../test_source_session_registry_denial.py | 4 +- .../test_source_session_lifetime.py | 2 +- .../test_machine_guard_context_contract.py | 6 +- .../test_replan_context_evidence.py | 2 +- .../content_digest_single_owner.test.ts | 4 +- .../control_plane_ts/zcode_app_server.test.ts | 2 +- tests/control_plane_ts/zcode_guard.test.ts | 4 +- .../zcode_native_goal.test.ts | 8 +- tests/presentation/test_chat_bundle.py | 2 +- tests/test_atomic_write_modes.py | 2 +- tests/test_audit_cli_and_runtime_fixes.py | 2 +- ...laude_goal_harden_settings_preservation.py | 2 +- ...est_claude_goal_install_python_launcher.py | 2 +- .../test_claude_goal_mode_hook_fail_closed.py | 4 +- tests/test_claude_goal_mode_stdio_utf8.py | 6 +- .../test_claude_goal_release_qualification.py | 6 +- tests/test_host_vision_recovery.py | 2 +- ...st_hosts_goal_mode_batch2_consolidation.py | 83 ++++++++++++++++++ tests/test_kunluncode_goal_mode.py | 16 ++-- tests/test_runtime_subprocess_utf8.py | 2 +- .../test_slash_command_install_equivalence.py | 11 ++- tests/test_zcode_doctor_skill_delivery.py | 4 +- tests/test_zcode_goal_bridge.py | 18 ++-- tests/test_zcode_host_diagnostics.py | 2 +- tests/test_zcode_host_surface.py | 2 +- tsconfig.control-plane.json | 2 +- 100 files changed, 268 insertions(+), 173 deletions(-) rename loopx/{claude_goal_mode => hosts/claude}/.claude-plugin/plugin.json (100%) rename loopx/{claude_goal_mode => hosts/claude}/README.md (94%) rename loopx/{claude_goal_mode => hosts/claude}/__init__.py (100%) rename loopx/{claude_goal_mode => hosts/claude}/commands/loopx.md (100%) rename loopx/{claude_goal_mode => hosts/claude}/hooks/goal_policy.py (100%) rename loopx/{claude_goal_mode => hosts/claude}/hooks/goal_state.py (98%) rename loopx/{claude_goal_mode => hosts/claude}/hooks/hooks.json (100%) rename loopx/{claude_goal_mode => hosts/claude}/hooks/stdio_utf8.py (100%) rename loopx/{claude_goal_mode => hosts/claude}/mcp/loopx_mcp.py (95%) rename loopx/{claude_goal_mode => hosts/claude}/scripts/connect.py (95%) rename loopx/{claude_goal_mode => hosts/claude}/scripts/goalmode_cmd.py (100%) rename loopx/{claude_goal_mode => hosts/claude}/scripts/install.py (99%) rename loopx/{claude_goal_mode => hosts/claude}/settings.example.json (81%) rename loopx/{claude_goal_mode => hosts/claude}/statusline/goal_status.py (100%) rename loopx/{kunluncode_goal_mode => hosts/kunluncode}/README.md (100%) rename loopx/{kunluncode_goal_mode => hosts/kunluncode}/__init__.py (100%) rename loopx/{kunluncode_goal_mode => hosts/kunluncode}/app_server.py (100%) rename loopx/{kunluncode_goal_mode => hosts/kunluncode}/cli.py (97%) rename loopx/{kunluncode_goal_mode => hosts/kunluncode}/context.py (100%) rename loopx/{kunluncode_goal_mode => hosts/kunluncode}/control_plane.py (100%) rename loopx/{kunluncode_goal_mode => hosts/kunluncode}/guards.py (100%) rename loopx/{kunluncode_goal_mode => hosts/kunluncode}/runtime.py (99%) rename loopx/{kunluncode_goal_mode => hosts/kunluncode}/server.py (80%) rename loopx/{zcode_goal_mode => hosts/zcode}/README.md (100%) rename loopx/{zcode_goal_mode => hosts/zcode}/__init__.py (100%) rename loopx/{zcode_goal_mode => hosts/zcode}/api.py (98%) rename loopx/{zcode_goal_mode => hosts/zcode}/app-server.ts (100%) rename loopx/{zcode_goal_mode => hosts/zcode}/bridge.py (95%) rename loopx/{zcode_goal_mode => hosts/zcode}/cli.ts (98%) rename loopx/{zcode_goal_mode => hosts/zcode}/contract.json (100%) rename loopx/{zcode_goal_mode => hosts/zcode}/contract.ts (100%) rename loopx/{zcode_goal_mode => hosts/zcode}/diagnostics.py (100%) rename loopx/{zcode_goal_mode => hosts/zcode}/guard.ts (100%) rename loopx/{zcode_goal_mode => hosts/zcode}/images/native-error-mobile.png (100%) rename loopx/{zcode_goal_mode => hosts/zcode}/images/native-quota-desktop.png (100%) rename loopx/{zcode_goal_mode => hosts/zcode}/runtime.ts (98%) create mode 100644 tests/test_hosts_goal_mode_batch2_consolidation.py 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/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/claude_goal_mode/scripts/install.py b/loopx/hosts/claude/scripts/install.py similarity index 99% rename from loopx/claude_goal_mode/scripts/install.py rename to loopx/hosts/claude/scripts/install.py index 4aa8d8a5b9..09786adf21 100644 --- a/loopx/claude_goal_mode/scripts/install.py +++ b/loopx/hosts/claude/scripts/install.py @@ -33,9 +33,9 @@ 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/ +# 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[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/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..be4930ce6d 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 @@ -151,7 +151,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("/loopx/hosts/kunluncode/server.py") ) 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..6eb819b992 100644 --- a/loopx/slash_command_install.py +++ b/loopx/slash_command_install.py @@ -48,7 +48,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 +601,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,7 +636,7 @@ 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"))) 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..c8bb424bb1 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", @@ -76,7 +76,6 @@ def test_backend_mixed_and_full_risk_tiering(self): "packages/loopx-core/prepare.py", "unknown"): with self.subTest(full_path=path): self.assertEqual(candidate([Change("M", path)])[0], "full") - self.assertEqual(candidate([Change("M", "loopx/web/chat/index.html"), Change("M", path)])[0], "full") def test_invalid_empty_and_non_pr_are_full(self): for changes in ([], [Change("T", "docs/a.md")], [Change("M", "docs/../code.md")], 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..1de5f10e56 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/**"], } 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_equivalence.py b/tests/test_slash_command_install_equivalence.py index 136afe5833..ee49bab4aa 100644 --- a/tests/test_slash_command_install_equivalence.py +++ b/tests/test_slash_command_install_equivalence.py @@ -46,8 +46,17 @@ def _load_baseline_module( module = ModuleType("loopx._baseline_slash_command_install") module.__file__ = str(REPOSITORY_ROOT / relpath) module.__package__ = "loopx" + # Historical commit e5d5945f6 imported zcode_goal_mode and claude_goal_mode + # before those packages moved under loopx/hosts/. + compiled_source = ( + source.replace("from .zcode_goal_mode", "from .hosts.zcode") + .replace("from loopx.claude_goal_mode", "from loopx.hosts.claude") + .replace("from .claude_goal_mode", "from .hosts.claude") + if source_override is None + else source + ) try: - code = compile(source, f"{commit}:{relpath}", "exec") + code = compile(compiled_source, f"{commit}:{relpath}", "exec") exec(code, module.__dict__) except Exception as exc: raise RuntimeError( diff --git a/tests/test_zcode_doctor_skill_delivery.py b/tests/test_zcode_doctor_skill_delivery.py index 1d1f62c22d..f813d7aa1d 100644 --- a/tests/test_zcode_doctor_skill_delivery.py +++ b/tests/test_zcode_doctor_skill_delivery.py @@ -47,7 +47,7 @@ def doctor_context(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> 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", From bfd1e3bb521dbc58d01faa4d11dbba7efaf2806d Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 27 Nov 2026 03:39:18 +0800 Subject: [PATCH 2/5] fix(hosts): preserve Claude and KunlunCode upgrade paths and restore CI assertion Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/cli_commands/slash_commands.py | 7 + loopx/hosts/claude/scripts/install.py | 217 ++++++++++++++++++- loopx/hosts/kunluncode/cli.py | 8 +- loopx/slash_command_install.py | 145 +++++++++++++ scripts/ci/test_impact_plan.py | 1 + tests/test_kunluncode_goal_mode.py | 86 ++++++++ tests/test_slash_command_install.py | 289 ++++++++++++++++++++++++++ 7 files changed, 751 insertions(+), 2 deletions(-) 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/hosts/claude/scripts/install.py b/loopx/hosts/claude/scripts/install.py index 09786adf21..4a0d51756e 100644 --- a/loopx/hosts/claude/scripts/install.py +++ b/loopx/hosts/claude/scripts/install.py @@ -24,6 +24,7 @@ import argparse import json import os +import re import shlex import shutil import subprocess @@ -39,7 +40,7 @@ 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 +from loopx.file_lock import write_bytes_atomic, write_json_atomic # noqa: E402 def _p(*parts: str) -> str: @@ -521,5 +522,219 @@ def main() -> int: 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 + + +def _migrated_settings_payload(raw_data: dict[str, Any], *, py_exe: str) -> dict[str, Any] | None: + powershell = _uses_powershell() + py_cmd = _shell_command(py_exe, powershell=powershell) + gate_literal = _shell_literal(_p("hooks", "goal_policy.py"), powershell=powershell) + status_literal = _shell_literal(_p("statusline", "goal_status.py"), powershell=powershell) + updated: dict[str, Any] = dict(raw_data) + changed = False + + 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 _LEGACY_POLICY_HOOK_SUFFIX + in str(item.get("command", "")).replace("\\", "/") + ): + new_item = dict(item) + new_item["command"] = f"{py_cmd} {gate_literal}" + new_group_hooks.append(new_item) + group_changed = True + else: + 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 _LEGACY_STATUSLINE_SCRIPT_SUFFIX + in str(sl_obj.get("command", "")).replace("\\", "/") + ): + new_sl = dict(sl_obj) + new_sl["command"] = f"{py_cmd} {status_literal}" + updated["statusLine"] = new_sl + changed = True + + return updated if changed else None + + +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 = ( + _migrated_settings_payload(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 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/hosts/kunluncode/cli.py b/loopx/hosts/kunluncode/cli.py index be4930ce6d..6052ea5c1b 100644 --- a/loopx/hosts/kunluncode/cli.py +++ b/loopx/hosts/kunluncode/cli.py @@ -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/hosts/kunluncode/server.py") + .endswith(_MANAGED_MCP_SCRIPT_SUFFIXES) ) diff --git a/loopx/slash_command_install.py b/loopx/slash_command_install.py index 6eb819b992..3504ccd789 100644 --- a/loopx/slash_command_install.py +++ b/loopx/slash_command_install.py @@ -1,12 +1,14 @@ from __future__ import annotations import contextlib +import json import os import re import sys 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, @@ -642,6 +644,138 @@ def _loopx_mcp_command() -> tuple[str, str] | 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: + payload_obj: object = json.loads(registry_file.read_text(encoding="utf-8")) + 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, +) -> 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, + ): + 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 +971,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( @@ -907,6 +1043,15 @@ 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, + ) if "gemini" in effective_surfaces: # Gemini CLI discovers user skills from GEMINI_HOME/skills. Files are diff --git a/scripts/ci/test_impact_plan.py b/scripts/ci/test_impact_plan.py index c8bb424bb1..6bca8179fd 100644 --- a/scripts/ci/test_impact_plan.py +++ b/scripts/ci/test_impact_plan.py @@ -76,6 +76,7 @@ def test_backend_mixed_and_full_risk_tiering(self): "packages/loopx-core/prepare.py", "unknown"): with self.subTest(full_path=path): self.assertEqual(candidate([Change("M", path)])[0], "full") + self.assertEqual(candidate([Change("M", "loopx/web/chat/index.html"), Change("M", path)])[0], "full") def test_invalid_empty_and_non_pr_are_full(self): for changes in ([], [Change("T", "docs/a.md")], [Change("M", "docs/../code.md")], diff --git a/tests/test_kunluncode_goal_mode.py b/tests/test_kunluncode_goal_mode.py index 1de5f10e56..d1b349da74 100644 --- a/tests/test_kunluncode_goal_mode.py +++ b/tests/test_kunluncode_goal_mode.py @@ -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_slash_command_install.py b/tests/test_slash_command_install.py index 6523d5c8b0..369ef482d7 100644 --- a/tests/test_slash_command_install.py +++ b/tests/test_slash_command_install.py @@ -1388,3 +1388,292 @@ 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 From b1b3f51f71c64c65bc1ce90bca3b23d5efc9eb6d Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 27 Nov 2026 04:40:56 +0800 Subject: [PATCH 3/5] fix(hosts): use registry codec and preserve wrapped Claude hooks Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/hosts/claude/scripts/install.py | 212 +++++++++++++++++++++++--- loopx/slash_command_install.py | 7 +- tests/test_slash_command_install.py | 145 ++++++++++++++++++ 3 files changed, 339 insertions(+), 25 deletions(-) diff --git a/loopx/hosts/claude/scripts/install.py b/loopx/hosts/claude/scripts/install.py index 4a0d51756e..5173835a04 100644 --- a/loopx/hosts/claude/scripts/install.py +++ b/loopx/hosts/claude/scripts/install.py @@ -566,11 +566,169 @@ def _migrated_command_md_text(raw: str, *, py_exe: str) -> str | None: 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"} +) + + +def _tokenize_shell_spans( + raw_command: str, *, powershell: bool +) -> list[tuple[int, int, str]]: + """Return `(start, end, unquoted)` spans without rewriting surrounding tokens.""" + n = len(raw_command) + i = 0 + tokens: list[tuple[int, int, str]] = [] + while i < n: + while i < n and raw_command[i].isspace(): + i += 1 + if i >= n: + break + start = i + buf: list[str] = [] + while i < n and not raw_command[i].isspace(): + 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 [] + 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 [] + i += 1 + elif ( + ch == "\\" + and not powershell + and i + 1 < n + and (raw_command[i + 1].isspace() or raw_command[i + 1] in {"'", '"', "\\"}) + ): + i += 1 + buf.append(raw_command[i]) + i += 1 + else: + buf.append(ch) + i += 1 + tokens.append((start, i, "".join(buf))) + 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 _rewrite_legacy_claude_command( + raw_command: str, + *, + legacy_suffix: str, + new_script: str, + py_exe: str, + powershell: bool, +) -> str | None: + """Upgrade a legacy Claude hook/statusline path while keeping wrappers and flags.""" + if legacy_suffix not in raw_command.replace("\\", "/"): + return None + tokens = _tokenize_shell_spans(raw_command, powershell=powershell) + if not tokens: + return None + + script_idx: int | None = None + for index, (start, _end, unquoted) in enumerate(tokens): + normalized = unquoted.replace("\\", "/") + if not normalized.startswith("-") and normalized.endswith(legacy_suffix): + script_idx = index + break + if ( + index >= 1 + and tokens[index - 1][2] in {"-c", "-lc"} + and raw_command[start] in {"'", '"'} + and legacy_suffix in normalized + ): + inner = _rewrite_legacy_claude_command( + unquoted, + legacy_suffix=legacy_suffix, + new_script=new_script, + py_exe=py_exe, + powershell=False, + ) + if inner is None: + return None + literal = _shell_literal(inner, powershell=powershell) + return raw_command[:start] + literal + raw_command[tokens[index][1] :] + if script_idx is None: + return None + + py_idx: int | None = None + probe_idx = script_idx - 1 + while probe_idx >= 0 and tokens[probe_idx][2] in _PYTHON_PASSTHROUGH_FLAGS: + probe_idx -= 1 + if probe_idx >= 0 and _looks_like_python_token(tokens[probe_idx][2]): + py_idx = probe_idx + + script_start, script_end, _ = tokens[script_idx] + script_literal = _shell_literal(new_script, powershell=powershell) + edits: list[tuple[int, int, str]] = [] + if py_idx is not None: + py_start, py_end, _ = tokens[py_idx] + needs_ps_call = powershell and ( + py_idx == 0 or tokens[py_idx - 1][2] in {";", "&&", "||", "|"} + ) + py_replacement = ( + _shell_command(py_exe, powershell=True) + if needs_ps_call + else _shell_literal(py_exe, powershell=powershell) + ) + edits.append((script_start, script_end, script_literal)) + edits.append((py_start, py_end, py_replacement)) + else: + needs_ps_call = powershell and ( + script_idx == 0 or tokens[script_idx - 1][2] in {";", "&&", "||", "|"} + ) + py_replacement = ( + _shell_command(py_exe, powershell=True) + if needs_ps_call + else _shell_literal(py_exe, powershell=powershell) + ) + edits.append((script_start, script_end, f"{py_replacement} {script_literal}")) + + updated = raw_command + for start, end, replacement in edits: + updated = updated[:start] + replacement + updated[end:] + return updated if updated != raw_command else None + + def _migrated_settings_payload(raw_data: dict[str, Any], *, py_exe: str) -> dict[str, Any] | None: powershell = _uses_powershell() - py_cmd = _shell_command(py_exe, powershell=powershell) - gate_literal = _shell_literal(_p("hooks", "goal_policy.py"), powershell=powershell) - status_literal = _shell_literal(_p("statusline", "goal_status.py"), powershell=powershell) + gate_script = _p("hooks", "goal_policy.py") + status_script = _p("statusline", "goal_status.py") updated: dict[str, Any] = dict(raw_data) changed = False @@ -591,17 +749,21 @@ def _migrated_settings_payload(raw_data: dict[str, Any], *, py_exe: str) -> dict new_group_hooks: list[Any] = [] group_changed = False for item in group_hooks: - if ( - isinstance(item, dict) - and _LEGACY_POLICY_HOOK_SUFFIX - in str(item.get("command", "")).replace("\\", "/") - ): - new_item = dict(item) - new_item["command"] = f"{py_cmd} {gate_literal}" - new_group_hooks.append(new_item) - group_changed = True - else: - new_group_hooks.append(item) + if isinstance(item, dict) and isinstance(item.get("command"), str): + migrated_cmd = _rewrite_legacy_claude_command( + item["command"], + legacy_suffix=_LEGACY_POLICY_HOOK_SUFFIX, + new_script=gate_script, + py_exe=py_exe, + powershell=powershell, + ) + 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 @@ -616,15 +778,19 @@ def _migrated_settings_payload(raw_data: dict[str, Any], *, py_exe: str) -> dict changed = True sl_obj = raw_data.get("statusLine") - if ( - isinstance(sl_obj, dict) - and _LEGACY_STATUSLINE_SCRIPT_SUFFIX - in str(sl_obj.get("command", "")).replace("\\", "/") - ): - new_sl = dict(sl_obj) - new_sl["command"] = f"{py_cmd} {status_literal}" - updated["statusLine"] = new_sl - changed = True + if isinstance(sl_obj, dict) and isinstance(sl_obj.get("command"), str): + migrated_sl = _rewrite_legacy_claude_command( + sl_obj["command"], + legacy_suffix=_LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=status_script, + py_exe=py_exe, + powershell=powershell, + ) + 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 diff --git a/loopx/slash_command_install.py b/loopx/slash_command_install.py index 3504ccd789..7697e35506 100644 --- a/loopx/slash_command_install.py +++ b/loopx/slash_command_install.py @@ -1,7 +1,6 @@ from __future__ import annotations import contextlib -import json import os import re import sys @@ -657,7 +656,11 @@ def _projects_from_registry_file(registry_file: Path) -> list[Path]: if not registry_file.is_file(): return [] try: - payload_obj: object = json.loads(registry_file.read_text(encoding="utf-8")) + 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): diff --git a/tests/test_slash_command_install.py b/tests/test_slash_command_install.py index 369ef482d7..7d388c2f52 100644 --- a/tests/test_slash_command_install.py +++ b/tests/test_slash_command_install.py @@ -1677,3 +1677,148 @@ def test_claude_legacy_migration_skips_targeted_uninstall_and_unowned_or_corrupt 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 From bd711a7df78b3804d9afd08d571d5f6e342d65cf Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 27 Nov 2026 05:45:03 +0800 Subject: [PATCH 4/5] fix(hosts): tokenize unquoted shell operators and match command-position Claude launchers Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/hosts/claude/scripts/install.py | 406 ++++++++++++++++++++++---- tests/test_slash_command_install.py | 204 +++++++++++++ 2 files changed, 548 insertions(+), 62 deletions(-) diff --git a/loopx/hosts/claude/scripts/install.py b/loopx/hosts/claude/scripts/install.py index 5173835a04..5cf91fd708 100644 --- a/loopx/hosts/claude/scripts/install.py +++ b/loopx/hosts/claude/scripts/install.py @@ -19,7 +19,7 @@ """ from __future__ import annotations -from typing import Any +from typing import Any, NamedTuple import argparse import json @@ -572,23 +572,73 @@ def _migrated_command_md_text(raw: str, *, py_exe: str) -> str | None: _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"}) + + +class _ShellToken(NamedTuple): + start: int + end: int + unquoted: str + is_operator: bool = False def _tokenize_shell_spans( raw_command: str, *, powershell: bool -) -> list[tuple[int, int, str]]: - """Return `(start, end, unquoted)` spans without rewriting surrounding tokens.""" +) -> list[_ShellToken]: + """Return word and operator tokens with original offsets intact.""" n = len(raw_command) i = 0 - tokens: list[tuple[int, int, str]] = [] + tokens: list[_ShellToken] = [] while i < n: - while i < n and raw_command[i].isspace(): + 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: + tokens.append(_ShellToken(i, i + len(matched_op), matched_op, is_operator=True)) + i += len(matched_op) + continue + start = i buf: list[str] = [] - while i < n and not raw_command[i].isspace(): + 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 @@ -626,7 +676,10 @@ def _tokenize_shell_spans( ch == "\\" and not powershell and i + 1 < n - and (raw_command[i + 1].isspace() or raw_command[i + 1] in {"'", '"', "\\"}) + and ( + raw_command[i + 1].isspace() + or raw_command[i + 1] in {"'", '"', "\\", "|", "&", ";", "(", ")", "<", ">"} + ) ): i += 1 buf.append(raw_command[i]) @@ -634,7 +687,7 @@ def _tokenize_shell_spans( else: buf.append(ch) i += 1 - tokens.append((start, i, "".join(buf))) + tokens.append(_ShellToken(start, i, "".join(buf))) return tokens @@ -645,6 +698,273 @@ def _looks_like_python_token(unquoted: str) -> bool: 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], *, powershell: bool +) -> list[tuple[list[_ShellToken], bool]]: + segments: list[tuple[list[_ShellToken], bool]] = [] + words: list[_ShellToken] = [] + has_ps_call = 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 words: + segments.append((words, has_ps_call)) + words = [] + has_ps_call = False + idx += 1 + continue + words.append(tok) + idx += 1 + if words: + segments.append((words, has_ps_call)) + return segments + + +def _advance_command_wrappers( + words: list[_ShellToken], + *, + raw_command: str, + legacy_suffix: str, + powershell: bool, +) -> int | None: + idx = 0 + while idx < len(words): + if not powershell and _is_unquoted_env_assignment(words[idx], raw_command=raw_command): + idx += 1 + continue + if ( + not powershell + and words[idx].unquoted == "!" + and raw_command[words[idx].start : words[idx].end] == "!" + ): + idx += 1 + continue + if powershell: + break + + cmd_word = words[idx].unquoted + cmd_name = Path(cmd_word.replace("\\", "/")).name.lower() + 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 + 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 + 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 or flag != "-p": + return 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 + if probe > len(words): + return 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 + 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 + if probe >= len(words): + return None + dur = words[probe].unquoted + if dur.startswith("-") or dur.replace("\\", "/").endswith(legacy_suffix): + return None + idx = probe + 1 + continue + break + return idx if idx < len(words) else 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, +) -> list[tuple[int, int, str]]: + cmd_idx = _advance_command_wrappers( + words, + raw_command=raw_command, + legacy_suffix=legacy_suffix, + powershell=powershell, + ) + if cmd_idx is None: + return [] + + cmd_tok = words[cmd_idx] + cmd_name = Path(cmd_tok.unquoted.replace("\\", "/")).name.lower() + 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 [] + inner_tok = words[probe] + if legacy_suffix not in inner_tok.unquoted.replace("\\", "/"): + return [] + inner = _rewrite_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 [] + return [(inner_tok.start, inner_tok.end, _shell_literal(inner, powershell=powershell))] + + 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 [] + if arg in _PYTHON_VALUE_FLAGS: + probe += 2 + if probe > len(words): + return [] + 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("-"): + return [] + break + if probe >= len(words): + return [] + 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), + ] + return [] + + 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}")] + return [] + + def _rewrite_legacy_claude_command( raw_command: str, *, @@ -653,75 +973,37 @@ def _rewrite_legacy_claude_command( py_exe: str, powershell: bool, ) -> str | None: - """Upgrade a legacy Claude hook/statusline path while keeping wrappers and flags.""" + """Upgrade executed legacy Claude hook/statusline commands while keeping wrappers and data args.""" if legacy_suffix not in raw_command.replace("\\", "/"): return None tokens = _tokenize_shell_spans(raw_command, powershell=powershell) if not tokens: return None - script_idx: int | None = None - for index, (start, _end, unquoted) in enumerate(tokens): - normalized = unquoted.replace("\\", "/") - if not normalized.startswith("-") and normalized.endswith(legacy_suffix): - script_idx = index - break - if ( - index >= 1 - and tokens[index - 1][2] in {"-c", "-lc"} - and raw_command[start] in {"'", '"'} - and legacy_suffix in normalized - ): - inner = _rewrite_legacy_claude_command( - unquoted, + edits: list[tuple[int, int, str]] = [] + for words, has_ps_call in _split_command_segments(tokens, powershell=powershell): + edits.extend( + _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=False, + powershell=powershell, ) - if inner is None: - return None - literal = _shell_literal(inner, powershell=powershell) - return raw_command[:start] + literal + raw_command[tokens[index][1] :] - if script_idx is None: - return None - - py_idx: int | None = None - probe_idx = script_idx - 1 - while probe_idx >= 0 and tokens[probe_idx][2] in _PYTHON_PASSTHROUGH_FLAGS: - probe_idx -= 1 - if probe_idx >= 0 and _looks_like_python_token(tokens[probe_idx][2]): - py_idx = probe_idx - - script_start, script_end, _ = tokens[script_idx] - script_literal = _shell_literal(new_script, powershell=powershell) - edits: list[tuple[int, int, str]] = [] - if py_idx is not None: - py_start, py_end, _ = tokens[py_idx] - needs_ps_call = powershell and ( - py_idx == 0 or tokens[py_idx - 1][2] in {";", "&&", "||", "|"} - ) - py_replacement = ( - _shell_command(py_exe, powershell=True) - if needs_ps_call - else _shell_literal(py_exe, powershell=powershell) ) - edits.append((script_start, script_end, script_literal)) - edits.append((py_start, py_end, py_replacement)) - else: - needs_ps_call = powershell and ( - script_idx == 0 or tokens[script_idx - 1][2] in {";", "&&", "||", "|"} - ) - py_replacement = ( - _shell_command(py_exe, powershell=True) - if needs_ps_call - else _shell_literal(py_exe, powershell=powershell) - ) - edits.append((script_start, script_end, f"{py_replacement} {script_literal}")) + if not edits: + return None + 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 updated = updated[:start] + replacement + updated[end:] + last_start = start return updated if updated != raw_command else None diff --git a/tests/test_slash_command_install.py b/tests/test_slash_command_install.py index 7d388c2f52..dfa5e5b7fa 100644 --- a/tests/test_slash_command_install.py +++ b/tests/test_slash_command_install.py @@ -1822,3 +1822,207 @@ def test_claude_legacy_migration_preserves_wrapped_commands_and_reads_v2_envelop 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) == [] From c5b6f14bb1b74a58246f3cc33423cfd2a269d684 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 27 Nov 2026 06:34:41 +0800 Subject: [PATCH 5/5] fix(hosts): preserve here-document bodies and migrate compound Claude control clauses Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/hosts/claude/scripts/install.py | 335 ++++++++++++++++++++------ loopx/slash_command_install.py | 38 ++- tests/test_slash_command_install.py | 248 +++++++++++++++++++ 3 files changed, 537 insertions(+), 84 deletions(-) diff --git a/loopx/hosts/claude/scripts/install.py b/loopx/hosts/claude/scripts/install.py index 5cf91fd708..24acfbc3c0 100644 --- a/loopx/hosts/claude/scripts/install.py +++ b/loopx/hosts/claude/scripts/install.py @@ -604,6 +604,8 @@ def _migrated_command_md_text(raw: str, *, py_exe: str) -> str | None: _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): @@ -613,13 +615,37 @@ class _ShellToken(NamedTuple): 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]: - """Return word and operator tokens with original offsets intact.""" +) -> 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 @@ -632,8 +658,18 @@ def _tokenize_shell_spans( 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 @@ -655,7 +691,7 @@ def _tokenize_shell_spans( buf.append(raw_command[i]) i += 1 if not closed: - return [] + return None elif ch == '"': i += 1 while i < n and raw_command[i] != '"': @@ -670,24 +706,33 @@ def _tokenize_shell_spans( buf.append(raw_command[i]) i += 1 if i >= n: - return [] + return None i += 1 elif ( ch == "\\" and not powershell and i + 1 < n and ( - raw_command[i + 1].isspace() + 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 - tokens.append(_ShellToken(start, i, "".join(buf))) + 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 @@ -709,11 +754,14 @@ def _is_unquoted_env_assignment(token: _ShellToken, *, raw_command: str) -> bool def _split_command_segments( - tokens: list[_ShellToken], *, powershell: bool + 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] @@ -730,15 +778,50 @@ def _split_command_segments( 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: + if words and not (case_depth > 0 and expect_case_pattern): segments.append((words, has_ps_call)) return segments @@ -749,24 +832,31 @@ def _advance_command_wrappers( raw_command: str, legacy_suffix: str, powershell: bool, -) -> int | None: +) -> tuple[int | None, str | None]: idx = 0 while idx < len(words): - if not powershell and _is_unquoted_env_assignment(words[idx], raw_command=raw_command): - idx += 1 - continue - if ( - not powershell - and words[idx].unquoted == "!" - and raw_command[words[idx].start : words[idx].end] == "!" - ): - idx += 1 - continue + 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): @@ -775,7 +865,12 @@ def _advance_command_wrappers( probe += 1 break if arg in {"-S", "--split-string"} or arg.startswith(("-S", "--split-string=")): - return None + 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 @@ -784,14 +879,21 @@ def _advance_command_wrappers( continue break if probe > len(words): - return None + 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 or flag != "-p": - return None + 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 @@ -808,9 +910,14 @@ def _advance_command_wrappers( elif len(flag) > 1 and set(flag[1:]) <= {"c", "l"}: probe += 1 else: - return None + return ( + None, + f"unsupported `exec {flag}` option around legacy Claude command" + if has_legacy_tail + else None, + ) if probe > len(words): - return None + return (None, None) idx = probe continue if cmd_word in {"nohup", "time"} or cmd_name == "nice": @@ -825,7 +932,7 @@ def _advance_command_wrappers( ): probe += 1 if probe > len(words): - return None + return (None, None) idx = probe continue if cmd_name == "timeout": @@ -844,16 +951,21 @@ def _advance_command_wrappers( }: probe += 1 else: - return None + return ( + None, + f"unsupported `timeout {arg}` option around legacy Claude command" + if has_legacy_tail + else None, + ) if probe >= len(words): - return None + return (None, None) dur = words[probe].unquoted if dur.startswith("-") or dur.replace("\\", "/").endswith(legacy_suffix): - return None + return (None, None) idx = probe + 1 continue break - return idx if idx < len(words) else None + return (idx, None) if idx < len(words) else (None, None) def _segment_edits( @@ -865,18 +977,23 @@ def _segment_edits( new_script: str, py_exe: str, powershell: bool, -) -> list[tuple[int, int, str]]: - cmd_idx = _advance_command_wrappers( +) -> 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 [] + 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 @@ -896,11 +1013,11 @@ def _segment_edits( break probe += 1 if not saw_dash_c or probe >= len(words): - return [] + return ([], None) inner_tok = words[probe] if legacy_suffix not in inner_tok.unquoted.replace("\\", "/"): - return [] - inner = _rewrite_legacy_claude_command( + return ([], None) + inner, inner_reason = _inspect_legacy_claude_command( inner_tok.unquoted, legacy_suffix=legacy_suffix, new_script=new_script, @@ -908,8 +1025,8 @@ def _segment_edits( powershell=False, ) if inner is None: - return [] - return [(inner_tok.start, inner_tok.end, _shell_literal(inner, powershell=powershell))] + 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 = ( @@ -924,11 +1041,11 @@ def _segment_edits( while probe < len(words): arg = words[probe].unquoted if arg in _PYTHON_TERMINAL_FLAGS or arg.startswith(("-c", "-m")): - return [] + return ([], None) if arg in _PYTHON_VALUE_FLAGS: probe += 2 if probe > len(words): - return [] + return ([], None) continue if arg.startswith(("-W", "-X", "--check-hash-based-pycs=")): probe += 1 @@ -942,18 +1059,29 @@ def _segment_edits( probe += 1 continue if arg.startswith("-"): - return [] + 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 [] + 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), - ] - return [] + 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 ( @@ -961,58 +1089,87 @@ def _segment_edits( 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}")] - return [] + return ([(cmd_tok.start, cmd_tok.end, f"{py_replacement} {script_literal}")], None) + return ([], None) -def _rewrite_legacy_claude_command( +def _inspect_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.""" +) -> 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 + 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 + return (None, None) edits: list[tuple[int, int, str]] = [] - for words, has_ps_call in _split_command_segments(tokens, powershell=powershell): - edits.extend( - _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, - ) + 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 + 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 + 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 + return (updated if updated != raw_command else None, manual_reason) -def _migrated_settings_payload(raw_data: dict[str, Any], *, py_exe: str) -> dict[str, Any] | None: +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): @@ -1032,13 +1189,15 @@ def _migrated_settings_payload(raw_data: dict[str, Any], *, py_exe: str) -> dict group_changed = False for item in group_hooks: if isinstance(item, dict) and isinstance(item.get("command"), str): - migrated_cmd = _rewrite_legacy_claude_command( + 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 @@ -1061,20 +1220,27 @@ def _migrated_settings_payload(raw_data: dict[str, Any], *, py_exe: str) -> dict sl_obj = raw_data.get("statusLine") if isinstance(sl_obj, dict) and isinstance(sl_obj.get("command"), str): - migrated_sl = _rewrite_legacy_claude_command( + 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 + 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: @@ -1153,10 +1319,10 @@ def resolve_py() -> str: settings_path = claude_dir / "settings.json" if settings_path.is_file(): raw_settings = _read_json_dict_fail_closed(settings_path) - updated_settings = ( - _migrated_settings_payload(raw_settings, py_exe=resolve_py()) + updated_settings, manual_reasons = ( + _inspect_settings_migration(raw_settings, py_exe=resolve_py()) if raw_settings is not None - else None + else (None, []) ) if updated_settings is not None: if execute: @@ -1166,6 +1332,25 @@ def resolve_py() -> str: 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" diff --git a/loopx/slash_command_install.py b/loopx/slash_command_install.py index 7697e35506..13636fd911 100644 --- a/loopx/slash_command_install.py +++ b/loopx/slash_command_install.py @@ -751,6 +751,7 @@ def _migrate_legacy_claude_configs( 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 @@ -767,16 +768,32 @@ def _migrate_legacy_claude_configs( project_dir=proj_dir, execute=execute, ): - 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"], + 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: @@ -1003,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( @@ -1054,6 +1072,7 @@ def install_slash_commands( registry_path=registry_path, runtime_root=runtime_root, execute=execute, + extra_notes=migration_notes, ) if "gemini" in effective_surfaces: @@ -1328,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/tests/test_slash_command_install.py b/tests/test_slash_command_install.py index dfa5e5b7fa..596b722c39 100644 --- a/tests/test_slash_command_install.py +++ b/tests/test_slash_command_install.py @@ -2026,3 +2026,251 @@ def test_claude_legacy_migration_command_position_and_operator_boundaries( 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 <