diff --git a/README.ja.md b/README.ja.md index 386c087b7c..451a7ead69 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/hosts/kiro_cli/README.md)、または [DeepSeek Harness のターンアダプター](loopx/hosts/dsh/README.md)を確認できます。 diff --git a/README.md b/README.md index 14a89ffce2..aef21f81d0 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/hosts/kiro_cli/README.md), or the [DeepSeek Harness turn adapter](loopx/hosts/dsh/README.md). diff --git a/README.zh-CN.md b/README.zh-CN.md index ce0f196c8c..fa798fa7cd 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/hosts/kiro_cli/README.md),以及 [DeepSeek Harness turn adapter](loopx/hosts/dsh/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 7a555c6a7d..3aab523314 100644 --- a/docs/architecture/rfcs/loopx-overall-roadmap-v0.md +++ b/docs/architecture/rfcs/loopx-overall-roadmap-v0.md @@ -190,10 +190,10 @@ top-level packages: fence fidelity—never claiming autonomous execution or budget enforcement a host cannot verify. - **Consolidating `loopx/*_goal_mode/` into `loopx/hosts/`:** migrate the `9` - top-level `loopx/*_goal_mode/` packages (`6` migrated into `loopx/hosts/`: - `hosts/agy`, `hosts/dsh`, `hosts/kiro_cli`, `hosts/opencode`, `hosts/opencode2`, - `hosts/pi`; `3` remaining: `claude_goal_mode`, `kunluncode_goal_mode`, - `zcode_goal_mode`) under shared `HostHarnessCapabilities` projections per + top-level `loopx/*_goal_mode/` packages (`9` migrated into `loopx/hosts/`: + `hosts/agy`, `hosts/claude`, `hosts/dsh`, `hosts/kiro_cli`, `hosts/kunluncode`, + `hosts/opencode`, `hosts/opencode2`, `hosts/pi`, `hosts/zcode`; `0` remaining) + under shared `HostHarnessCapabilities` projections per [the unified contract's retirement gate](controller-executor-unified-contract-v0.md#3-normative-retirement-backlog-and-ratchet-rules) and [`top_level_module_budget.json`](../../../tests/architecture/top_level_module_budget.json), keeping CLI compatibility aliases strictly until caller cutover completes. @@ -470,7 +470,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 5864e2a225..531d0286be 100644 --- a/docs/architecture/rfcs/loopx-overall-roadmap-v0.zh-CN.md +++ b/docs/architecture/rfcs/loopx-overall-roadmap-v0.zh-CN.md @@ -146,9 +146,9 @@ LoopX 的权威与决策基座(`AuthorityStore`、`CAS`、`claim/lease`、`Tur [统一契约的退役门禁](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/` 包迁入 `loopx/hosts/` 并收敛至共享 `HostHarnessCapabilities` - 投影(已迁入 `6` 个:`hosts/agy`、`hosts/dsh`、`hosts/kiro_cli`、`hosts/opencode`、 - `hosts/opencode2`、`hosts/pi`;待迁移 `3` 个:`claude_goal_mode`、`kunluncode_goal_mode`、 - `zcode_goal_mode`),仅在调用方切换完成前保留 CLI 兼容别名。 + 投影(已迁入 `9` 个:`hosts/agy`、`hosts/claude`、`hosts/dsh`、`hosts/kiro_cli`、 + `hosts/kunluncode`、`hosts/opencode`、`hosts/opencode2`、`hosts/pi`、 + `hosts/zcode`;待迁移 `0` 个),仅在调用方切换完成前保留 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 89657c213c..6c58b7a7d8 100644 --- a/docs/book/chapters/00-reading-guide.md +++ b/docs/book/chapters/00-reading-guide.md @@ -257,7 +257,6 @@ live operation 不进入当前主线。需要这些能力时,应回到官方 接入主线只以 Codex App 与 Codex CLI 为例,因为这两条路径可以端到端复现。LoopX 的 agent type 覆盖面更宽:`loopx/host_loop_activation.py` 的 `SUPPORTED_AGENT_TYPES` 列出 21 个类型,其中 9 个 -另有目标模式适配包(`hosts/{agy,dsh,kiro_cli,opencode,opencode2,pi}` 已迁入 `loopx/hosts/`,其余为 -`claude_goal_mode`、`kunluncode_goal_mode`、`zcode_goal_mode` 等)。 +另有目标模式适配包(`hosts/{agy,claude,dsh,kiro_cli,kunluncode,opencode,opencode2,pi,zcode}` 已迁入 `loopx/hosts/`)。 路线选择是教学取舍:其余 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 f17b4a917a..5147d374ae 100644 --- a/docs/book/en/chapters/00-reading-guide.md +++ b/docs/book/en/chapters/00-reading-guide.md @@ -286,7 +286,6 @@ 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 -(`hosts/{agy,dsh,kiro_cli,opencode,opencode2,pi}` consolidated under `loopx/hosts/`, alongside -`claude_goal_mode`, `kunluncode_goal_mode`, `zcode_goal_mode`, and others). Choosing two routes is a teaching +(`hosts/{agy,claude,dsh,kiro_cli,kunluncode,opencode,opencode2,pi,zcode}` consolidated under `loopx/hosts/`). 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 05006513a2..3f78d7bf8e 100644 --- a/docs/development/testing-and-quality.md +++ b/docs/development/testing-and-quality.md @@ -814,7 +814,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 17a585fe0a..146c985548 100644 --- a/loopx/chat_server.py +++ b/loopx/chat_server.py @@ -20,7 +20,7 @@ if TYPE_CHECKING: from .capabilities.native_chat.transports import ChatConversationTransports from .attached_session_api import AttachedSessionRequestMixin -from .zcode_goal_mode.api import ZCodeGoalRequestMixin +from .hosts.zcode.api import ZCodeGoalRequestMixin from .chat import TodoReviewPreviewConflict, redact_local_paths from .chat_agent import CodexChatAgentError from .capabilities.native_chat.project_context import ChatProjectContexts diff --git a/loopx/claude_goal_mode/__init__.py b/loopx/claude_goal_mode/__init__.py index 713bc21932..c5131b1797 100644 --- a/loopx/claude_goal_mode/__init__.py +++ b/loopx/claude_goal_mode/__init__.py @@ -1,49 +1,20 @@ -"""Claude Code adapter for loopx. - -loopx is a deterministic (no-LLM) control plane. On Claude Code the RUN LOOP is -Claude Code's native ``/loop``; loopx provides the control-plane protocol (we do -NOT use ``/goal``, which judges completion from the transcript). Pieces: - -- ``mcp/loopx_mcp.py`` — MCP server: should_run / list_todos / claim_task / - complete_task (the deterministic control plane) -- ``scripts/goalmode_cmd.py`` — the ``/loopx`` setup helper: sets a goal and writes - ``.claude/loop.md`` (the per-iteration protocol that - native ``/loop`` runs each tick) -- ``hooks/goal_state.py`` — registry-driven goal context + "armed" (loop.md) check -- ``hooks/goal_policy.py`` — OPTIONAL PreToolUse should_run gate (opt-in via --harden) -- ``statusline/goal_status.py`` — optional glanceable goal state -- ``scripts/install.py`` — explicit, scoped, opt-in installer (MCP + /loopx [+ --harden]) -- ``scripts/connect.py`` — project-scoped connect + install -- ``plugin`` assets — ``.claude-plugin/plugin.json``, ``commands/loopx.md``, - ``hooks/hooks.json`` (the optional gate) - -The retired benchmark-only baseline contract remains in Git history and is -no longer part of the working tree or a LoopX runtime module. -""" +"""Compatibility shim forwarding ``loopx.claude_goal_mode`` to ``loopx.hosts.claude``.""" from __future__ import annotations -from ..hosts.capabilities import ( - HostHarnessCapabilities, - _register_builtin_host_capabilities, -) - -CLAUDE_HOST_CAPABILITIES: HostHarnessCapabilities = _register_builtin_host_capabilities( - HostHarnessCapabilities( - host_id="claude", - integration_tier="boundary_cli", - adapter_module="loopx.claude_goal_mode", - supported_capabilities=("verifier_hook",), - hook_events=("PreToolUse",), - requires_utf8_stdio=True, - native_goal_primitive=False, - native_scheduler_primitive=True, - description=( - "Claude Code boundary CLI adapter driven by native /loop, MCP " - "control-plane tools, and opt-in PreToolUse should_run/write_scope " - "policy verification." - ), - ) -) - -__all__: list[str] = ["CLAUDE_HOST_CAPABILITIES"] +import importlib + +from loopx.hosts import claude as _target + +_SUBMODULES = frozenset({"hooks", "mcp", "scripts", "statusline"}) +__all__ = list(_target.__all__) + + +def __getattr__(name: str) -> object: + if name in _SUBMODULES: + return importlib.import_module(f"loopx.hosts.claude.{name}") + return getattr(_target, name) + + +def __dir__() -> list[str]: + return sorted(set(dir(_target)) | _SUBMODULES) diff --git a/loopx/claude_goal_mode/hooks/goal_policy.py b/loopx/claude_goal_mode/hooks/goal_policy.py index 293d527dba..9e6c527b7b 100644 --- a/loopx/claude_goal_mode/hooks/goal_policy.py +++ b/loopx/claude_goal_mode/hooks/goal_policy.py @@ -1,295 +1,26 @@ -#!/usr/bin/env python3 -"""PreToolUse policy gate for goal-mode — OPTIONAL deterministic hardening. +"""Compatibility entrypoint forwarding ``loopx.claude_goal_mode.hooks.goal_policy`` to ``loopx.hosts.claude.hooks.goal_policy``.""" -In the native-`/loop` design, Claude Code's `/loop` is the runtime and loopx's -MCP `should_run` is the per-tick gate. This hook is NOT installed by default — -it is opt-in (`install.py --harden` / `connect.py --harden`), project-scoped, and -adds a per-TOOL-CALL gate on top of the loop: - -- should_run gate (fail-closed) -> may the agent spend this turn right now? -- Edit/Write -> write_scope -> deny file edits outside the goal's scope -- Bash -> destructive denylist -> deny obviously dangerous commands - -It only acts in a project where loopx is armed (a `.claude/loop.md` exists). - -Limitation (by design): Bash is gated only by a denylist, so a determined shell -command can still write outside write_scope or reach the network. For STRONG -isolation (untrusted code / unattended high-stakes), run Claude Code inside a dev -container or VM, which contains the whole process at the environment level. - -Behavior (only while goal-mode is ARMED for the event's project): -- no goal here / goal-mode off -> {} (no-op; normal permission flow) -- event unreadable -> deny (FAIL-CLOSED) - (no usable session cwd, no usable tool_name) -- read-only/safe tools -> allow -- non-read-only tool, unreadable event value -> deny (FAIL-CLOSED) - (non-object tool_input, non-string command/file path) -- should_run == false (quota/gate closed) -> deny -- should_run probe unavailable (error) -> deny for non-read-only tools (FAIL-CLOSED) -- should_run == true: - * Edit/Write outside write_scope -> deny - * Edit/Write within write_scope -> allow - * destructive Bash -> deny - * Bash / other -> allow - -Fail-closed: if the deterministic ``should_run`` probe cannot be reached, a -non-read-only tool is denied rather than allowed, so a flaky/broken control -plane pauses delivery instead of running ungated. Read-only tools stay allowed. -An event this hook cannot read joins that rule: ``rc=1`` with no decision is a -non-blocking hook error to Claude Code, which then continues the tool call with -no gate at all, so an unreadable event (undecodable stdin, malformed or -non-object JSON, no session cwd or one that cannot be resolved as a path, no -usable tool name, or - for a non-read-only tool - a non-object ``tool_input`` or -a non-string command/file path field) is answered with an explicit deny instead -of dying. Read-only tools keep their unconditional allow. - -Identity-aware: when the active goal registered an agent (loopx -``coordination.registered_agents``), the context carries ``agent_id`` and this -hook forwards it as ``--agent-id`` to ``loopx quota should-run``. Without it -loopx returns ``automation_prompt_upgrade_required`` and should_run=false — the -Claude Code analogue of Codex's identity-scoped heartbeat prompt. -""" from __future__ import annotations -import json -import os -import shutil -import subprocess -import sys from pathlib import Path +import sys -# Goal context is resolved PER PROJECT from the event's cwd via the registry, and -# "armed" = the project's .claude/loop.md exists (see goal_state.py). The registry -# is the single source of truth; there is no separate active-state file. -from goal_state import active_context -from stdio_utf8 import pin_utf8_stdio - -# Read-only tools are always allowed under goal-mode. Edit/Write are scoped to -# write_scope; Bash is gated by a destructive-command denylist. (No OS sandbox in -# this design — the hook is the whole gate; see the module docstring.) -# NOTE: `Task` is deliberately NOT here. It can launch a subagent that performs -# writes, so allowing it unconditionally would bypass the gate when -# should_run=false. It must go through the gate: denied when should_run=false, -# otherwise deferred to Claude Code's normal permission flow (unknown tool). -READONLY_TOOLS = {"Read", "Glob", "Grep", "NotebookRead", "TodoWrite", "WebFetch", "WebSearch", "ToolSearch"} -WRITE_TOOLS = {"Edit", "Write", "MultiEdit", "NotebookEdit"} -DESTRUCTIVE = ( - "rm -rf", "rm -fr", "mkfs", "dd if=", ":(){", "shutdown", "reboot", - "git push --force", "git reset --hard", "> /dev/sd", "format ", -) -CLAUDE_RUNTIME_PROFILE_ARGS = ["--runtime-profile", "claude_code"] -CLAUDE_LEGACY_SCHEDULER_ARGS = [ - "--host-surface", "claude_code", - "--scheduler-owner", "agent_cli_loop", - "--execution-mode", "interactive", -] - - -def within(path: str, root: str) -> bool: - """True if `path` resolves to `root` or a descendant of it.""" - try: - p = Path(path).resolve() - r = Path(root).resolve() - return r == p or r in p.parents - except Exception: - return False - - -def _usable_cwd(value: str) -> bool: - """True if a decoded session cwd can be resolved as a filesystem path. - - A string can still be unusable as a path: an embedded NUL makes - ``Path.resolve`` raise ``ValueError``, and a lone surrogate raises - ``UnicodeEncodeError`` (a ``ValueError``) against the filesystem encoding. - ``active_context`` must never receive such a value, or the exception escapes - ``decide`` as the rc=1/no-decision hook error the module docstring refuses. - """ - try: - Path(value).resolve() - except (OSError, RuntimeError, ValueError): - return False - return True - - -def _gh_prefix(): - _exe = shutil.which("loopx") - return [_exe] if _exe else [__import__("sys").executable, "-m", "loopx.cli"] - - -def _runtime_profile_flag_is_unsupported(out: subprocess.CompletedProcess) -> bool: - diagnostic = str(out.stderr or "").lower() - return ( - out.returncode == 2 - and "--runtime-profile" in diagnostic - and ( - "unrecognized arguments" in diagnostic - or "invalid choice" in diagnostic - ) - ) - - -def should_run(registry, goal_id, agent_id=None) -> bool | None: - """Return True/False from loopx quota should-run, or None if unknown.""" - if not goal_id: - return None - cmd = list(_gh_prefix()) - if registry: - cmd += ["--registry", registry] - cmd += ["--format", "json", "quota", "should-run", "--goal-id", goal_id] - if agent_id: - cmd += ["--agent-id", agent_id] - try: - out = subprocess.run( - [*cmd, *CLAUDE_RUNTIME_PROFILE_ARGS], - capture_output=True, - text=True, encoding="utf-8", errors="replace", - timeout=10, - env={**os.environ, "LOOPX_CONTEXT_DELIVERY": "off"}, - ) - if _runtime_profile_flag_is_unsupported(out): - out = subprocess.run( - [*cmd, *CLAUDE_LEGACY_SCHEDULER_ARGS], - capture_output=True, - text=True, encoding="utf-8", errors="replace", - timeout=10, - env={**os.environ, "LOOPX_CONTEXT_DELIVERY": "off"}, - ) - except Exception: - return None # caller fails CLOSED on None for non-read-only tools - try: - data = json.loads(out.stdout or "{}") - except (json.JSONDecodeError, TypeError, ValueError): - return None - should_run_value = data.get("should_run") - return should_run_value if isinstance(should_run_value, bool) else None - - -def decide(ev: dict) -> dict: - """Pure policy: given a PreToolUse event, return the hookSpecificOutput dict - (or {} for no-op). Reused by the CLI hook AND the Agent SDK in-process hook. - - The hook is the whole gate (no OS sandbox): should_run (fail-closed) + - Edit/Write write_scope + a destructive-Bash denylist. An event value this - gate cannot use - no usable session cwd or tool name, or a non-object - tool_input / non-string command or file path on a non-read-only tool - is - refused rather than deferred, because the event cannot be classified (the - module docstring states the fail-closed rule).""" - def d(decision, reason): - return {"hookSpecificOutput": { - "hookEventName": "PreToolUse", - "permissionDecision": decision, - "permissionDecisionReason": reason}} - - # Claude Code feeds the session's working directory on the event; resolve the - # goal from THAT project's registry, and gate only while goal-mode is armed - # (the project's .claude/loop.md exists). Unrelated/unarmed projects -> no-op. - cwd = ev.get("cwd") - workspace = ev.get("workspace") - if not isinstance(cwd, str) or not cwd: - cwd = workspace.get("current_dir") if isinstance(workspace, dict) else None - if not isinstance(cwd, str) or not cwd: - # Every real PreToolUse event carries the session cwd. Without one this - # hook cannot tell an armed project from an unrelated one, so it cannot - # decide to stay out of the way: refusing is the same fail-closed rule - # the unreachable-should_run branch below applies. Unreadable events - # (see main) arrive here as an empty dict. - return d("deny", "unreadable PreToolUse event (no session cwd) - failing closed under goal-mode") - if not _usable_cwd(cwd): - # A decoded cwd can still be unusable as a path (embedded NUL, lone - # surrogate, OS-level resolution failure). active_context cannot - # attribute the event to a project then, so the event stays unreadable - # for this gate and is refused instead of raising out of decide. - return d("deny", "unreadable PreToolUse event (session cwd is not a usable path) - failing closed under goal-mode") - - ctx = active_context(cwd) - if not ctx: - return {} # no goal here, or goal-mode off -> defer to normal flow - - goal_id = ctx.get("goal_id") - registry = ctx.get("registry") - agent_id = ctx.get("agent_id") - scope = ctx.get("write_scope") or [] - tool = ev.get("tool_name") - if not isinstance(tool, str) or not tool: - # Every real PreToolUse event names its tool; without a usable name the - # gate cannot apply its read-only/gated classification (and the set - # membership tests below would raise on an unhashable value). - return d("deny", "unreadable PreToolUse event (tool_name is not a usable string) - failing closed under goal-mode") - ti = ev.get("tool_input") - if ti is None: - # Only an absent/null field takes the empty-input default. Other falsy - # values (`[]`, `false`, `0`, `""`) are present non-objects and must - # stay visible to the check below instead of being hidden by `or {}`. - ti = {} - - if tool in READONLY_TOOLS: - return d("allow", "read-only/safe tool under goal-mode") - - if not isinstance(ti, dict): - # A tool_input that is present but not an object cannot be read: refuse - # the non-read-only tool instead of crashing on `ti.get` (same - # fail-closed rule as an unreachable `should_run` probe). - return d("deny", "unreadable PreToolUse event (tool_input is not an object) - failing closed under goal-mode") +if not __package__: + _package_parent = str(Path(__file__).resolve().parents[3]) + if _package_parent not in sys.path: + sys.path.insert(0, _package_parent) - # Every value the gate reads below must be readable before the probe is - # consulted, so an unreadable event is refused whether or not the gate is - # open (an absent/null field keeps its empty default). - if tool in WRITE_TOOLS: - file_path = ti.get("file_path") - notebook_path = ti.get("notebook_path") - if file_path is not None and not isinstance(file_path, str): - return d("deny", "unreadable PreToolUse event (tool_input.file_path is not a string) - failing closed under goal-mode") - if notebook_path is not None and not isinstance(notebook_path, str): - return d("deny", "unreadable PreToolUse event (tool_input.notebook_path is not a string) - failing closed under goal-mode") - elif tool == "Bash": - command = ti.get("command") - if command is not None and not isinstance(command, str): - return d("deny", "unreadable PreToolUse event (tool_input.command is not a string) - failing closed under goal-mode") +from loopx.hosts.claude.hooks import goal_policy as _target # noqa: E402 - sr = should_run(registry, goal_id, agent_id) # True / False / None - if sr is False: - return d("deny", f"goal '{goal_id}' should_run=false (quota/gate closed)") - if sr is None: - # deterministic should_run probe unavailable -> fail closed (non-read-only tool) - return d("deny", "loopx should_run probe unavailable — failing closed under goal-mode") - # should_run == True. Scope the Edit/Write file tools to write_scope, and - # gate Bash with the destructive denylist (the hook is the whole gate). - if tool in WRITE_TOOLS: - fp = ti.get("file_path") or ti.get("notebook_path") or "" - if scope: - if not fp.strip(): - return d( - "deny", - "unreadable PreToolUse event (missing file_path/notebook_path) - failing closed under goal-mode", - ) - resolved_fp = fp if Path(fp).is_absolute() else str(Path(cwd) / fp) - if not any(within(resolved_fp, s) for s in scope): - return d("deny", f"'{fp}' outside goal write_scope {scope}") - return d("allow", "write within goal scope") - if tool == "Bash": - low = (ti.get("command") or "").lower() - if any(tok in low for tok in DESTRUCTIVE): - return d("deny", "destructive command blocked by goal policy") - return d("allow", "bash permitted under goal policy") - return {} # unknown tool: defer to normal flow +def __getattr__(name: str) -> object: + return getattr(_target, name) -def main(): - try: - # `ValueError` also covers `UnicodeDecodeError`: the strict stdin pin - # (stdio_utf8) never repairs a bad byte into a different event, so an - # event that cannot be read becomes the explicit deny in decide() - # instead of a traceback with no decision. - ev = json.loads(sys.stdin.read()) - except ValueError: - ev = {} - if not isinstance(ev, dict): - ev = {} - result = decide(ev) - sys.stdout.write(json.dumps(result) if result else "{}") +def __dir__() -> list[str]: + return sorted(dir(_target)) if __name__ == "__main__": - pin_utf8_stdio() - main() + getattr(_target, "pin_utf8_stdio")() + getattr(_target, "main")() diff --git a/loopx/claude_goal_mode/hooks/goal_state.py b/loopx/claude_goal_mode/hooks/goal_state.py index 1d0668422d..d4c35a102c 100644 --- a/loopx/claude_goal_mode/hooks/goal_state.py +++ b/loopx/claude_goal_mode/hooks/goal_state.py @@ -1,107 +1,21 @@ -#!/usr/bin/env python3 -"""Goal-mode context resolution — registry-driven, mirroring the Codex model. +"""Compatibility shim forwarding ``loopx.claude_goal_mode.hooks.goal_state`` to ``loopx.hosts.claude.hooks.goal_state``.""" -LoopX's registry (``.loopx/registry.json``) is the single source of truth for the -project's goal (goal_id / agent / scope), exactly as on Codex. We resolve it by -walking up from cwd to the nearest ``.loopx/`` (or legacy ``.goal-harness/``) -registry — so two sessions in different projects are independent, and two -sessions in the SAME project share the one goal. - -"Goal-mode ON / armed" for a project = a ``.claude/loop.md`` exists (written by -``/loopx ``). That file is the per-iteration protocol that Claude Code's -native ``/loop`` runs; its presence means loopx is driving this project. The -OPTIONAL PreToolUse hook + statusline gate on this, so they only act where loopx -is actually active. ``LOOPX_GOAL_FORCE=1`` forces armed=true for tests. -""" from __future__ import annotations -import json -import os -import re -import sys from pathlib import Path +import sys -REPO_ROOT = Path(__file__).resolve().parents[3] -if str(REPO_ROOT) not in sys.path: - sys.path.insert(0, str(REPO_ROOT)) - -from loopx.goal_mode_context import ( # noqa: E402 - find_registry as _find_registry, - first_registered_agent, - project_root_for as _project_root_for, - resolve_goal_context, -) - -_ARMED_RE = re.compile(r"") - - -def find_registry(cwd) -> Path | None: - """Nearest ancestor of cwd (inclusive) holding a registry.json, else None.""" - return _find_registry(cwd) - - -def project_root_for(cwd) -> Path | None: - return _project_root_for(cwd) - - -def _agent_of(goal: dict): - return first_registered_agent(goal) - - -def loop_md_path(project_root) -> Path: - return Path(project_root) / ".claude" / "loop.md" - - -def read_armed_goal(project_root) -> dict | None: - """The goal_id/agent_id that `/loopx` armed for THIS project, parsed from the - `loopx:armed` marker it writes at the top of `.claude/loop.md`. None if the - project isn't armed or the marker is absent/unparseable. - - This is what lets goal_context resolve the *armed* goal rather than guessing - by registry order, so a multi-goal repo gates/claims/completes the goal the - user actually set up.""" - if not project_root: - return None - try: - text = loop_md_path(project_root).read_text(encoding="utf-8") - except Exception: - return None - m = _ARMED_RE.search(text) - if not m: - return None - try: - d = json.loads(m.group(1)) - except Exception: - return None - return d if isinstance(d, dict) and d.get("goal_id") else None - - -def goal_context(cwd) -> dict | None: - """The current project's goal, read live from the registry. None if no goal. +if not __package__: + _package_parent = str(Path(__file__).resolve().parents[3]) + if _package_parent not in sys.path: + sys.path.insert(0, _package_parent) - Returns goal_id, registry path, agent_id, write_scope (the goal's repo), and - project_root — everything the hooks / MCP / statusline need. When the project - is armed (`.claude/loop.md` carries a `loopx:armed` marker), the marker's goal - is authoritative; otherwise we fall back to the first registry goal.""" - root = project_root_for(cwd) - armed = read_armed_goal(root) if root else None - return resolve_goal_context( - cwd, - preferred_goal_id=str((armed or {}).get("goal_id") or "") or None, - preferred_agent_id=str((armed or {}).get("agent_id") or "") or None, - ) +from loopx.hosts.claude.hooks import goal_state as _target # noqa: E402 -def is_armed(project_root) -> bool: - """Armed = the project has a `.claude/loop.md` (loopx is driving), or forced.""" - if os.environ.get("LOOPX_GOAL_FORCE") == "1": - return True - return bool(project_root) and loop_md_path(project_root).exists() +def __getattr__(name: str) -> object: + return getattr(_target, name) -def active_context(cwd) -> dict | None: - """goal_context for cwd, but only when goal-mode is armed; else None.""" - ctx = goal_context(cwd) - if not ctx or not is_armed(ctx.get("project_root")): - return None - return ctx +def __dir__() -> list[str]: + return sorted(dir(_target)) diff --git a/loopx/claude_goal_mode/hooks/stdio_utf8.py b/loopx/claude_goal_mode/hooks/stdio_utf8.py index 9bbd4a6685..64c3ab0ae8 100644 --- a/loopx/claude_goal_mode/hooks/stdio_utf8.py +++ b/loopx/claude_goal_mode/hooks/stdio_utf8.py @@ -1,44 +1,21 @@ -#!/usr/bin/env python3 -"""Pin a Claude Code entry script's own stdio to UTF-8. - -Claude Code pipes UTF-8 across every stdio boundary of this plugin: the session / -tool-event JSON on stdin, and the hook decision, the statusline segment or the -``/loopx`` output on stdout. ``sys.stdin`` / ``sys.stdout`` default to the host -locale codec instead - ``cp936`` on a zh-CN Windows host. There, a non-ASCII -event decodes into mojibake, so ``active_context`` misses the project goal and -``goal_policy.py`` emits ``{}``: the should_run / write_scope gate silently fails -OPEN for every tool. Statusline and ``/loopx`` output are lost on the encode -side instead, because ``▶`` / ``⏸`` / ``⚠`` cannot be encoded in ``gbk``: the -state line of ``/loopx status`` raises ``UnicodeEncodeError`` whatever the path, -and the statusline prints nothing for a non-ASCII session path (with an ASCII -path the goal still resolves, so only its glyphs are lost). - -These scripts are launched directly by Claude Code, outside -``loopx/entrypoint.py``, and reach this module through the hooks directory that -is already on their ``sys.path``. That CLI entrypoint pins the same streams for -the shipped CLI with the same policy - skip a stream that already reports UTF-8, -strict stdin, ``replace`` output - deliberately kept as a separate -implementation so a plugin hook never depends on the CLI bootstrap; change both -together. Input stays strict so a non-UTF-8 byte is never repaired into a -different event; output falls back to ``replace`` so an unencodable character -cannot abort an already-computed answer. -""" +"""Compatibility shim forwarding ``loopx.claude_goal_mode.hooks.stdio_utf8`` to ``loopx.hosts.claude.hooks.stdio_utf8``.""" + from __future__ import annotations +from pathlib import Path import sys +if not __package__: + _package_parent = str(Path(__file__).resolve().parents[3]) + if _package_parent not in sys.path: + sys.path.insert(0, _package_parent) + +from loopx.hosts.claude.hooks import stdio_utf8 as _target # noqa: E402 + + +def __getattr__(name: str) -> object: + return getattr(_target, name) + -def pin_utf8_stdio() -> None: - """Reconfigure stdin/stdout/stderr to UTF-8 unless they already are.""" - - for stream in (sys.stdin, sys.stdout, sys.stderr): - reconfigure = getattr(stream, "reconfigure", None) - if reconfigure is None: - continue - if str(getattr(stream, "encoding", "") or "").lower().replace("_", "-") == "utf-8": - continue - errors = "strict" if stream is sys.stdin else "replace" - try: - reconfigure(encoding="utf-8", errors=errors) - except (OSError, ValueError): - continue +def __dir__() -> list[str]: + return sorted(dir(_target)) diff --git a/loopx/claude_goal_mode/mcp/loopx_mcp.py b/loopx/claude_goal_mode/mcp/loopx_mcp.py index 57627e2199..33cb462d36 100644 --- a/loopx/claude_goal_mode/mcp/loopx_mcp.py +++ b/loopx/claude_goal_mode/mcp/loopx_mcp.py @@ -1,36 +1,25 @@ -#!/usr/bin/env python3 -"""Claude Code entrypoint for the shared LoopX MCP control plane.""" +"""Compatibility entrypoint forwarding ``loopx.claude_goal_mode.mcp.loopx_mcp`` to ``loopx.hosts.claude.mcp.loopx_mcp``.""" + from __future__ import annotations -import sys from pathlib import Path +import sys +if not __package__: + _package_parent = str(Path(__file__).resolve().parents[3]) + if _package_parent not in sys.path: + sys.path.insert(0, _package_parent) -REPO_ROOT = Path(__file__).resolve().parents[3] -if str(REPO_ROOT) not in sys.path: - sys.path.insert(0, str(REPO_ROOT)) - -HOOKS_DIR = Path(__file__).resolve().parent.parent / "hooks" -if str(HOOKS_DIR) not in sys.path: - sys.path.insert(0, str(HOOKS_DIR)) +from loopx.hosts.claude.mcp import loopx_mcp as _target # noqa: E402 +from loopx.hosts.claude.mcp.loopx_mcp import mcp # noqa: E402 -from goal_state import goal_context # noqa: E402 -from loopx.goal_mode_mcp import GoalModeMCPConfig, create_fastmcp_server # noqa: E402 +def __getattr__(name: str) -> object: + return getattr(_target, name) -CONFIG = GoalModeMCPConfig( - server_name="loopx", - runtime_profile="claude_code", - legacy_host_surface="claude_code", - setup_hint="run /loopx first", -) -mcp, control = create_fastmcp_server(CONFIG, lambda: goal_context(Path.cwd())) -# Compatibility names used by existing smoke tests and local integrations. -should_run = control.should_run -list_todos = control.list_todos -claim_task = control.claim_task -complete_task = control.complete_task +def __dir__() -> list[str]: + return sorted(set(dir(_target)) | {"mcp"}) if __name__ == "__main__": diff --git a/loopx/claude_goal_mode/scripts/connect.py b/loopx/claude_goal_mode/scripts/connect.py index dcf7d5f5d8..01a8ac53ec 100644 --- a/loopx/claude_goal_mode/scripts/connect.py +++ b/loopx/claude_goal_mode/scripts/connect.py @@ -1,113 +1,25 @@ -#!/usr/bin/env python3 -"""Connect a project to loopx for Claude Code (PROJECT-scoped). +"""Compatibility entrypoint forwarding ``loopx.claude_goal_mode.scripts.connect`` to ``loopx.hosts.claude.scripts.connect``.""" -Thin wrapper: (1) `loopx connect` the repo, (2) mark `agent_backends += claude` -in the project registry, (3) install the Claude adapter at PROJECT scope (the -loopx MCP + the `/loopx` command into this project's `.claude/`) by delegating to -install.py. No global config, no OS sandbox. The run loop is native `/loop`. - - python connect.py --project DIR --goal-id G [--objective "…"] [--harden] -""" from __future__ import annotations -import argparse -import shutil -import subprocess -import sys from pathlib import Path +import sys -from loopx.control_plane.projects.registry_codec import ( - 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") - return [exe] if exe else [sys.executable, "-m", "loopx.cli"] - +if not __package__: + _package_parent = str(Path(__file__).resolve().parents[3]) + if _package_parent not in sys.path: + sys.path.insert(0, _package_parent) -def main(): - ap = argparse.ArgumentParser() - ap.add_argument("--project", required=True) - ap.add_argument("--goal-id", required=True) - ap.add_argument("--objective", default=None) - ap.add_argument("--registry", default=None) - ap.add_argument("--harden", action="store_true", - help="also install the optional PreToolUse should_run gate + statusline (project scope)") - ap.add_argument("--dry-run", action="store_true") - a = ap.parse_args() - proj = Path(a.project).resolve() - dry = a.dry_run +from loopx.hosts.claude.scripts import connect as _target # noqa: E402 - # 1. connect the repo to loopx (optional, when an objective is given) - if a.objective: - cmd = list(_gh_prefix()) + (["--registry", a.registry] if a.registry else []) + \ - ["connect", "--goal-id", a.goal_id, "--objective", a.objective, - "--state-file", f".claude/goals/{a.goal_id}/ACTIVE_GOAL_STATE.md"] - print("[connect]", " ".join(cmd)) - if not dry: - try: - rc = subprocess.run(cmd, cwd=str(proj), timeout=120) - except Exception as e: - print(f"[connect] FAILED to run loopx connect: {e}") - sys.exit(1) - if rc.returncode != 0: - # Fail closed: a non-zero connect (e.g. a global route collision) - # must stop the helper rather than print a misleading "next steps". - print(f"[connect] FAILED (exit {rc.returncode}) — not continuing. " - "Resolve the error above and re-run.") - sys.exit(rc.returncode) - # 2. mark agent_backends += claude in the project registry (additive) - if a.registry: - reg = Path(a.registry) - else: - reg = proj / ".loopx" / "registry.json" - if not reg.exists() and (proj / ".goal-harness" / "registry.json").exists(): - reg = proj / ".goal-harness" / "registry.json" - if reg.exists(): - try: - payload = load_project_registry(reg) - require_runtime_compatible_project_registry( - payload, - operation="Claude Goal adapter", - ) - print(f"[registry] mark agent_backends += claude ({reg})") - if not dry: - add_project_registry_backend(reg, "claude") - except ProjectRegistryProtocolError as e: - print(f"[registry] FAILED: {e}") - sys.exit(1) - except Exception as e: - print(" (registry annotate skipped:", e, ")") - else: - print(f"[registry] {reg} not found yet (run with --objective to connect first)") +def __getattr__(name: str) -> object: + return getattr(_target, name) - # 3. install the Claude adapter at PROJECT scope (MCP + /loopx command [+ --harden]) - installer = PLUGIN_ROOT / "scripts" / "install.py" - inst = [sys.executable, str(installer), "--scope", "project", "--project", str(proj)] - if a.harden: - inst.append("--harden") - if dry: - inst.append("--dry-run") - print("[install]", " ".join(inst)) - ri = subprocess.run(inst, cwd=str(proj)) - if ri.returncode != 0: - # Fail closed: don't claim success / print next steps if the adapter - # install failed. - print(f"[install] FAILED (exit {ri.returncode}).") - sys.exit(ri.returncode) - print("\nNext: open Claude Code in the project, then:") - print(" /loopx # set the goal, write .claude/loop.md, do the first segment") - print(" /loop # drive the loop (native; loopx should_run gates each tick)") - print(" /loopx off # remove the loop protocol") +def __dir__() -> list[str]: + return sorted(dir(_target)) if __name__ == "__main__": - main() + getattr(_target, "main")() diff --git a/loopx/claude_goal_mode/scripts/goalmode_cmd.py b/loopx/claude_goal_mode/scripts/goalmode_cmd.py index 29002f47f2..ebfe84425b 100644 --- a/loopx/claude_goal_mode/scripts/goalmode_cmd.py +++ b/loopx/claude_goal_mode/scripts/goalmode_cmd.py @@ -1,292 +1,26 @@ -#!/usr/bin/env python3 -"""Smart entry for the `/loopx` slash command — the loopx setup helper. +"""Compatibility entrypoint forwarding ``loopx.claude_goal_mode.scripts.goalmode_cmd`` to ``loopx.hosts.claude.scripts.goalmode_cmd``.""" -LoopX does NOT own the run loop on Claude Code. Claude Code's native `/loop` is -the scheduler/executor; loopx provides the control-plane protocol (the MCP tools -+ a per-iteration `.claude/loop.md`). `/loopx` just sets a goal up and hands off -to `/loop`. - -Routing by first token: - -> ONE-SHOT: ensure a goal exists for this project (bootstrap - if needed), register a default agent, add the task as a - todo, write `.claude/loop.md` (the protocol), and do one - bounded first segment. Then drive it with native `/loop`. - (no args) / on -> (re)write `.claude/loop.md` for this project's existing - goal and show how to drive it with `/loop`. - status -> the project's goal detail (objective, state, next, todos). - off -> remove `.claude/loop.md` (native `/loop` then has nothing - to run). Registry/goal are left intact. - -The LoopX registry (`.loopx/registry.json`) is the single source of truth for -goal_id/agent/scope. The default agent `cc` is registered so the loopx identity -contract is active and `quota should-run --agent-id cc` is satisfied. -""" from __future__ import annotations -import json -import os -import re -import shutil -import subprocess -import sys from pathlib import Path +import sys -HERE = Path(__file__).resolve().parent -DEFAULT_AGENT = "cc" - -# registry-driven context, shared with the hooks/MCP -sys.path.insert(0, str(HERE.parent / "hooks")) -from goal_state import goal_context, find_registry, loop_md_path # noqa: E402 -from stdio_utf8 import pin_utf8_stdio # noqa: E402 -from loopx.control_plane.heartbeat.rules import ( # noqa: E402 - HOST_LOOP_SAFETY_RULE, - RUNTIME_REPAIR_ROUTING_RULE, - SCOPE_BOUNDED_WORK_RULE, -) -from loopx.history import load_registry # noqa: E402 - - -def gh_prefix(): - """Cross-platform loopx invocation: the CLI shim if on PATH, else the module.""" - exe = shutil.which("loopx") - return [exe] if exe else [sys.executable, "-m", "loopx.cli"] - - -def gh(args, cwd=None): - return subprocess.run(gh_prefix() + args, cwd=cwd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=120) - - -def slug(name: str) -> str: - s = re.sub(r"[^a-zA-Z0-9]+", "-", name).strip("-").lower() or "project" - return f"cc-{s}"[:48] - - -def loop_execution_content(goal_id, agent_id) -> str: - """The per-iteration protocol that native `/loop` runs (written to - .claude/loop.md). loopx's should_run is the deterministic per-tick gate; the - agent uses the wired loopx MCP tools, never raw CLI guessing. - - The leading `loopx:armed` marker persists WHICH goal /loopx armed for this - project, so goal_state.goal_context() resolves the right goal in multi-goal - registries instead of guessing from registry order.""" - armed = json.dumps({"goal_id": goal_id, "agent_id": agent_id}) - return ( - f"\n" - f"loopx tick — advance goal `{goal_id}` (agent `{agent_id}`). Use the wired loopx MCP\n" - f"tools; do NOT run `loopx --help` or guess ids.\n\n" - f"{HOST_LOOP_SAFETY_RULE}\n{RUNTIME_REPAIR_ROUTING_RULE}\n" - "Read complete successful `should_run()` JSON each work iteration. Follow its\n" - "current `interaction_contract`: selection/re-entry before admitted work,\n" - "then validation and settlement. Never infer completion from an empty Todo list.\n" - f"{SCOPE_BOUNDED_WORK_RULE}\n" - "Honor claim/lease and user/repository authority; claim only when required.\n" - "Run real acceptance checks before `complete_task`; supply truthful evidence\n" - f"and the bound agent_id=\"{agent_id}\". Complete only finished Todos, not partial work.\n" - "That MCP operation owns writeback/spend: use it INSTEAD OF the raw CLI sequence.\n" - "Use interaction_contract.mcp_channel for tool ownership and vision input limits.\n" - "At material delivery, compare the Goal's vision/acceptance with actual evidence.\n" - "Pass the resulting agent_vision or a justified vision_unchanged_reason to\n" - "complete_task. If omitted, call review_task_vision with only that Todo and\n" - "Agent to read the basis; rejudge, then submit read_context_id with the decision.\n" - "Stale/replaced receipts require rereading; lost replies retry the same receipt\n" - "and decision. Recovery never spends again. This is not a Goal-stop\n" - "shortcut: open acceptance needs replan; vision_closed closes a stage and needs\n" - "a successor vision; no_followup requires evidence of no remaining scoped work.\n" - "For new replan work not covered by these tools, use the exact live\n" - "interaction_contract CLI actions, preserving its binding and settlement order.\n" - "Link already planned follow-up via successor_todo_ids; next_agent_todo creates\n" - "new work, not a reference to an existing id. Do not duplicate the current plan.\n" - "After a lost response, read back or retry the same completion intent; do not\n" - "invent a new successor or settlement identity. Recheck `should_run()` afterward.\n" - "Continue authorized work while the live contract requires it; notification\n" - "silence is not execution silence. Waiting is not completion: follow current\n" - "host scheduling guidance without repeated unchanged polling. Terminal\n" - "no-follow-up ends this Goal's work; cancel only its own recurring wakeup.\n" - "Repair entrypoint errors within authority; an unavailable/incomplete contract\n" - "permits neither work nor spending and must not be reported as completion.\n" - ) - - -def loop_md_content(goal_id, agent_id) -> str: - from loopx.control_plane.heartbeat.bootstrap_prompt import BOOTSTRAP_INSTRUCTION - armed = json.dumps({"goal_id": goal_id, "agent_id": agent_id}) - return (f"\nLoopX managed MCP bootstrap v1\n" - "Each entry/resume: call the bound LoopX `host_prompt` MCP tool, " - "verify its goal_id and agent_id match the armed binding above, " - "then read its complete task_body. Do not create another Goal or scheduler.\n" - f"{BOOTSTRAP_INSTRUCTION}\n") - - -def write_loop_md(proj: Path, goal_id, agent_id) -> Path: - """Write the protocol to /.claude/loop.md (bare `/loop` runs it).""" - path = loop_md_path(proj) - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(loop_md_content(goal_id, agent_id), encoding="utf-8") - return path - - -def goal_detail(ctx): - """Objective (from the registry goal entry's active-state file) + live state - (from quota should-run) for the `/loopx status` detail view.""" - gid, reg, agent = ctx.get("goal_id"), ctx.get("registry"), ctx.get("agent_id") - objective = "" - if reg: - try: - regp = Path(reg) - data = load_registry(regp) - entry = next((g for g in data.get("goals", []) if g.get("id") == gid), None) - sf = (entry or {}).get("state_file") - if sf: - text = (regp.parent.parent / sf).read_text(encoding="utf-8") - m = re.search(r"^objective:\s*(.+)$", text, re.MULTILINE) - if m: - objective = m.group(1).strip().strip('"').strip("'") - except Exception: - pass - payload = {} - try: - cmd = gh_prefix() + (["--registry", reg] if reg else []) + \ - ["--format", "json", "quota", "should-run", "--goal-id", gid] - if agent: - cmd += ["--agent-id", agent] - out = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=15, - env={**os.environ, "LOOPX_CONTEXT_DELIVERY": "off"}) - payload = json.loads(out.stdout or "{}") - except Exception: - pass - return objective, payload - - -def print_status(ctx): - gid = ctx.get("goal_id") - objective, d = goal_detail(ctx) - a = d.get("agent_todo_summary") or {} - done, open_ = a.get("done_count"), a.get("open_count") - gate = d.get("gate_prompt") - if gate: - state = f"⚠ needs you: {gate}" - elif d.get("should_run") is True: - state = "▶ running" - else: - state = f"⏸ {d.get('state') or 'paused'}" + (f" — {d['reason']}" if d.get("reason") else "") - print(f"goal : {gid}") - print(f"agent : {ctx.get('agent_id') or DEFAULT_AGENT}") - if objective: - print(f"objective : {objective}") - print(f"state : {state}") - if d.get("recommended_action"): - print(f"next : {d['recommended_action']}") - if done is not None or open_ is not None: - print(f"todos : {done} done / {open_} open") - for it in (a.get("first_open_items") or [])[:8]: - t = (it.get("text") or "").strip() - if t: - print(f" ▸ {t}") - armed_root = Path(ctx.get("project_root") or Path.cwd()) - armed = "armed (.claude/loop.md present)" if loop_md_path(armed_root).exists() else "not armed (run /loopx to arm)" - print(f"loop : {armed} — drive with native /loop") - - -def main(): - args = sys.argv[1:] - first = args[0] if args else None - proj = Path.cwd() - - # off: remove the loop protocol; native /loop then has nothing to run. - if first == "off": - reg = find_registry(proj) - target_root = reg.parent.parent if reg is not None else proj - lp = loop_md_path(target_root) - if not lp.exists(): - print("goal-mode OFF (no .claude/loop.md here).") - return - try: - lp.unlink() - print("goal-mode OFF — removed .claude/loop.md. (Press Esc to stop a running /loop.)") - except OSError as e: - print(f"goal-mode OFF — could not remove {lp} ({e}); remove it manually.") - return - - # status: full goal detail. - if first == "status": - ctx = goal_context(proj) - if not ctx: - print("loopx goal-mode: no goal in this project yet — run `/loopx ` to create one.") - return - print_status(ctx) - return - - # bare (=on) / on: (re)arm THIS project's existing goal and show how to drive it. - if not args or first == "on": - ctx = goal_context(proj) - if not ctx or not ctx.get("goal_id"): - print("loopx goal-mode: ready — no goal set in this project yet.") - print("Tell me what to work on and I'll set it up:") - print(" /loopx e.g. /loopx 写一个 RTL 模块并跑通仿真") - return - write_loop_md(proj, ctx["goal_id"], ctx.get("agent_id") or DEFAULT_AGENT) - print(f"goal-mode armed goal={ctx['goal_id']} agent={ctx.get('agent_id') or DEFAULT_AGENT}") - print("Drive it with native /loop: `/loop` (Claude self-paces) | `/loop 10m` (fixed).") - print("Stop with Esc; `/loopx off` removes the loop protocol.") - return +if not __package__: + _package_parent = str(Path(__file__).resolve().parents[3]) + if _package_parent not in sys.path: + sys.path.insert(0, _package_parent) - # free-text task -> one-shot setup + write loop.md + first bounded segment. - task = " ".join(args).strip().strip('"').strip("'") - reg = find_registry(proj) - if reg is not None: - ctx = goal_context(proj) or {} - goal_id = ctx.get("goal_id") - registry = str(reg) - else: - goal_id = slug(proj.name) - registry = str(proj / ".loopx" / "registry.json") - # Claude projects keep goal state under .claude/ (not the Codex-default .codex/) - state_file = f".claude/goals/{goal_id}/ACTIVE_GOAL_STATE.md" - r = gh(["bootstrap", "--project", str(proj), "--goal-id", goal_id, - "--objective", task, "--state-file", state_file]) - if "ok: `True`" not in r.stdout and "ok=True" not in r.stdout and r.returncode != 0: - print("[loopx] bootstrap failed:\n" + (r.stdout + r.stderr)[:600]) - sys.exit(1) +from loopx.hosts.claude.scripts import goalmode_cmd as _target # noqa: E402 - if not goal_id: - print("[loopx] could not determine goal id") - sys.exit(1) - # register the default agent (identity contract) and add the task as a todo - cfg = gh(["--registry", registry, "configure-goal", "--goal-id", goal_id, - "--agent-model", "peer_v1", "--registered-agent", DEFAULT_AGENT, "--execute"]) - if cfg.returncode != 0: - print("[loopx] configure-goal failed:\n" + (cfg.stdout + cfg.stderr)[:600]) - sys.exit(1) - add = gh(["--registry", registry, "--format", "json", "todo", "add", - "--goal-id", goal_id, "--role", "agent", "--text", task]) - if add.returncode != 0: - print("[loopx] todo add failed:\n" + (add.stdout + add.stderr)[:600]) - sys.exit(1) - todo_id = "" - try: - todo_id = json.loads(add.stdout).get("todo_id", "") - except Exception: - pass +def __getattr__(name: str) -> object: + return getattr(_target, name) - # write the per-iteration protocol; the RUN happens when the user types /loop - # (this command only SETS UP the goal — it must not do the work itself). - write_loop_md(proj, goal_id, DEFAULT_AGENT) - tid = todo_id or "(see should_run output)" - print("goal set up. loopx is the control plane; Claude Code's native /loop is the runtime.") - print(f" goal_id : {goal_id}") - print(f" agent : {DEFAULT_AGENT}") - print(f" todo_id : {tid}") - print(f" scope : {proj}") - print(f" task : {task}") - print(" wrote : .claude/loop.md (the per-tick protocol)") - print() - print("START WORKING — run native `/loop` (Claude self-paces) or `/loop 10m` (fixed cadence).") - print("Each /loop tick follows should_run's current contract; complete_task settles only verified, finished work.") - print("Stop with Esc or `/loopx off`.") +def __dir__() -> list[str]: + return sorted(dir(_target)) if __name__ == "__main__": - pin_utf8_stdio() - main() + getattr(_target, "pin_utf8_stdio")() + getattr(_target, "main")() diff --git a/loopx/claude_goal_mode/scripts/install.py b/loopx/claude_goal_mode/scripts/install.py index 4aa8d8a5b9..a53a0425f9 100644 --- a/loopx/claude_goal_mode/scripts/install.py +++ b/loopx/claude_goal_mode/scripts/install.py @@ -1,524 +1,25 @@ -#!/usr/bin/env python3 -"""Install the loopx Claude Code adapter — EXPLICIT, scoped, opt-in. +"""Compatibility entrypoint forwarding ``loopx.claude_goal_mode.scripts.install`` to ``loopx.hosts.claude.scripts.install``.""" -This is NOT run by the default loopx installer. It is invoked deliberately -(`LOOPX_INSTALL_CLAUDE=1 scripts/install-local.sh`, or directly). It installs the -minimum: the loopx **MCP server** (the control-plane tools) + the **`/loopx`** -slash command. The run loop is Claude Code's native `/loop`; loopx only provides -the `should_run` protocol, so NO global hooks are wired by default. - - python install.py --scope project [--project DIR] # this project only (preferred) - python install.py --scope user # all your Claude Code projects - python install.py --scope ... --harden # ALSO add the optional - # PreToolUse should_run gate - # + statusline at that scope - -`--scope` is required (a deliberate choice). User scope is announced loudly. We -NEVER delete existing permission rules; legacy loopx entries get a printed -cleanup suggestion instead. -""" from __future__ import annotations -from typing import Any - -import argparse -import json -import os -import shlex -import shutil -import subprocess -import sys from pathlib import Path +import sys -PLUGIN_ROOT = Path(__file__).resolve().parents[1] -MCP_VENV = Path.home() / ".local" / "share" / "loopx" / "mcp-venv" - -# This script is run by path (`python /loopx/claude_goal_mode/scripts/ -# install.py`), so the package root is not on `sys.path` by default. -REPO_ROOT = Path(__file__).resolve().parents[3] -if str(REPO_ROOT) not in sys.path: - sys.path.insert(0, str(REPO_ROOT)) - -from loopx.file_lock import write_json_atomic # noqa: E402 - - -def _p(*parts: str) -> str: - return str(PLUGIN_ROOT.joinpath(*parts)).replace("\\", "/") - - -def _is_git_bash(path: str) -> bool: - """True when `path` is the MSYS/Cygwin bash Claude Code dispatches to. - - The WSL `bash.exe` that sits on some PATHs is a Linux shell, not the Git - Bash Claude Code spawns for a Windows command string, and its `uname` says - `Linux`; the System32 alias is rejected by name and everything else by - asking the candidate for its `uname`.""" - system32 = Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32" - resolved = os.path.normcase(os.path.realpath(path)) - system32_resolved = os.path.normcase(os.path.realpath(system32)) - if resolved == system32_resolved or resolved.startswith(system32_resolved + os.sep): - return False - try: - probe = subprocess.run([path, "-c", "uname -s"], capture_output=True, timeout=10) - except (OSError, subprocess.SubprocessError): - return False - return probe.returncode == 0 and probe.stdout.decode("utf-8", "replace").startswith( - ("MINGW", "MSYS", "CYGWIN") - ) - - -# Claude Code honors `CLAUDE_CODE_GIT_BASH_PATH` only when the file name is one -# of these (env-vars reference, 2.1.219+); any other name is ignored and Git -# Bash detection continues as if the variable were unset - even when the file -# exists and runs. -_GIT_BASH_OVERRIDE_NAMES = frozenset({"bash.exe", "sh.exe", "bash", "sh"}) - - -def _git_bash() -> str | None: - """The Git Bash Claude Code runs a shell-form command string with, if any. - - Claude Code passes a hook or statusline string to Git Bash on Windows when - Git Bash is installed, to PowerShell when it is not, and to `/bin/sh` on - macOS/Linux (Claude Code hooks reference, "Exec form and shell form"). It - finds Git Bash through its `CLAUDE_CODE_GIT_BASH_PATH` override, the Git - installation or a `bash` on PATH, or a default Git for Windows location; - this mirrors those sources so the encoding can follow the same choice. Like - that consumer, an override whose file name is not `bash.exe`, `sh.exe`, - `bash` or `sh` (compared case-insensitively) is ignored and detection - continues as if it were unset.""" - if sys.platform != "win32": - return None - candidates: list[str] = [] - override = os.environ.get("CLAUDE_CODE_GIT_BASH_PATH") - if override and Path(override).name.lower() in _GIT_BASH_OVERRIDE_NAMES: - candidates.append(override) - git = shutil.which("git") - if git: - root = Path(git).resolve().parent.parent - candidates += [str(root / "bin" / "bash.exe"), str(root / "usr" / "bin" / "bash.exe")] - on_path = shutil.which("bash") - if on_path: - candidates.append(on_path) - for base, sub in ( - (os.environ.get("ProgramFiles"), "Git"), - (os.environ.get("ProgramFiles(x86)"), "Git"), - (os.environ.get("LocalAppData"), "Programs/Git"), - ): - if base: - candidates.append(str(Path(base) / sub / "bin" / "bash.exe")) - for candidate in candidates: - if os.path.isfile(candidate) and _is_git_bash(candidate): - return candidate - return None - - -def _uses_powershell() -> bool: - """Whether Claude Code runs these command strings through PowerShell. - - A Windows host without Git Bash gets PowerShell for shell-form hooks and - the statusline; every other host runs `/bin/sh` or Git Bash.""" - return sys.platform == "win32" and _git_bash() is None - - -def _shell_literal(value: str, *, powershell: bool) -> str: - """Render `value` as one literal token the consumer shell reads back whole. - - Double quotes are not literal in either shell: `$NAME` expands inside them - and an inner `"` can close the token. Single quotes are literal in both, so - POSIX/Git Bash targets get `shlex.quote`'s form and PowerShell a `'...'` - string with its `''` escape. A bare Windows path would lose its - backslashes under Git Bash, so those are quoted too.""" - if powershell: - return "'" + value.replace("'", "''") + "'" - return shlex.quote(value) - - -def _shell_command(value: str, *, powershell: bool) -> str: - """`_shell_literal` in command position: PowerShell needs its `&` operator.""" - token = _shell_literal(value, powershell=powershell) - return f"& {token}" if powershell else token - - -def _launches_python(py: str) -> bool: - """True when running `py` starts a supported Python 3.11+ interpreter. - - `shutil.which` only proves a file is executable, not that it runs Python. On - Windows it can return the 0-byte `WindowsApps` App Execution Alias, which - never starts Python: on some hosts it exits non-zero (9009), on others - launching it raises OSError, and it writes nothing either way. Anything that - bakes that path (the PreToolUse hook, the statusline, `/loopx`) then - silently does nothing.""" - try: - return subprocess.run( - [py, "-c", "import sys; raise SystemExit(sys.version_info < (3, 11))"], - capture_output=True, - timeout=10, - ).returncode == 0 - except (OSError, subprocess.SubprocessError): - return False - - -def _python_cmd() -> str: - """Interpreter to bake into hook / statusline / command strings — robust where - only `python` (not `python3`) is registered, and where `python3` resolves to a - launcher that cannot run supported Python (including the Windows - `WindowsApps` alias and an older PATH interpreter).""" - for candidate in (shutil.which("python3"), shutil.which("python")): - if candidate and _launches_python(candidate): - return candidate - return sys.executable - - -def deep_merge(base: dict[str, Any], add: dict[str, Any]) -> dict[str, Any]: - for k, v in add.items(): - if isinstance(v, dict) and isinstance(base.get(k), dict): - deep_merge(base[k], v) - elif isinstance(v, list) and isinstance(base.get(k), list): - base[k] += [x for x in v if x not in base[k]] - else: - base[k] = v - return base - - -# ---- optional hardening (only with --harden) -------------------------------- - -def hardening_block() -> dict[str, Any]: - """The OPTIONAL per-tool gate + statusline. Not installed unless --harden.""" - powershell = _uses_powershell() - py = _shell_command(_python_cmd(), powershell=powershell) - gate = _shell_literal(_p("hooks", "goal_policy.py"), powershell=powershell) - status = _shell_literal(_p("statusline", "goal_status.py"), powershell=powershell) - return { - "hooks": { - "PreToolUse": [{"matcher": "*", "hooks": [ - {"type": "command", "command": f"{py} {gate}", "timeout": 10}]}], - }, - "statusLine": {"type": "command", "command": f"{py} {status}"}, - } - - -# ---- MCP dependency provisioning -------------------------------------------- - -def _venv_python(venv: Path) -> Path: - sub = "Scripts" if sys.platform == "win32" else "bin" - exe = "python.exe" if sys.platform == "win32" else "python" - return venv / sub / exe - - -# The server imports `mcp.server.fastmcp`, which MCP SDK 2.x no longer ships. -# Checking a bare `import mcp` accepts an interpreter that cannot actually run -# the server, so registration would write a config that fails to start — -# `cursor-agent mcp list` reports "Connection failed" and Claude silently drops -# the tools. Probe the module the server really needs. -MCP_PROBE = "import mcp.server.fastmcp" -# Upper bound for the same reason; drop it once loopx_mcp.py speaks the 2.x API. -MCP_REQUIREMENT = "mcp<2" - - -def _has_mcp(py: str | Path) -> bool: - try: - return subprocess.run([str(py), "-c", MCP_PROBE], capture_output=True).returncode == 0 - except (FileNotFoundError, OSError): - return False - - -def provision_mcp_python(dry: bool, allow_system_pip: bool = False) -> str: - """Return an interpreter that can `import mcp`, installing it into a dedicated - venv if needed (works under PEP 668 externally-managed pythons). - - We install `mcp` ONLY into a dedicated venv we own. We never silently mutate - the user's active/system interpreter (`pip install --break-system-packages`); - that is gated behind an explicit ``allow_system_pip`` opt-in.""" - if _has_mcp(sys.executable): - print(f"[deps] mcp already importable by {sys.executable}") - return sys.executable - vpy = _venv_python(MCP_VENV) - if _has_mcp(vpy): - print(f"[deps] reusing mcp venv {MCP_VENV}") - return str(vpy) - if dry: - print(f"[deps] (dry-run) would create venv {MCP_VENV} and pip install mcp") - return str(vpy) - print(f"[deps] creating mcp venv {MCP_VENV} …") - MCP_VENV.parent.mkdir(parents=True, exist_ok=True) - r = subprocess.run([sys.executable, "-m", "venv", str(MCP_VENV)], capture_output=True, text=True, encoding="utf-8", errors="replace",) - if r.returncode == 0: - subprocess.run([str(vpy), "-m", "pip", "install", "-q", "--upgrade", "pip"], capture_output=True, text=True, encoding="utf-8", errors="replace",) - pip = subprocess.run([str(vpy), "-m", "pip", "install", "-q", MCP_REQUIREMENT], capture_output=True, text=True, encoding="utf-8", errors="replace",) - if pip.returncode == 0 and _has_mcp(vpy): - print(f"[deps] mcp installed into {MCP_VENV}") - return str(vpy) - print("[deps] venv pip install failed:\n" + (pip.stdout + pip.stderr)[:300]) - else: - print("[deps] venv creation failed:\n" + (r.stdout + r.stderr)[:300]) - # The dedicated venv is the only place we install `mcp`. Do NOT touch the - # user's active/system interpreter unless they explicitly opted in. - if allow_system_pip: - print("[deps] --allow-system-pip: pip install --break-system-packages mcp") - subprocess.run([sys.executable, "-m", "pip", "install", "-q", "--break-system-packages", MCP_REQUIREMENT], - capture_output=True, text=True, encoding="utf-8", errors="replace",) - if _has_mcp(sys.executable): - return sys.executable - print("[deps] WARNING: could not provision `mcp` into a dedicated venv, and we will\n" - " NOT modify your system Python. The loopx MCP tools will not load until\n" - " you install `mcp` yourself, e.g.:\n" - f" {sys.executable} -m venv {MCP_VENV} && {vpy} -m pip install '{MCP_REQUIREMENT}'\n" - " (or re-run install.py with --allow-system-pip to use the active interpreter).") - return _python_cmd() - - -def install_mcp( - dry: bool, - py: str, - scope: str, - migrate_goal_harness: bool = False, - project_dir: Path | None = None, -) -> bool: - """Register the loopx MCP server at the chosen scope via `claude mcp add`. - - We replace only OUR `loopx` entry. A legacy/user-owned `goal-harness` MCP is - left untouched by default — we don't delete a server we don't own. If one - exists we print a manual cleanup hint; `--migrate-goal-harness` removes it. - - Returns whether the `loopx` entry is registered afterwards: True only when - `claude mcp add` reported success. A missing `claude` CLI and a failed add - both leave the server unregistered and print the manual command instead, so - a caller that narrates the install must read that receipt, not the attempt.""" - if scope == "project" and project_dir is None: - raise ValueError("project_dir is required for project-scoped MCP registration") - cwd_run = str(project_dir) if scope == "project" else None - claude = shutil.which("claude") - mcp_path = _p("mcp", "loopx_mcp.py") - add = ["mcp", "add", "--scope", scope, "loopx", "--", py, mcp_path] - if not claude: - print("[mcp] claude CLI not on PATH — add the MCP server manually:\n claude " + " ".join(add)) - return False - print(f"[mcp] claude mcp add --scope {scope} loopx -- {py} ") - if dry: - return False - subprocess.run( - [claude, "mcp", "remove", "--scope", scope, "loopx"], - capture_output=True, - text=True, encoding="utf-8", errors="replace", - cwd=cwd_run, - ) - has_gh = subprocess.run( - [claude, "mcp", "get", "goal-harness"], - capture_output=True, - text=True, encoding="utf-8", errors="replace", - cwd=cwd_run, - ).returncode == 0 - if has_gh: - if migrate_goal_harness: - print(f"[mcp] --migrate-goal-harness: removing legacy goal-harness MCP at {scope} scope") - subprocess.run( - [claude, "mcp", "remove", "--scope", scope, "goal-harness"], - capture_output=True, - text=True, encoding="utf-8", errors="replace", - cwd=cwd_run, - ) - else: - print("[mcp] note: a legacy `goal-harness` MCP entry exists — left untouched. Remove it " - f"yourself with `claude mcp remove --scope {scope} goal-harness`, or re-run with " - "--migrate-goal-harness.") - r = subprocess.run( - [claude, *add], - capture_output=True, - text=True, encoding="utf-8", errors="replace", - cwd=cwd_run, - ) - if r.returncode != 0: - print(" (mcp add failed; add manually:\n claude " + " ".join(add) + "\n " + (r.stdout + r.stderr)[:200] + ")") - return False - return True - - -# ---- /loopx command ---------------------------------------------------------- - -def command_md() -> str: - # The `!` line runs through the Bash tool - `sh`/Git Bash on every host - so - # it is always a POSIX literal, never the PowerShell form; a Windows host - # without Git Bash cannot run `!` lines at all (README). - entry = _shell_literal(_p("scripts", "goalmode_cmd.py"), powershell=False) - py = _shell_literal(_python_cmd(), powershell=False) - return ( - "---\n" - "description: loopx goal-mode setup. " - "`/loopx ` sets up a goal + writes .claude/loop.md; drive the loop with native /loop. " - "bare /loopx = arm; off | status.\n" - "argument-hint: | (no args = arm) | off | status\n" - f"allowed-tools: Bash({py}:*)\n" - "---\n\n" - "Run the loopx setup helper and read its output:\n\n" - f"!`{py} {entry} $ARGUMENTS`\n\n" - "The output is loopx control-plane SETUP / status info — it is the COMPLETE, user-facing " - "result. Show it to the user VERBATIM and STOP. Do NOT do any work, claim todos, write " - "files, or loop here: the WORK runs when the user types Claude Code's native `/loop` (which " - "executes `.claude/loop.md`). Do not summarize a multi-line `status` detail block into one line.\n\n" - "The run loop is native `/loop`; loopx provides the deterministic " - "`should_run` protocol.\n" - ) - - -def install_command(dry: bool, cmd_dir: Path) -> None: - path = cmd_dir / "loopx.md" - print(f"[command] /loopx -> {path}") - if dry: - return - cmd_dir.mkdir(parents=True, exist_ok=True) - old = cmd_dir / "goalmode.md" # migrate the legacy /goalmode entry name - if old.exists(): - old.unlink() - path.write_text(command_md(), encoding="utf-8") - - -class HardenSettingsUnreadable(RuntimeError): - """`--harden` refuses to rewrite a settings file it cannot read as JSON.""" - - -def add_hardening(dry: bool, settings_path: Path) -> None: - """Deep-merge the optional hook + statusline into settings_path, preserving - existing config. NEVER deletes permission rules. - - The merge rewrites the whole file, so a settings file that exists but does - not parse is refused instead of replaced: substituting `{}` for it would - drop every key the user owns - permission rules, `env`, `model`, other - hooks, MCP approvals - leaving only the loopx block, at exit status 0. The - file is user-owned (LoopX did not create it), which is why the sibling - merge in `loopx/slash_command_install.py` fails closed on the same input. - """ - cur = {} - if settings_path.exists(): - try: - cur = json.loads(settings_path.read_text(encoding="utf-8")) - except (OSError, ValueError) as exc: - raise HardenSettingsUnreadable( - f"{settings_path} exists but is not readable as JSON ({exc}); refusing to " - "rewrite it. Fix or move that file, then re-run with --harden." - ) from exc - if not isinstance(cur, dict): - raise HardenSettingsUnreadable( - f"{settings_path} exists but is not a JSON object; refusing to rewrite it. " - "Fix or move that file, then re-run with --harden." - ) - # prune prior loopx PreToolUse entries (avoid stacking on reinstall) - for grp in (cur.get("hooks", {}) or {}).get("PreToolUse", []) or []: - grp["hooks"] = [h for h in grp.get("hooks", []) if "goal_policy.py" not in str(h.get("command", ""))] - if isinstance(cur.get("hooks", {}).get("PreToolUse"), list): - cur["hooks"]["PreToolUse"] = [g for g in cur["hooks"]["PreToolUse"] if g.get("hooks")] - merged = deep_merge(cur, hardening_block()) - print(f"[harden] PreToolUse should_run gate + statusline -> {settings_path}") - if not dry: - # One replace, not a truncate-in-place: an interrupted install must not - # leave the user's settings.json as a partial document. The destination - # is resolved first so a dotfiles-managed symlink keeps pointing at its - # target instead of being replaced by the rename. - write_json_atomic(settings_path.resolve(), merged, preserve_mode=True) - - -def warn_legacy_perms(settings_path: Path) -> None: - """Detect a legacy loopx credential-deny and SUGGEST manual cleanup. Never mutate.""" - try: - cur = json.loads(settings_path.read_text(encoding="utf-8")) - except Exception: - return - deny = ((cur.get("permissions") or {}).get("deny")) or [] - legacy = [r for r in deny if r in ("Read(~/.ssh/**)", "Read(~/.aws/**)")] - if legacy: - print(f"[note] {settings_path} has loopx-era permission deny rules {legacy}. " - "We no longer add these and will NOT remove them automatically. " - "To drop them, edit that file's `permissions.deny` by hand.") - +if not __package__: + _package_parent = str(Path(__file__).resolve().parents[3]) + if _package_parent not in sys.path: + sys.path.insert(0, _package_parent) -def main() -> int: - ap = argparse.ArgumentParser() - ap.add_argument("--scope", choices=["user", "project"], required=True, - help="user = ~/.claude (all projects); project = THIS project's .claude (preferred)") - ap.add_argument("--project", default=None, help="project dir for --scope project (default: cwd)") - ap.add_argument("--harden", action="store_true", - help="ALSO install the optional PreToolUse should_run gate + statusline") - ap.add_argument("--skip-mcp", action="store_true", - help="skip MCP venv provisioning + `claude mcp add` (for tests/CI)") - ap.add_argument("--allow-system-pip", action="store_true", - help="if the dedicated mcp venv can't be built, fall back to " - "`pip install --break-system-packages mcp` into the active interpreter " - "(off by default — we don't mutate your system Python)") - ap.add_argument("--migrate-goal-harness", action="store_true", - help="also remove a legacy `goal-harness` MCP entry at this scope " - "(off by default — we don't delete MCP servers we don't own)") - ap.add_argument("--dry-run", action="store_true") - a = ap.parse_args() - dry = a.dry_run +from loopx.hosts.claude.scripts import install as _target # noqa: E402 +from loopx.hosts.claude.scripts.install import main # noqa: E402 - project_dir = None - if a.scope == "project": - project_dir = Path(a.project).resolve() if a.project else Path.cwd() - claude_dir = project_dir / ".claude" - print(f"[scope] PROJECT — installs into {claude_dir} (this project only)") - else: - claude_dir = Path.home() / ".claude" - print("[scope] USER — installs into ~/.claude. The /loopx command and MCP become") - print(" available in ALL your Claude Code projects." + - (" --harden adds USER-LEVEL, matcher-wide hooks too." if a.harden else "")) - mcp_registered = False - if a.skip_mcp: - print("[mcp] skipped (--skip-mcp)") - else: - mcp_python = provision_mcp_python(dry, a.allow_system_pip) - mcp_registered = install_mcp( - dry, - mcp_python, - a.scope, - a.migrate_goal_harness, - project_dir=project_dir, - ) - install_command(dry, claude_dir / "commands") +def __getattr__(name: str) -> object: + return getattr(_target, name) - settings_path = claude_dir / "settings.json" - if a.harden: - try: - add_hardening(dry, settings_path) - except HardenSettingsUnreadable as exc: - print(f"[harden] {exc}", file=sys.stderr) - outcome = ( - "nothing was written (dry-run)" - if dry - else "the settings file is unchanged" - ) - print( - f"[harden] the optional should_run gate + statusline were skipped; {outcome}.", - file=sys.stderr, - ) - if not dry: - # The rest of the install did run, so name only what happened: - # the /loopx command was written just above, and the MCP state is - # the registration receipt `install_mcp` returned - not the - # attempt. A missing CLI or a failed `claude mcp add` leaves the - # server unregistered, and reporting that attempt as an install - # would let a user skip the manual command printed above. - if a.skip_mcp: - mcp_state = "the MCP server was skipped (--skip-mcp)" - elif mcp_registered: - mcp_state = "the MCP server was registered" - else: - mcp_state = ("the MCP server was not registered — run the " - "`claude mcp add` command printed above") - print( - f"[harden] the /loopx command was installed; {mcp_state}.", - file=sys.stderr, - ) - return 2 - else: - print("[harden] skipped (default): no hooks/statusline installed. Add later with --harden.") - warn_legacy_perms(settings_path) - print("\nloopx Claude adapter installed.") - print("Next: in a project with a goal, type `/loopx `, then drive it with native `/loop`.") - print("Restart any open Claude Code session so the command/MCP load.") - if dry: - print("(dry-run: nothing written)") - return 0 +def __dir__() -> list[str]: + return sorted(set(dir(_target)) | {"main"}) if __name__ == "__main__": diff --git a/loopx/claude_goal_mode/statusline/goal_status.py b/loopx/claude_goal_mode/statusline/goal_status.py index 88a65ae3f7..d56d1f2352 100644 --- a/loopx/claude_goal_mode/statusline/goal_status.py +++ b/loopx/claude_goal_mode/statusline/goal_status.py @@ -1,101 +1,26 @@ -#!/usr/bin/env python3 -"""Statusline segment: a glanceable loopx goal state for the Claude Code CLI. +"""Compatibility entrypoint forwarding ``loopx.claude_goal_mode.statusline.goal_status`` to ``loopx.hosts.claude.statusline.goal_status``.""" -Claude Code feeds session JSON on stdin; we resolve THIS project's goal (only -while goal-mode is armed) and run one quick `loopx quota should-run` probe, then -render a single compact line. We surface the signals a watching user actually -needs, in priority order: - - 1. ⚠ needs you — an operator gate / open user todo is blocking (highest signal) - 2. ▶ working — should_run=true, plus the next concrete action loopx picked - 3. ⏸ — paused/holding, plus the short reason (quota, gate, health…) - -…always tailed with todo progress (done✓/open▸). Prints nothing when there is no -goal here or goal-mode is off. -""" from __future__ import annotations -import json -import os -import subprocess -import sys from pathlib import Path +import sys -# Share the registry-driven resolver with the hooks so the statusline shows THIS -# session's project goal, and only while goal-mode is armed (heartbeat installed). -sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hooks")) -from goal_state import active_context -from stdio_utf8 import pin_utf8_stdio - - -import shutil as _shutil -def _gh_prefix(): - _exe = _shutil.which("loopx") - return [_exe] if _exe else [__import__("sys").executable, "-m", "loopx.cli"] - - -def _clip(s, n: int) -> str: - s = " ".join(str(s or "").split()) # collapse whitespace/newlines - return s if len(s) <= n else s[: n - 1] + "…" - - -def _render(gid: str, d: dict) -> str: - """Turn a `quota should-run` payload into one compact statusline string.""" - agent = d.get("agent_todo_summary") or {} - done, open_ = agent.get("done_count"), agent.get("open_count") - prog = f"{done}✓/{open_}▸" if (done is not None or open_ is not None) else "" - - ic = d.get("interaction_contract") or {} - user_ch = ic.get("user_channel") or {} - users = d.get("user_todo_summary") or {} - gate = d.get("gate_prompt") - needs_user = bool(gate) or bool(user_ch.get("action_required")) or bool(users.get("open_count")) +if not __package__: + _package_parent = str(Path(__file__).resolve().parents[3]) + if _package_parent not in sys.path: + sys.path.insert(0, _package_parent) - if needs_user: - msg = gate or f"{users.get('open_count') or 'a'} user todo(s) to answer" - return f"[loopx {gid} · ⚠ needs you: {_clip(msg, 46)}]" +from loopx.hosts.claude.statusline import goal_status as _target # noqa: E402 - if d.get("should_run") is True: - nxt = d.get("recommended_action") - head = f"▶ {prog}".rstrip() if prog else "▶ working" - return f"[loopx {gid} · {head}" + (f" · next: {_clip(nxt, 40)}]" if nxt else "]") - # paused / holding: lead with WHY (state + short reason), then progress - state = (d.get("state") or "paused").strip() - reason = d.get("reason") - tail = f" · {prog}" if prog else "" - return f"[loopx {gid} · ⏸ {state}" + (f": {_clip(reason, 38)}" if reason else "") + f"{tail}]" +def __getattr__(name: str) -> object: + return getattr(_target, name) -def main(): - raw = sys.stdin.read() # Claude's session json carries this session's cwd - cwd = None - try: - sess = json.loads(raw or "{}") - cwd = sess.get("cwd") or (sess.get("workspace") or {}).get("current_dir") - except Exception: - pass - st = active_context(cwd or Path.cwd()) - if not st: - print("") # no goal here, or goal-mode off -> no segment - return - gid = st.get("goal_id", "?") - try: - cmd = list(_gh_prefix()) - if st.get("registry"): - cmd += ["--registry", st["registry"]] - cmd += ["--format", "json", "quota", "should-run", "--goal-id", gid] - if st.get("agent_id"): - cmd += ["--agent-id", st["agent_id"]] - out = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=8, - env={**os.environ, "LOOPX_CONTEXT_DELIVERY": "off"}) - d = json.loads(out.stdout or "{}") - print(_render(gid, d)) - except Exception: - # probe failed: still show that goal-mode is armed, without counts/state - print(f"[loopx {gid}]") +def __dir__() -> list[str]: + return sorted(dir(_target)) if __name__ == "__main__": - pin_utf8_stdio() - main() + getattr(_target, "pin_utf8_stdio")() + getattr(_target, "main")() diff --git a/loopx/cli_commands/slash_commands.py b/loopx/cli_commands/slash_commands.py index b304e96af0..e8c3777fb9 100644 --- a/loopx/cli_commands/slash_commands.py +++ b/loopx/cli_commands/slash_commands.py @@ -219,6 +219,11 @@ def handle_slash_commands_command( if agy_goal_id and getattr(args, "runtime_root", None) else None ) + resolved_runtime_root = ( + str(Path(args.runtime_root).expanduser().resolve()) + if getattr(args, "runtime_root", None) + else None + ) payload = install_slash_commands( execute=bool((args.install or args.uninstall) and not args.dry_run), uninstall=bool(args.uninstall), @@ -242,6 +247,8 @@ def handle_slash_commands_command( agy_registry=agy_registry, pi_project=args.pi_project, pi_scope=args.pi_scope, + registry_path=str(resolved_registry.resolve()) if resolved_registry is not None else None, + runtime_root=resolved_runtime_root, ) print_payload(payload, output_format(args), render_slash_command_install_markdown) return 0 if payload.get("ok") is True else 1 diff --git a/loopx/cli_commands/zcode_goal.py b/loopx/cli_commands/zcode_goal.py index 13ab665603..03b88aa5fe 100644 --- a/loopx/cli_commands/zcode_goal.py +++ b/loopx/cli_commands/zcode_goal.py @@ -4,7 +4,7 @@ from pathlib import Path from typing import Any, Callable -from ..zcode_goal_mode.bridge import ZCODE_GOAL_ACTIONS, zcode_goal_operation +from ..hosts.zcode.bridge import ZCODE_GOAL_ACTIONS, zcode_goal_operation AddFormat = Callable[[argparse.ArgumentParser], None] diff --git a/loopx/cli_runtime.py b/loopx/cli_runtime.py index 9f2af735ff..df54d1ff62 100644 --- a/loopx/cli_runtime.py +++ b/loopx/cli_runtime.py @@ -284,7 +284,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/hosts/host_harness_capabilities.ts b/loopx/control_plane/hosts/host_harness_capabilities.ts index 5e755480f8..81622df995 100644 --- a/loopx/control_plane/hosts/host_harness_capabilities.ts +++ b/loopx/control_plane/hosts/host_harness_capabilities.ts @@ -391,7 +391,7 @@ export const CLAUDE_HOST_CAPABILITIES: HostHarnessCapabilities = defineHostHarnessCapabilities({ host_id: "claude", integration_tier: "boundary_cli", - adapter_module: "loopx.claude_goal_mode", + adapter_module: "loopx.hosts.claude", supported_capabilities: ["verifier_hook"], hook_events: ["PreToolUse"], requires_utf8_stdio: true, 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 7279490667..dc95f45500 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",) @@ -1376,7 +1376,7 @@ def collect_doctor( if companion_fix: payload["fix"] = f"{companion_fix}\n{payload['fix']}" 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, @@ -1692,7 +1692,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 935f028d46..a6d1a2e0e3 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 .hosts.codex_capabilities import ( CODEX_APP_HOST_CAPABILITIES as CODEX_APP_HOST_CAPABILITIES, diff --git a/loopx/hosts/capabilities.py b/loopx/hosts/capabilities.py index 3dc599560d..767a360219 100644 --- a/loopx/hosts/capabilities.py +++ b/loopx/hosts/capabilities.py @@ -93,7 +93,7 @@ BUILTIN_HOST_ADAPTER_MODULES: Mapping[str, str] = { "agy": "loopx.hosts.agy", - "claude": "loopx.claude_goal_mode", + "claude": "loopx.hosts.claude", "codex-app": "loopx.hosts.codex_capabilities", "codex-app-server": "loopx.hosts.codex_capabilities", "codex-cli": "loopx.hosts.codex_capabilities", 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/hosts/claude/__init__.py b/loopx/hosts/claude/__init__.py new file mode 100644 index 0000000000..21bdd6028d --- /dev/null +++ b/loopx/hosts/claude/__init__.py @@ -0,0 +1,49 @@ +"""Claude Code adapter for loopx. + +loopx is a deterministic (no-LLM) control plane. On Claude Code the RUN LOOP is +Claude Code's native ``/loop``; loopx provides the control-plane protocol (we do +NOT use ``/goal``, which judges completion from the transcript). Pieces: + +- ``mcp/loopx_mcp.py`` — MCP server: should_run / list_todos / claim_task / + complete_task (the deterministic control plane) +- ``scripts/goalmode_cmd.py`` — the ``/loopx`` setup helper: sets a goal and writes + ``.claude/loop.md`` (the per-iteration protocol that + native ``/loop`` runs each tick) +- ``hooks/goal_state.py`` — registry-driven goal context + "armed" (loop.md) check +- ``hooks/goal_policy.py`` — OPTIONAL PreToolUse should_run gate (opt-in via --harden) +- ``statusline/goal_status.py`` — optional glanceable goal state +- ``scripts/install.py`` — explicit, scoped, opt-in installer (MCP + /loopx [+ --harden]) +- ``scripts/connect.py`` — project-scoped connect + install +- ``plugin`` assets — ``.claude-plugin/plugin.json``, ``commands/loopx.md``, + ``hooks/hooks.json`` (the optional gate) + +The retired benchmark-only baseline contract remains in Git history and is +no longer part of the working tree or a LoopX runtime module. +""" + +from __future__ import annotations + +from ..capabilities import ( + HostHarnessCapabilities, + _register_builtin_host_capabilities, +) + +CLAUDE_HOST_CAPABILITIES: HostHarnessCapabilities = _register_builtin_host_capabilities( + HostHarnessCapabilities( + host_id="claude", + integration_tier="boundary_cli", + adapter_module="loopx.hosts.claude", + supported_capabilities=("verifier_hook",), + hook_events=("PreToolUse",), + requires_utf8_stdio=True, + native_goal_primitive=False, + native_scheduler_primitive=True, + description=( + "Claude Code boundary CLI adapter driven by native /loop, MCP " + "control-plane tools, and opt-in PreToolUse should_run/write_scope " + "policy verification." + ), + ) +) + +__all__: list[str] = ["CLAUDE_HOST_CAPABILITIES"] 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/hosts/claude/hooks/goal_policy.py b/loopx/hosts/claude/hooks/goal_policy.py new file mode 100644 index 0000000000..5229ff1a8f --- /dev/null +++ b/loopx/hosts/claude/hooks/goal_policy.py @@ -0,0 +1,299 @@ +#!/usr/bin/env python3 +"""PreToolUse policy gate for goal-mode — OPTIONAL deterministic hardening. + +In the native-`/loop` design, Claude Code's `/loop` is the runtime and loopx's +MCP `should_run` is the per-tick gate. This hook is NOT installed by default — +it is opt-in (`install.py --harden` / `connect.py --harden`), project-scoped, and +adds a per-TOOL-CALL gate on top of the loop: + +- should_run gate (fail-closed) -> may the agent spend this turn right now? +- Edit/Write -> write_scope -> deny file edits outside the goal's scope +- Bash -> destructive denylist -> deny obviously dangerous commands + +It only acts in a project where loopx is armed (a `.claude/loop.md` exists). + +Limitation (by design): Bash is gated only by a denylist, so a determined shell +command can still write outside write_scope or reach the network. For STRONG +isolation (untrusted code / unattended high-stakes), run Claude Code inside a dev +container or VM, which contains the whole process at the environment level. + +Behavior (only while goal-mode is ARMED for the event's project): +- no goal here / goal-mode off -> {} (no-op; normal permission flow) +- event unreadable -> deny (FAIL-CLOSED) + (no usable session cwd, no usable tool_name) +- read-only/safe tools -> allow +- non-read-only tool, unreadable event value -> deny (FAIL-CLOSED) + (non-object tool_input, non-string command/file path) +- should_run == false (quota/gate closed) -> deny +- should_run probe unavailable (error) -> deny for non-read-only tools (FAIL-CLOSED) +- should_run == true: + * Edit/Write outside write_scope -> deny + * Edit/Write within write_scope -> allow + * destructive Bash -> deny + * Bash / other -> allow + +Fail-closed: if the deterministic ``should_run`` probe cannot be reached, a +non-read-only tool is denied rather than allowed, so a flaky/broken control +plane pauses delivery instead of running ungated. Read-only tools stay allowed. +An event this hook cannot read joins that rule: ``rc=1`` with no decision is a +non-blocking hook error to Claude Code, which then continues the tool call with +no gate at all, so an unreadable event (undecodable stdin, malformed or +non-object JSON, no session cwd or one that cannot be resolved as a path, no +usable tool name, or - for a non-read-only tool - a non-object ``tool_input`` or +a non-string command/file path field) is answered with an explicit deny instead +of dying. Read-only tools keep their unconditional allow. + +Identity-aware: when the active goal registered an agent (loopx +``coordination.registered_agents``), the context carries ``agent_id`` and this +hook forwards it as ``--agent-id`` to ``loopx quota should-run``. Without it +loopx returns ``automation_prompt_upgrade_required`` and should_run=false — the +Claude Code analogue of Codex's identity-scoped heartbeat prompt. +""" +from __future__ import annotations + +import json +import os +import shutil +import subprocess +import sys +from pathlib import Path + +# Goal context is resolved PER PROJECT from the event's cwd via the registry, and +# "armed" = the project's .claude/loop.md exists (see goal_state.py). The registry +# is the single source of truth; there is no separate active-state file. +HOOKS_DIR = Path(__file__).resolve().parent +if str(HOOKS_DIR) not in sys.path: + sys.path.insert(0, str(HOOKS_DIR)) + +from goal_state import active_context # noqa: E402 +from stdio_utf8 import pin_utf8_stdio # noqa: E402 + +# Read-only tools are always allowed under goal-mode. Edit/Write are scoped to +# write_scope; Bash is gated by a destructive-command denylist. (No OS sandbox in +# this design — the hook is the whole gate; see the module docstring.) +# NOTE: `Task` is deliberately NOT here. It can launch a subagent that performs +# writes, so allowing it unconditionally would bypass the gate when +# should_run=false. It must go through the gate: denied when should_run=false, +# otherwise deferred to Claude Code's normal permission flow (unknown tool). +READONLY_TOOLS = {"Read", "Glob", "Grep", "NotebookRead", "TodoWrite", "WebFetch", "WebSearch", "ToolSearch"} +WRITE_TOOLS = {"Edit", "Write", "MultiEdit", "NotebookEdit"} +DESTRUCTIVE = ( + "rm -rf", "rm -fr", "mkfs", "dd if=", ":(){", "shutdown", "reboot", + "git push --force", "git reset --hard", "> /dev/sd", "format ", +) +CLAUDE_RUNTIME_PROFILE_ARGS = ["--runtime-profile", "claude_code"] +CLAUDE_LEGACY_SCHEDULER_ARGS = [ + "--host-surface", "claude_code", + "--scheduler-owner", "agent_cli_loop", + "--execution-mode", "interactive", +] + + +def within(path: str, root: str) -> bool: + """True if `path` resolves to `root` or a descendant of it.""" + try: + p = Path(path).resolve() + r = Path(root).resolve() + return r == p or r in p.parents + except Exception: + return False + + +def _usable_cwd(value: str) -> bool: + """True if a decoded session cwd can be resolved as a filesystem path. + + A string can still be unusable as a path: an embedded NUL makes + ``Path.resolve`` raise ``ValueError``, and a lone surrogate raises + ``UnicodeEncodeError`` (a ``ValueError``) against the filesystem encoding. + ``active_context`` must never receive such a value, or the exception escapes + ``decide`` as the rc=1/no-decision hook error the module docstring refuses. + """ + try: + Path(value).resolve() + except (OSError, RuntimeError, ValueError): + return False + return True + + +def _gh_prefix(): + _exe = shutil.which("loopx") + return [_exe] if _exe else [__import__("sys").executable, "-m", "loopx.cli"] + + +def _runtime_profile_flag_is_unsupported(out: subprocess.CompletedProcess) -> bool: + diagnostic = str(out.stderr or "").lower() + return ( + out.returncode == 2 + and "--runtime-profile" in diagnostic + and ( + "unrecognized arguments" in diagnostic + or "invalid choice" in diagnostic + ) + ) + + +def should_run(registry, goal_id, agent_id=None) -> bool | None: + """Return True/False from loopx quota should-run, or None if unknown.""" + if not goal_id: + return None + cmd = list(_gh_prefix()) + if registry: + cmd += ["--registry", registry] + cmd += ["--format", "json", "quota", "should-run", "--goal-id", goal_id] + if agent_id: + cmd += ["--agent-id", agent_id] + try: + out = subprocess.run( + [*cmd, *CLAUDE_RUNTIME_PROFILE_ARGS], + capture_output=True, + text=True, encoding="utf-8", errors="replace", + timeout=10, + env={**os.environ, "LOOPX_CONTEXT_DELIVERY": "off"}, + ) + if _runtime_profile_flag_is_unsupported(out): + out = subprocess.run( + [*cmd, *CLAUDE_LEGACY_SCHEDULER_ARGS], + capture_output=True, + text=True, encoding="utf-8", errors="replace", + timeout=10, + env={**os.environ, "LOOPX_CONTEXT_DELIVERY": "off"}, + ) + except Exception: + return None # caller fails CLOSED on None for non-read-only tools + try: + data = json.loads(out.stdout or "{}") + except (json.JSONDecodeError, TypeError, ValueError): + return None + should_run_value = data.get("should_run") + return should_run_value if isinstance(should_run_value, bool) else None + + +def decide(ev: dict) -> dict: + """Pure policy: given a PreToolUse event, return the hookSpecificOutput dict + (or {} for no-op). Reused by the CLI hook AND the Agent SDK in-process hook. + + The hook is the whole gate (no OS sandbox): should_run (fail-closed) + + Edit/Write write_scope + a destructive-Bash denylist. An event value this + gate cannot use - no usable session cwd or tool name, or a non-object + tool_input / non-string command or file path on a non-read-only tool - is + refused rather than deferred, because the event cannot be classified (the + module docstring states the fail-closed rule).""" + def d(decision, reason): + return {"hookSpecificOutput": { + "hookEventName": "PreToolUse", + "permissionDecision": decision, + "permissionDecisionReason": reason}} + + # Claude Code feeds the session's working directory on the event; resolve the + # goal from THAT project's registry, and gate only while goal-mode is armed + # (the project's .claude/loop.md exists). Unrelated/unarmed projects -> no-op. + cwd = ev.get("cwd") + workspace = ev.get("workspace") + if not isinstance(cwd, str) or not cwd: + cwd = workspace.get("current_dir") if isinstance(workspace, dict) else None + if not isinstance(cwd, str) or not cwd: + # Every real PreToolUse event carries the session cwd. Without one this + # hook cannot tell an armed project from an unrelated one, so it cannot + # decide to stay out of the way: refusing is the same fail-closed rule + # the unreachable-should_run branch below applies. Unreadable events + # (see main) arrive here as an empty dict. + return d("deny", "unreadable PreToolUse event (no session cwd) - failing closed under goal-mode") + if not _usable_cwd(cwd): + # A decoded cwd can still be unusable as a path (embedded NUL, lone + # surrogate, OS-level resolution failure). active_context cannot + # attribute the event to a project then, so the event stays unreadable + # for this gate and is refused instead of raising out of decide. + return d("deny", "unreadable PreToolUse event (session cwd is not a usable path) - failing closed under goal-mode") + + ctx = active_context(cwd) + if not ctx: + return {} # no goal here, or goal-mode off -> defer to normal flow + + goal_id = ctx.get("goal_id") + registry = ctx.get("registry") + agent_id = ctx.get("agent_id") + scope = ctx.get("write_scope") or [] + tool = ev.get("tool_name") + if not isinstance(tool, str) or not tool: + # Every real PreToolUse event names its tool; without a usable name the + # gate cannot apply its read-only/gated classification (and the set + # membership tests below would raise on an unhashable value). + return d("deny", "unreadable PreToolUse event (tool_name is not a usable string) - failing closed under goal-mode") + ti = ev.get("tool_input") + if ti is None: + # Only an absent/null field takes the empty-input default. Other falsy + # values (`[]`, `false`, `0`, `""`) are present non-objects and must + # stay visible to the check below instead of being hidden by `or {}`. + ti = {} + + if tool in READONLY_TOOLS: + return d("allow", "read-only/safe tool under goal-mode") + + if not isinstance(ti, dict): + # A tool_input that is present but not an object cannot be read: refuse + # the non-read-only tool instead of crashing on `ti.get` (same + # fail-closed rule as an unreachable `should_run` probe). + return d("deny", "unreadable PreToolUse event (tool_input is not an object) - failing closed under goal-mode") + + # Every value the gate reads below must be readable before the probe is + # consulted, so an unreadable event is refused whether or not the gate is + # open (an absent/null field keeps its empty default). + if tool in WRITE_TOOLS: + file_path = ti.get("file_path") + notebook_path = ti.get("notebook_path") + if file_path is not None and not isinstance(file_path, str): + return d("deny", "unreadable PreToolUse event (tool_input.file_path is not a string) - failing closed under goal-mode") + if notebook_path is not None and not isinstance(notebook_path, str): + return d("deny", "unreadable PreToolUse event (tool_input.notebook_path is not a string) - failing closed under goal-mode") + elif tool == "Bash": + command = ti.get("command") + if command is not None and not isinstance(command, str): + return d("deny", "unreadable PreToolUse event (tool_input.command is not a string) - failing closed under goal-mode") + + sr = should_run(registry, goal_id, agent_id) # True / False / None + if sr is False: + return d("deny", f"goal '{goal_id}' should_run=false (quota/gate closed)") + if sr is None: + # deterministic should_run probe unavailable -> fail closed (non-read-only tool) + return d("deny", "loopx should_run probe unavailable — failing closed under goal-mode") + + # should_run == True. Scope the Edit/Write file tools to write_scope, and + # gate Bash with the destructive denylist (the hook is the whole gate). + if tool in WRITE_TOOLS: + fp = ti.get("file_path") or ti.get("notebook_path") or "" + if scope: + if not fp.strip(): + return d( + "deny", + "unreadable PreToolUse event (missing file_path/notebook_path) - failing closed under goal-mode", + ) + resolved_fp = fp if Path(fp).is_absolute() else str(Path(cwd) / fp) + if not any(within(resolved_fp, s) for s in scope): + return d("deny", f"'{fp}' outside goal write_scope {scope}") + return d("allow", "write within goal scope") + if tool == "Bash": + low = (ti.get("command") or "").lower() + if any(tok in low for tok in DESTRUCTIVE): + return d("deny", "destructive command blocked by goal policy") + return d("allow", "bash permitted under goal policy") + return {} # unknown tool: defer to normal flow + + +def main(): + try: + # `ValueError` also covers `UnicodeDecodeError`: the strict stdin pin + # (stdio_utf8) never repairs a bad byte into a different event, so an + # event that cannot be read becomes the explicit deny in decide() + # instead of a traceback with no decision. + ev = json.loads(sys.stdin.read()) + except ValueError: + ev = {} + if not isinstance(ev, dict): + ev = {} + result = decide(ev) + sys.stdout.write(json.dumps(result) if result else "{}") + + +if __name__ == "__main__": + pin_utf8_stdio() + main() diff --git a/loopx/hosts/claude/hooks/goal_state.py b/loopx/hosts/claude/hooks/goal_state.py new file mode 100644 index 0000000000..f87d0aa341 --- /dev/null +++ b/loopx/hosts/claude/hooks/goal_state.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +"""Goal-mode context resolution — registry-driven, mirroring the Codex model. + +LoopX's registry (``.loopx/registry.json``) is the single source of truth for the +project's goal (goal_id / agent / scope), exactly as on Codex. We resolve it by +walking up from cwd to the nearest ``.loopx/`` (or legacy ``.goal-harness/``) +registry — so two sessions in different projects are independent, and two +sessions in the SAME project share the one goal. + +"Goal-mode ON / armed" for a project = a ``.claude/loop.md`` exists (written by +``/loopx ``). That file is the per-iteration protocol that Claude Code's +native ``/loop`` runs; its presence means loopx is driving this project. The +OPTIONAL PreToolUse hook + statusline gate on this, so they only act where loopx +is actually active. ``LOOPX_GOAL_FORCE=1`` forces armed=true for tests. +""" +from __future__ import annotations + +import json +import os +import re +import sys +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[4] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from loopx.goal_mode_context import ( # noqa: E402 + find_registry as _find_registry, + first_registered_agent, + project_root_for as _project_root_for, + resolve_goal_context, +) + +_ARMED_RE = re.compile(r"") + + +def find_registry(cwd) -> Path | None: + """Nearest ancestor of cwd (inclusive) holding a registry.json, else None.""" + return _find_registry(cwd) + + +def project_root_for(cwd) -> Path | None: + return _project_root_for(cwd) + + +def _agent_of(goal: dict): + return first_registered_agent(goal) + + +def loop_md_path(project_root) -> Path: + return Path(project_root) / ".claude" / "loop.md" + + +def read_armed_goal(project_root) -> dict | None: + """The goal_id/agent_id that `/loopx` armed for THIS project, parsed from the + `loopx:armed` marker it writes at the top of `.claude/loop.md`. None if the + project isn't armed or the marker is absent/unparseable. + + This is what lets goal_context resolve the *armed* goal rather than guessing + by registry order, so a multi-goal repo gates/claims/completes the goal the + user actually set up.""" + if not project_root: + return None + try: + text = loop_md_path(project_root).read_text(encoding="utf-8") + except Exception: + return None + m = _ARMED_RE.search(text) + if not m: + return None + try: + d = json.loads(m.group(1)) + except Exception: + return None + return d if isinstance(d, dict) and d.get("goal_id") else None + + +def goal_context(cwd) -> dict | None: + """The current project's goal, read live from the registry. None if no goal. + + Returns goal_id, registry path, agent_id, write_scope (the goal's repo), and + project_root — everything the hooks / MCP / statusline need. When the project + is armed (`.claude/loop.md` carries a `loopx:armed` marker), the marker's goal + is authoritative; otherwise we fall back to the first registry goal.""" + root = project_root_for(cwd) + armed = read_armed_goal(root) if root else None + return resolve_goal_context( + cwd, + preferred_goal_id=str((armed or {}).get("goal_id") or "") or None, + preferred_agent_id=str((armed or {}).get("agent_id") or "") or None, + ) + + +def is_armed(project_root) -> bool: + """Armed = the project has a `.claude/loop.md` (loopx is driving), or forced.""" + if os.environ.get("LOOPX_GOAL_FORCE") == "1": + return True + return bool(project_root) and loop_md_path(project_root).exists() + + +def active_context(cwd) -> dict | None: + """goal_context for cwd, but only when goal-mode is armed; else None.""" + ctx = goal_context(cwd) + if not ctx or not is_armed(ctx.get("project_root")): + return None + return ctx 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/hosts/claude/hooks/stdio_utf8.py b/loopx/hosts/claude/hooks/stdio_utf8.py new file mode 100644 index 0000000000..9bbd4a6685 --- /dev/null +++ b/loopx/hosts/claude/hooks/stdio_utf8.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 +"""Pin a Claude Code entry script's own stdio to UTF-8. + +Claude Code pipes UTF-8 across every stdio boundary of this plugin: the session / +tool-event JSON on stdin, and the hook decision, the statusline segment or the +``/loopx`` output on stdout. ``sys.stdin`` / ``sys.stdout`` default to the host +locale codec instead - ``cp936`` on a zh-CN Windows host. There, a non-ASCII +event decodes into mojibake, so ``active_context`` misses the project goal and +``goal_policy.py`` emits ``{}``: the should_run / write_scope gate silently fails +OPEN for every tool. Statusline and ``/loopx`` output are lost on the encode +side instead, because ``▶`` / ``⏸`` / ``⚠`` cannot be encoded in ``gbk``: the +state line of ``/loopx status`` raises ``UnicodeEncodeError`` whatever the path, +and the statusline prints nothing for a non-ASCII session path (with an ASCII +path the goal still resolves, so only its glyphs are lost). + +These scripts are launched directly by Claude Code, outside +``loopx/entrypoint.py``, and reach this module through the hooks directory that +is already on their ``sys.path``. That CLI entrypoint pins the same streams for +the shipped CLI with the same policy - skip a stream that already reports UTF-8, +strict stdin, ``replace`` output - deliberately kept as a separate +implementation so a plugin hook never depends on the CLI bootstrap; change both +together. Input stays strict so a non-UTF-8 byte is never repaired into a +different event; output falls back to ``replace`` so an unencodable character +cannot abort an already-computed answer. +""" +from __future__ import annotations + +import sys + + +def pin_utf8_stdio() -> None: + """Reconfigure stdin/stdout/stderr to UTF-8 unless they already are.""" + + for stream in (sys.stdin, sys.stdout, sys.stderr): + reconfigure = getattr(stream, "reconfigure", None) + if reconfigure is None: + continue + if str(getattr(stream, "encoding", "") or "").lower().replace("_", "-") == "utf-8": + continue + errors = "strict" if stream is sys.stdin else "replace" + try: + reconfigure(encoding="utf-8", errors=errors) + except (OSError, ValueError): + continue diff --git a/loopx/hosts/claude/mcp/loopx_mcp.py b/loopx/hosts/claude/mcp/loopx_mcp.py new file mode 100644 index 0000000000..604488c206 --- /dev/null +++ b/loopx/hosts/claude/mcp/loopx_mcp.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 +"""Claude Code entrypoint for the shared LoopX MCP control plane.""" +from __future__ import annotations + +import sys +from pathlib import Path + + +REPO_ROOT = Path(__file__).resolve().parents[4] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +HOOKS_DIR = Path(__file__).resolve().parent.parent / "hooks" +if str(HOOKS_DIR) not in sys.path: + sys.path.insert(0, str(HOOKS_DIR)) + +from goal_state import goal_context # noqa: E402 +from loopx.goal_mode_mcp import GoalModeMCPConfig, create_fastmcp_server # noqa: E402 + + +CONFIG = GoalModeMCPConfig( + server_name="loopx", + runtime_profile="claude_code", + legacy_host_surface="claude_code", + setup_hint="run /loopx first", +) +mcp, control = create_fastmcp_server(CONFIG, lambda: goal_context(Path.cwd())) + +# Compatibility names used by existing smoke tests and local integrations. +should_run = control.should_run +list_todos = control.list_todos +claim_task = control.claim_task +complete_task = control.complete_task + + +if __name__ == "__main__": + mcp.run() diff --git a/loopx/hosts/claude/scripts/connect.py b/loopx/hosts/claude/scripts/connect.py new file mode 100644 index 0000000000..8bfca84cc2 --- /dev/null +++ b/loopx/hosts/claude/scripts/connect.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Connect a project to loopx for Claude Code (PROJECT-scoped). + +Thin wrapper: (1) `loopx connect` the repo, (2) mark `agent_backends += claude` +in the project registry, (3) install the Claude adapter at PROJECT scope (the +loopx MCP + the `/loopx` command into this project's `.claude/`) by delegating to +install.py. No global config, no OS sandbox. The run loop is native `/loop`. + + python connect.py --project DIR --goal-id G [--objective "…"] [--harden] +""" +from __future__ import annotations + +import argparse +import shutil +import subprocess +import sys +from pathlib import Path + +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, +) + + +def _gh_prefix(): + exe = shutil.which("loopx") + return [exe] if exe else [sys.executable, "-m", "loopx.cli"] + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--project", required=True) + ap.add_argument("--goal-id", required=True) + ap.add_argument("--objective", default=None) + ap.add_argument("--registry", default=None) + ap.add_argument("--harden", action="store_true", + help="also install the optional PreToolUse should_run gate + statusline (project scope)") + ap.add_argument("--dry-run", action="store_true") + a = ap.parse_args() + proj = Path(a.project).resolve() + dry = a.dry_run + + # 1. connect the repo to loopx (optional, when an objective is given) + if a.objective: + cmd = list(_gh_prefix()) + (["--registry", a.registry] if a.registry else []) + \ + ["connect", "--goal-id", a.goal_id, "--objective", a.objective, + "--state-file", f".claude/goals/{a.goal_id}/ACTIVE_GOAL_STATE.md"] + print("[connect]", " ".join(cmd)) + if not dry: + try: + rc = subprocess.run(cmd, cwd=str(proj), timeout=120) + except Exception as e: + print(f"[connect] FAILED to run loopx connect: {e}") + sys.exit(1) + if rc.returncode != 0: + # Fail closed: a non-zero connect (e.g. a global route collision) + # must stop the helper rather than print a misleading "next steps". + print(f"[connect] FAILED (exit {rc.returncode}) — not continuing. " + "Resolve the error above and re-run.") + sys.exit(rc.returncode) + + # 2. mark agent_backends += claude in the project registry (additive) + if a.registry: + reg = Path(a.registry) + else: + reg = proj / ".loopx" / "registry.json" + if not reg.exists() and (proj / ".goal-harness" / "registry.json").exists(): + reg = proj / ".goal-harness" / "registry.json" + if reg.exists(): + try: + payload = load_project_registry(reg) + require_runtime_compatible_project_registry( + payload, + operation="Claude Goal adapter", + ) + print(f"[registry] mark agent_backends += claude ({reg})") + if not dry: + add_project_registry_backend(reg, "claude") + except ProjectRegistryProtocolError as e: + print(f"[registry] FAILED: {e}") + sys.exit(1) + except Exception as e: + print(" (registry annotate skipped:", e, ")") + else: + print(f"[registry] {reg} not found yet (run with --objective to connect first)") + + # 3. install the Claude adapter at PROJECT scope (MCP + /loopx command [+ --harden]) + installer = PLUGIN_ROOT / "scripts" / "install.py" + inst = [sys.executable, str(installer), "--scope", "project", "--project", str(proj)] + if a.harden: + inst.append("--harden") + if dry: + inst.append("--dry-run") + print("[install]", " ".join(inst)) + ri = subprocess.run(inst, cwd=str(proj)) + if ri.returncode != 0: + # Fail closed: don't claim success / print next steps if the adapter + # install failed. + print(f"[install] FAILED (exit {ri.returncode}).") + sys.exit(ri.returncode) + + print("\nNext: open Claude Code in the project, then:") + print(" /loopx # set the goal, write .claude/loop.md, do the first segment") + print(" /loop # drive the loop (native; loopx should_run gates each tick)") + print(" /loopx off # remove the loop protocol") + + +if __name__ == "__main__": + main() diff --git a/loopx/hosts/claude/scripts/goalmode_cmd.py b/loopx/hosts/claude/scripts/goalmode_cmd.py new file mode 100644 index 0000000000..29002f47f2 --- /dev/null +++ b/loopx/hosts/claude/scripts/goalmode_cmd.py @@ -0,0 +1,292 @@ +#!/usr/bin/env python3 +"""Smart entry for the `/loopx` slash command — the loopx setup helper. + +LoopX does NOT own the run loop on Claude Code. Claude Code's native `/loop` is +the scheduler/executor; loopx provides the control-plane protocol (the MCP tools ++ a per-iteration `.claude/loop.md`). `/loopx` just sets a goal up and hands off +to `/loop`. + +Routing by first token: + -> ONE-SHOT: ensure a goal exists for this project (bootstrap + if needed), register a default agent, add the task as a + todo, write `.claude/loop.md` (the protocol), and do one + bounded first segment. Then drive it with native `/loop`. + (no args) / on -> (re)write `.claude/loop.md` for this project's existing + goal and show how to drive it with `/loop`. + status -> the project's goal detail (objective, state, next, todos). + off -> remove `.claude/loop.md` (native `/loop` then has nothing + to run). Registry/goal are left intact. + +The LoopX registry (`.loopx/registry.json`) is the single source of truth for +goal_id/agent/scope. The default agent `cc` is registered so the loopx identity +contract is active and `quota should-run --agent-id cc` is satisfied. +""" +from __future__ import annotations + +import json +import os +import re +import shutil +import subprocess +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +DEFAULT_AGENT = "cc" + +# registry-driven context, shared with the hooks/MCP +sys.path.insert(0, str(HERE.parent / "hooks")) +from goal_state import goal_context, find_registry, loop_md_path # noqa: E402 +from stdio_utf8 import pin_utf8_stdio # noqa: E402 +from loopx.control_plane.heartbeat.rules import ( # noqa: E402 + HOST_LOOP_SAFETY_RULE, + RUNTIME_REPAIR_ROUTING_RULE, + SCOPE_BOUNDED_WORK_RULE, +) +from loopx.history import load_registry # noqa: E402 + + +def gh_prefix(): + """Cross-platform loopx invocation: the CLI shim if on PATH, else the module.""" + exe = shutil.which("loopx") + return [exe] if exe else [sys.executable, "-m", "loopx.cli"] + + +def gh(args, cwd=None): + return subprocess.run(gh_prefix() + args, cwd=cwd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=120) + + +def slug(name: str) -> str: + s = re.sub(r"[^a-zA-Z0-9]+", "-", name).strip("-").lower() or "project" + return f"cc-{s}"[:48] + + +def loop_execution_content(goal_id, agent_id) -> str: + """The per-iteration protocol that native `/loop` runs (written to + .claude/loop.md). loopx's should_run is the deterministic per-tick gate; the + agent uses the wired loopx MCP tools, never raw CLI guessing. + + The leading `loopx:armed` marker persists WHICH goal /loopx armed for this + project, so goal_state.goal_context() resolves the right goal in multi-goal + registries instead of guessing from registry order.""" + armed = json.dumps({"goal_id": goal_id, "agent_id": agent_id}) + return ( + f"\n" + f"loopx tick — advance goal `{goal_id}` (agent `{agent_id}`). Use the wired loopx MCP\n" + f"tools; do NOT run `loopx --help` or guess ids.\n\n" + f"{HOST_LOOP_SAFETY_RULE}\n{RUNTIME_REPAIR_ROUTING_RULE}\n" + "Read complete successful `should_run()` JSON each work iteration. Follow its\n" + "current `interaction_contract`: selection/re-entry before admitted work,\n" + "then validation and settlement. Never infer completion from an empty Todo list.\n" + f"{SCOPE_BOUNDED_WORK_RULE}\n" + "Honor claim/lease and user/repository authority; claim only when required.\n" + "Run real acceptance checks before `complete_task`; supply truthful evidence\n" + f"and the bound agent_id=\"{agent_id}\". Complete only finished Todos, not partial work.\n" + "That MCP operation owns writeback/spend: use it INSTEAD OF the raw CLI sequence.\n" + "Use interaction_contract.mcp_channel for tool ownership and vision input limits.\n" + "At material delivery, compare the Goal's vision/acceptance with actual evidence.\n" + "Pass the resulting agent_vision or a justified vision_unchanged_reason to\n" + "complete_task. If omitted, call review_task_vision with only that Todo and\n" + "Agent to read the basis; rejudge, then submit read_context_id with the decision.\n" + "Stale/replaced receipts require rereading; lost replies retry the same receipt\n" + "and decision. Recovery never spends again. This is not a Goal-stop\n" + "shortcut: open acceptance needs replan; vision_closed closes a stage and needs\n" + "a successor vision; no_followup requires evidence of no remaining scoped work.\n" + "For new replan work not covered by these tools, use the exact live\n" + "interaction_contract CLI actions, preserving its binding and settlement order.\n" + "Link already planned follow-up via successor_todo_ids; next_agent_todo creates\n" + "new work, not a reference to an existing id. Do not duplicate the current plan.\n" + "After a lost response, read back or retry the same completion intent; do not\n" + "invent a new successor or settlement identity. Recheck `should_run()` afterward.\n" + "Continue authorized work while the live contract requires it; notification\n" + "silence is not execution silence. Waiting is not completion: follow current\n" + "host scheduling guidance without repeated unchanged polling. Terminal\n" + "no-follow-up ends this Goal's work; cancel only its own recurring wakeup.\n" + "Repair entrypoint errors within authority; an unavailable/incomplete contract\n" + "permits neither work nor spending and must not be reported as completion.\n" + ) + + +def loop_md_content(goal_id, agent_id) -> str: + from loopx.control_plane.heartbeat.bootstrap_prompt import BOOTSTRAP_INSTRUCTION + armed = json.dumps({"goal_id": goal_id, "agent_id": agent_id}) + return (f"\nLoopX managed MCP bootstrap v1\n" + "Each entry/resume: call the bound LoopX `host_prompt` MCP tool, " + "verify its goal_id and agent_id match the armed binding above, " + "then read its complete task_body. Do not create another Goal or scheduler.\n" + f"{BOOTSTRAP_INSTRUCTION}\n") + + +def write_loop_md(proj: Path, goal_id, agent_id) -> Path: + """Write the protocol to /.claude/loop.md (bare `/loop` runs it).""" + path = loop_md_path(proj) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(loop_md_content(goal_id, agent_id), encoding="utf-8") + return path + + +def goal_detail(ctx): + """Objective (from the registry goal entry's active-state file) + live state + (from quota should-run) for the `/loopx status` detail view.""" + gid, reg, agent = ctx.get("goal_id"), ctx.get("registry"), ctx.get("agent_id") + objective = "" + if reg: + try: + regp = Path(reg) + data = load_registry(regp) + entry = next((g for g in data.get("goals", []) if g.get("id") == gid), None) + sf = (entry or {}).get("state_file") + if sf: + text = (regp.parent.parent / sf).read_text(encoding="utf-8") + m = re.search(r"^objective:\s*(.+)$", text, re.MULTILINE) + if m: + objective = m.group(1).strip().strip('"').strip("'") + except Exception: + pass + payload = {} + try: + cmd = gh_prefix() + (["--registry", reg] if reg else []) + \ + ["--format", "json", "quota", "should-run", "--goal-id", gid] + if agent: + cmd += ["--agent-id", agent] + out = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=15, + env={**os.environ, "LOOPX_CONTEXT_DELIVERY": "off"}) + payload = json.loads(out.stdout or "{}") + except Exception: + pass + return objective, payload + + +def print_status(ctx): + gid = ctx.get("goal_id") + objective, d = goal_detail(ctx) + a = d.get("agent_todo_summary") or {} + done, open_ = a.get("done_count"), a.get("open_count") + gate = d.get("gate_prompt") + if gate: + state = f"⚠ needs you: {gate}" + elif d.get("should_run") is True: + state = "▶ running" + else: + state = f"⏸ {d.get('state') or 'paused'}" + (f" — {d['reason']}" if d.get("reason") else "") + print(f"goal : {gid}") + print(f"agent : {ctx.get('agent_id') or DEFAULT_AGENT}") + if objective: + print(f"objective : {objective}") + print(f"state : {state}") + if d.get("recommended_action"): + print(f"next : {d['recommended_action']}") + if done is not None or open_ is not None: + print(f"todos : {done} done / {open_} open") + for it in (a.get("first_open_items") or [])[:8]: + t = (it.get("text") or "").strip() + if t: + print(f" ▸ {t}") + armed_root = Path(ctx.get("project_root") or Path.cwd()) + armed = "armed (.claude/loop.md present)" if loop_md_path(armed_root).exists() else "not armed (run /loopx to arm)" + print(f"loop : {armed} — drive with native /loop") + + +def main(): + args = sys.argv[1:] + first = args[0] if args else None + proj = Path.cwd() + + # off: remove the loop protocol; native /loop then has nothing to run. + if first == "off": + reg = find_registry(proj) + target_root = reg.parent.parent if reg is not None else proj + lp = loop_md_path(target_root) + if not lp.exists(): + print("goal-mode OFF (no .claude/loop.md here).") + return + try: + lp.unlink() + print("goal-mode OFF — removed .claude/loop.md. (Press Esc to stop a running /loop.)") + except OSError as e: + print(f"goal-mode OFF — could not remove {lp} ({e}); remove it manually.") + return + + # status: full goal detail. + if first == "status": + ctx = goal_context(proj) + if not ctx: + print("loopx goal-mode: no goal in this project yet — run `/loopx ` to create one.") + return + print_status(ctx) + return + + # bare (=on) / on: (re)arm THIS project's existing goal and show how to drive it. + if not args or first == "on": + ctx = goal_context(proj) + if not ctx or not ctx.get("goal_id"): + print("loopx goal-mode: ready — no goal set in this project yet.") + print("Tell me what to work on and I'll set it up:") + print(" /loopx e.g. /loopx 写一个 RTL 模块并跑通仿真") + return + write_loop_md(proj, ctx["goal_id"], ctx.get("agent_id") or DEFAULT_AGENT) + print(f"goal-mode armed goal={ctx['goal_id']} agent={ctx.get('agent_id') or DEFAULT_AGENT}") + print("Drive it with native /loop: `/loop` (Claude self-paces) | `/loop 10m` (fixed).") + print("Stop with Esc; `/loopx off` removes the loop protocol.") + return + + # free-text task -> one-shot setup + write loop.md + first bounded segment. + task = " ".join(args).strip().strip('"').strip("'") + reg = find_registry(proj) + if reg is not None: + ctx = goal_context(proj) or {} + goal_id = ctx.get("goal_id") + registry = str(reg) + else: + goal_id = slug(proj.name) + registry = str(proj / ".loopx" / "registry.json") + # Claude projects keep goal state under .claude/ (not the Codex-default .codex/) + state_file = f".claude/goals/{goal_id}/ACTIVE_GOAL_STATE.md" + r = gh(["bootstrap", "--project", str(proj), "--goal-id", goal_id, + "--objective", task, "--state-file", state_file]) + if "ok: `True`" not in r.stdout and "ok=True" not in r.stdout and r.returncode != 0: + print("[loopx] bootstrap failed:\n" + (r.stdout + r.stderr)[:600]) + sys.exit(1) + + if not goal_id: + print("[loopx] could not determine goal id") + sys.exit(1) + + # register the default agent (identity contract) and add the task as a todo + cfg = gh(["--registry", registry, "configure-goal", "--goal-id", goal_id, + "--agent-model", "peer_v1", "--registered-agent", DEFAULT_AGENT, "--execute"]) + if cfg.returncode != 0: + print("[loopx] configure-goal failed:\n" + (cfg.stdout + cfg.stderr)[:600]) + sys.exit(1) + add = gh(["--registry", registry, "--format", "json", "todo", "add", + "--goal-id", goal_id, "--role", "agent", "--text", task]) + if add.returncode != 0: + print("[loopx] todo add failed:\n" + (add.stdout + add.stderr)[:600]) + sys.exit(1) + todo_id = "" + try: + todo_id = json.loads(add.stdout).get("todo_id", "") + except Exception: + pass + + # write the per-iteration protocol; the RUN happens when the user types /loop + # (this command only SETS UP the goal — it must not do the work itself). + write_loop_md(proj, goal_id, DEFAULT_AGENT) + + tid = todo_id or "(see should_run output)" + print("goal set up. loopx is the control plane; Claude Code's native /loop is the runtime.") + print(f" goal_id : {goal_id}") + print(f" agent : {DEFAULT_AGENT}") + print(f" todo_id : {tid}") + print(f" scope : {proj}") + print(f" task : {task}") + print(" wrote : .claude/loop.md (the per-tick protocol)") + print() + print("START WORKING — run native `/loop` (Claude self-paces) or `/loop 10m` (fixed cadence).") + print("Each /loop tick follows should_run's current contract; complete_task settles only verified, finished work.") + print("Stop with Esc or `/loopx off`.") + + +if __name__ == "__main__": + pin_utf8_stdio() + main() diff --git a/loopx/hosts/claude/scripts/install.py b/loopx/hosts/claude/scripts/install.py new file mode 100644 index 0000000000..387254d1c6 --- /dev/null +++ b/loopx/hosts/claude/scripts/install.py @@ -0,0 +1,1508 @@ +#!/usr/bin/env python3 +"""Install the loopx Claude Code adapter — EXPLICIT, scoped, opt-in. + +This is NOT run by the default loopx installer. It is invoked deliberately +(`LOOPX_INSTALL_CLAUDE=1 scripts/install-local.sh`, or directly). It installs the +minimum: the loopx **MCP server** (the control-plane tools) + the **`/loopx`** +slash command. The run loop is Claude Code's native `/loop`; loopx only provides +the `should_run` protocol, so NO global hooks are wired by default. + + python install.py --scope project [--project DIR] # this project only (preferred) + python install.py --scope user # all your Claude Code projects + python install.py --scope ... --harden # ALSO add the optional + # PreToolUse should_run gate + # + statusline at that scope + +`--scope` is required (a deliberate choice). User scope is announced loudly. We +NEVER delete existing permission rules; legacy loopx entries get a printed +cleanup suggestion instead. +""" +from __future__ import annotations + +from typing import Any, NamedTuple + +import argparse +import json +import os +import re +import shlex +import shutil +import subprocess +import sys +from pathlib import Path + +PLUGIN_ROOT = Path(__file__).resolve().parents[1] +MCP_VENV = Path.home() / ".local" / "share" / "loopx" / "mcp-venv" + +# This script is run by path (`python /loopx/hosts/claude/scripts/ +# install.py`), so the package root is not on `sys.path` by default. +REPO_ROOT = Path(__file__).resolve().parents[4] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from loopx.file_lock import write_bytes_atomic, write_json_atomic # noqa: E402 + + +def _p(*parts: str) -> str: + return str(PLUGIN_ROOT.joinpath(*parts)).replace("\\", "/") + + +def _is_git_bash(path: str) -> bool: + """True when `path` is the MSYS/Cygwin bash Claude Code dispatches to. + + The WSL `bash.exe` that sits on some PATHs is a Linux shell, not the Git + Bash Claude Code spawns for a Windows command string, and its `uname` says + `Linux`; the System32 alias is rejected by name and everything else by + asking the candidate for its `uname`.""" + system32 = Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32" + resolved = os.path.normcase(os.path.realpath(path)) + system32_resolved = os.path.normcase(os.path.realpath(system32)) + if resolved == system32_resolved or resolved.startswith(system32_resolved + os.sep): + return False + try: + probe = subprocess.run([path, "-c", "uname -s"], capture_output=True, timeout=10) + except (OSError, subprocess.SubprocessError): + return False + return probe.returncode == 0 and probe.stdout.decode("utf-8", "replace").startswith( + ("MINGW", "MSYS", "CYGWIN") + ) + + +# Claude Code honors `CLAUDE_CODE_GIT_BASH_PATH` only when the file name is one +# of these (env-vars reference, 2.1.219+); any other name is ignored and Git +# Bash detection continues as if the variable were unset - even when the file +# exists and runs. +_GIT_BASH_OVERRIDE_NAMES = frozenset({"bash.exe", "sh.exe", "bash", "sh"}) + + +def _git_bash() -> str | None: + """The Git Bash Claude Code runs a shell-form command string with, if any. + + Claude Code passes a hook or statusline string to Git Bash on Windows when + Git Bash is installed, to PowerShell when it is not, and to `/bin/sh` on + macOS/Linux (Claude Code hooks reference, "Exec form and shell form"). It + finds Git Bash through its `CLAUDE_CODE_GIT_BASH_PATH` override, the Git + installation or a `bash` on PATH, or a default Git for Windows location; + this mirrors those sources so the encoding can follow the same choice. Like + that consumer, an override whose file name is not `bash.exe`, `sh.exe`, + `bash` or `sh` (compared case-insensitively) is ignored and detection + continues as if it were unset.""" + if sys.platform != "win32": + return None + candidates: list[str] = [] + override = os.environ.get("CLAUDE_CODE_GIT_BASH_PATH") + if override and Path(override).name.lower() in _GIT_BASH_OVERRIDE_NAMES: + candidates.append(override) + git = shutil.which("git") + if git: + root = Path(git).resolve().parent.parent + candidates += [str(root / "bin" / "bash.exe"), str(root / "usr" / "bin" / "bash.exe")] + on_path = shutil.which("bash") + if on_path: + candidates.append(on_path) + for base, sub in ( + (os.environ.get("ProgramFiles"), "Git"), + (os.environ.get("ProgramFiles(x86)"), "Git"), + (os.environ.get("LocalAppData"), "Programs/Git"), + ): + if base: + candidates.append(str(Path(base) / sub / "bin" / "bash.exe")) + for candidate in candidates: + if os.path.isfile(candidate) and _is_git_bash(candidate): + return candidate + return None + + +def _uses_powershell() -> bool: + """Whether Claude Code runs these command strings through PowerShell. + + A Windows host without Git Bash gets PowerShell for shell-form hooks and + the statusline; every other host runs `/bin/sh` or Git Bash.""" + return sys.platform == "win32" and _git_bash() is None + + +def _shell_literal(value: str, *, powershell: bool) -> str: + """Render `value` as one literal token the consumer shell reads back whole. + + Double quotes are not literal in either shell: `$NAME` expands inside them + and an inner `"` can close the token. Single quotes are literal in both, so + POSIX/Git Bash targets get `shlex.quote`'s form and PowerShell a `'...'` + string with its `''` escape. A bare Windows path would lose its + backslashes under Git Bash, so those are quoted too.""" + if powershell: + return "'" + value.replace("'", "''") + "'" + return shlex.quote(value) + + +def _shell_command(value: str, *, powershell: bool) -> str: + """`_shell_literal` in command position: PowerShell needs its `&` operator.""" + token = _shell_literal(value, powershell=powershell) + return f"& {token}" if powershell else token + + +def _launches_python(py: str) -> bool: + """True when running `py` starts a supported Python 3.11+ interpreter. + + `shutil.which` only proves a file is executable, not that it runs Python. On + Windows it can return the 0-byte `WindowsApps` App Execution Alias, which + never starts Python: on some hosts it exits non-zero (9009), on others + launching it raises OSError, and it writes nothing either way. Anything that + bakes that path (the PreToolUse hook, the statusline, `/loopx`) then + silently does nothing.""" + try: + return subprocess.run( + [py, "-c", "import sys; raise SystemExit(sys.version_info < (3, 11))"], + capture_output=True, + timeout=10, + ).returncode == 0 + except (OSError, subprocess.SubprocessError): + return False + + +def _python_cmd() -> str: + """Interpreter to bake into hook / statusline / command strings — robust where + only `python` (not `python3`) is registered, and where `python3` resolves to a + launcher that cannot run supported Python (including the Windows + `WindowsApps` alias and an older PATH interpreter).""" + for candidate in (shutil.which("python3"), shutil.which("python")): + if candidate and _launches_python(candidate): + return candidate + return sys.executable + + +def deep_merge(base: dict[str, Any], add: dict[str, Any]) -> dict[str, Any]: + for k, v in add.items(): + if isinstance(v, dict) and isinstance(base.get(k), dict): + deep_merge(base[k], v) + elif isinstance(v, list) and isinstance(base.get(k), list): + base[k] += [x for x in v if x not in base[k]] + else: + base[k] = v + return base + + +# ---- optional hardening (only with --harden) -------------------------------- + +def hardening_block() -> dict[str, Any]: + """The OPTIONAL per-tool gate + statusline. Not installed unless --harden.""" + powershell = _uses_powershell() + py = _shell_command(_python_cmd(), powershell=powershell) + gate = _shell_literal(_p("hooks", "goal_policy.py"), powershell=powershell) + status = _shell_literal(_p("statusline", "goal_status.py"), powershell=powershell) + return { + "hooks": { + "PreToolUse": [{"matcher": "*", "hooks": [ + {"type": "command", "command": f"{py} {gate}", "timeout": 10}]}], + }, + "statusLine": {"type": "command", "command": f"{py} {status}"}, + } + + +# ---- MCP dependency provisioning -------------------------------------------- + +def _venv_python(venv: Path) -> Path: + sub = "Scripts" if sys.platform == "win32" else "bin" + exe = "python.exe" if sys.platform == "win32" else "python" + return venv / sub / exe + + +# The server imports `mcp.server.fastmcp`, which MCP SDK 2.x no longer ships. +# Checking a bare `import mcp` accepts an interpreter that cannot actually run +# the server, so registration would write a config that fails to start — +# `cursor-agent mcp list` reports "Connection failed" and Claude silently drops +# the tools. Probe the module the server really needs. +MCP_PROBE = "import mcp.server.fastmcp" +# Upper bound for the same reason; drop it once loopx_mcp.py speaks the 2.x API. +MCP_REQUIREMENT = "mcp<2" + + +def _has_mcp(py: str | Path) -> bool: + try: + return subprocess.run([str(py), "-c", MCP_PROBE], capture_output=True).returncode == 0 + except (FileNotFoundError, OSError): + return False + + +def provision_mcp_python(dry: bool, allow_system_pip: bool = False) -> str: + """Return an interpreter that can `import mcp`, installing it into a dedicated + venv if needed (works under PEP 668 externally-managed pythons). + + We install `mcp` ONLY into a dedicated venv we own. We never silently mutate + the user's active/system interpreter (`pip install --break-system-packages`); + that is gated behind an explicit ``allow_system_pip`` opt-in.""" + if _has_mcp(sys.executable): + print(f"[deps] mcp already importable by {sys.executable}") + return sys.executable + vpy = _venv_python(MCP_VENV) + if _has_mcp(vpy): + print(f"[deps] reusing mcp venv {MCP_VENV}") + return str(vpy) + if dry: + print(f"[deps] (dry-run) would create venv {MCP_VENV} and pip install mcp") + return str(vpy) + print(f"[deps] creating mcp venv {MCP_VENV} …") + MCP_VENV.parent.mkdir(parents=True, exist_ok=True) + r = subprocess.run([sys.executable, "-m", "venv", str(MCP_VENV)], capture_output=True, text=True, encoding="utf-8", errors="replace",) + if r.returncode == 0: + subprocess.run([str(vpy), "-m", "pip", "install", "-q", "--upgrade", "pip"], capture_output=True, text=True, encoding="utf-8", errors="replace",) + pip = subprocess.run([str(vpy), "-m", "pip", "install", "-q", MCP_REQUIREMENT], capture_output=True, text=True, encoding="utf-8", errors="replace",) + if pip.returncode == 0 and _has_mcp(vpy): + print(f"[deps] mcp installed into {MCP_VENV}") + return str(vpy) + print("[deps] venv pip install failed:\n" + (pip.stdout + pip.stderr)[:300]) + else: + print("[deps] venv creation failed:\n" + (r.stdout + r.stderr)[:300]) + # The dedicated venv is the only place we install `mcp`. Do NOT touch the + # user's active/system interpreter unless they explicitly opted in. + if allow_system_pip: + print("[deps] --allow-system-pip: pip install --break-system-packages mcp") + subprocess.run([sys.executable, "-m", "pip", "install", "-q", "--break-system-packages", MCP_REQUIREMENT], + capture_output=True, text=True, encoding="utf-8", errors="replace",) + if _has_mcp(sys.executable): + return sys.executable + print("[deps] WARNING: could not provision `mcp` into a dedicated venv, and we will\n" + " NOT modify your system Python. The loopx MCP tools will not load until\n" + " you install `mcp` yourself, e.g.:\n" + f" {sys.executable} -m venv {MCP_VENV} && {vpy} -m pip install '{MCP_REQUIREMENT}'\n" + " (or re-run install.py with --allow-system-pip to use the active interpreter).") + return _python_cmd() + + +def install_mcp( + dry: bool, + py: str, + scope: str, + migrate_goal_harness: bool = False, + project_dir: Path | None = None, +) -> bool: + """Register the loopx MCP server at the chosen scope via `claude mcp add`. + + We replace only OUR `loopx` entry. A legacy/user-owned `goal-harness` MCP is + left untouched by default — we don't delete a server we don't own. If one + exists we print a manual cleanup hint; `--migrate-goal-harness` removes it. + + Returns whether the `loopx` entry is registered afterwards: True only when + `claude mcp add` reported success. A missing `claude` CLI and a failed add + both leave the server unregistered and print the manual command instead, so + a caller that narrates the install must read that receipt, not the attempt.""" + if scope == "project" and project_dir is None: + raise ValueError("project_dir is required for project-scoped MCP registration") + cwd_run = str(project_dir) if scope == "project" else None + claude = shutil.which("claude") + mcp_path = _p("mcp", "loopx_mcp.py") + add = ["mcp", "add", "--scope", scope, "loopx", "--", py, mcp_path] + if not claude: + print("[mcp] claude CLI not on PATH — add the MCP server manually:\n claude " + " ".join(add)) + return False + print(f"[mcp] claude mcp add --scope {scope} loopx -- {py} ") + if dry: + return False + subprocess.run( + [claude, "mcp", "remove", "--scope", scope, "loopx"], + capture_output=True, + text=True, encoding="utf-8", errors="replace", + cwd=cwd_run, + ) + has_gh = subprocess.run( + [claude, "mcp", "get", "goal-harness"], + capture_output=True, + text=True, encoding="utf-8", errors="replace", + cwd=cwd_run, + ).returncode == 0 + if has_gh: + if migrate_goal_harness: + print(f"[mcp] --migrate-goal-harness: removing legacy goal-harness MCP at {scope} scope") + subprocess.run( + [claude, "mcp", "remove", "--scope", scope, "goal-harness"], + capture_output=True, + text=True, encoding="utf-8", errors="replace", + cwd=cwd_run, + ) + else: + print("[mcp] note: a legacy `goal-harness` MCP entry exists — left untouched. Remove it " + f"yourself with `claude mcp remove --scope {scope} goal-harness`, or re-run with " + "--migrate-goal-harness.") + r = subprocess.run( + [claude, *add], + capture_output=True, + text=True, encoding="utf-8", errors="replace", + cwd=cwd_run, + ) + if r.returncode != 0: + print(" (mcp add failed; add manually:\n claude " + " ".join(add) + "\n " + (r.stdout + r.stderr)[:200] + ")") + return False + return True + + +# ---- /loopx command ---------------------------------------------------------- + +def command_md() -> str: + # The `!` line runs through the Bash tool - `sh`/Git Bash on every host - so + # it is always a POSIX literal, never the PowerShell form; a Windows host + # without Git Bash cannot run `!` lines at all (README). + entry = _shell_literal(_p("scripts", "goalmode_cmd.py"), powershell=False) + py = _shell_literal(_python_cmd(), powershell=False) + return ( + "---\n" + "description: loopx goal-mode setup. " + "`/loopx ` sets up a goal + writes .claude/loop.md; drive the loop with native /loop. " + "bare /loopx = arm; off | status.\n" + "argument-hint: | (no args = arm) | off | status\n" + f"allowed-tools: Bash({py}:*)\n" + "---\n\n" + "Run the loopx setup helper and read its output:\n\n" + f"!`{py} {entry} $ARGUMENTS`\n\n" + "The output is loopx control-plane SETUP / status info — it is the COMPLETE, user-facing " + "result. Show it to the user VERBATIM and STOP. Do NOT do any work, claim todos, write " + "files, or loop here: the WORK runs when the user types Claude Code's native `/loop` (which " + "executes `.claude/loop.md`). Do not summarize a multi-line `status` detail block into one line.\n\n" + "The run loop is native `/loop`; loopx provides the deterministic " + "`should_run` protocol.\n" + ) + + +def install_command(dry: bool, cmd_dir: Path) -> None: + path = cmd_dir / "loopx.md" + print(f"[command] /loopx -> {path}") + if dry: + return + cmd_dir.mkdir(parents=True, exist_ok=True) + old = cmd_dir / "goalmode.md" # migrate the legacy /goalmode entry name + if old.exists(): + old.unlink() + path.write_text(command_md(), encoding="utf-8") + + +class HardenSettingsUnreadable(RuntimeError): + """`--harden` refuses to rewrite a settings file it cannot read as JSON.""" + + +def add_hardening(dry: bool, settings_path: Path) -> None: + """Deep-merge the optional hook + statusline into settings_path, preserving + existing config. NEVER deletes permission rules. + + The merge rewrites the whole file, so a settings file that exists but does + not parse is refused instead of replaced: substituting `{}` for it would + drop every key the user owns - permission rules, `env`, `model`, other + hooks, MCP approvals - leaving only the loopx block, at exit status 0. The + file is user-owned (LoopX did not create it), which is why the sibling + merge in `loopx/slash_command_install.py` fails closed on the same input. + """ + cur = {} + if settings_path.exists(): + try: + cur = json.loads(settings_path.read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + raise HardenSettingsUnreadable( + f"{settings_path} exists but is not readable as JSON ({exc}); refusing to " + "rewrite it. Fix or move that file, then re-run with --harden." + ) from exc + if not isinstance(cur, dict): + raise HardenSettingsUnreadable( + f"{settings_path} exists but is not a JSON object; refusing to rewrite it. " + "Fix or move that file, then re-run with --harden." + ) + # prune prior loopx PreToolUse entries (avoid stacking on reinstall) + for grp in (cur.get("hooks", {}) or {}).get("PreToolUse", []) or []: + grp["hooks"] = [h for h in grp.get("hooks", []) if "goal_policy.py" not in str(h.get("command", ""))] + if isinstance(cur.get("hooks", {}).get("PreToolUse"), list): + cur["hooks"]["PreToolUse"] = [g for g in cur["hooks"]["PreToolUse"] if g.get("hooks")] + merged = deep_merge(cur, hardening_block()) + print(f"[harden] PreToolUse should_run gate + statusline -> {settings_path}") + if not dry: + # One replace, not a truncate-in-place: an interrupted install must not + # leave the user's settings.json as a partial document. The destination + # is resolved first so a dotfiles-managed symlink keeps pointing at its + # target instead of being replaced by the rename. + write_json_atomic(settings_path.resolve(), merged, preserve_mode=True) + + +def warn_legacy_perms(settings_path: Path) -> None: + """Detect a legacy loopx credential-deny and SUGGEST manual cleanup. Never mutate.""" + try: + cur = json.loads(settings_path.read_text(encoding="utf-8")) + except Exception: + return + deny = ((cur.get("permissions") or {}).get("deny")) or [] + legacy = [r for r in deny if r in ("Read(~/.ssh/**)", "Read(~/.aws/**)")] + if legacy: + print(f"[note] {settings_path} has loopx-era permission deny rules {legacy}. " + "We no longer add these and will NOT remove them automatically. " + "To drop them, edit that file's `permissions.deny` by hand.") + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--scope", choices=["user", "project"], required=True, + help="user = ~/.claude (all projects); project = THIS project's .claude (preferred)") + ap.add_argument("--project", default=None, help="project dir for --scope project (default: cwd)") + ap.add_argument("--harden", action="store_true", + help="ALSO install the optional PreToolUse should_run gate + statusline") + ap.add_argument("--skip-mcp", action="store_true", + help="skip MCP venv provisioning + `claude mcp add` (for tests/CI)") + ap.add_argument("--allow-system-pip", action="store_true", + help="if the dedicated mcp venv can't be built, fall back to " + "`pip install --break-system-packages mcp` into the active interpreter " + "(off by default — we don't mutate your system Python)") + ap.add_argument("--migrate-goal-harness", action="store_true", + help="also remove a legacy `goal-harness` MCP entry at this scope " + "(off by default — we don't delete MCP servers we don't own)") + ap.add_argument("--dry-run", action="store_true") + a = ap.parse_args() + dry = a.dry_run + + project_dir = None + if a.scope == "project": + project_dir = Path(a.project).resolve() if a.project else Path.cwd() + claude_dir = project_dir / ".claude" + print(f"[scope] PROJECT — installs into {claude_dir} (this project only)") + else: + claude_dir = Path.home() / ".claude" + print("[scope] USER — installs into ~/.claude. The /loopx command and MCP become") + print(" available in ALL your Claude Code projects." + + (" --harden adds USER-LEVEL, matcher-wide hooks too." if a.harden else "")) + + mcp_registered = False + if a.skip_mcp: + print("[mcp] skipped (--skip-mcp)") + else: + mcp_python = provision_mcp_python(dry, a.allow_system_pip) + mcp_registered = install_mcp( + dry, + mcp_python, + a.scope, + a.migrate_goal_harness, + project_dir=project_dir, + ) + install_command(dry, claude_dir / "commands") + + settings_path = claude_dir / "settings.json" + if a.harden: + try: + add_hardening(dry, settings_path) + except HardenSettingsUnreadable as exc: + print(f"[harden] {exc}", file=sys.stderr) + outcome = ( + "nothing was written (dry-run)" + if dry + else "the settings file is unchanged" + ) + print( + f"[harden] the optional should_run gate + statusline were skipped; {outcome}.", + file=sys.stderr, + ) + if not dry: + # The rest of the install did run, so name only what happened: + # the /loopx command was written just above, and the MCP state is + # the registration receipt `install_mcp` returned - not the + # attempt. A missing CLI or a failed `claude mcp add` leaves the + # server unregistered, and reporting that attempt as an install + # would let a user skip the manual command printed above. + if a.skip_mcp: + mcp_state = "the MCP server was skipped (--skip-mcp)" + elif mcp_registered: + mcp_state = "the MCP server was registered" + else: + mcp_state = ("the MCP server was not registered — run the " + "`claude mcp add` command printed above") + print( + f"[harden] the /loopx command was installed; {mcp_state}.", + file=sys.stderr, + ) + return 2 + else: + print("[harden] skipped (default): no hooks/statusline installed. Add later with --harden.") + warn_legacy_perms(settings_path) + + print("\nloopx Claude adapter installed.") + print("Next: in a project with a goal, type `/loopx `, then drive it with native `/loop`.") + print("Restart any open Claude Code session so the command/MCP load.") + if dry: + print("(dry-run: nothing written)") + return 0 + + +_LEGACY_COMMAND_SCRIPT_SUFFIX = "/loopx/claude_goal_mode/scripts/goalmode_cmd.py" +_LEGACY_POLICY_HOOK_SUFFIX = "/loopx/claude_goal_mode/hooks/goal_policy.py" +_LEGACY_STATUSLINE_SCRIPT_SUFFIX = "/loopx/claude_goal_mode/statusline/goal_status.py" +_LEGACY_MCP_SCRIPT_SUFFIX = "/loopx/claude_goal_mode/mcp/loopx_mcp.py" +_LEGACY_COMMAND_LINE_RE = re.compile( + r"^!`[^`\r\n]*/loopx/claude_goal_mode/scripts/goalmode_cmd\.py[^`\r\n]*`\s*$" +) +_ALLOWED_TOOLS_BASH_RE = re.compile(r"^allowed-tools:\s*Bash\([^\r\n]*\)\s*$") + + +def _migration_python_cmd() -> str: + """Prefer the running LoopX Python interpreter so upgraded venv commands resolve `loopx`.""" + if sys.executable and _launches_python(sys.executable): + return sys.executable + return _python_cmd() + + +def _resolve_live_python_command( + raw_cmd: str, + *, + live_py_cache: dict[str, bool] | None = None, +) -> bool: + """True when ``raw_cmd`` resolves to an executable Python 3.11+ interpreter.""" + if not raw_cmd: + return False + if live_py_cache is not None and raw_cmd in live_py_cache: + return live_py_cache[raw_cmd] + candidate_path = Path(raw_cmd) + if "/" in raw_cmd or "\\" in raw_cmd: + resolved = ( + str(candidate_path) + if candidate_path.is_absolute() and candidate_path.is_file() + else None + ) + else: + resolved = shutil.which(raw_cmd) + ok = bool(resolved) and _launches_python(resolved) # type: ignore[arg-type] + if live_py_cache is not None: + live_py_cache[raw_cmd] = ok + return ok + + +def _is_live_legacy_shim_path(raw_path: str, *, legacy_suffix: str) -> bool: + """True when ``raw_path`` resolves to this install's active ``claude_goal_mode`` shim.""" + normalized = raw_path.replace("\\", "/") + if not normalized.endswith(legacy_suffix): + return False + expected_shim = REPO_ROOT / legacy_suffix.lstrip("/") + if not expected_shim.is_file(): + return False + candidate = Path(raw_path) + if not candidate.is_file(): + return False + try: + return os.path.normcase(str(candidate.resolve())) == os.path.normcase( + str(expected_shim.resolve()) + ) + except OSError: + return False + + +def _migrated_command_md_text( + raw: str, + *, + py_exe: str, + live_py_cache: dict[str, bool] | None = None, +) -> 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 + bare_cmd_line = lines[command_index].rstrip("\r\n") + leading_ws_len = len(bare_cmd_line) - len(bare_cmd_line.lstrip()) + inner_cmd = bare_cmd_line.strip()[2:-1] + migrated_inner, _ = _inspect_legacy_claude_command( + inner_cmd, + legacy_suffix=_LEGACY_COMMAND_SCRIPT_SUFFIX, + new_script=_p("scripts", "goalmode_cmd.py"), + py_exe=py_exe, + powershell=False, + live_py_cache=live_py_cache, + ) + if migrated_inner is None: + return None + py = _shell_literal(py_exe, powershell=False) + cmd_nl = "\r\n" if lines[command_index].endswith("\r\n") else "\n" + lines[command_index] = f"{bare_cmd_line[:leading_ws_len]}!`{migrated_inner}`{cmd_nl}" + if allowed_index is not None: + allowed_nl = "\r\n" if lines[allowed_index].endswith("\r\n") else "\n" + lines[allowed_index] = f"allowed-tools: Bash({py}:*){allowed_nl}" + updated = "".join(lines) + return updated if updated != raw else None + + +_PYTHON_EXE_NAME_RE = re.compile( + r"^(?:pypy3?|python(?:w|3(?:\.\d+)?)?)(?:\.exe)?$" +) +_PYTHON_PASSTHROUGH_FLAGS = frozenset( + {"-B", "-E", "-I", "-O", "-OO", "-P", "-S", "-s", "-u", "-v", "-q"} +) +_PYTHON_SHORT_FLAG_CHARS = frozenset("BbEdiIOPqRsSuvx") +_PYTHON_VALUE_FLAGS = frozenset({"-W", "-X", "--check-hash-based-pycs"}) +_PYTHON_TERMINAL_FLAGS = frozenset({"-c", "-m", "-"}) +_SHELL_OPERATORS_ORDERED = ( + "<<-", + "<<<", + ";;&", + "&&", + "||", + "|&", + ";;", + ";&", + ">>", + ">&", + "<&", + "<<", + "<>", + ";", + "|", + "&", + "(", + ")", + "<", + ">", + "\n", +) +_SHELL_OPERATOR_CHARS = frozenset(";|&()<>\n") +_REDIRECTION_OPS = frozenset({"<<-", "<<<", ">>", ">&", "<&", "<<", "<>", "<", ">"}) +_ENV_ASSIGN_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=.*") +_ENV_VALUE_FLAGS = frozenset({"-u", "--unset", "-C", "--chdir", "-P", "-a", "--argv0"}) +_TIMEOUT_VALUE_FLAGS = frozenset({"-k", "--kill-after", "-s", "--signal"}) +_SHELL_NAMES = frozenset({"sh", "bash", "zsh", "dash", "ash", "ksh"}) +_CLAUSE_STARTERS = frozenset({"if", "elif", "then", "else", "while", "until", "do", "{"}) +_CLAUSE_HEADERS_NON_COMMAND = frozenset({"for", "select", "case"}) + + +class _ShellToken(NamedTuple): + start: int + end: int + unquoted: str + is_operator: bool = False + + +def _consume_heredoc_bodies( + raw_command: str, i: int, pending_heredocs: list[tuple[str, bool]] +) -> int | None: + """Skip pending POSIX here-document bodies and delimiters starting after `\\n`.""" + n = len(raw_command) + for delim, strip_tabs in pending_heredocs: + closed = False + while i < n: + line_end = raw_command.find("\n", i) + if line_end == -1: + line_end = n + line_text = raw_command[i:line_end].rstrip("\r") + candidate = line_text.lstrip("\t") if strip_tabs else line_text + i = line_end + 1 if line_end < n else n + if candidate == delim: + closed = True + break + if not closed: + return None + return i + + +def _tokenize_shell_spans( + raw_command: str, *, powershell: bool +) -> list[_ShellToken] | None: + """Return word/operator tokens with original offsets, or ``None`` on shell syntax failure.""" + n = len(raw_command) + i = 0 + tokens: list[_ShellToken] = [] + awaiting_heredoc: bool | None = None + pending_heredocs: list[tuple[str, bool]] = [] + while i < n: + while i < n and ( + raw_command[i] in " \t\r\v\f" + or (not powershell and raw_command.startswith("\\\n", i)) + ): + i += 2 if (not powershell and raw_command.startswith("\\\n", i)) else 1 + if i >= n: + break + if not powershell and awaiting_heredoc is None and raw_command[i] == "#": + while i < n and raw_command[i] != "\n": + i += 1 + continue + matched_op: str | None = None + if raw_command[i] in _SHELL_OPERATOR_CHARS: + for candidate in _SHELL_OPERATORS_ORDERED: + if raw_command.startswith(candidate, i): + matched_op = candidate + break + if matched_op is not None: + if awaiting_heredoc is not None: + return None + tokens.append(_ShellToken(i, i + len(matched_op), matched_op, is_operator=True)) + i += len(matched_op) + if not powershell and matched_op in {"<<", "<<-"}: + awaiting_heredoc = matched_op == "<<-" + elif not powershell and matched_op == "\n" and pending_heredocs: + next_i = _consume_heredoc_bodies(raw_command, i, pending_heredocs) + if next_i is None: + return None + pending_heredocs.clear() + i = next_i + continue + + start = i + word_end = i + buf: list[str] = [] + while i < n and raw_command[i] not in " \t\r\v\f" and raw_command[i] not in _SHELL_OPERATOR_CHARS: + ch = raw_command[i] + if ch == "'": + i += 1 + closed = False + while i < n: + if raw_command[i] == "'": + if powershell and i + 1 < n and raw_command[i + 1] == "'": + buf.append("'") + i += 2 + continue + i += 1 + closed = True + break + buf.append(raw_command[i]) + i += 1 + if not closed: + return None + word_end = i + elif ch == '"': + i += 1 + while i < n and raw_command[i] != '"': + if ( + not powershell + and raw_command[i] == "\\" + and i + 1 < n + and raw_command[i + 1] == "\n" + ): + i += 2 + continue + if ( + raw_command[i] == "\\" + and i + 1 < n + and raw_command[i + 1] == '"' + ): + buf.append('"') + i += 2 + continue + buf.append(raw_command[i]) + i += 1 + if i >= n: + return None + i += 1 + word_end = i + elif ( + ch == "\\" + and not powershell + and i + 1 < n + and ( + awaiting_heredoc is not None + or raw_command[i + 1].isspace() + or raw_command[i + 1] in {"'", '"', "\\", "|", "&", ";", "(", ")", "<", ">"} + ) + ): + if raw_command[i + 1] == "\n": + if awaiting_heredoc is not None: + return None + i += 2 + continue + i += 1 + buf.append(raw_command[i]) + i += 1 + word_end = i + else: + buf.append(ch) + i += 1 + word_end = i + unquoted_word = "".join(buf) + tokens.append(_ShellToken(start, word_end, unquoted_word)) + if awaiting_heredoc is not None: + pending_heredocs.append((unquoted_word, awaiting_heredoc)) + awaiting_heredoc = None + if awaiting_heredoc is not None or pending_heredocs: + return None + return tokens + + +def _looks_like_python_token(unquoted: str) -> bool: + if "=" in unquoted: + return False + name = Path(unquoted.replace("\\", "/")).name.lower() + return bool(_PYTHON_EXE_NAME_RE.fullmatch(name)) + + +def _is_unquoted_env_assignment(token: _ShellToken, *, raw_command: str) -> bool: + if not _ENV_ASSIGN_RE.fullmatch(token.unquoted): + return False + eq_pos = raw_command.find("=", token.start, token.end) + if eq_pos <= token.start: + return False + prefix = raw_command[token.start : eq_pos] + return bool(re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", prefix)) + + +def _split_command_segments( + tokens: list[_ShellToken], *, raw_command: str, powershell: bool +) -> list[tuple[list[_ShellToken], bool]]: + segments: list[tuple[list[_ShellToken], bool]] = [] + words: list[_ShellToken] = [] + has_ps_call = False + in_case_header = False + case_depth = 0 + expect_case_pattern = False + idx = 0 + while idx < len(tokens): + tok = tokens[idx] + if tok.is_operator: + if tok.unquoted in _REDIRECTION_OPS: + if words and words[-1].end == tok.start and words[-1].unquoted.isdigit(): + words.pop() + if idx + 1 < len(tokens) and not tokens[idx + 1].is_operator: + idx += 2 + else: + idx += 1 + continue + if tok.unquoted == "&" and powershell and not words and not has_ps_call: + has_ps_call = True + idx += 1 + continue + if case_depth > 0 and expect_case_pattern: + if tok.unquoted == ")": + expect_case_pattern = False + words = [] + has_ps_call = False + idx += 1 + continue + if words: + segments.append((words, has_ps_call)) + words = [] + has_ps_call = False + in_case_header = False + if case_depth > 0 and tok.unquoted in {";;", ";&", ";;&"}: + expect_case_pattern = True + idx += 1 + continue + + raw_slice = raw_command[tok.start : tok.end] + if not powershell: + if case_depth > 0 and expect_case_pattern: + if not words and raw_slice == "esac": + case_depth -= 1 + expect_case_pattern = False + idx += 1 + continue + idx += 1 + continue + if case_depth > 0 and not words and raw_slice == "esac": + case_depth -= 1 + idx += 1 + continue + if in_case_header and raw_slice == "in": + in_case_header = False + case_depth += 1 + expect_case_pattern = True + words = [] + idx += 1 + continue + if not words and raw_slice == "case": + in_case_header = True + + words.append(tok) + idx += 1 + if words and not (case_depth > 0 and expect_case_pattern): + segments.append((words, has_ps_call)) + return segments + + +def _advance_command_wrappers( + words: list[_ShellToken], + *, + raw_command: str, + legacy_suffix: str, + powershell: bool, +) -> tuple[int | None, str | None]: + idx = 0 + while idx < len(words): + if not powershell: + tok = words[idx] + raw_slice = raw_command[tok.start : tok.end] + if raw_slice == tok.unquoted and tok.unquoted in _CLAUSE_STARTERS: + idx += 1 + continue + if raw_slice == tok.unquoted and tok.unquoted in _CLAUSE_HEADERS_NON_COMMAND: + return (None, None) + if _is_unquoted_env_assignment(tok, raw_command=raw_command): + idx += 1 + continue + if tok.unquoted == "!" and raw_slice == "!": + idx += 1 + continue + if powershell: + break + + cmd_word = words[idx].unquoted + cmd_name = Path(cmd_word.replace("\\", "/")).name.lower() + has_legacy_tail = any( + legacy_suffix in w.unquoted.replace("\\", "/") for w in words[idx:] + ) + probe = idx + 1 + if cmd_name == "env": + while probe < len(words): + arg = words[probe].unquoted + if arg == "--": + probe += 1 + break + if arg in {"-S", "--split-string"} or arg.startswith(("-S", "--split-string=")): + return ( + None, + "unsupported `env -S` wrapper around legacy Claude command" + if has_legacy_tail + else None, + ) + if arg in _ENV_VALUE_FLAGS: + probe += 2 + continue + if arg.startswith("-") or _ENV_ASSIGN_RE.fullmatch(arg): + probe += 1 + continue + break + if probe > len(words): + return (None, None) + idx = probe + continue + if cmd_word == "command": + while probe < len(words) and words[probe].unquoted.startswith("-") and words[probe].unquoted != "--": + flag = words[probe].unquoted + if "v" in flag or "V" in flag: + return (None, None) + if flag != "-p": + return ( + None, + f"unsupported `command {flag}` option around legacy Claude command" + if has_legacy_tail + else None, + ) + probe += 1 + if probe < len(words) and words[probe].unquoted == "--": + probe += 1 + idx = probe + continue + if cmd_word == "exec": + while probe < len(words) and words[probe].unquoted.startswith("-"): + flag = words[probe].unquoted + if flag == "--": + probe += 1 + break + if flag == "-a": + probe += 2 + elif len(flag) > 1 and set(flag[1:]) <= {"c", "l"}: + probe += 1 + else: + return ( + None, + f"unsupported `exec {flag}` option around legacy Claude command" + if has_legacy_tail + else None, + ) + if probe > len(words): + return (None, None) + idx = probe + continue + if cmd_word in {"nohup", "time"} or cmd_name == "nice": + if cmd_word == "time" and probe < len(words) and words[probe].unquoted == "-p": + probe += 1 + elif cmd_name == "nice" and probe < len(words): + arg = words[probe].unquoted + if arg in {"-n", "--adjustment"}: + probe += 2 + elif arg.startswith("--adjustment=") or ( + arg.startswith("-") and arg[1:].lstrip("+-").isdigit() + ): + probe += 1 + if probe > len(words): + return (None, None) + idx = probe + continue + if cmd_name == "timeout": + while probe < len(words) and words[probe].unquoted.startswith("-"): + arg = words[probe].unquoted + if arg == "--": + probe += 1 + break + if arg in _TIMEOUT_VALUE_FLAGS: + probe += 2 + elif arg.startswith(("--kill-after=", "--signal=")) or arg in { + "-v", + "--verbose", + "--foreground", + "--preserve-status", + }: + probe += 1 + else: + return ( + None, + f"unsupported `timeout {arg}` option around legacy Claude command" + if has_legacy_tail + else None, + ) + if probe >= len(words): + return (None, None) + dur = words[probe].unquoted + if dur.startswith("-") or dur.replace("\\", "/").endswith(legacy_suffix): + return (None, None) + idx = probe + 1 + continue + break + return (idx, None) if idx < len(words) else (None, None) + + +def _segment_edits( + words: list[_ShellToken], + *, + has_ps_call: bool, + raw_command: str, + legacy_suffix: str, + new_script: str, + py_exe: str, + powershell: bool, + live_py_cache: dict[str, bool] | None = None, +) -> tuple[list[tuple[int, int, str]], str | None]: + cmd_idx, wrapper_reason = _advance_command_wrappers( + words, + raw_command=raw_command, + legacy_suffix=legacy_suffix, + powershell=powershell, + ) + if cmd_idx is None: + return ([], wrapper_reason) + + cmd_tok = words[cmd_idx] + cmd_name = Path(cmd_tok.unquoted.replace("\\", "/")).name.lower() + if not powershell and cmd_tok.unquoted == "eval": + if any(legacy_suffix in w.unquoted.replace("\\", "/") for w in words[cmd_idx + 1 :]): + return ([], "dynamic `eval` command references legacy Claude launcher") + return ([], None) + + if cmd_name.removesuffix(".exe") in _SHELL_NAMES and not cmd_tok.unquoted.startswith("-"): + probe = cmd_idx + 1 + saw_dash_c = False + while probe < len(words): + arg = words[probe].unquoted + if arg == "--": + probe += 1 + break + if not arg.startswith("-") and not (arg.startswith("+") and len(arg) > 1): + break + if arg in {"-o", "+o"}: + probe += 2 + continue + if arg.startswith("-") and not arg.startswith("--") and "c" in arg[1:]: + saw_dash_c = True + probe += 1 + break + probe += 1 + if not saw_dash_c or probe >= len(words): + return ([], None) + inner_tok = words[probe] + if legacy_suffix not in inner_tok.unquoted.replace("\\", "/"): + return ([], None) + inner, inner_reason = _inspect_legacy_claude_command( + inner_tok.unquoted, + legacy_suffix=legacy_suffix, + new_script=new_script, + py_exe=py_exe, + powershell=False, + live_py_cache=live_py_cache, + ) + if inner is None: + return ([], inner_reason) + return ([(inner_tok.start, inner_tok.end, _shell_literal(inner, powershell=powershell))], inner_reason) + + needs_ps_call = powershell and not (has_ps_call and cmd_idx == 0) + py_replacement = ( + _shell_command(py_exe, powershell=True) + if needs_ps_call + else _shell_literal(py_exe, powershell=powershell) + ) + script_literal = _shell_literal(new_script, powershell=powershell) + + if _looks_like_python_token(cmd_tok.unquoted): + probe = cmd_idx + 1 + while probe < len(words): + arg = words[probe].unquoted + if arg in _PYTHON_TERMINAL_FLAGS or arg.startswith(("-c", "-m")): + return ([], None) + if arg in _PYTHON_VALUE_FLAGS: + probe += 2 + if probe > len(words): + return ([], None) + continue + if arg.startswith(("-W", "-X", "--check-hash-based-pycs=")): + probe += 1 + continue + if arg in _PYTHON_PASSTHROUGH_FLAGS or ( + len(arg) > 1 + and arg[0] == "-" + and not arg.startswith("--") + and set(arg[1:]) <= _PYTHON_SHORT_FLAG_CHARS + ): + probe += 1 + continue + if arg.startswith("-"): + has_legacy_tail = any( + legacy_suffix in w.unquoted.replace("\\", "/") for w in words[probe + 1 :] + ) + return ( + [], + f"unsupported Python option `{arg}` around legacy Claude launcher" + if has_legacy_tail + else None, + ) + break + if probe >= len(words): + return ([], None) + script_tok = words[probe] + normalized = script_tok.unquoted.replace("\\", "/") + if not normalized.startswith("-") and normalized.endswith(legacy_suffix): + if _is_live_legacy_shim_path( + script_tok.unquoted, legacy_suffix=legacy_suffix + ) and _resolve_live_python_command( + cmd_tok.unquoted, live_py_cache=live_py_cache + ): + return ([], None) + return ( + [ + (script_tok.start, script_tok.end, script_literal), + (cmd_tok.start, cmd_tok.end, py_replacement), + ], + None, + ) + return ([], None) + + normalized_cmd = cmd_tok.unquoted.replace("\\", "/") + if ( + not normalized_cmd.startswith("-") + and not _ENV_ASSIGN_RE.fullmatch(normalized_cmd) + and normalized_cmd.endswith(legacy_suffix) + ): + if ( + os.name != "nt" + and _is_live_legacy_shim_path( + cmd_tok.unquoted, legacy_suffix=legacy_suffix + ) + and os.access(Path(cmd_tok.unquoted), os.X_OK) + and _resolve_live_python_command("python3", live_py_cache=live_py_cache) + ): + return ([], None) + return ([(cmd_tok.start, cmd_tok.end, f"{py_replacement} {script_literal}")], None) + return ([], None) + + +def _inspect_legacy_claude_command( + raw_command: str, + *, + legacy_suffix: str, + new_script: str, + py_exe: str, + powershell: bool, + live_py_cache: dict[str, bool] | None = None, +) -> tuple[str | None, str | None]: + """Upgrade certified executed legacy commands and report uncertifiable dynamic legacy references.""" + prefilter_command = raw_command.replace("\\\n", "") if not powershell else raw_command + if legacy_suffix not in prefilter_command.replace("\\", "/"): + return (None, None) + tokens = _tokenize_shell_spans(raw_command, powershell=powershell) + if tokens is None: + return (None, "unterminated shell quote or here-document around legacy Claude command") + if not tokens: + return (None, None) + + edits: list[tuple[int, int, str]] = [] + manual_reasons: list[str] = [] + for words, has_ps_call in _split_command_segments( + tokens, raw_command=raw_command, powershell=powershell + ): + seg_edits, seg_reason = _segment_edits( + words, + has_ps_call=has_ps_call, + raw_command=raw_command, + legacy_suffix=legacy_suffix, + new_script=new_script, + py_exe=py_exe, + powershell=powershell, + live_py_cache=live_py_cache, + ) + edits.extend(seg_edits) + if seg_reason and seg_reason not in manual_reasons: + manual_reasons.append(seg_reason) + manual_reason = "; ".join(manual_reasons) if manual_reasons else None + if not edits: + return (None, manual_reason) + + edits.sort(key=lambda item: item[0], reverse=True) + updated = raw_command + last_start = len(raw_command) + 1 + for start, end, replacement in edits: + if end > last_start: + return (None, "overlapping shell spans prevent safe automatic migration") + updated = updated[:start] + replacement + updated[end:] + last_start = start + return (updated if updated != raw_command else None, manual_reason) + + +def _rewrite_legacy_claude_command( + raw_command: str, + *, + legacy_suffix: str, + new_script: str, + py_exe: str, + powershell: bool, +) -> str | None: + """Upgrade executed legacy Claude hook/statusline commands while keeping wrappers and data args.""" + updated, _ = _inspect_legacy_claude_command( + raw_command, + legacy_suffix=legacy_suffix, + new_script=new_script, + py_exe=py_exe, + powershell=powershell, + ) + return updated + + +def _inspect_settings_migration( + raw_data: dict[str, Any], + *, + py_exe: str, + live_py_cache: dict[str, bool] | None = None, +) -> tuple[dict[str, Any] | None, list[str]]: + powershell = _uses_powershell() + gate_script = _p("hooks", "goal_policy.py") + status_script = _p("statusline", "goal_status.py") + updated: dict[str, Any] = dict(raw_data) + changed = False + manual_reasons: list[str] = [] + + hooks_obj = raw_data.get("hooks") + if isinstance(hooks_obj, dict): + pre_obj = hooks_obj.get("PreToolUse") + if isinstance(pre_obj, list): + new_pre: list[Any] = [] + pre_changed = False + for group in pre_obj: + if not isinstance(group, dict): + new_pre.append(group) + continue + group_hooks = group.get("hooks") + if not isinstance(group_hooks, list): + new_pre.append(group) + continue + new_group_hooks: list[Any] = [] + group_changed = False + for item in group_hooks: + if isinstance(item, dict) and isinstance(item.get("command"), str): + migrated_cmd, manual_reason = _inspect_legacy_claude_command( + item["command"], + legacy_suffix=_LEGACY_POLICY_HOOK_SUFFIX, + new_script=gate_script, + py_exe=py_exe, + powershell=powershell, + live_py_cache=live_py_cache, + ) + if manual_reason and manual_reason not in manual_reasons: + manual_reasons.append(manual_reason) + if migrated_cmd is not None: + new_item = dict(item) + new_item["command"] = migrated_cmd + new_group_hooks.append(new_item) + group_changed = True + continue + new_group_hooks.append(item) + if group_changed: + new_group = dict(group) + new_group["hooks"] = new_group_hooks + new_pre.append(new_group) + pre_changed = True + else: + new_pre.append(group) + if pre_changed: + new_hooks = dict(hooks_obj) + new_hooks["PreToolUse"] = new_pre + updated["hooks"] = new_hooks + changed = True + + sl_obj = raw_data.get("statusLine") + if isinstance(sl_obj, dict) and isinstance(sl_obj.get("command"), str): + migrated_sl, sl_reason = _inspect_legacy_claude_command( + sl_obj["command"], + legacy_suffix=_LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=status_script, + py_exe=py_exe, + powershell=powershell, + live_py_cache=live_py_cache, + ) + if sl_reason and sl_reason not in manual_reasons: + manual_reasons.append(sl_reason) + if migrated_sl is not None: + new_sl = dict(sl_obj) + new_sl["command"] = migrated_sl + updated["statusLine"] = new_sl + changed = True + + return (updated if changed else None, manual_reasons) + + +def _migrated_settings_payload(raw_data: dict[str, Any], *, py_exe: str) -> dict[str, Any] | None: + updated, _ = _inspect_settings_migration(raw_data, py_exe=py_exe) + return updated + + +def _migrated_mcp_json_payload( + raw_data: dict[str, Any], + *, + live_py_cache: dict[str, bool] | None = None, +) -> 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 + cmd = loopx_entry.get("command") + live_cmd = isinstance(cmd, str) and _resolve_live_python_command( + cmd, live_py_cache=live_py_cache + ) + 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("\\", "/"): + if live_cmd and _is_live_legacy_shim_path( + arg, legacy_suffix=_LEGACY_MCP_SCRIPT_SUFFIX + ): + updated_args.append(arg) + else: + 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 + live_py_cache: dict[str, bool] = {} + + 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(), live_py_cache=live_py_cache + ) + if raw_cmd + else None + ) + if updated_cmd is not None: + if execute: + write_bytes_atomic( + cmd_path.resolve(), + updated_cmd.encode("utf-8"), + preserve_mode=True, + ) + results.append({"path": str(cmd_path), "status": "updated" if execute else "would_write"}) + + settings_path = claude_dir / "settings.json" + if settings_path.is_file(): + raw_settings = _read_json_dict_fail_closed(settings_path) + updated_settings, manual_reasons = ( + _inspect_settings_migration( + raw_settings, py_exe=resolve_py(), live_py_cache=live_py_cache + ) + if raw_settings is not None + else (None, []) + ) + if updated_settings is not None: + if execute: + write_json_atomic( + settings_path.resolve(), + updated_settings, + preserve_mode=True, + ) + results.append({"path": str(settings_path), "status": "updated" if execute else "would_write"}) + if manual_reasons: + scope_args = ( + f"--scope project --project {shlex.quote(str(project_dir))} --harden" + if project_dir is not None + else "--scope user --harden" + ) + recovery_cmd = f"{_shell_literal(resolve_py(), powershell=_uses_powershell())} {_shell_literal(str(Path(__file__).resolve()), powershell=_uses_powershell())} {scope_args}" + results.append( + { + "path": str(settings_path), + "status": "manual_migration_required", + "reason": "; ".join(manual_reasons), + "recovery": recovery_cmd, + "note": ( + f"Manual Claude migration required for {settings_path} " + f"({'; '.join(manual_reasons)}). Recover with: {recovery_cmd}" + ), + } + ) + + if project_dir is not None: + mcp_path = project_dir / ".mcp.json" + if mcp_path.is_file(): + raw_mcp = _read_json_dict_fail_closed(mcp_path) + updated_mcp = ( + _migrated_mcp_json_payload(raw_mcp, live_py_cache=live_py_cache) + if raw_mcp is not None + else None + ) + if updated_mcp is not None: + if execute: + write_json_atomic( + mcp_path.resolve(), + updated_mcp, + preserve_mode=True, + ) + results.append({"path": str(mcp_path), "status": "updated" if execute else "would_write"}) + + return results + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/loopx/claude_goal_mode/settings.example.json b/loopx/hosts/claude/settings.example.json similarity index 81% rename from loopx/claude_goal_mode/settings.example.json rename to loopx/hosts/claude/settings.example.json index 21f246fd26..b04d670acc 100644 --- a/loopx/claude_goal_mode/settings.example.json +++ b/loopx/hosts/claude/settings.example.json @@ -1,5 +1,5 @@ { - "_comment": "OPTIONAL manual hardening for loopx on Claude Code. The loopx adapter's runtime is Claude Code's native /loop + the loopx MCP server (added via `claude mcp add` or install.py) + the /loopx command — NONE of which live in settings.json. This file is ONLY the optional should_run PreToolUse gate + statusline. Merge it into a PROJECT's .claude/settings.json (preferred) or ~/.claude/settings.json. Replace with the absolute path to loopx/claude_goal_mode; if your machine has `python` but not `python3`, replace `python3` accordingly. For strong isolation, run Claude Code inside a dev container / VM.", + "_comment": "OPTIONAL manual hardening for loopx on Claude Code. The loopx adapter's runtime is Claude Code's native /loop + the loopx MCP server (added via `claude mcp add` or install.py) + the /loopx command — NONE of which live in settings.json. This file is ONLY the optional should_run PreToolUse gate + statusline. Merge it into a PROJECT's .claude/settings.json (preferred) or ~/.claude/settings.json. Replace with the absolute path to loopx/hosts/claude; if your machine has `python` but not `python3`, replace `python3` accordingly. For strong isolation, run Claude Code inside a dev container / VM.", "hooks": { "PreToolUse": [ { diff --git a/loopx/hosts/claude/statusline/goal_status.py b/loopx/hosts/claude/statusline/goal_status.py new file mode 100644 index 0000000000..88a65ae3f7 --- /dev/null +++ b/loopx/hosts/claude/statusline/goal_status.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""Statusline segment: a glanceable loopx goal state for the Claude Code CLI. + +Claude Code feeds session JSON on stdin; we resolve THIS project's goal (only +while goal-mode is armed) and run one quick `loopx quota should-run` probe, then +render a single compact line. We surface the signals a watching user actually +needs, in priority order: + + 1. ⚠ needs you — an operator gate / open user todo is blocking (highest signal) + 2. ▶ working — should_run=true, plus the next concrete action loopx picked + 3. ⏸ — paused/holding, plus the short reason (quota, gate, health…) + +…always tailed with todo progress (done✓/open▸). Prints nothing when there is no +goal here or goal-mode is off. +""" +from __future__ import annotations + +import json +import os +import subprocess +import sys +from pathlib import Path + +# Share the registry-driven resolver with the hooks so the statusline shows THIS +# session's project goal, and only while goal-mode is armed (heartbeat installed). +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "hooks")) +from goal_state import active_context +from stdio_utf8 import pin_utf8_stdio + + +import shutil as _shutil +def _gh_prefix(): + _exe = _shutil.which("loopx") + return [_exe] if _exe else [__import__("sys").executable, "-m", "loopx.cli"] + + +def _clip(s, n: int) -> str: + s = " ".join(str(s or "").split()) # collapse whitespace/newlines + return s if len(s) <= n else s[: n - 1] + "…" + + +def _render(gid: str, d: dict) -> str: + """Turn a `quota should-run` payload into one compact statusline string.""" + agent = d.get("agent_todo_summary") or {} + done, open_ = agent.get("done_count"), agent.get("open_count") + prog = f"{done}✓/{open_}▸" if (done is not None or open_ is not None) else "" + + ic = d.get("interaction_contract") or {} + user_ch = ic.get("user_channel") or {} + users = d.get("user_todo_summary") or {} + gate = d.get("gate_prompt") + needs_user = bool(gate) or bool(user_ch.get("action_required")) or bool(users.get("open_count")) + + if needs_user: + msg = gate or f"{users.get('open_count') or 'a'} user todo(s) to answer" + return f"[loopx {gid} · ⚠ needs you: {_clip(msg, 46)}]" + + if d.get("should_run") is True: + nxt = d.get("recommended_action") + head = f"▶ {prog}".rstrip() if prog else "▶ working" + return f"[loopx {gid} · {head}" + (f" · next: {_clip(nxt, 40)}]" if nxt else "]") + + # paused / holding: lead with WHY (state + short reason), then progress + state = (d.get("state") or "paused").strip() + reason = d.get("reason") + tail = f" · {prog}" if prog else "" + return f"[loopx {gid} · ⏸ {state}" + (f": {_clip(reason, 38)}" if reason else "") + f"{tail}]" + + +def main(): + raw = sys.stdin.read() # Claude's session json carries this session's cwd + cwd = None + try: + sess = json.loads(raw or "{}") + cwd = sess.get("cwd") or (sess.get("workspace") or {}).get("current_dir") + except Exception: + pass + st = active_context(cwd or Path.cwd()) + if not st: + print("") # no goal here, or goal-mode off -> no segment + return + gid = st.get("goal_id", "?") + try: + cmd = list(_gh_prefix()) + if st.get("registry"): + cmd += ["--registry", st["registry"]] + cmd += ["--format", "json", "quota", "should-run", "--goal-id", gid] + if st.get("agent_id"): + cmd += ["--agent-id", st["agent_id"]] + out = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=8, + env={**os.environ, "LOOPX_CONTEXT_DELIVERY": "off"}) + d = json.loads(out.stdout or "{}") + print(_render(gid, d)) + except Exception: + # probe failed: still show that goal-mode is armed, without counts/state + print(f"[loopx {gid}]") + + +if __name__ == "__main__": + pin_utf8_stdio() + main() 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/hosts/kunluncode/__init__.py b/loopx/hosts/kunluncode/__init__.py new file mode 100644 index 0000000000..f571f40c16 --- /dev/null +++ b/loopx/hosts/kunluncode/__init__.py @@ -0,0 +1,4 @@ +"""First-class KunlunCode host adapter for LoopX goal mode.""" + +DEFAULT_AGENT_ID = "kunlun" +MCP_SERVER_NAME = "loopx-kunluncode" diff --git a/loopx/hosts/kunluncode/app_server.py b/loopx/hosts/kunluncode/app_server.py new file mode 100644 index 0000000000..1ea6988d23 --- /dev/null +++ b/loopx/hosts/kunluncode/app_server.py @@ -0,0 +1,484 @@ +"""Minimal JSON-RPC client for KunlunCode's native Goal runtime.""" + +from __future__ import annotations + +import hashlib +import json +import os +import queue +import subprocess +import threading +import time +from collections import deque +from collections.abc import Callable, Mapping +from pathlib import Path +from typing import Any, TextIO + + +KUNLUN_APP_SERVER_PROTOCOL_VERSION = "2026-07-27" +KUNLUN_APP_SERVER_CLIENT_NAME = "loopx-kunluncode" +KUNLUN_APP_SERVER_CLIENT_VERSION = "0.1.0" +NATIVE_GOAL_MODES = {"goal": "arrangement", "goal-pro": "strict"} +TERMINAL_GOAL_STATUSES = { + "blocked", + "budget_limited", + "complete", + "paused", + "usage_limited", +} + + +class KunlunAppServerError(RuntimeError): + """Raised when the KunlunCode app-server contract cannot be completed.""" + + +def stable_text_digest(text: str) -> str: + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + +def build_app_server_command( + kunluncode_bin: str, + *, + project: Path, + permission_mode: str, + max_duration_secs: int, + scenario: str | None = None, +) -> list[str]: + command = [ + kunluncode_bin, + "app-server", + "--listen", + "stdio://", + "--cwd", + str(project.resolve()), + "--permission-mode", + permission_mode, + "--tool-profile", + "full", + "--max-duration-secs", + str(max(1, max_duration_secs)), + ] + if scenario: + command += ["--scenario", scenario] + return command + + +def goal_from_result(result: Mapping[str, Any] | None) -> dict[str, Any]: + if not isinstance(result, Mapping): + return {} + nested = result.get("goal") + if isinstance(nested, Mapping): + return dict(nested) + if any(key in result for key in ("goalId", "goal_id", "objective", "status")): + return dict(result) + return {} + + +def goal_value(goal: Mapping[str, Any], *names: str) -> Any: + for name in names: + if name in goal: + return goal[name] + return None + + +def goal_event_kinds(goal: Mapping[str, Any]) -> list[str]: + values: list[str] = [] + raw_events = goal_value(goal, "events", "history") + if not isinstance(raw_events, list): + return values + for event in raw_events: + if isinstance(event, str): + values.append(event.strip().lower()) + continue + if not isinstance(event, Mapping): + continue + for key in ("kind", "type", "event", "name", "status"): + value = event.get(key) + if isinstance(value, str) and value.strip(): + values.append(value.strip().lower()) + return values + + +def strict_goal_verification_passed(goal: Mapping[str, Any]) -> bool: + if "verification_passed" in goal_event_kinds(goal): + return True + for key in ("verification", "verifier", "verificationResult"): + value = goal.get(key) + if not isinstance(value, Mapping): + continue + status = str(value.get("status") or value.get("result") or "").lower() + if status in {"pass", "passed", "verification_passed"}: + return True + return False + + +def compact_goal(goal: Mapping[str, Any]) -> dict[str, Any]: + objective = str(goal.get("objective") or "") + return { + "goal_id": goal_value(goal, "goalId", "goal_id", "id"), + "revision": goal.get("revision"), + "mode": goal.get("mode"), + "verification_kind": goal_value(goal, "verificationKind", "verification_kind"), + "status": goal.get("status"), + "objective_sha256": stable_text_digest(objective) if objective else None, + "event_kinds": sorted(set(goal_event_kinds(goal))), + "verification_passed": strict_goal_verification_passed(goal), + } + + +def native_goal_success(goal: Mapping[str, Any], *, mode: str) -> bool: + expected_mode = NATIVE_GOAL_MODES.get(mode) + if expected_mode is None: + raise ValueError(f"unsupported native KunlunCode goal mode: {mode}") + if str(goal.get("status") or "") != "complete": + return False + if str(goal.get("mode") or "") != expected_mode: + return False + return mode != "goal-pro" or strict_goal_verification_passed(goal) + + +def _stdout_reader( + stream: TextIO, + output: "queue.Queue[dict[str, Any] | BaseException]", +) -> None: + try: + for line in stream: + if not line.strip(): + continue + try: + value = json.loads(line) + if not isinstance(value, dict): + raise ValueError("app-server message is not a JSON object") + output.put(value) + except BaseException as exc: # pragma: no cover - defensive protocol path + output.put(exc) + finally: + output.put(EOFError("KunlunCode app-server stdout closed")) + + +def _stderr_reader(stream: TextIO, output: "deque[str]") -> None: + for line in stream: + value = line.rstrip() + if value: + output.append(value[-1000:]) + + +class KunlunAppServerClient: + """One single-threaded stdio JSON-RPC connection to KunlunCode.""" + + def __init__( + self, + command: list[str], + *, + cwd: Path, + env: Mapping[str, str] | None = None, + event_handler: Callable[[dict[str, Any]], None] | None = None, + ) -> None: + self.command = list(command) + self.event_handler = event_handler + self._request_id = 0 + self._messages: "queue.Queue[dict[str, Any] | BaseException]" = queue.Queue( + maxsize=2048 + ) + self._stderr: "deque[str]" = deque(maxlen=24) + self.process = subprocess.Popen( + self.command, + cwd=str(cwd.resolve()), + env=dict(env or os.environ), + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, encoding="utf-8", errors="replace", + bufsize=1, + ) + if self.process.stdout is None or self.process.stderr is None: + self.close() + raise KunlunAppServerError("KunlunCode app-server pipes are unavailable") + self._stdout_thread = threading.Thread( + target=_stdout_reader, + args=(self.process.stdout, self._messages), + daemon=True, + ) + self._stderr_thread = threading.Thread( + target=_stderr_reader, + args=(self.process.stderr, self._stderr), + daemon=True, + ) + self._stdout_thread.start() + self._stderr_thread.start() + + def __enter__(self) -> "KunlunAppServerClient": + return self + + def __exit__(self, *_args: object) -> None: + self.close() + + def diagnostic_tail(self) -> str: + return "\n".join(self._stderr)[-3000:] + + def _failure(self, message: str) -> KunlunAppServerError: + diagnostic = self.diagnostic_tail() + if diagnostic: + return KunlunAppServerError(f"{message}\nKunlunCode stderr:\n{diagnostic}") + return KunlunAppServerError(message) + + def _send(self, message: Mapping[str, Any]) -> None: + if self.process.stdin is None or self.process.stdin.closed: + raise self._failure("KunlunCode app-server stdin is closed") + try: + self.process.stdin.write(json.dumps(dict(message)) + "\n") + self.process.stdin.flush() + except OSError as exc: + raise self._failure("failed to write to KunlunCode app-server") from exc + + def _handle_notification(self, message: dict[str, Any]) -> None: + if self.event_handler is not None: + self.event_handler(message) + + def _next_message(self, timeout_seconds: float) -> dict[str, Any]: + try: + message = self._messages.get(timeout=max(0.01, timeout_seconds)) + except queue.Empty as exc: + raise self._failure("timed out waiting for KunlunCode app-server") from exc + if isinstance(message, EOFError): + raise self._failure( + "KunlunCode app-server exited before completing the request" + ) + if isinstance(message, BaseException): + raise self._failure(str(message)) from message + return message + + def request( + self, + method: str, + params: Mapping[str, Any] | None = None, + *, + timeout_seconds: float = 15.0, + ) -> dict[str, Any]: + self._request_id += 1 + request_id = self._request_id + self._send( + { + "jsonrpc": "2.0", + "id": request_id, + "method": method, + "params": dict(params or {}), + } + ) + deadline = time.monotonic() + max(0.1, timeout_seconds) + while time.monotonic() < deadline: + message = self._next_message(max(0.01, deadline - time.monotonic())) + incoming_method = message.get("method") + if incoming_method: + if message.get("id") is not None: + self._send( + { + "jsonrpc": "2.0", + "id": message["id"], + "error": { + "code": -32001, + "message": ( + "LoopX native Goal runs do not service interactive " + "app-server requests" + ), + }, + } + ) + raise self._failure( + "KunlunCode requested interactive input via " + f"{incoming_method!r}; use a non-interactive permission mode" + ) + self._handle_notification(message) + continue + if message.get("id") != request_id: + raise self._failure("KunlunCode returned an unexpected response id") + error = message.get("error") + if error: + raise self._failure( + f"KunlunCode {method} failed: " + + json.dumps(error, ensure_ascii=False, sort_keys=True) + ) + result = message.get("result") + if result is None: + return {} + if not isinstance(result, dict): + raise self._failure(f"KunlunCode {method} returned a non-object result") + return result + raise self._failure(f"timed out waiting for KunlunCode {method}") + + def notify(self, method: str, params: Mapping[str, Any] | None = None) -> None: + self._send( + { + "jsonrpc": "2.0", + "method": method, + "params": dict(params or {}), + } + ) + + def initialize(self, *, timeout_seconds: float = 15.0) -> dict[str, Any]: + result = self.request( + "initialize", + { + "protocolVersion": KUNLUN_APP_SERVER_PROTOCOL_VERSION, + "clientInfo": { + "name": KUNLUN_APP_SERVER_CLIENT_NAME, + "version": KUNLUN_APP_SERVER_CLIENT_VERSION, + }, + "capabilities": {"experimentalApi": True}, + }, + timeout_seconds=timeout_seconds, + ) + observed = str(result.get("protocolVersion") or "") + if observed != KUNLUN_APP_SERVER_PROTOCOL_VERSION: + raise self._failure( + "KunlunCode app-server protocol mismatch: " + f"expected {KUNLUN_APP_SERVER_PROTOCOL_VERSION}, got {observed or 'missing'}" + ) + self.notify("initialized") + return result + + def start_thread(self, project: Path) -> str: + result = self.request("thread/start", {"cwd": str(project.resolve())}) + thread = result.get("thread") + thread_id = ( + str(thread.get("id") or "") + if isinstance(thread, Mapping) + else str(result.get("threadId") or result.get("thread_id") or "") + ) + if not thread_id: + raise self._failure("KunlunCode thread/start returned no thread id") + return thread_id + + def resume_thread(self, thread_id: str) -> dict[str, Any]: + return self.request("thread/resume", {"threadId": thread_id}) + + def set_goal( + self, + thread_id: str, + *, + objective: str, + mode: str, + token_budget: int | None = None, + ) -> dict[str, Any]: + native_mode = NATIVE_GOAL_MODES.get(mode) + if native_mode is None: + raise ValueError(f"unsupported native KunlunCode goal mode: {mode}") + params: dict[str, Any] = { + "threadId": thread_id, + "objective": objective, + "mode": native_mode, + "requireNoGoal": True, + } + if token_budget is not None: + if token_budget <= 0: + raise ValueError("KunlunCode native goal token budget must be positive") + params["tokenBudget"] = token_budget + return goal_from_result(self.request("thread/goal/set", params)) + + def get_goal( + self, thread_id: str, *, timeout_seconds: float = 15.0 + ) -> dict[str, Any]: + goal = goal_from_result( + self.request( + "thread/goal/get", + {"threadId": thread_id}, + timeout_seconds=timeout_seconds, + ) + ) + if not goal: + raise self._failure("KunlunCode thread/goal/get returned no goal") + return goal + + def start_turn(self, thread_id: str, prompt: str) -> dict[str, Any]: + if not prompt.strip(): + raise ValueError("KunlunCode turn prompt must be non-empty") + return self.request( + "turn/start", + { + "threadId": thread_id, + "input": [{"type": "text", "text": prompt}], + }, + ) + + def wait_for_goal_terminal( + self, + thread_id: str, + *, + timeout_seconds: float, + poll_interval_seconds: float = 0.5, + ) -> dict[str, Any]: + deadline = time.monotonic() + max(0.1, timeout_seconds) + last_goal: dict[str, Any] = {} + while time.monotonic() < deadline: + remaining = max(0.1, deadline - time.monotonic()) + last_goal = self.get_goal( + thread_id, + timeout_seconds=min(15.0, remaining), + ) + status = str(last_goal.get("status") or "") + if status in TERMINAL_GOAL_STATUSES: + return last_goal + wait_until = min( + deadline, time.monotonic() + max(0.05, poll_interval_seconds) + ) + while time.monotonic() < wait_until: + try: + message = self._messages.get( + timeout=max(0.01, wait_until - time.monotonic()) + ) + except queue.Empty: + break + if isinstance(message, EOFError): + raise self._failure( + "KunlunCode app-server exited while the native goal was active" + ) + if isinstance(message, BaseException): + raise self._failure(str(message)) from message + if message.get("method"): + if message.get("id") is not None: + self._send( + { + "jsonrpc": "2.0", + "id": message["id"], + "error": { + "code": -32001, + "message": ( + "LoopX native Goal runs do not service interactive " + "app-server requests" + ), + }, + } + ) + raise self._failure( + "KunlunCode requested interactive input while the native goal was active" + ) + self._handle_notification(message) + continue + raise self._failure( + "KunlunCode returned an unexpected asynchronous response" + ) + compact = compact_goal(last_goal) + raise self._failure( + "timed out while KunlunCode native goal remained non-terminal: " + + json.dumps(compact, ensure_ascii=False, sort_keys=True) + ) + + def close(self) -> None: + process = getattr(self, "process", None) + if process is None or process.poll() is not None: + return + try: + if process.stdin is not None and not process.stdin.closed: + process.stdin.close() + except OSError: + pass + try: + process.wait(timeout=3) + return + except subprocess.TimeoutExpired: + process.terminate() + try: + process.wait(timeout=2) + except subprocess.TimeoutExpired: # pragma: no cover - defensive shutdown + process.kill() + process.wait(timeout=2) diff --git a/loopx/hosts/kunluncode/cli.py b/loopx/hosts/kunluncode/cli.py new file mode 100644 index 0000000000..6052ea5c1b --- /dev/null +++ b/loopx/hosts/kunluncode/cli.py @@ -0,0 +1,768 @@ +"""Install, bind, inspect, and run the LoopX KunlunCode adapter.""" + +from __future__ import annotations + +import argparse +import importlib.metadata +import json +import os +import shutil +import subprocess +import sys +from pathlib import Path +from typing import Any + +from loopx.control_plane.projects.registry_codec import ( + load_project_registry, + mutate_project_registry, + require_runtime_compatible_project_registry, +) +from loopx.goal_mode_context import registered_agent_ids +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, +) + + +# Single source for the adapter's `mcp` pin. It is an exact pin: +# 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/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 +# below derive from it. +MCP_SDK_VERSION = "1.28.1" +MCP_REQUIREMENT = f"mcp=={MCP_SDK_VERSION}" +MCP_SCRIPT = Path(__file__).with_name("server.py").resolve() +DEFAULT_MCP_VENV = ( + Path.home() / ".local" / "share" / "loopx" / "kunluncode-mcp" / ".venv" +) + + +def _run( + command: list[str], + *, + cwd: Path | None = None, + timeout: int = 120, +) -> subprocess.CompletedProcess[str]: + return subprocess.run( + command, + cwd=str(cwd) if cwd else None, + capture_output=True, + text=True, encoding="utf-8", errors="replace", + timeout=timeout, + ) + + +def _loopx_prefix() -> list[str]: + executable = shutil.which("loopx") + return [executable] if executable else [sys.executable, "-m", "loopx.cli"] + + +def _venv_python(venv: Path) -> Path: + return venv / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python") + + +def _compatible_python(value: str | Path) -> bool: + probe = _run( + [ + str(value), + "-c", + ( + "from importlib.metadata import version; " + "from mcp.server.fastmcp import FastMCP; " + "import loopx.hosts.kunluncode.server; " + f"assert version('mcp') == '{MCP_SDK_VERSION}'" + ), + ], + timeout=30, + ) + return probe.returncode == 0 + + +def _source_root() -> Path | None: + candidate = Path(__file__).resolve().parents[3] + return candidate if (candidate / "pyproject.toml").is_file() else None + + +def provision_mcp_python(*, dry_run: bool = False) -> str: + """Provision the adapter only through uv; never mutate system Python.""" + if _compatible_python(sys.executable): + return sys.executable + uv = shutil.which("uv") + if not uv: + raise RuntimeError("uv is required to provision the KunlunCode MCP environment") + venv_python = _venv_python(DEFAULT_MCP_VENV) + source_root = _source_root() + loopx_requirement = ( + ["-e", str(source_root)] + if source_root is not None + else [f"loopx=={importlib.metadata.version('loopx')}"] + ) + if dry_run: + return str(venv_python) + DEFAULT_MCP_VENV.parent.mkdir(parents=True, exist_ok=True) + if not venv_python.is_file(): + created = _run([uv, "venv", "--python", sys.executable, str(DEFAULT_MCP_VENV)]) + if created.returncode != 0: + raise RuntimeError( + "uv venv failed: " + (created.stdout + created.stderr)[-800:] + ) + installed = _run( + [ + uv, + "pip", + "install", + "--python", + str(venv_python), + *loopx_requirement, + MCP_REQUIREMENT, + ], + timeout=300, + ) + if installed.returncode != 0 or not _compatible_python(venv_python): + raise RuntimeError( + "uv pip install failed: " + (installed.stdout + installed.stderr)[-1200:] + ) + return str(venv_python) + + +def _configured_mcp_servers(kunluncode: str) -> list[dict[str, Any]]: + result = _run([kunluncode, "config", "get", "mcp_servers"]) + if result.returncode != 0: + raise RuntimeError("cannot read KunlunCode MCP configuration") + try: + payload = json.loads(result.stdout or "[]") + except json.JSONDecodeError as exc: + raise RuntimeError("KunlunCode returned invalid mcp_servers JSON") from exc + 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 ( + entry.get("name") == MCP_SERVER_NAME + and len(args) == 1 + and str(args[0]) + .replace("\\", "/") + .endswith(_MANAGED_MCP_SCRIPT_SUFFIXES) + ) + + +def _mcp_add_command( + kunluncode: str, + *, + name: str, + command: str, + args: list[str], +) -> list[str]: + result = [ + kunluncode, + "mcp", + "add", + name, + "--command", + command, + ] + if args: + result.extend(["--args", *args]) + return result + + +def _restorable_mcp_command( + kunluncode: str, entry: dict[str, Any] +) -> list[str] | None: + command = entry.get("command") + args = entry.get("args", []) + if not isinstance(command, str) or not command.strip() or not isinstance(args, list): + return None + if not all(isinstance(argument, str) for argument in args): + return None + return _mcp_add_command( + kunluncode, + name=str(entry.get("name") or MCP_SERVER_NAME), + command=command, + args=args, + ) + + +def install_mcp(*, python: str | None, dry_run: bool, replace: bool) -> str: + kunluncode = shutil.which("kunluncode") + if not kunluncode: + raise RuntimeError("kunluncode is not on PATH") + if python: + selected_path = Path(python).expanduser() + if not selected_path.is_absolute(): + selected_path = Path.cwd() / selected_path + selected_python = str(selected_path.absolute()) + else: + selected_python = provision_mcp_python(dry_run=dry_run) + if not dry_run and not _compatible_python(selected_python): + raise RuntimeError( + f"{selected_python} must import LoopX and {MCP_REQUIREMENT}; " + "use uv to sync the adapter environment" + ) + existing = next( + ( + item + for item in _configured_mcp_servers(kunluncode) + if item.get("name") == MCP_SERVER_NAME + ), + None, + ) + if existing and not _is_managed_server(existing) and not replace: + raise RuntimeError( + f"KunlunCode MCP server {MCP_SERVER_NAME!r} is user-owned; pass --replace to replace it" + ) + restore_command = ( + _restorable_mcp_command(kunluncode, existing) if existing else None + ) + if existing and restore_command is None: + raise RuntimeError( + f"KunlunCode MCP server {MCP_SERVER_NAME!r} cannot be safely replaced because its " + "registration cannot be restored with `mcp add`; back it up and remove it manually" + ) + if dry_run: + return selected_python + if existing: + removed = _run([kunluncode, "mcp", "remove", MCP_SERVER_NAME]) + if removed.returncode != 0: + raise RuntimeError("failed to remove prior managed KunlunCode MCP entry") + added = _run( + _mcp_add_command( + kunluncode, + name=MCP_SERVER_NAME, + command=selected_python, + args=[str(MCP_SCRIPT)], + ) + ) + if added.returncode != 0: + if restore_command is not None: + restored = _run(restore_command) + if restored.returncode == 0: + raise RuntimeError( + "KunlunCode MCP registration failed; the previous entry was restored: " + + (added.stdout + added.stderr)[-800:] + ) + raise RuntimeError( + "KunlunCode MCP registration failed and automatic restoration of the previous " + "entry also failed; inspect `kunluncode config get mcp_servers` before retrying" + ) + raise RuntimeError( + "KunlunCode MCP registration failed: " + + (added.stdout + added.stderr)[-800:] + ) + return selected_python + + +def uninstall_mcp(*, dry_run: bool) -> bool: + kunluncode = shutil.which("kunluncode") + if not kunluncode: + raise RuntimeError("kunluncode is not on PATH") + existing = next( + ( + item + for item in _configured_mcp_servers(kunluncode) + if item.get("name") == MCP_SERVER_NAME + ), + None, + ) + if existing is None: + return False + if not _is_managed_server(existing): + raise RuntimeError( + f"refusing to remove user-owned MCP server {MCP_SERVER_NAME!r}" + ) + if not dry_run: + removed = _run([kunluncode, "mcp", "remove", MCP_SERVER_NAME]) + if removed.returncode != 0: + raise RuntimeError("failed to remove KunlunCode MCP entry") + return True + + +def _registry_path(project: Path) -> Path: + current = project / ".loopx" / "registry.json" + legacy = project / ".goal-harness" / "registry.json" + return current if current.is_file() or not legacy.is_file() else legacy + + +def _annotate_registry(registry: Path, *, goal_id: str, agent_id: str) -> None: + def reduce(payload: dict[str, Any]) -> None: + goals = payload.get("goals") or [] + if not any( + str(goal.get("id") or "") == goal_id + for goal in goals + if isinstance(goal, dict) + ): + raise RuntimeError(f"goal {goal_id!r} is not registered in {registry}") + backends = payload.setdefault("agent_backends", []) + if "kunluncode" not in backends: + backends.append("kunluncode") + + mutate_project_registry( + registry, + operation="kunluncode_registry_annotate", + reducer=reduce, + ) + write_binding(registry.parent.parent, goal_id=goal_id, agent_id=agent_id) + + +def _registered_agents_for_goal(registry: Path, goal_id: str) -> list[str]: + payload = load_project_registry(registry) + require_runtime_compatible_project_registry( + payload, + operation="KunlunCode Goal adapter", + ) + goal = next( + ( + item + for item in payload.get("goals") or [] + if isinstance(item, dict) and str(item.get("id") or "") == goal_id + ), + None, + ) + if goal is None: + raise RuntimeError(f"goal {goal_id!r} is not registered in {registry}") + return list(registered_agent_ids(goal)) + + +def _bootstrap_if_needed( + project: Path, + *, + goal_id: str, + objective: str | None, + dry_run: bool, +) -> Path: + registry = _registry_path(project) + if registry.is_file(): + return registry + if not objective: + raise RuntimeError( + "project has no LoopX registry; --objective is required for first connect" + ) + command = [ + *_loopx_prefix(), + "bootstrap", + "--project", + str(project), + "--goal-id", + goal_id, + "--objective", + objective, + "--state-file", + f".loopx/goals/{goal_id}/ACTIVE_GOAL_STATE.md", + "--no-global-sync", + ] + if dry_run: + return registry + result = _run(command, cwd=project) + if result.returncode != 0: + raise RuntimeError( + "LoopX bootstrap failed: " + (result.stdout + result.stderr)[-1200:] + ) + return registry + + +def connect_project( + *, + project: Path, + goal_id: str, + agent_id: str, + objective: str | None, + python: str | None, + skip_mcp: bool, + replace: bool, + dry_run: bool, +) -> dict[str, Any]: + project = project.resolve() + registry = _bootstrap_if_needed( + project, goal_id=goal_id, objective=objective, dry_run=dry_run + ) + if not dry_run: + registered_agents = _registered_agents_for_goal(registry, goal_id) + if agent_id not in registered_agents: + registered_agents.append(agent_id) + agent_arguments = [ + argument + for registered_agent in registered_agents + for argument in ("--registered-agent", registered_agent) + ] + configured = _run( + [ + *_loopx_prefix(), + "--registry", + str(registry), + "configure-goal", + "--goal-id", + goal_id, + "--agent-model", + "peer_v1", + *agent_arguments, + "--execute", + ], + cwd=project, + ) + if configured.returncode != 0: + raise RuntimeError( + "LoopX agent registration failed: " + + (configured.stdout + configured.stderr)[-1200:] + ) + _annotate_registry(registry, goal_id=goal_id, agent_id=agent_id) + selected_python = None + if not skip_mcp: + selected_python = install_mcp(python=python, dry_run=dry_run, replace=replace) + return { + "ok": True, + "dry_run": dry_run, + "project": str(project), + "registry": str(registry), + "goal_id": goal_id, + "agent_id": agent_id, + "binding": str(project / ".loopx" / "kunluncode.json"), + "mcp_server": None if skip_mcp else MCP_SERVER_NAME, + "mcp_python": selected_python, + "global_mcp_registration": not skip_mcp, + "native_app_server": True, + "default_run_mode": "goal-pro", + } + + +def add_todo(project: Path, text: str) -> dict[str, Any]: + context = goal_context(project) + if context is None: + raise RuntimeError( + "KunlunCode is not bound; run loopx-kunluncode connect first" + ) + result = _run( + [ + *_loopx_prefix(), + "--registry", + context["registry"], + "--format", + "json", + "todo", + "add", + "--goal-id", + context["goal_id"], + "--role", + "agent", + "--text", + text, + "--claimed-by", + context["agent_id"], + ], + cwd=project, + ) + if result.returncode != 0: + raise RuntimeError( + "todo add failed: " + (result.stdout + result.stderr)[-1000:] + ) + return json.loads(result.stdout) + + +def worker_prompt(agent_id: str) -> str: + return ( + f"You are the LoopX KunlunCode worker bound as agent {agent_id!r}. " + f"Use the {MCP_SERVER_NAME} MCP lifecycle tools; do not use a Claude binding or guess ids. " + "Call should_run first. If should_run is false, report the reason and stop. " + "If true, claim exactly the selected todo with claim_task, perform one bounded segment, " + "verify it with a real check, then call complete_task with the same agent_id and compact " + "public-safe evidence. Supply either next_agent_todo or no_follow_up=true. " + "Leave the unused field empty and never reuse the completed todo_id as next_agent_todo. " + "When the selected todo already names a check, run that check directly instead of exploring unrelated help or files. " + "Re-check should_run once and stop. Stay inside the projected goal boundary; writes, " + "publishing, destructive actions, and production actions still require their existing authority." + ) + + +def run_worker( + project: Path, + *, + permission_mode: str, + max_duration_secs: int, + json_output: bool, + dry_run: bool, + mode: str = "goal-pro", + controller_timeout_secs: int = 3600, + token_budget: int | None = None, +) -> int: + context = goal_context(project) + if context is None: + raise RuntimeError( + "KunlunCode is not bound; run loopx-kunluncode connect first" + ) + kunluncode = shutil.which("kunluncode") + if not kunluncode: + raise RuntimeError("kunluncode is not on PATH") + if mode != "headless": + if dry_run: + command = build_app_server_command( + kunluncode, + project=project, + permission_mode=permission_mode, + max_duration_secs=max_duration_secs, + ) + payload = { + "ok": True, + "dry_run": True, + "mode": mode, + "command": command, + "side_effects": "none", + } + print( + json.dumps(payload, indent=2) + if json_output + else " ".join(command) + " " + ) + return 0 + payload = run_native_goal( + project, + context, + mode=mode, + permission_mode=permission_mode, + max_duration_secs=max_duration_secs, + controller_timeout_secs=controller_timeout_secs, + token_budget=token_budget, + kunluncode_bin=kunluncode, + ) + if json_output: + print(json.dumps(payload, indent=2)) + elif payload.get("status") == "skipped": + print( + "KunlunCode native Goal skipped: " + + str(payload.get("reason") or "not due") + ) + else: + runtime = ( + payload.get("runtime") + if isinstance(payload.get("runtime"), dict) + else {} + ) + print( + f"KunlunCode {mode} committed for todo {runtime.get('todo_id')}; " + "native verification and LoopX writeback completed." + ) + return 0 + command = [ + kunluncode, + "--cwd", + str(project.resolve()), + "--permission-mode", + permission_mode, + "--tool-profile", + "full", + "--max-duration-secs", + str(max_duration_secs), + ] + if json_output: + command.append("--json") + command.append(worker_prompt(context["agent_id"])) + if dry_run: + print(" ".join(command[:-1]) + " ") + return 0 + environment = dict(os.environ) + adapter_bin = str(Path(sys.executable).absolute().parent) + environment["PATH"] = adapter_bin + os.pathsep + environment.get("PATH", "") + return subprocess.run( + command, + cwd=str(project.resolve()), + env=environment, + ).returncode + + +def status(project: Path) -> dict[str, Any]: + context = goal_context(project) + if context is None: + raise RuntimeError( + "KunlunCode is not bound; run loopx-kunluncode connect first" + ) + result = _run( + [ + *_loopx_prefix(), + "--registry", + context["registry"], + "--format", + "json", + "quota", + "should-run", + "--goal-id", + context["goal_id"], + "--agent-id", + context["agent_id"], + "--runtime-profile", + "kunluncode", + "--available-capability", + "shell", + "--available-capability", + "filesystem_write", + ], + cwd=project, + ) + if result.returncode != 0: + raise RuntimeError("status failed: " + (result.stdout + result.stderr)[-1000:]) + payload = json.loads(result.stdout) + payload["kunluncode_native_goal"] = compact_runtime_state( + read_runtime_state(project.resolve()) + ) + return payload + + +def _parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(prog="loopx-kunluncode") + subparsers = parser.add_subparsers(dest="command", required=True) + + connect = subparsers.add_parser( + "connect", help="Bind one project goal and install the MCP server." + ) + connect.add_argument("--project", default=".") + connect.add_argument("--goal-id", required=True) + connect.add_argument("--agent-id", default=DEFAULT_AGENT_ID) + connect.add_argument("--objective") + connect.add_argument("--python") + connect.add_argument("--skip-mcp", action="store_true") + connect.add_argument("--replace", action="store_true") + connect.add_argument("--dry-run", action="store_true") + + install = subparsers.add_parser( + "install", help="Install the global KunlunCode MCP entry." + ) + install.add_argument("--python") + install.add_argument("--replace", action="store_true") + install.add_argument("--dry-run", action="store_true") + + uninstall = subparsers.add_parser( + "uninstall", help="Remove only the managed KunlunCode MCP entry." + ) + uninstall.add_argument("--dry-run", action="store_true") + + add = subparsers.add_parser( + "add", help="Add and assign one todo to the bound KunlunCode agent." + ) + add.add_argument("text", nargs="+") + add.add_argument("--project", default=".") + + run = subparsers.add_parser( + "run", + help="Run a recoverable native KunlunCode Goal (Goal Pro by default).", + ) + run.add_argument("--project", default=".") + run.add_argument( + "--mode", + choices=["goal-pro", "goal", "headless"], + default="goal-pro", + help=( + "goal-pro uses strict independent verification; goal uses native Arrangement; " + "headless preserves the legacy one-turn MCP worker" + ), + ) + run.add_argument( + "--permission-mode", + choices=["ask", "auto", "accept-edits", "dont-ask", "bypass", "yolo"], + default="auto", + ) + run.add_argument("--max-duration-secs", type=int, default=600) + run.add_argument( + "--controller-timeout-secs", + type=int, + default=3600, + help="Overall wait budget across native Goal auto-continuations.", + ) + run.add_argument( + "--token-budget", + type=int, + help="Optional positive KunlunCode native Goal token budget.", + ) + run.add_argument("--json", action="store_true") + run.add_argument("--dry-run", action="store_true") + + status_parser = subparsers.add_parser( + "status", help="Read the bound KunlunCode lane status." + ) + status_parser.add_argument("--project", default=".") + return parser + + +def main(argv: list[str] | None = None) -> int: + args = _parser().parse_args(argv) + try: + if args.command == "connect": + payload = connect_project( + project=Path(args.project), + goal_id=args.goal_id, + agent_id=args.agent_id, + objective=args.objective, + python=args.python, + skip_mcp=args.skip_mcp, + replace=args.replace, + dry_run=args.dry_run, + ) + print(json.dumps(payload, indent=2)) + return 0 + if args.command == "install": + selected = install_mcp( + python=args.python, dry_run=args.dry_run, replace=args.replace + ) + print( + json.dumps( + { + "ok": True, + "mcp_server": MCP_SERVER_NAME, + "python": selected, + "dry_run": args.dry_run, + }, + indent=2, + ) + ) + return 0 + if args.command == "uninstall": + removed = uninstall_mcp(dry_run=args.dry_run) + print( + json.dumps( + {"ok": True, "removed": removed, "dry_run": args.dry_run}, indent=2 + ) + ) + return 0 + if args.command == "add": + print( + json.dumps(add_todo(Path(args.project), " ".join(args.text)), indent=2) + ) + return 0 + if args.command == "run": + return run_worker( + Path(args.project), + permission_mode=args.permission_mode, + max_duration_secs=args.max_duration_secs, + json_output=args.json, + dry_run=args.dry_run, + mode=args.mode, + controller_timeout_secs=args.controller_timeout_secs, + token_budget=args.token_budget, + ) + if args.command == "status": + print(json.dumps(status(Path(args.project)), indent=2)) + return 0 + except ( + OSError, + RuntimeError, + json.JSONDecodeError, + importlib.metadata.PackageNotFoundError, + ) as exc: + print(json.dumps({"ok": False, "error": str(exc)}, indent=2), file=sys.stderr) + return 1 + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/loopx/hosts/kunluncode/context.py b/loopx/hosts/kunluncode/context.py new file mode 100644 index 0000000000..caedf2224a --- /dev/null +++ b/loopx/hosts/kunluncode/context.py @@ -0,0 +1,70 @@ +"""KunlunCode-specific LoopX goal and agent binding.""" +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +from loopx.file_lock import exclusive_file_lock +from loopx.goal_mode_context import find_registry, resolve_goal_context +from loopx.registry import atomic_write_json + + +BINDING_SCHEMA_VERSION = "loopx_kunluncode_binding_v0" +BINDING_FILENAME = "kunluncode.json" + + +def binding_path(project_root: str | Path) -> Path: + return Path(project_root) / ".loopx" / BINDING_FILENAME + + +def read_binding(project_root: str | Path) -> dict[str, str] | None: + path = binding_path(project_root) + try: + payload: Any = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return None + if not isinstance(payload, dict): + return None + if payload.get("schema_version") != BINDING_SCHEMA_VERSION: + return None + goal_id = str(payload.get("goal_id") or "").strip() + agent_id = str(payload.get("agent_id") or "").strip() + if not goal_id or not agent_id: + return None + return {"goal_id": goal_id, "agent_id": agent_id} + + +def write_binding( + project_root: str | Path, + *, + goal_id: str, + agent_id: str, +) -> Path: + path = binding_path(project_root) + path.parent.mkdir(parents=True, exist_ok=True) + payload = { + "schema_version": BINDING_SCHEMA_VERSION, + "host": "kunluncode", + "goal_id": goal_id, + "agent_id": agent_id, + } + with exclusive_file_lock(path, operation="kunluncode_binding_write"): + atomic_write_json(path, payload) + return path + + +def goal_context(cwd: str | Path) -> dict[str, Any] | None: + registry = find_registry(cwd) + if registry is None: + return None + root = registry.parent.parent + binding = read_binding(root) + if binding is None: + return None + return resolve_goal_context( + cwd, + preferred_goal_id=binding["goal_id"], + preferred_agent_id=binding["agent_id"], + require_preferred_binding=True, + ) diff --git a/loopx/hosts/kunluncode/control_plane.py b/loopx/hosts/kunluncode/control_plane.py new file mode 100644 index 0000000000..a61cae4d82 --- /dev/null +++ b/loopx/hosts/kunluncode/control_plane.py @@ -0,0 +1,235 @@ +"""Narrow LoopX CLI seam for the native KunlunCode Goal controller.""" + +from __future__ import annotations + +import json +import shutil +import subprocess +import sys +from collections.abc import Callable, Mapping +from pathlib import Path +from typing import Any + +from loopx.control_plane.agents.workspace_guard import capture_delivery_workspace + + +AVAILABLE_CAPABILITIES = ("shell", "filesystem_write") +VERIFIED_CLASSIFICATIONS = { + "goal": "kunluncode_native_goal_verified", + "goal-pro": "kunluncode_native_goal_pro_verified", +} + + +class KunlunNativeGoalRuntimeError(RuntimeError): + """Raised when native Goal execution or LoopX reconciliation fails closed.""" + + +def _default_loopx_prefix() -> list[str]: + executable = shutil.which("loopx") + return [executable] if executable else [sys.executable, "-m", "loopx.cli"] + + +CommandRunner = Callable[..., subprocess.CompletedProcess[str]] + + +def _default_command_runner( + command: list[str], + *, + cwd: Path, + timeout: int = 120, +) -> subprocess.CompletedProcess[str]: + return subprocess.run( + command, + cwd=str(cwd), + capture_output=True, + text=True, encoding="utf-8", errors="replace", + timeout=timeout, + ) + + +class LoopXControlPlane: + """JSON CLI operations used by the native KunlunCode controller.""" + + def __init__( + self, + project: Path, + context: Mapping[str, Any], + *, + command_prefix: list[str] | None = None, + runner: CommandRunner | None = None, + ) -> None: + self.project = project.resolve() + self.registry = str(context.get("registry") or "") + self.goal_id = str(context.get("goal_id") or "") + self.agent_id = str(context.get("agent_id") or "") + if not self.registry or not self.goal_id or not self.agent_id: + raise KunlunNativeGoalRuntimeError( + "KunlunCode binding is missing registry, goal, or agent identity" + ) + self.command_prefix = list(command_prefix or _default_loopx_prefix()) + self.runner = runner or _default_command_runner + + def _run_json(self, arguments: list[str], *, timeout: int = 120) -> dict[str, Any]: + command = [ + *self.command_prefix, + "--registry", + self.registry, + "--format", + "json", + *arguments, + ] + result = self.runner(command, cwd=self.project, timeout=timeout) + try: + payload = json.loads(result.stdout or "{}") + except json.JSONDecodeError as exc: + diagnostic = (result.stderr or result.stdout or "")[-1200:] + raise KunlunNativeGoalRuntimeError( + "LoopX returned non-JSON output" + + (f": {diagnostic}" if diagnostic else "") + ) from exc + if not isinstance(payload, dict): + raise KunlunNativeGoalRuntimeError( + "LoopX returned a non-object JSON payload" + ) + if result.returncode != 0 or payload.get("ok") is False: + reason = payload.get("error") or payload.get("reason") or result.stderr + raise KunlunNativeGoalRuntimeError( + "LoopX control-plane command failed: " + + str(reason or "unknown error")[-1200:] + ) + return payload + + @staticmethod + def _capability_args() -> list[str]: + return [ + argument + for capability in AVAILABLE_CAPABILITIES + for argument in ("--available-capability", capability) + ] + + def should_run(self) -> dict[str, Any]: + return self._run_json( + [ + "quota", + "should-run", + "--goal-id", + self.goal_id, + "--agent-id", + self.agent_id, + "--runtime-profile", + "kunluncode", + *self._capability_args(), + ] + ) + + def claim(self, todo_id: str) -> dict[str, Any]: + return self._run_json( + [ + "todo", + "claim", + "--goal-id", + self.goal_id, + "--todo-id", + todo_id, + "--claimed-by", + self.agent_id, + "--agent-id", + self.agent_id, + ] + ) + + def evidence_since(self, since: str, *, todo_id: str) -> dict[str, Any]: + # Recovery reads its owning persisted event source directly. An agent-facing + # diagnostic command is not a dependency of native writeback reconciliation. + from loopx.history import load_registry + from loopx.paths import resolve_runtime_root + from loopx.rollout_event_log import load_rollout_events, rollout_event_log_path + from loopx.control_plane.runtime.agent_evidence_history import build_agent_scoped_evidence_log + + try: + registry_path = Path(self.registry).expanduser() + if not registry_path.is_absolute(): + registry_path = self.project / registry_path + registry = load_registry(registry_path) + runtime_root = resolve_runtime_root(registry, None, registry_path=registry_path) + events = load_rollout_events(rollout_event_log_path(runtime_root, self.goal_id), limit=400) + return build_agent_scoped_evidence_log( + goal_id=self.goal_id, agent_id=self.agent_id, todo_id=todo_id, + since=since, rollout_events=events, history_runs=[], limit=128, + ) + except (OSError, ValueError, TypeError) as exc: + raise KunlunNativeGoalRuntimeError(f"writeback evidence unavailable: {exc}") from exc + + def record_verified_delivery(self, *, mode: str, todo_id: str) -> dict[str, Any]: + workspace_arguments = ( + ["--delivery-workspace-path", str(self.project)] + if capture_delivery_workspace(self.project) + else [] + ) + return self._run_json( + [ + "refresh-state", + "--goal-id", + self.goal_id, + "--todo-id", + todo_id, + "--project", + str(self.project), + "--classification", + VERIFIED_CLASSIFICATIONS[mode], + "--recommended-action", + "Reconcile the verifier-approved KunlunCode todo and continue from LoopX quota.", + "--delivery-batch-scale", + "single_surface", + "--delivery-outcome", + "outcome_progress", + *workspace_arguments, + "--agent-id", + self.agent_id, + "--progress-scope", + "goal", + *self._capability_args(), + "--suppress-external-sinks", + ], + timeout=300, + ) + + def complete(self, todo_id: str, *, evidence: str) -> dict[str, Any]: + return self._run_json( + [ + "todo", + "complete", + "--goal-id", + self.goal_id, + "--todo-id", + todo_id, + "--claimed-by", + self.agent_id, + "--agent-id", + self.agent_id, + "--evidence", + evidence, + "--no-follow-up", + ] + ) + + def spend(self, *, todo_id: str) -> dict[str, Any]: + return self._run_json( + [ + "quota", + "spend-slot", + "--goal-id", + self.goal_id, + "--todo-id", + todo_id, + "--slots", + "1", + "--source", + "adapter", + "--execute", + "--agent-id", + self.agent_id, + *self._capability_args(), + ], + timeout=300, + ) diff --git a/loopx/hosts/kunluncode/guards.py b/loopx/hosts/kunluncode/guards.py new file mode 100644 index 0000000000..03d15e6a86 --- /dev/null +++ b/loopx/hosts/kunluncode/guards.py @@ -0,0 +1,110 @@ +"""Write-ownership guards for a LoopX-controlled native KunlunCode Goal.""" + +from __future__ import annotations + +import json +import os +from typing import Any + + +NATIVE_CONTROLLER_ENV = "LOOPX_KUNLUNCODE_OUTER_CONTROLLER" +NATIVE_CONTROLLER_GOAL_ENV = "LOOPX_KUNLUNCODE_OUTER_GOAL_ID" +NATIVE_CONTROLLER_AGENT_ENV = "LOOPX_KUNLUNCODE_OUTER_AGENT_ID" + + +def _native_controller_rejection(operation: str) -> str: + return json.dumps( + { + "ok": False, + "error": ( + f"{operation} is owned by the LoopX outer controller during a native " + "KunlunCode Goal run; wait for verifier-backed terminal writeback" + ), + } + ) + + +def guard_native_controller_writeback(control_plane: Any) -> None: + """Prevent model-visible MCP tools from committing before native verification.""" + + if os.environ.get(NATIVE_CONTROLLER_ENV) != "1": + return + + def blocked_claim(_todo_id: str, _agent_id: str) -> str: + return _native_controller_rejection("claim_task") + + def blocked_complete(*_args: Any, **_kwargs: Any) -> str: + return _native_controller_rejection("complete_task") + + control_plane.claim_task = blocked_claim + control_plane.complete_task = blocked_complete + + def blocked_vision(*_args: Any, **_kwargs: Any) -> str: + return _native_controller_rejection("review_task_vision") + + control_plane.review_task_vision = blocked_vision + + +def native_controller_cli_write_block(arguments: Any) -> dict[str, Any] | None: + """Block direct model CLI writes to the Goal owned by the outer controller.""" + + if os.environ.get(NATIVE_CONTROLLER_ENV) != "1": + return None + goal_id = str(os.environ.get(NATIVE_CONTROLLER_GOAL_ENV) or "").strip() + if not goal_id: + return None + raw_goal_ids: list[Any] = [] + for attribute in ("goal_id", "goal_ids"): + value = getattr(arguments, attribute, None) + if isinstance(value, (list, tuple, set)): + raw_goal_ids.extend(value) + else: + raw_goal_ids.append(value) + requested_goal_ids = { + str(value).strip() for value in raw_goal_ids if str(value or "").strip() + } + if goal_id not in requested_goal_ids: + return None + + command = str(getattr(arguments, "command", None) or "") + operation: str | None = None + if command == "todo": + todo_command = str(getattr(arguments, "todo_command", None) or "add") + if todo_command not in {"list", "suggest"}: + operation = f"todo {todo_command}" + elif command == "quota": + quota_command = str(getattr(arguments, "quota_command", None) or "status") + if quota_command not in {"status", "plan", "should-run"}: + operation = f"quota {quota_command}" + elif command == "task-lease": + lease_command = str(getattr(arguments, "task_lease_command", None) or "") + if lease_command != "inspect": + operation = f"task-lease {lease_command}".strip() + elif command == "turn" and getattr(arguments, "turn_command", None) == "run-once": + operation = "turn run-once" + elif command == "goal-lifecycle" and getattr(arguments, "execute", False): + operation = f"goal-lifecycle {getattr(arguments, 'operation', '')}".strip() + elif command in { + "archive-runtime", + "configure-goal", + "operator-gate", + "refresh-state", + "register-agent", + "retire-global-goal", + "reward", + }: + operation = command + if operation is None: + return None + return { + "ok": False, + "error_code": "kunluncode_outer_controller_write_owned", + "error": ( + f"{operation} for goal {goal_id!r} is owned by the LoopX outer controller " + "during this native KunlunCode Goal run" + ), + "goal_id": goal_id, + "agent_id": str(os.environ.get(NATIVE_CONTROLLER_AGENT_ENV) or "") or None, + "operation": operation, + "next_action": "wait for verifier-backed terminal writeback", + } diff --git a/loopx/hosts/kunluncode/runtime.py b/loopx/hosts/kunluncode/runtime.py new file mode 100644 index 0000000000..f4938ee558 --- /dev/null +++ b/loopx/hosts/kunluncode/runtime.py @@ -0,0 +1,741 @@ +"""Recoverable LoopX controller for KunlunCode native Goal and Goal Pro.""" + +from __future__ import annotations + +import json +import os +import shutil +import sys +from collections.abc import Callable, Mapping +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +from loopx.file_lock import exclusive_file_lock +from loopx.control_plane.goals.first_party_host_admission import ( + FirstPartyHostGoalAdmission, + capture_first_party_host_goal_ref, +) +from loopx.hosts.kunluncode.app_server import ( + NATIVE_GOAL_MODES, + KunlunAppServerClient, + KunlunAppServerError, + build_app_server_command, + compact_goal, + native_goal_success, + stable_text_digest, +) +from loopx.hosts.kunluncode.control_plane import ( + VERIFIED_CLASSIFICATIONS, + KunlunNativeGoalRuntimeError, + LoopXControlPlane, +) +from loopx.hosts.kunluncode.guards import ( + NATIVE_CONTROLLER_AGENT_ENV, + NATIVE_CONTROLLER_ENV, + NATIVE_CONTROLLER_GOAL_ENV, +) +from loopx.registry import atomic_write_json + + +RUNTIME_STATE_SCHEMA_VERSION = "loopx_kunluncode_runtime_v0" +RUNTIME_STATE_FILENAME = "kunluncode-runtime.json" + + +def _now() -> str: + return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") + + +def runtime_state_path(project: str | Path) -> Path: + return Path(project) / ".loopx" / RUNTIME_STATE_FILENAME + + +def _validate_runtime_state_payload(payload: dict[str, Any]) -> None: + if payload.get("schema_version") != RUNTIME_STATE_SCHEMA_VERSION: + raise KunlunNativeGoalRuntimeError( + "KunlunCode runtime journal has an unsupported schema" + ) + binding = payload.get("binding") + native = payload.get("native") + writeback = payload.get("writeback") + if not isinstance(binding, dict): + raise KunlunNativeGoalRuntimeError( + "KunlunCode runtime journal is missing a binding object" + ) + if not isinstance(native, dict): + raise KunlunNativeGoalRuntimeError( + "KunlunCode runtime journal is missing a native state object" + ) + if not isinstance(writeback, dict): + raise KunlunNativeGoalRuntimeError( + "KunlunCode runtime journal is missing a writeback state object" + ) + if not all(str(binding.get(key) or "").strip() for key in ("goal_id", "agent_id")): + raise KunlunNativeGoalRuntimeError( + "KunlunCode runtime journal has an incomplete goal or agent binding" + ) + if not str(payload.get("todo_id") or "").strip(): + raise KunlunNativeGoalRuntimeError( + "KunlunCode runtime journal is missing its todo identity" + ) + if native.get("mode") not in NATIVE_GOAL_MODES: + raise KunlunNativeGoalRuntimeError( + "KunlunCode runtime journal has an unsupported native goal mode" + ) + objective_digest = str(native.get("objective_sha256") or "") + if len(objective_digest) != 64 or any( + character not in "0123456789abcdef" for character in objective_digest + ): + raise KunlunNativeGoalRuntimeError( + "KunlunCode runtime journal has an invalid objective digest" + ) + for key in ("verification_passed", "verified", "resumed"): + if not isinstance(native.get(key), bool): + raise KunlunNativeGoalRuntimeError( + f"KunlunCode runtime journal native field {key!r} must be boolean" + ) + for key in ("delivery_recorded", "todo_completed", "quota_spent"): + if not isinstance(writeback.get(key), bool): + raise KunlunNativeGoalRuntimeError( + f"KunlunCode runtime journal writeback field {key!r} must be boolean" + ) + if writeback["todo_completed"] and not writeback["delivery_recorded"]: + raise KunlunNativeGoalRuntimeError( + "KunlunCode runtime journal records todo completion before delivery" + ) + if writeback["quota_spent"] and not writeback["todo_completed"]: + raise KunlunNativeGoalRuntimeError( + "KunlunCode runtime journal records quota spend before todo completion" + ) + if any(writeback.values()) and native["verified"] is not True: + raise KunlunNativeGoalRuntimeError( + "KunlunCode runtime journal records writeback before native verification" + ) + if native["verified"] and native.get("status") != "complete": + raise KunlunNativeGoalRuntimeError( + "KunlunCode runtime journal marks a non-complete native goal verified" + ) + if ( + native["verified"] + and native.get("mode") == "goal-pro" + and native["verification_passed"] is not True + ): + raise KunlunNativeGoalRuntimeError( + "KunlunCode Goal Pro runtime journal is verified without verifier proof" + ) + + +def read_runtime_state(project: str | Path) -> dict[str, Any] | None: + path = runtime_state_path(project) + if not path.is_file(): + return None + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + raise KunlunNativeGoalRuntimeError( + f"KunlunCode runtime journal is unreadable: {path}" + ) from exc + if not isinstance(payload, dict): + raise KunlunNativeGoalRuntimeError( + "KunlunCode runtime journal is not an object" + ) + _validate_runtime_state_payload(payload) + return payload + + +def write_runtime_state(project: str | Path, state: dict[str, Any]) -> Path: + state["updated_at"] = _now() + _validate_runtime_state_payload(state) + path = runtime_state_path(project) + atomic_write_json(path, state) + return path + + +def _writeback_state(state: Mapping[str, Any]) -> dict[str, Any]: + value = state.get("writeback") + return dict(value) if isinstance(value, Mapping) else {} + + +def runtime_phase(state: Mapping[str, Any]) -> str: + native = state.get("native") if isinstance(state.get("native"), Mapping) else {} + writeback = _writeback_state(state) + if writeback.get("quota_spent") is True: + return "committed" + if writeback.get("todo_completed") is True: + return "todo_completed" + if writeback.get("delivery_recorded") is True: + return "delivery_recorded" + if native.get("verified") is True: + return "native_verified" + if native.get("thread_id"): + return "native_active" + return "planned" + + +def compact_runtime_state(state: Mapping[str, Any] | None) -> dict[str, Any] | None: + if not isinstance(state, Mapping): + return None + binding = state.get("binding") if isinstance(state.get("binding"), Mapping) else {} + native = state.get("native") if isinstance(state.get("native"), Mapping) else {} + writeback = _writeback_state(state) + return { + "schema_version": state.get("schema_version"), + "phase": runtime_phase(state), + "goal_id": binding.get("goal_id"), + "agent_id": binding.get("agent_id"), + "todo_id": state.get("todo_id"), + "mode": native.get("mode"), + "thread_id": native.get("thread_id"), + "native_goal_id": native.get("goal_id"), + "native_status": native.get("status"), + "verification_passed": native.get("verification_passed") is True, + "resumed": native.get("resumed") is True, + "delivery_recorded": writeback.get("delivery_recorded") is True, + "todo_completed": writeback.get("todo_completed") is True, + "quota_spent": writeback.get("quota_spent") is True, + "updated_at": state.get("updated_at"), + } + + +def build_native_goal_objective(todo: Mapping[str, Any], *, agent_id: str) -> str: + todo_id = str(todo.get("todo_id") or "").strip() + text = str(todo.get("text") or "").strip() + if not todo_id or not text: + raise KunlunNativeGoalRuntimeError( + "LoopX selected todo must include a stable todo_id and non-empty text" + ) + scopes = [ + str(item).strip() + for item in todo.get("required_write_scopes") or [] + if str(item).strip() + ] + scope_text = ", ".join(scopes) if scopes else "the active LoopX goal boundary" + return ( + f"Complete LoopX todo {todo_id} as bound agent {agent_id}: {text}\n\n" + f"Write boundary: {scope_text}. Preserve all existing repository and user authority gates. " + "Run focused validation for the actual artifact. Continue under this native Goal until the " + "objective is genuinely complete. The LoopX outer controller exclusively owns claim, todo " + "completion, state refresh, and quota accounting; do not call LoopX MCP claim_task or " + "complete_task and do not run LoopX lifecycle write commands. Use KunlunCode's native " + "update_goal lifecycle only after the work and its validation are complete." + ) + + +def native_goal_turn_prompt(mode: str) -> str: + label = "/goal-pro" if mode == "goal-pro" else "/goal" + return ( + f"Work autonomously toward the already-active native KunlunCode {label} objective. " + "Inspect current repository state before editing, stay inside the stated write boundary, " + "and run real focused validation. Do not create a second goal. Do not call LoopX lifecycle " + "write tools; the outer controller will reconcile LoopX only after this native goal reaches " + "an accepted terminal state." + ) + + +def _new_state( + context: Mapping[str, Any], + *, + todo_id: str, + mode: str, + objective_sha256: str, + goal_ref: Mapping[str, str] | None = None, +) -> dict[str, Any]: + timestamp = _now() + binding = { + "goal_id": str(context.get("goal_id") or ""), + "agent_id": str(context.get("agent_id") or ""), + } + if goal_ref is not None: + binding["goal_instance_id"] = goal_ref["goal_instance_id"] + return { + "schema_version": RUNTIME_STATE_SCHEMA_VERSION, + "created_at": timestamp, + "updated_at": timestamp, + "binding": binding, + "todo_id": todo_id, + "native": { + "mode": mode, + "objective_sha256": objective_sha256, + "thread_id": None, + "goal_id": None, + "revision": None, + "status": "planned", + "verification_kind": None, + "verification_passed": False, + "verified": False, + "verified_at": None, + "resumed": False, + "event_counts": {}, + }, + "writeback": { + "delivery_recorded": False, + "todo_completed": False, + "quota_spent": False, + }, + } + + +def _validate_binding(state: Mapping[str, Any], context: Mapping[str, Any]) -> None: + binding = state.get("binding") if isinstance(state.get("binding"), Mapping) else {} + expected = { + "goal_id": str(context.get("goal_id") or ""), + "agent_id": str(context.get("agent_id") or ""), + } + actual = {key: str(binding.get(key) or "") for key in expected} + if actual != expected: + raise KunlunNativeGoalRuntimeError( + "KunlunCode runtime journal belongs to another LoopX goal or agent" + ) + + +def _runtime_goal_ref(state: Mapping[str, Any]) -> object: + binding = state.get("binding") + if not isinstance(binding, Mapping): + return {"malformed": True} + goal_ref = {"goal_id": binding.get("goal_id")} + if "goal_instance_id" in binding: + goal_ref["goal_instance_id"] = binding.get("goal_instance_id") + return goal_ref + + +def _commit_runtime_state( + project: Path, + state: dict[str, Any], + goal_admission: FirstPartyHostGoalAdmission, +) -> Path: + return goal_admission.accept_result(lambda: write_runtime_state(project, state)) + + +def _compact_receipt( + payload: Mapping[str, Any], fields: tuple[str, ...] +) -> dict[str, Any]: + return {key: payload.get(key) for key in fields if key in payload} + + +def _reconcile_writeback_evidence( + project: Path, + state: dict[str, Any], + control: LoopXControlPlane, + goal_admission: FirstPartyHostGoalAdmission, +) -> None: + native = state["native"] + since = str(native.get("verified_at") or "") + if not since: + return + todo_id = str(state.get("todo_id") or "") + goal_admission.require_current() + payload = control.evidence_since(since, todo_id=todo_id) + if payload.get("schema_version") != "agent_scoped_evidence_log_v0" or not isinstance(payload.get("ledger"), list): + raise KunlunNativeGoalRuntimeError("invalid internal writeback evidence schema") + ledger = payload["ledger"] + writeback = state["writeback"] + classification = VERIFIED_CLASSIFICATIONS[str(native.get("mode") or "goal-pro")] + for event in ledger: + if not isinstance(event, Mapping): + continue + event_kind = str(event.get("event_kind") or "") + if str(event.get("todo_id") or "") != todo_id: + continue + if ( + event_kind == "refresh_state" + and event.get("classification") == classification + ): + writeback["delivery_recorded"] = True + if event_kind == "todo_complete" and str(event.get("todo_id") or "") == todo_id: + writeback["todo_completed"] = True + if event_kind in {"quota_spend", "quota_slot_spent"}: + writeback["quota_spent"] = True + _commit_runtime_state(project, state, goal_admission) + + +def _verified_evidence(state: Mapping[str, Any]) -> str: + native = state.get("native") if isinstance(state.get("native"), Mapping) else {} + mode = str(native.get("mode") or "goal-pro") + verification = "passed" if native.get("verification_passed") else "not-required" + digest = str(native.get("objective_sha256") or "")[:16] + native_goal_id = str(native.get("goal_id") or "") + return ( + f"KunlunCode native {mode} terminal accepted; status=complete; " + f"verification={verification}; objective_sha256={digest}; " + f"native_goal_id={native_goal_id}" + ) + + +def _closeout_writeback( + project: Path, + state: dict[str, Any], + control: LoopXControlPlane, + goal_admission: FirstPartyHostGoalAdmission, +) -> None: + goal_admission.require_current() + _reconcile_writeback_evidence(project, state, control, goal_admission) + writeback = state["writeback"] + mode = str(state["native"]["mode"]) + if writeback.get("delivery_recorded") is not True: + goal_admission.require_current() + payload = control.record_verified_delivery( + mode=mode, + todo_id=str(state["todo_id"]), + ) + if payload.get("appended") is not True: + raise KunlunNativeGoalRuntimeError( + "LoopX did not append the verified KunlunCode delivery record" + ) + writeback["delivery_recorded"] = True + writeback["delivery_receipt"] = _compact_receipt( + payload, ("classification", "generated_at", "appended") + ) + _commit_runtime_state(project, state, goal_admission) + if writeback.get("todo_completed") is not True: + goal_admission.require_current() + payload = control.complete( + str(state["todo_id"]), evidence=_verified_evidence(state) + ) + if payload.get("completed") is not True or payload.get("status") != "done": + raise KunlunNativeGoalRuntimeError( + "LoopX did not accept the verified KunlunCode todo completion" + ) + writeback["todo_completed"] = True + writeback["todo_receipt"] = _compact_receipt( + payload, ("todo_id", "status", "status_changed", "changed") + ) + _commit_runtime_state(project, state, goal_admission) + if writeback.get("quota_spent") is not True: + goal_admission.require_current() + payload = control.spend(todo_id=str(state["todo_id"])) + if payload.get("appended") is not True: + raise KunlunNativeGoalRuntimeError( + "LoopX did not append quota accounting for the verified KunlunCode delivery: " + + str(payload.get("reason") or "unknown reason") + ) + writeback["quota_spent"] = True + writeback["quota_receipt"] = _compact_receipt( + payload, ("classification", "generated_at", "appended", "slots") + ) + _commit_runtime_state(project, state, goal_admission) + + +def _update_native_from_goal(state: dict[str, Any], goal: Mapping[str, Any]) -> None: + compact = compact_goal(goal) + native = state["native"] + native["goal_id"] = compact.get("goal_id") + native["revision"] = compact.get("revision") + native["status"] = compact.get("status") + native["verification_kind"] = compact.get("verification_kind") + native["verification_passed"] = compact.get("verification_passed") is True + + +def _validate_native_identity( + state: Mapping[str, Any], + goal: Mapping[str, Any], +) -> None: + native = state["native"] + compact = compact_goal(goal) + expected_goal_id = str(native.get("goal_id") or "") + observed_goal_id = str(compact.get("goal_id") or "") + if expected_goal_id and observed_goal_id != expected_goal_id: + raise KunlunNativeGoalRuntimeError( + "resumed KunlunCode thread contains a different native goal" + ) + objective_sha256 = str(compact.get("objective_sha256") or "") + if objective_sha256 and objective_sha256 != native.get("objective_sha256"): + raise KunlunNativeGoalRuntimeError( + "resumed KunlunCode native goal objective no longer matches the LoopX todo" + ) + expected_mode = NATIVE_GOAL_MODES[str(native.get("mode") or "")] + observed_mode = str(compact.get("mode") or "") + if observed_mode and observed_mode != expected_mode: + raise KunlunNativeGoalRuntimeError( + "resumed KunlunCode native goal mode does not match the runtime journal" + ) + + +def _run_native_host( + project: Path, + state: dict[str, Any], + *, + objective: str, + kunluncode_bin: str, + permission_mode: str, + max_duration_secs: int, + controller_timeout_secs: int, + token_budget: int | None, + scenario: str | None, + client_factory: Callable[..., Any], + goal_admission: FirstPartyHostGoalAdmission, +) -> None: + command = build_app_server_command( + kunluncode_bin, + project=project, + permission_mode=permission_mode, + max_duration_secs=max_duration_secs, + scenario=scenario, + ) + environment = dict(os.environ) + environment[NATIVE_CONTROLLER_ENV] = "1" + environment[NATIVE_CONTROLLER_GOAL_ENV] = str(state["binding"]["goal_id"]) + environment[NATIVE_CONTROLLER_AGENT_ENV] = str(state["binding"]["agent_id"]) + adapter_bin = str(Path(sys.executable).absolute().parent) + environment["PATH"] = adapter_bin + os.pathsep + environment.get("PATH", "") + event_counts: dict[str, int] = {} + + def record_event(message: Mapping[str, Any]) -> None: + method = str(message.get("method") or "") + if method: + event_counts[method] = event_counts.get(method, 0) + 1 + + native = state["native"] + goal_admission.require_current() + with client_factory( + command, + cwd=project, + env=environment, + event_handler=record_event, + ) as client: + client.initialize() + thread_id = str(native.get("thread_id") or "") + resumed = False + goal: dict[str, Any] = {} + if thread_id: + client.resume_thread(thread_id) + resumed = True + if not thread_id: + thread_id = client.start_thread(project) + native["thread_id"] = thread_id + native["status"] = "thread_started" + _commit_runtime_state(project, state, goal_admission) + elif native.get("goal_id"): + goal = client.get_goal(thread_id) + _validate_native_identity(state, goal) + else: + try: + goal = client.get_goal(thread_id) + _validate_native_identity(state, goal) + except KunlunAppServerError: + goal = {} + native["resumed"] = resumed + if not goal: + goal = client.set_goal( + thread_id, + objective=objective, + mode=str(native["mode"]), + token_budget=token_budget, + ) + _validate_native_identity(state, goal) + _update_native_from_goal(state, goal) + _commit_runtime_state(project, state, goal_admission) + else: + _update_native_from_goal(state, goal) + _commit_runtime_state(project, state, goal_admission) + + if not native_goal_success(goal, mode=str(native["mode"])): + status = str(goal.get("status") or "") + if status != "active": + raise KunlunNativeGoalRuntimeError( + "KunlunCode native goal stopped without an accepted completion: " + + json.dumps(compact_goal(goal), ensure_ascii=False, sort_keys=True) + ) + client.start_turn( + thread_id, + native_goal_turn_prompt(str(native["mode"])), + ) + goal = client.wait_for_goal_terminal( + thread_id, + timeout_seconds=controller_timeout_secs, + ) + _validate_native_identity(state, goal) + _update_native_from_goal(state, goal) + native["event_counts"] = dict(sorted(event_counts.items())) + if not native_goal_success(goal, mode=str(native["mode"])): + _commit_runtime_state(project, state, goal_admission) + raise KunlunNativeGoalRuntimeError( + "KunlunCode native goal did not reach an accepted terminal state: " + + json.dumps(compact_goal(goal), ensure_ascii=False, sort_keys=True) + ) + native["verified"] = True + native["verified_at"] = native.get("verified_at") or _now() + _commit_runtime_state(project, state, goal_admission) + + +def run_native_goal( + project: Path, + context: Mapping[str, Any], + *, + mode: str, + permission_mode: str, + max_duration_secs: int, + controller_timeout_secs: int, + token_budget: int | None = None, + scenario: str | None = None, + kunluncode_bin: str | None = None, + control_plane: LoopXControlPlane | None = None, + client_factory: Callable[..., Any] = KunlunAppServerClient, +) -> dict[str, Any]: + if mode not in NATIVE_GOAL_MODES: + raise KunlunNativeGoalRuntimeError( + f"unsupported native KunlunCode goal mode: {mode}" + ) + if max_duration_secs <= 0 or controller_timeout_secs <= 0: + raise KunlunNativeGoalRuntimeError( + "KunlunCode turn and controller timeouts must be positive" + ) + if token_budget is not None and token_budget <= 0: + raise KunlunNativeGoalRuntimeError( + "KunlunCode native goal token budget must be positive" + ) + if permission_mode == "ask": + raise KunlunNativeGoalRuntimeError( + "native app-server runs cannot service interactive approvals; use --permission-mode auto " + "or another explicitly non-interactive KunlunCode mode" + ) + project = project.resolve() + binary = kunluncode_bin or shutil.which("kunluncode") + if not binary: + raise KunlunNativeGoalRuntimeError("kunluncode is not on PATH") + control = control_plane or LoopXControlPlane(project, context) + goal_id = str(context.get("goal_id") or "") + registry_path = Path( + str(context.get("registry") or project / ".loopx" / "registry.json") + ) + goal_ref = capture_first_party_host_goal_ref( + registry_path=registry_path, + goal_id=goal_id, + ) + goal_admission = FirstPartyHostGoalAdmission.for_plan( + registry_path=registry_path, + goal_id=goal_id, + planned_goal_ref=goal_ref, + ) + journal_path = runtime_state_path(project) + with exclusive_file_lock( + journal_path, + agent_id=str(context.get("agent_id") or ""), + operation="kunluncode_native_goal", + ): + state = goal_admission.select_state( + read_state=lambda: read_runtime_state(project), + goal_ref_of=_runtime_goal_ref, + ) + if state is not None: + _validate_binding(state, context) + if ( + state["native"].get("verified") is True + and runtime_phase(state) != "committed" + ): + _closeout_writeback( + project, + state, + control, + goal_admission, + ) + return { + "ok": True, + "status": "committed", + "recovered": True, + "runtime": compact_runtime_state(state), + } + + decision = control.should_run() + if decision.get("should_run") is not True: + return { + "ok": True, + "status": "skipped", + "reason": decision.get("reason"), + "runtime": compact_runtime_state(state), + } + todo = decision.get("selected_todo") + if not isinstance(todo, Mapping): + raise KunlunNativeGoalRuntimeError( + "LoopX allowed a KunlunCode turn without selecting an agent todo" + ) + todo_id = str(todo.get("todo_id") or "") + preparation = ( + decision.get("execution_preparation") + if isinstance(decision.get("execution_preparation"), Mapping) + else {} + ) + if preparation.get("state") == "claim_required": + # The Host performs the projected atomic claim before any model + # work. A fresh guard must observe the resulting lease; the + # preview itself never grants execution authority. + goal_admission.require_current() + control.claim(todo_id) + decision = control.should_run() + if decision.get("should_run") is not True: + raise KunlunNativeGoalRuntimeError( + "LoopX did not admit execution after automatic task preparation" + ) + todo = decision.get("selected_todo") + preparation = ( + decision.get("execution_preparation") + if isinstance(decision.get("execution_preparation"), Mapping) + else {} + ) + if ( + not isinstance(todo, Mapping) + or str(todo.get("todo_id") or "") != todo_id + or preparation.get("state") != "ready" + ): + raise KunlunNativeGoalRuntimeError( + "LoopX automatic task preparation did not preserve the selected Todo and current lease" + ) + claimed_by = str(todo.get("claimed_by") or "") + agent_id = str(context.get("agent_id") or "") + if claimed_by and claimed_by != agent_id: + raise KunlunNativeGoalRuntimeError( + "LoopX selected todo is claimed by another agent" + ) + objective = build_native_goal_objective(todo, agent_id=agent_id) + objective_sha256 = stable_text_digest(objective) + if state is not None and str(state.get("todo_id") or "") == todo_id: + native = state["native"] + if native.get("mode") != mode: + raise KunlunNativeGoalRuntimeError( + "unfinished KunlunCode runtime journal uses a different native goal mode" + ) + if native.get("objective_sha256") != objective_sha256: + raise KunlunNativeGoalRuntimeError( + "LoopX selected todo changed after the KunlunCode native goal started" + ) + elif state is not None and runtime_phase(state) != "committed": + raise KunlunNativeGoalRuntimeError( + "unfinished KunlunCode runtime journal belongs to another todo" + ) + else: + state = _new_state( + context, + todo_id=todo_id, + mode=mode, + objective_sha256=objective_sha256, + goal_ref=goal_ref, + ) + _commit_runtime_state(project, state, goal_admission) + if not claimed_by: + goal_admission.require_current() + control.claim(todo_id) + _run_native_host( + project, + state, + objective=objective, + kunluncode_bin=binary, + permission_mode=permission_mode, + max_duration_secs=max_duration_secs, + controller_timeout_secs=controller_timeout_secs, + token_budget=token_budget, + scenario=scenario, + client_factory=client_factory, + goal_admission=goal_admission, + ) + goal_admission.require_current() + _closeout_writeback( + project, + state, + control, + goal_admission, + ) + return { + "ok": True, + "status": "committed", + "recovered": state["native"].get("resumed") is True, + "runtime": compact_runtime_state(state), + } diff --git a/loopx/hosts/kunluncode/server.py b/loopx/hosts/kunluncode/server.py new file mode 100644 index 0000000000..484636c3ac --- /dev/null +++ b/loopx/hosts/kunluncode/server.py @@ -0,0 +1,27 @@ +"""KunlunCode stdio MCP entrypoint.""" + +from __future__ import annotations + +from pathlib import Path + +from loopx.goal_mode_mcp import GoalModeMCPConfig, create_fastmcp_server +from loopx.hosts.kunluncode.context import goal_context +from loopx.hosts.kunluncode.guards import guard_native_controller_writeback + + +CONFIG = GoalModeMCPConfig( + server_name="loopx-kunluncode", + runtime_profile="kunluncode", + legacy_host_surface="kunluncode", + setup_hint="run loopx-kunluncode connect --project --goal-id ", +) +mcp, control = create_fastmcp_server(CONFIG, lambda: goal_context(Path.cwd())) +guard_native_controller_writeback(control) + + +def main() -> None: + mcp.run() + + +if __name__ == "__main__": + main() diff --git a/loopx/hosts/skill_facade.py b/loopx/hosts/skill_facade.py index d00134e1d8..e7b4c391e7 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/hosts/zcode/__init__.py b/loopx/hosts/zcode/__init__.py new file mode 100644 index 0000000000..12fb487600 --- /dev/null +++ b/loopx/hosts/zcode/__init__.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +import os +import shlex +from typing import Any +from pathlib import Path + +ZCODE_INSTALL_SURFACE = "zcode" +ZCODE_HOME_ENV = "ZCODE_HOME" +DEFAULT_ZCODE_HOME = ".zcode" +SKILLS_SUBDIR = "skills" +SKILLS_ROOT_LABEL = "ZCODE_HOME/skills" + + +def zcode_home(value: str | None = None) -> Path: + """ZCode discovers user skills from ZCODE_HOME/skills (default ~/.zcode). + + The default skill entry gates the session turn loop by quota. A separate + native CLI binding is an explicit opt-in and does not change this root. + """ + raw = ( + value + or os.environ.get(ZCODE_HOME_ENV) + or os.environ.get("ZCODE_AGENTS_HOME") + or str(Path.home() / DEFAULT_ZCODE_HOME) + ) + return Path(raw).expanduser() + + +def native_goal_activation( + *, cli_bin: str, runtime_root: str | None, goal_id: str, + agent_id: str | None, activation_allowed: bool, +) -> dict[str, Any]: + """Discover the optional provider; generating commands performs no effects.""" + prefix = [cli_bin] + if runtime_root: + prefix.extend(["--runtime-root", runtime_root]) + commands = { + action: shlex.join([*prefix, "--format", "json", "zcode-goal", action, + "--goal-id", goal_id, "--agent-id", str(agent_id)]) + for action in ("bind", "start", "pause", "resume", "stop", "status") + } if activation_allowed else {} + return { + "default_off": True, "execution_mode": "managed_runtime", "host_surface": "zcode_cli", + "commands": commands, "requires_explicit_host_selection": True, + "quota_boundary": "Admission before start/resume and serial revocation checks during execution; no per-model-call token limit.", + "session_boundary": "One managed app-server session. This does not attach the current Desktop or terminal conversation.", + } diff --git a/loopx/hosts/zcode/api.py b/loopx/hosts/zcode/api.py new file mode 100644 index 0000000000..f58e4b5f26 --- /dev/null +++ b/loopx/hosts/zcode/api.py @@ -0,0 +1,78 @@ +"""Loopback Chat projection for the explicitly bound ZCode CLI provider.""" +from __future__ import annotations + +from typing import Any +from urllib.parse import unquote, urlparse + +from ...chat import redact_local_paths +from ...status_server import is_loopback_host +from .bridge import ZCodeGoalBridgeError, zcode_goal_operation + + +def public_zcode_goal_readback(payload: dict[str, Any]) -> dict[str, Any]: + result = {key: payload[key] for key in ("ok", "available", "goal_id", "goal_ref", "goal_creation_operation_id", "identity_scope", "agent_id", "actions") if key in payload} + if "reason" in payload: + result["reason"] = redact_local_paths(str(payload["reason"])) + binding = payload.get("binding") + result["binding"] = {key: binding[key] for key in ("mode", "connected", "cli_path", "protocol") if key in binding} if isinstance(binding, dict) else None + native = payload.get("native") + result["native"] = {key: native[key] for key in ("session_id", "target_id", "status", "raw_status", "session_status", "objective_sha256", "running", "usage", "selected_model", "available_models") if key in native} if isinstance(native, dict) else None + quota = payload.get("quota") + result["quota"] = {key: quota[key] for key in ("should_run", "checked_at") if key in quota} if isinstance(quota, dict) else None + if isinstance(quota, dict) and "reason" in quota: + result["quota"]["reason"] = redact_local_paths(str(quota["reason"])) + return result + + +class ZCodeGoalRequestMixin: + server: Any + path: str + + def _read_json(self) -> dict[str, Any]: + raise NotImplementedError + + def _require_loopback_origin(self) -> bool: + raise NotImplementedError + + def _send_error(self, message: str, **kwargs: Any) -> None: + raise NotImplementedError + + def _send_json(self, payload: dict[str, Any], *, status: int = 200) -> None: + raise NotImplementedError + + def _dispatch_zcode_goal(self, path: str, *, apply: bool = False) -> bool: + parts = path.strip("/").split("/") + if len(parts) != 6 or parts[:2] != ["api", "goals"] or parts[3] != "agents" or parts[5] != "zcode-goal": + return False + if not is_loopback_host(str(self.server.server_address[0])): + self._send_error("Managed ZCode operations require a loopback server.", status=403, error_code="zcode_goal_loopback_required") + return True + if not self._require_loopback_origin(): + return True + try: + if urlparse(self.path).query: + raise ValueError("ZCode Goal routes do not accept query parameters.") + goal_id, agent_id = unquote(parts[2]), unquote(parts[4]) + body = self._read_json() if apply else {} + if body is None: + return True + if set(body) - {"action", "cli_path", "model_selection", "expected_binding"}: + raise ValueError("ZCode Goal accepts action, expected_binding, optional cli_path and model_selection.") + action = body.get("action") if apply else "status" + if not isinstance(action, str): + raise ValueError("ZCode Goal action must be a string.") + if "cli_path" in body and (not isinstance(body["cli_path"], str) or not body["cli_path"].strip() or len(body["cli_path"]) > 4096): + raise ValueError("cli_path must be a nonempty string of at most 4096 characters.") + if "model_selection" in body and (action != "select_model" or not isinstance(body["model_selection"], dict)): + raise ValueError("model_selection is a selection object accepted only by select_model.") + if apply and not isinstance(body.get("expected_binding"), dict): + raise ValueError("POST requires expected_binding from the current Goal readback.") + payload = zcode_goal_operation( + action=action, registry_path=self.server.registry_path, goal_id=goal_id, agent_id=agent_id, + cli_path=body.get("cli_path"), runtime_root=self.server.runtime_root_override, model_selection=body.get("model_selection"), expected_binding=body.get("expected_binding"), + ) + except (ValueError, OSError) as exc: + self._send_error(redact_local_paths(str(exc)), status=exc.status if isinstance(exc, ZCodeGoalBridgeError) else 400, error_code=getattr(exc, "code", "invalid_zcode_goal_request")) + else: + self._send_json(public_zcode_goal_readback(payload)) + return True 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/hosts/zcode/bridge.py b/loopx/hosts/zcode/bridge.py new file mode 100644 index 0000000000..07964229f6 --- /dev/null +++ b/loopx/hosts/zcode/bridge.py @@ -0,0 +1,327 @@ +"""ZCode transport and exact Goal/Agent admission; provider decisions live in TS.""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +from typing import Any + +from loopx.agent_registry import agent_profile_for_goal, load_goal_from_registry, registered_agent_ids_for_goal, require_registered_agent_id +from loopx.control_plane.coordination.local_authority import local_authority_is_promoted +from loopx.control_plane.goals.acceptance import inspect_goal_acceptance +from loopx.control_plane.goals.activation import goal_is_stopped +from loopx.control_plane.goals.goal_ref_validation import exact_goal_ref, require_goal_id +from loopx.control_plane.runtime.goal_project_route import resolve_goal_project_route +from loopx.control_plane.runtime.node_probe import node_typescript_flags +from loopx.control_plane.projects.registry_codec import load_registry +from loopx.host_loop_activation import normalize_agent_type +from loopx.registry import registry_goals + +# The bundled provider contract is the single action vocabulary for Python and TS. +ZCODE_GOAL_ACTIONS: tuple[str, ...] = tuple( + json.loads(Path(__file__).with_name("contract.json").read_text(encoding="utf-8"))["actions"] +) +MAX_TRANSPORT_BYTES = 1_048_576 +_UNSET = object() + + +class ZCodeGoalBridgeError(ValueError): + def __init__(self, message: str, *, code: str = "invalid_zcode_goal_request", status: int = 400): + super().__init__(message) + self.code = code + self.status = status + + +def _zcode_host_compatible(profile: dict[str, Any] | None) -> bool: + declared_host = (profile or {}).get("agent_type") or (profile or {}).get("host_surface") + # An advisory profile need not declare a host. Binding remains an explicit choice. + if declared_host is None: + return True + if not isinstance(declared_host, str): + return False + try: + return normalize_agent_type(declared_host) == "zcode" + except ValueError: + return False + + +def zcode_goal_eligible_agent_ids(goal: dict[str, Any]) -> list[str]: + """Project registered actors compatible with this host, without probing it.""" + return [agent_id for agent_id in registered_agent_ids_for_goal(goal) + if _zcode_host_compatible(agent_profile_for_goal(goal, agent_id))] + + +def validate_zcode_binding( + *, registry_path: Path, goal_id: str, agent_id: str, + project: str | Path | None = None, goal_ref: dict[str, str] | None = None, + require_active: bool = True, goal_creation_operation_id: object = _UNSET, +) -> dict[str, Any]: + """Read existing authority only; never create an instance or register an agent.""" + require_goal_id(goal_id) + _, canonical_project, route = resolve_goal_project_route( + registry_path=registry_path, goal_id=goal_id, project_override=project, + ) + source_registry = Path(route["source_registry"]).resolve() + registry = load_registry(source_registry) + matches = [item for item in registry_goals(registry) if item.get("id") == goal_id] + if len(matches) != 1: + raise ZCodeGoalBridgeError("Goal must be registered exactly once.", code="zcode_goal_authority_changed", status=409) + goal = matches[0] + if require_active and (goal_is_stopped(goal) or goal.get("status", "active") != "active"): + raise ZCodeGoalBridgeError("The LoopX Goal is no longer active.", code="zcode_goal_authority_changed", status=409) + # Generic Goal routing already rejects lifecycle-only source-session registries. + # Existing exact identities remain exact; first-party legacy aliases stay compatible. + instance_id = goal.get("goal_instance_id") + if instance_id is not None: + if not isinstance(instance_id, str): + raise ZCodeGoalBridgeError("Goal instance identifier is invalid.") + current_ref = exact_goal_ref(goal_id, instance_id) + identity_scope = "exact_goal_instance" + else: + current_ref = {"goal_id": goal_id} + identity_scope = "legacy_goal_alias" + if goal_ref is not None and goal_ref != current_ref: + raise ZCodeGoalBridgeError("Goal instance changed; inspect the current Goal before binding again.", code="zcode_goal_authority_changed", status=409) + creation_id = goal.get("creation_operation_id") + if creation_id is not None and (not isinstance(creation_id, str) or not creation_id): + raise ZCodeGoalBridgeError("Goal creation witness is invalid.") + if goal_creation_operation_id is not _UNSET and goal_creation_operation_id != creation_id: + raise ZCodeGoalBridgeError("Goal creation witness changed; inspect the current Goal before binding again.", code="zcode_goal_authority_changed", status=409) + normalized_agent = require_registered_agent_id( + registry_path=source_registry, goal_id=goal_id, agent_id=agent_id, field="agent_id", + ) + profile = agent_profile_for_goal(goal, normalized_agent) + if not _zcode_host_compatible(profile): + raise ZCodeGoalBridgeError("The registered Agent explicitly declares a different host.") + if not canonical_project.is_dir(): + raise ZCodeGoalBridgeError("The canonical Goal project is unavailable.") + return { + "ok": True, "goal_id": goal_id, "goal_ref": current_ref, "agent_id": normalized_agent, + "project": str(canonical_project), "registry": str(source_registry), + "runtime_root": str(route["source_runtime_root"]), + "identity_scope": identity_scope, "goal_creation_operation_id": creation_id, + } + + +def _node_command() -> str: + from loopx.control_plane.effect_runtime import _node_executable, EffectRuntimeStartupError + try: + return _node_executable() + except EffectRuntimeStartupError as exc: + raise ZCodeGoalBridgeError(str(exc), code="zcode_goal_runtime_unavailable", status=503) from exc + + +def _cli_command(cli_path: str | None, node: str) -> list[str]: + requested = cli_path if cli_path is not None else "zcode" + if not isinstance(requested, str) or not requested.strip() or len(requested) > 4096: + raise ZCodeGoalBridgeError("ZCode CLI path must be a nonempty string of at most 4096 characters.") + requested = requested.strip() + resolved = shutil.which(requested) or str(Path(requested).expanduser().resolve()) + path = Path(resolved) + if not path.is_file(): + raise ZCodeGoalBridgeError("ZCode CLI is unavailable. Supply its executable or JS bundle when binding.", code="zcode_cli_unavailable", status=503) + if (path.parent / "resources/glm/zcode.cjs").is_file() or (path.parent / "resources/app.asar").is_file(): + raise ZCodeGoalBridgeError("Select ZCode CLI; a Desktop executable cannot be bound to the managed CLI provider.") + if path.suffix.lower() in {".cmd", ".bat"}: + raise ZCodeGoalBridgeError("Windows shell shims cannot be used by the managed stdio transport. Supply the installed ZCode JS bundle for bind.") + if path.suffix.lower() in {".js", ".cjs", ".mjs"}: + return [node, str(path.resolve()), "app-server"] + return [str(path.resolve()), "app-server"] + + +def _run_json(command: list[str], *, project: str, request: dict[str, Any] | None = None) -> dict[str, Any]: + environment = {**os.environ, "PYTHONUTF8": "1", "PYTHONDONTWRITEBYTECODE": "1"} + try: + completed = subprocess.run( + command, input=json.dumps(request, ensure_ascii=False) if request is not None else None, + cwd=project, env=environment, capture_output=True, text=True, + encoding="utf-8", errors="strict", timeout=45, check=False, + ) + except (OSError, UnicodeError, subprocess.TimeoutExpired) as exc: + raise ZCodeGoalBridgeError("ZCode provider did not return a bounded response. Read status before retrying an operation.", code="zcode_goal_transport_unavailable", status=503) from exc + if len(completed.stdout.encode("utf-8")) > MAX_TRANSPORT_BYTES: + raise ZCodeGoalBridgeError("ZCode provider response exceeded the transport limit.", code="zcode_goal_invalid_readback", status=503) + try: + payload = json.loads(completed.stdout) + except json.JSONDecodeError as exc: + raise ZCodeGoalBridgeError("ZCode provider did not return a JSON readback.", code="zcode_goal_invalid_readback", status=503) from exc + if not isinstance(payload, dict) or not isinstance(payload.get("ok"), bool): + raise ZCodeGoalBridgeError("ZCode provider returned an invalid readback.", code="zcode_goal_invalid_readback", status=503) + if completed.returncode and payload.get("ok") is True: + raise ZCodeGoalBridgeError("ZCode provider failed despite a successful readback.", code="zcode_goal_invalid_readback", status=503) + return payload + + +def _heartbeat_task(binding: dict[str, Any], loopx_command: list[str]) -> str: + payload = _run_json([ + *loopx_command, "--registry", binding["registry"], "--format", "json", + "heartbeat-prompt", "--goal-id", binding["goal_id"], "--agent-id", binding["agent_id"], + "--runtime-profile", "generic_cli", "--thin", + ], project=binding["project"]) + body = payload.get("task_body") + if payload.get("ok") is not True or not isinstance(body, str) or not body.strip(): + raise ZCodeGoalBridgeError("Canonical heartbeat instructions are unavailable. Repair the Goal state before starting ZCode.") + return body + + +def _goal_basis(binding: dict[str, Any]) -> dict[str, Any]: + """Read the current criterion/source revisions the native objective must be consumed under. + + This is the Session RFC basis: existing acceptance-contract and explicit + authority-source revisions, not a whole-prompt hash. An unpromoted Goal has + no acceptance owner and reports ``None``; an unreadable owner fails closed so + a stale basis is never presented as current. + """ + registry_path = Path(binding["registry"]) + goal = load_goal_from_registry(registry_path, binding["goal_id"]) + if goal is None: + raise ZCodeGoalBridgeError("Goal must be registered exactly once.", code="zcode_goal_authority_changed", status=409) + sources: list[dict[str, Any]] = [] + for item in goal.get("authority_sources") or []: + if not isinstance(item, dict): + continue + source_id = str(item.get("id") or item.get("source_id") or "") + if not source_id: + continue + revision = item.get("revision") + sources.append({"id": source_id, "revision": revision if isinstance(revision, (int, str)) and not isinstance(revision, bool) else None}) + sources.sort(key=lambda row: row["id"]) + acceptance: dict[str, Any] | None = None + if local_authority_is_promoted(runtime_root=Path(binding["runtime_root"]), goal_id=binding["goal_id"]): + try: + observed = inspect_goal_acceptance(registry_path=registry_path, goal_id=binding["goal_id"], runtime_root=binding["runtime_root"]) + except (ValueError, TypeError, OSError, RuntimeError) as exc: + raise ZCodeGoalBridgeError( + "Current Goal acceptance basis is unavailable. Read status and repair the Goal authority before starting or resuming ZCode.", + code="zcode_goal_basis_unavailable", status=503, + ) from exc + revision = observed.get("revision") + digest = observed.get("contract_digest") + acceptance = { + "revision": revision if isinstance(revision, int) and not isinstance(revision, bool) else None, + "contract_digest": digest if isinstance(digest, str) else None, + } + return {"acceptance": acceptance, "authority_sources": sources} + + +def zcode_goal_operation( + *, action: str, registry_path: Path, goal_id: str, agent_id: str, + project: str | Path | None = None, cli_path: str | None = None, + runtime_root: str | Path | None = None, model_selection: dict[str, Any] | None = None, + expected_binding: dict[str, Any] | None = None, +) -> dict[str, Any]: + if action not in ZCODE_GOAL_ACTIONS: + raise ZCodeGoalBridgeError("Unsupported ZCode Goal operation.") + if model_selection is not None: + if action != "select_model": + raise ZCodeGoalBridgeError("Model selection is supported only by select_model.") + if not isinstance(model_selection, dict) or set(model_selection) - {"providerId", "modelId", "options"}: + raise ZCodeGoalBridgeError("Model selection accepts providerId, modelId and optional reasoning options.") + if any(not isinstance(model_selection.get(key), str) or not model_selection[key].strip() or len(model_selection[key]) > 256 for key in ("providerId", "modelId")): + raise ZCodeGoalBridgeError("Model selection requires bounded providerId and modelId strings.") + options = model_selection.get("options", {}) + if not isinstance(options, dict) or set(options) - {"reasoningLevel"} or ("reasoningLevel" in options and (not isinstance(options["reasoningLevel"], str) or not options["reasoningLevel"].strip() or len(options["reasoningLevel"]) > 128)): + raise ZCodeGoalBridgeError("Model selection options accept only a bounded reasoningLevel.") + elif action == "select_model": + raise ZCodeGoalBridgeError("select_model requires an explicit model_selection.") + if cli_path is not None and action != "bind": + raise ZCodeGoalBridgeError("ZCode CLI selection is supported only by an explicit bind operation.") + expected_ref = None + expected_creation: object = _UNSET + if expected_binding is not None: + if not isinstance(expected_binding, dict) or set(expected_binding) != {"goal_ref", "goal_creation_operation_id"}: + raise ZCodeGoalBridgeError("expected_binding requires goal_ref and goal_creation_operation_id.") + expected_ref = expected_binding["goal_ref"] + if not isinstance(expected_ref, dict) or set(expected_ref) not in ({"goal_id"}, {"goal_id", "goal_instance_id"}): + raise ZCodeGoalBridgeError("expected_binding requires an exact supported Goal reference shape.") + if not isinstance(expected_ref.get("goal_id"), str): + raise ZCodeGoalBridgeError("Expected Goal id must be a string.") + require_goal_id(expected_ref["goal_id"]) + if "goal_instance_id" in expected_ref: + if not isinstance(expected_ref["goal_instance_id"], str): + raise ZCodeGoalBridgeError("Expected Goal instance must be a string.") + exact_goal_ref(expected_ref["goal_id"], expected_ref["goal_instance_id"]) + expected_creation = expected_binding["goal_creation_operation_id"] + if expected_creation is not None and (not isinstance(expected_creation, str) or not expected_creation or len(expected_creation) > 256): + raise ZCodeGoalBridgeError("Expected creation witness must be a bounded string or null.") + require_active = action not in {"status", "pause", "stop"} + binding = validate_zcode_binding( + registry_path=registry_path, goal_id=goal_id, agent_id=agent_id, project=project, + require_active=require_active, goal_ref=expected_ref, goal_creation_operation_id=expected_creation, + ) + node = _node_command() + loopx_command = [sys.executable, "-m", "loopx.cli"] + state_root = Path(runtime_root).expanduser().resolve() if runtime_root is not None else Path(binding["runtime_root"]) + state_key = hashlib.sha256(json.dumps( + [binding["registry"], binding["goal_ref"], binding["goal_creation_operation_id"], binding["agent_id"]], sort_keys=True, + ).encode("utf-8")).hexdigest() + request: dict[str, Any] = { + "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.hosts.zcode.bridge", "--validate-binding"], + } + if model_selection is not None: + request["model_selection"] = model_selection + if action == "bind": + request["cli_command"] = _cli_command(cli_path, node) + request["cli_path"] = request["cli_command"][-2] + if action in {"bind", "start"}: + request["task_body"] = _heartbeat_task(binding, loopx_command) + if action in {"bind", "start", "resume"}: + request["goal_basis"] = _goal_basis(binding) + payload = _run_json( + [node, "--experimental-strip-types", *node_typescript_flags(), str(Path(__file__).with_name("cli.ts"))], + project=binding["project"], + request=request, + ) + for key in ("goal_id", "goal_ref", "goal_creation_operation_id", "agent_id"): + if key not in payload or payload[key] != binding[key]: + raise ZCodeGoalBridgeError("ZCode readback did not match the exact Goal and Agent requested.", code="zcode_goal_invalid_readback", status=409) + observed = validate_zcode_binding( + registry_path=registry_path, goal_id=goal_id, agent_id=agent_id, + project=binding["project"], goal_ref=binding["goal_ref"], require_active=require_active, + goal_creation_operation_id=binding["goal_creation_operation_id"], + ) + if observed["registry"] != binding["registry"]: + raise ZCodeGoalBridgeError("Canonical Goal authority changed during the operation.", code="zcode_goal_authority_changed", status=409) + return payload + + +def _validate_main() -> int: + parser = argparse.ArgumentParser(description="Internal read-only ZCode binding admission.") + parser.add_argument("--validate-binding", required=True, action="store_true") + parser.parse_args() + try: + encoded = sys.stdin.buffer.read(MAX_TRANSPORT_BYTES + 1) + if len(encoded) > MAX_TRANSPORT_BYTES: + raise ValueError("binding request exceeded the transport limit") + request = json.loads(encoded) + if not isinstance(request, dict) or not isinstance(request.get("goal_ref"), dict): + raise ValueError("an exact Goal reference is required") + action = request.get("action") + if not isinstance(action, str) or action not in ZCODE_GOAL_ACTIONS: + raise ValueError("an explicit known ZCode operation is required for binding admission") + required = ("registry", "project", "goal_id", "agent_id") + if any(not isinstance(request.get(key), str) or not request[key] for key in required): + raise ValueError("binding identity fields must be nonempty strings") + result = validate_zcode_binding( + registry_path=Path(request["registry"]), project=request["project"], + goal_id=request["goal_id"], agent_id=request["agent_id"], goal_ref=request["goal_ref"], + goal_creation_operation_id=request.get("goal_creation_operation_id", _UNSET), + require_active=action not in {"status", "pause", "stop"}, + ) + payload = {key: result[key] for key in ("ok", "goal_id", "goal_ref", "goal_creation_operation_id", "identity_scope", "agent_id")} + except (ValueError, OSError) as exc: + payload = {"ok": False, "error": str(exc), "error_code": getattr(exc, "code", "invalid_zcode_goal_binding")} + print(json.dumps(payload, ensure_ascii=False)) + return 0 if payload["ok"] else 1 + + +if __name__ == "__main__": + raise SystemExit(_validate_main()) 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/hosts/zcode/diagnostics.py b/loopx/hosts/zcode/diagnostics.py new file mode 100644 index 0000000000..b8ee997d08 --- /dev/null +++ b/loopx/hosts/zcode/diagnostics.py @@ -0,0 +1,358 @@ +from __future__ import annotations + +# Local host observations; no control-plane decisions or execution authority. +import json +import os +from pathlib import Path +import plistlib +import re +import shutil +import subprocess +import sys +import tempfile +import threading +import time +from typing import Any, Literal, TypedDict + +from loopx.extensions.process_runtime import prepare_owned_process_cleanup + +InterfaceStatus = Literal["advertised", "not_advertised", "unverified"] +ProbeStatus = Literal["observed", "failed", "timeout", "unreadable", "output_limit"] + + +class _ProbeReport(TypedDict): + status: ProbeStatus + exit_code: int | None + output: str + + +PROBE_TIMEOUT_SECONDS = 5 +MAX_METADATA_BYTES = 1_048_576 +INTERFACE_PATTERNS = { + "headless_prompt": r"(? dict[str, Any] | None: + try: + if path.stat().st_size > MAX_METADATA_BYTES: + return None + value = json.loads(path.read_text(encoding="utf-8")) + return value if isinstance(value, dict) else None + except (OSError, ValueError): + return None + + +def _run_probe(command: list[str], *, extra_env: dict[str, str] | None = None) -> _ProbeReport: + # Metadata/help only. Shared transport owns the complete isolated tree; + # the reader owns pipe close, which may otherwise wait on a descendant. + disposable = None + try: + disposable = tempfile.TemporaryDirectory(prefix="loopx-zcode-doctor-", ignore_cleanup_errors=True) + env = dict(os.environ) + env.update(extra_env or {}) + for name in ("ZCODE_HOME", "ZCODE_STORAGE_DIR", "ZCODE_DATA_BASE_DIR"): + env[name] = disposable.name + process = subprocess.Popen( + command, cwd=disposable.name, env=env, stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=0, + start_new_session=os.name == "posix", + creationflags=(getattr(subprocess, "CREATE_NO_WINDOW") | 4) if os.name == "nt" else 0, + ) + cleanup = prepare_owned_process_cleanup(process) + except OSError: + if disposable is not None: + disposable.cleanup() + return {"status": "unreadable", "exit_code": None, "output": ""} + + deadline = time.monotonic() + PROBE_TIMEOUT_SECONDS + output: list[bytes] = [] + limited = threading.Event() + read_failed = threading.Event() + stream = process.stdout + assert stream is not None + + def capture() -> None: + size = 0 + try: + while chunk := stream.read(4096): + size += len(chunk) + if size > 65536: + limited.set() + break + output.append(chunk) + except (OSError, ValueError): + read_failed.set() + finally: + try: + stream.close() + except OSError: + pass + + reader = threading.Thread(target=capture, daemon=True) + reader.start() + status: ProbeStatus + exit_code = None + while True: + exit_code = process.poll() + if limited.is_set(): + status = "output_limit" + break + if exit_code is not None and not reader.is_alive(): + status = "unreadable" if read_failed.is_set() else "observed" if exit_code == 0 else "failed" + break + if time.monotonic() >= deadline: + status = "timeout" + break + limited.wait(min(.01, max(0, deadline - time.monotonic()))) + try: + # Ownership survives leader exit; the shared transport confirms the + # isolated group is no longer executable before returning a report. + cleanup() + except (OSError, RuntimeError, subprocess.TimeoutExpired): + status = "unreadable" + reader.join(timeout=1) + if reader.is_alive(): + status = "unreadable" + else: + disposable.cleanup() + return { + "status": status, "exit_code": exit_code, + "output": b"".join(output).decode("utf-8", errors="replace") if status in {"observed", "failed"} else "", + } + + + +def _public_probe(probe: _ProbeReport) -> dict[str, Any]: + # Raw output may include private configuration/errors; never project it. + return {"status": probe["status"], "exit_code": probe["exit_code"]} + + +def _version(output: str) -> str | None: + for line in output.splitlines()[:8]: + match = re.fullmatch( + r"\s*(?:ZCode(?: CLI)?(?: version)?[: ]+)?v?(\d+\.\d+\.\d+(?:\.\d+)?(?:[-+][\w.-]+)?)\s*", + line, re.IGNORECASE, + ) + if match: + return match.group(1) + return None + + +def _unknown_interfaces() -> dict[str, dict[str, str]]: + return {name: {"status": "unverified", "evidence": "none"} for name in (*INTERFACE_PATTERNS, "stream_json_syntax")} + + +def _inspect_cli(path: Path | None, *, discovery: str) -> dict[str, Any]: + observation: dict[str, Any] = { + "status": "not_found", "path": str(path) if path else None, + "discovery": discovery, "version": None, "interfaces": _unknown_interfaces(), + "runtime_verified": False, "version_evidence": "unavailable", + "next_action": "Install ZCode CLI or supply --zcode-cli with its executable or existing JS bundle.", + } + if path is None: + return observation + try: + path = path.resolve() + observation["path"] = str(path) + if not path.is_file(): + return observation + except OSError: + observation["status"] = "unreadable" + return observation + if (path.parent / "resources/glm/zcode.cjs").is_file() or (path.parent / "resources/app.asar").is_file(): + observation.update(status="invalid", next_action="This is a Desktop installation. Use --zcode-desktop; the GUI executable is never used for CLI probes.") + return observation + is_js = path.suffix.lower() in {".js", ".cjs", ".mjs"} + node = shutil.which("node") if is_js else None + if is_js and node is None: + observation.update(status="probe_failed", next_action="Make node available on PATH to inspect this JS bundle.") + return observation + command = [node, str(path)] if node else [str(path)] + version = _run_probe([*command, "--version"]) + help_probe = _run_probe([*command, "--help", "--locale", "en-US"]) + observation["probes"] = {"version": _public_probe(version), "help": _public_probe(help_probe)} + if version["status"] == "observed": + observation["version"] = _version(version["output"]) + if observation["version"]: + observation["version_evidence"] = "--version" + identity = help_probe["status"] == "observed" and re.search( + r"(?im)^\s*zcode(?:\s+v?\d+\.\d+\.\d+|\s+\[command\])", + help_probe["output"], + ) is not None + observation["identity_verified"] = identity + if identity: + for name, pattern in INTERFACE_PATTERNS.items(): + status: InterfaceStatus = "advertised" if re.search(pattern, help_probe["output"]) else "not_advertised" + observation["interfaces"][name] = {"status": status, "evidence": "--help --locale en-US"} + # Version short-circuits before sessions/models: parser recognition + # does not verify a runtime stream or execution readiness. + syntax = _run_probe([*command, "--version", "--output-format", "stream-json"]) + invalid_syntax = _run_probe([*command, "--version", "--output-format", "loopx-doctor-invalid"]) + recognized = invalid_syntax["status"] == "failed" and syntax["status"] == "observed" and _version(syntax["output"]) == observation["version"] and observation["version"] is not None + observation["probes"]["stream_json_syntax"] = _public_probe(syntax) + observation["probes"]["invalid_output_format_control"] = _public_probe(invalid_syntax) + observation["interfaces"]["stream_json_syntax"] = { + "status": "advertised" if recognized else "unverified", + "evidence": "--version --output-format stream-json" if recognized else "none", + } + observation["status"] = "available" if identity and observation["version"] else "probe_failed" + observation["next_action"] = ( + "Help/version observed; sessions, models, permissions and native protocol execution remain unverified." + if observation["status"] == "available" else + "Check the CLI path, Node runtime and permissions; failed probes do not prove interface absence." + ) + return observation + + +def _desktop_candidates() -> list[Path]: + if os.name == "nt": + return [ + Path(os.environ[variable]) / suffix + for variable, suffix in ( + ("LOCALAPPDATA", "Programs/ZCode/ZCode.exe"), + ("LOCALAPPDATA", "ZCode/ZCode.exe"), + ("ProgramFiles", "ZCode/ZCode.exe"), + ) if os.environ.get(variable) + ] + if sys.platform == "darwin": + return [Path("/Applications/ZCode.app"), Path.home() / "Applications/ZCode.app"] + return [Path("/opt/ZCode/zcode"), Path("/opt/zcode/zcode")] + + +def _resolve_desktop(path: Path) -> tuple[Path, Path]: + # Locate executable/resources without starting the GUI. + if path.suffix.lower() == ".app": + return path / "Contents/MacOS/ZCode", path / "Contents/Resources" + if path.is_dir(): + return path / ("ZCode.exe" if os.name == "nt" else "zcode"), path / "resources" + if path.parent.name == "MacOS": + return path, path.parent.parent / "Resources" + return path, path.parent / "resources" + + +def _desktop_version(executable: Path, resources: Path) -> dict[str, Any]: + if executable.suffix.lower() == ".exe" and os.name == "nt": + powershell = shutil.which("powershell") or shutil.which("pwsh") + if powershell: + script = "(Get-Item -LiteralPath $env:LOOPX_ZCODE_METADATA_PATH -ErrorAction Stop).VersionInfo | Select-Object ProductVersion,ProductName | ConvertTo-Json -Compress" + probe = _run_probe( + [powershell, "-NoProfile", "-NonInteractive", "-Command", script], + extra_env={"LOOPX_ZCODE_METADATA_PATH": str(executable)}, + ) + try: + metadata = json.loads(probe["output"]) if probe["status"] == "observed" else {} + value = metadata.get("ProductVersion") + if isinstance(value, str) and _version(value): + return {"value": value, "evidence": "executable ProductVersion", "identity_verified": str(metadata.get("ProductName", "")).casefold() == "zcode"} + except (ValueError, AttributeError): + pass + plist_path = resources.parent / "Info.plist" + if plist_path.is_file(): + try: + with plist_path.open("rb") as stream: + value = plistlib.load(stream).get("CFBundleShortVersionString") + if isinstance(value, str): + return {"value": value, "evidence": "Info.plist CFBundleShortVersionString", "identity_verified": resources.parent.parent.name.casefold() == "zcode.app"} + except (OSError, ValueError, plistlib.InvalidFileException): + pass + package = _read_json(resources / "app/package.json") + if package and isinstance(package.get("version"), str): + return {"value": package["version"], "evidence": "installed app/package.json", "identity_verified": str(package.get("name", "")).casefold() == "zcode"} + return {"value": None, "evidence": "unavailable", "identity_verified": False} + + +def _inspect_desktop(path_text: str | None) -> dict[str, Any]: + explicit = path_text or os.environ.get("ZCODE_DESKTOP_PATH") + candidates = [Path(explicit).expanduser()] if explicit else _desktop_candidates() + selected = resources = None + for candidate in candidates: + executable, root = _resolve_desktop(candidate.resolve()) + if executable.is_file(): + selected, resources = executable, root + break + observation: dict[str, Any] = { + "status": "available" if selected else "not_found", + "path": str(selected) if selected else (str(candidates[0]) if explicit else None), + "discovery": "explicit" if explicit else "standard_install_locations", + "version": None, "version_evidence": "unavailable", "runtime_verified": False, + "next_action": "Supply --zcode-desktop with the executable, install directory or .app bundle; inaccessible locations do not prove no installation.", + } + if selected is not None and resources is not None: + metadata = _desktop_version(selected, resources) + identity = metadata.get("identity_verified", False) or (resources / "glm/zcode.cjs").is_file() + observation.update(version=metadata["value"], version_evidence=metadata["evidence"], identity_verified=identity) + if not identity: + observation.update(status="unverified", next_action="The selected file exists but ZCode Desktop identity could not be verified. Check its product metadata or installation resources.") + return observation + observation["bundled_cli"] = _inspect_cli(resources / "glm/zcode.cjs", discovery="desktop_bundle") + observation["next_action"] = "Desktop metadata and bundled CLI are separate; the Desktop UI and Automations have not been exercised." + return observation + + +def _inspect_source(path_text: str | None) -> dict[str, Any]: + text = path_text or os.environ.get("ZCODE_SOURCE_ROOT") + if not text: + return {"status": "not_selected", "path": None, "package_version": None} + root = Path(text).expanduser().resolve() + package = _read_json(root / "package.json") + valid = package is not None and str(package.get("name", "")).lower() == "zcode" + observation: dict[str, Any] = { + "status": "available" if valid else "invalid", "path": str(root), + "package_version": package.get("version") if valid and package is not None else None, + "version_evidence": "source package.json; not an installed/runtime version", + } + if valid: + observation["built_cli"] = _inspect_cli(root / "apps/zcode-cli/packages/cli/dist/zcode.cjs", discovery="source_bundle") + else: + observation["next_action"] = "Supply --zcode-source with a ZCode checkout containing its root package.json." + return observation + + +def collect_zcode_host_diagnostics( + *, cli_path: str | None = None, desktop_path: str | None = None, + source_root: str | None = None, +) -> dict[str, Any]: + explicit_cli = cli_path or os.environ.get("ZCODE_CLI_PATH") + found = shutil.which("zcode") if not explicit_cli else None + resolved_cli = Path(explicit_cli).expanduser() if explicit_cli else (Path(found) if found else None) + return { + "cli": _inspect_cli(resolved_cli, discovery="explicit" if explicit_cli else "PATH"), + "desktop": _inspect_desktop(desktop_path), + "source_checkout": _inspect_source(source_root), + "loopx_binding": {"mode": "skill_facade", "native_goal": "opt_in_managed_cli", "automations": "not_integrated"}, + "probe_boundary": "Isolated help/version only. No Desktop launch, session, model, app-server handshake or credential read. Interface observations do not certify runtime readiness.", + } + + +def render_zcode_diagnostics_markdown(payload: dict[str, Any]) -> list[str]: + lines = ["", "## ZCode hosts", ""] + hosts = [("CLI", payload["cli"]), ("Desktop", payload["desktop"])] + if payload["desktop"].get("bundled_cli"): + hosts.append(("Desktop bundled CLI", payload["desktop"]["bundled_cli"])) + source = payload["source_checkout"] + lines.append(f"- Source checkout: **{source['status']}**; declared package version: {source.get('package_version') or 'unknown'} (not runtime version).") + if source.get("path"): + lines.append(f" Path: {source['path']}") + if source.get("built_cli"): + hosts.append(("Source built CLI", source["built_cli"])) + for label, host in hosts: + lines.append(f"- {label}: **{host['status']}**; version: {host.get('version') or 'unknown'}; path: {host.get('path') or 'not discovered'}.") + if host.get("version_evidence"): + lines.append(f" Version evidence: {host['version_evidence']}.") + if host.get("interfaces"): + interfaces = ", ".join(f"{name}={row['status']}" for name, row in host["interfaces"].items()) + lines.append(f" Interface observations: {interfaces}.") + if host.get("next_action"): + lines.append(f" {host['next_action']}") + lines.extend(["", payload["probe_boundary"], "LoopX binding: Skill facade by default; managed native CLI Goal requires explicit zcode-goal bind. Desktop attachment and Automations are not integrated."]) + return lines 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/kunluncode_goal_mode/__init__.py b/loopx/kunluncode_goal_mode/__init__.py index f571f40c16..79bfdeb88b 100644 --- a/loopx/kunluncode_goal_mode/__init__.py +++ b/loopx/kunluncode_goal_mode/__init__.py @@ -1,4 +1,21 @@ -"""First-class KunlunCode host adapter for LoopX goal mode.""" +"""Compatibility shim forwarding ``loopx.kunluncode_goal_mode`` to ``loopx.hosts.kunluncode``.""" -DEFAULT_AGENT_ID = "kunlun" -MCP_SERVER_NAME = "loopx-kunluncode" +from __future__ import annotations + +import importlib + +from loopx.hosts import kunluncode as _target + +_SUBMODULES = frozenset( + {"app_server", "cli", "context", "control_plane", "guards", "runtime", "server"} +) + + +def __getattr__(name: str) -> object: + if name in _SUBMODULES: + return importlib.import_module(f"loopx.hosts.kunluncode.{name}") + return getattr(_target, name) + + +def __dir__() -> list[str]: + return sorted(set(dir(_target)) | _SUBMODULES) diff --git a/loopx/kunluncode_goal_mode/app_server.py b/loopx/kunluncode_goal_mode/app_server.py index 1ea6988d23..7a32f5c77e 100644 --- a/loopx/kunluncode_goal_mode/app_server.py +++ b/loopx/kunluncode_goal_mode/app_server.py @@ -1,484 +1,21 @@ -"""Minimal JSON-RPC client for KunlunCode's native Goal runtime.""" +"""Compatibility shim forwarding ``loopx.kunluncode_goal_mode.app_server`` to ``loopx.hosts.kunluncode.app_server``.""" from __future__ import annotations -import hashlib -import json -import os -import queue -import subprocess -import threading -import time -from collections import deque -from collections.abc import Callable, Mapping from pathlib import Path -from typing import Any, TextIO +import sys +if not __package__: + _package_parent = str(Path(__file__).resolve().parents[2]) + if _package_parent not in sys.path: + sys.path.insert(0, _package_parent) -KUNLUN_APP_SERVER_PROTOCOL_VERSION = "2026-07-27" -KUNLUN_APP_SERVER_CLIENT_NAME = "loopx-kunluncode" -KUNLUN_APP_SERVER_CLIENT_VERSION = "0.1.0" -NATIVE_GOAL_MODES = {"goal": "arrangement", "goal-pro": "strict"} -TERMINAL_GOAL_STATUSES = { - "blocked", - "budget_limited", - "complete", - "paused", - "usage_limited", -} +from loopx.hosts.kunluncode import app_server as _target # noqa: E402 -class KunlunAppServerError(RuntimeError): - """Raised when the KunlunCode app-server contract cannot be completed.""" +def __getattr__(name: str) -> object: + return getattr(_target, name) -def stable_text_digest(text: str) -> str: - return hashlib.sha256(text.encode("utf-8")).hexdigest() - - -def build_app_server_command( - kunluncode_bin: str, - *, - project: Path, - permission_mode: str, - max_duration_secs: int, - scenario: str | None = None, -) -> list[str]: - command = [ - kunluncode_bin, - "app-server", - "--listen", - "stdio://", - "--cwd", - str(project.resolve()), - "--permission-mode", - permission_mode, - "--tool-profile", - "full", - "--max-duration-secs", - str(max(1, max_duration_secs)), - ] - if scenario: - command += ["--scenario", scenario] - return command - - -def goal_from_result(result: Mapping[str, Any] | None) -> dict[str, Any]: - if not isinstance(result, Mapping): - return {} - nested = result.get("goal") - if isinstance(nested, Mapping): - return dict(nested) - if any(key in result for key in ("goalId", "goal_id", "objective", "status")): - return dict(result) - return {} - - -def goal_value(goal: Mapping[str, Any], *names: str) -> Any: - for name in names: - if name in goal: - return goal[name] - return None - - -def goal_event_kinds(goal: Mapping[str, Any]) -> list[str]: - values: list[str] = [] - raw_events = goal_value(goal, "events", "history") - if not isinstance(raw_events, list): - return values - for event in raw_events: - if isinstance(event, str): - values.append(event.strip().lower()) - continue - if not isinstance(event, Mapping): - continue - for key in ("kind", "type", "event", "name", "status"): - value = event.get(key) - if isinstance(value, str) and value.strip(): - values.append(value.strip().lower()) - return values - - -def strict_goal_verification_passed(goal: Mapping[str, Any]) -> bool: - if "verification_passed" in goal_event_kinds(goal): - return True - for key in ("verification", "verifier", "verificationResult"): - value = goal.get(key) - if not isinstance(value, Mapping): - continue - status = str(value.get("status") or value.get("result") or "").lower() - if status in {"pass", "passed", "verification_passed"}: - return True - return False - - -def compact_goal(goal: Mapping[str, Any]) -> dict[str, Any]: - objective = str(goal.get("objective") or "") - return { - "goal_id": goal_value(goal, "goalId", "goal_id", "id"), - "revision": goal.get("revision"), - "mode": goal.get("mode"), - "verification_kind": goal_value(goal, "verificationKind", "verification_kind"), - "status": goal.get("status"), - "objective_sha256": stable_text_digest(objective) if objective else None, - "event_kinds": sorted(set(goal_event_kinds(goal))), - "verification_passed": strict_goal_verification_passed(goal), - } - - -def native_goal_success(goal: Mapping[str, Any], *, mode: str) -> bool: - expected_mode = NATIVE_GOAL_MODES.get(mode) - if expected_mode is None: - raise ValueError(f"unsupported native KunlunCode goal mode: {mode}") - if str(goal.get("status") or "") != "complete": - return False - if str(goal.get("mode") or "") != expected_mode: - return False - return mode != "goal-pro" or strict_goal_verification_passed(goal) - - -def _stdout_reader( - stream: TextIO, - output: "queue.Queue[dict[str, Any] | BaseException]", -) -> None: - try: - for line in stream: - if not line.strip(): - continue - try: - value = json.loads(line) - if not isinstance(value, dict): - raise ValueError("app-server message is not a JSON object") - output.put(value) - except BaseException as exc: # pragma: no cover - defensive protocol path - output.put(exc) - finally: - output.put(EOFError("KunlunCode app-server stdout closed")) - - -def _stderr_reader(stream: TextIO, output: "deque[str]") -> None: - for line in stream: - value = line.rstrip() - if value: - output.append(value[-1000:]) - - -class KunlunAppServerClient: - """One single-threaded stdio JSON-RPC connection to KunlunCode.""" - - def __init__( - self, - command: list[str], - *, - cwd: Path, - env: Mapping[str, str] | None = None, - event_handler: Callable[[dict[str, Any]], None] | None = None, - ) -> None: - self.command = list(command) - self.event_handler = event_handler - self._request_id = 0 - self._messages: "queue.Queue[dict[str, Any] | BaseException]" = queue.Queue( - maxsize=2048 - ) - self._stderr: "deque[str]" = deque(maxlen=24) - self.process = subprocess.Popen( - self.command, - cwd=str(cwd.resolve()), - env=dict(env or os.environ), - stdin=subprocess.PIPE, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - text=True, encoding="utf-8", errors="replace", - bufsize=1, - ) - if self.process.stdout is None or self.process.stderr is None: - self.close() - raise KunlunAppServerError("KunlunCode app-server pipes are unavailable") - self._stdout_thread = threading.Thread( - target=_stdout_reader, - args=(self.process.stdout, self._messages), - daemon=True, - ) - self._stderr_thread = threading.Thread( - target=_stderr_reader, - args=(self.process.stderr, self._stderr), - daemon=True, - ) - self._stdout_thread.start() - self._stderr_thread.start() - - def __enter__(self) -> "KunlunAppServerClient": - return self - - def __exit__(self, *_args: object) -> None: - self.close() - - def diagnostic_tail(self) -> str: - return "\n".join(self._stderr)[-3000:] - - def _failure(self, message: str) -> KunlunAppServerError: - diagnostic = self.diagnostic_tail() - if diagnostic: - return KunlunAppServerError(f"{message}\nKunlunCode stderr:\n{diagnostic}") - return KunlunAppServerError(message) - - def _send(self, message: Mapping[str, Any]) -> None: - if self.process.stdin is None or self.process.stdin.closed: - raise self._failure("KunlunCode app-server stdin is closed") - try: - self.process.stdin.write(json.dumps(dict(message)) + "\n") - self.process.stdin.flush() - except OSError as exc: - raise self._failure("failed to write to KunlunCode app-server") from exc - - def _handle_notification(self, message: dict[str, Any]) -> None: - if self.event_handler is not None: - self.event_handler(message) - - def _next_message(self, timeout_seconds: float) -> dict[str, Any]: - try: - message = self._messages.get(timeout=max(0.01, timeout_seconds)) - except queue.Empty as exc: - raise self._failure("timed out waiting for KunlunCode app-server") from exc - if isinstance(message, EOFError): - raise self._failure( - "KunlunCode app-server exited before completing the request" - ) - if isinstance(message, BaseException): - raise self._failure(str(message)) from message - return message - - def request( - self, - method: str, - params: Mapping[str, Any] | None = None, - *, - timeout_seconds: float = 15.0, - ) -> dict[str, Any]: - self._request_id += 1 - request_id = self._request_id - self._send( - { - "jsonrpc": "2.0", - "id": request_id, - "method": method, - "params": dict(params or {}), - } - ) - deadline = time.monotonic() + max(0.1, timeout_seconds) - while time.monotonic() < deadline: - message = self._next_message(max(0.01, deadline - time.monotonic())) - incoming_method = message.get("method") - if incoming_method: - if message.get("id") is not None: - self._send( - { - "jsonrpc": "2.0", - "id": message["id"], - "error": { - "code": -32001, - "message": ( - "LoopX native Goal runs do not service interactive " - "app-server requests" - ), - }, - } - ) - raise self._failure( - "KunlunCode requested interactive input via " - f"{incoming_method!r}; use a non-interactive permission mode" - ) - self._handle_notification(message) - continue - if message.get("id") != request_id: - raise self._failure("KunlunCode returned an unexpected response id") - error = message.get("error") - if error: - raise self._failure( - f"KunlunCode {method} failed: " - + json.dumps(error, ensure_ascii=False, sort_keys=True) - ) - result = message.get("result") - if result is None: - return {} - if not isinstance(result, dict): - raise self._failure(f"KunlunCode {method} returned a non-object result") - return result - raise self._failure(f"timed out waiting for KunlunCode {method}") - - def notify(self, method: str, params: Mapping[str, Any] | None = None) -> None: - self._send( - { - "jsonrpc": "2.0", - "method": method, - "params": dict(params or {}), - } - ) - - def initialize(self, *, timeout_seconds: float = 15.0) -> dict[str, Any]: - result = self.request( - "initialize", - { - "protocolVersion": KUNLUN_APP_SERVER_PROTOCOL_VERSION, - "clientInfo": { - "name": KUNLUN_APP_SERVER_CLIENT_NAME, - "version": KUNLUN_APP_SERVER_CLIENT_VERSION, - }, - "capabilities": {"experimentalApi": True}, - }, - timeout_seconds=timeout_seconds, - ) - observed = str(result.get("protocolVersion") or "") - if observed != KUNLUN_APP_SERVER_PROTOCOL_VERSION: - raise self._failure( - "KunlunCode app-server protocol mismatch: " - f"expected {KUNLUN_APP_SERVER_PROTOCOL_VERSION}, got {observed or 'missing'}" - ) - self.notify("initialized") - return result - - def start_thread(self, project: Path) -> str: - result = self.request("thread/start", {"cwd": str(project.resolve())}) - thread = result.get("thread") - thread_id = ( - str(thread.get("id") or "") - if isinstance(thread, Mapping) - else str(result.get("threadId") or result.get("thread_id") or "") - ) - if not thread_id: - raise self._failure("KunlunCode thread/start returned no thread id") - return thread_id - - def resume_thread(self, thread_id: str) -> dict[str, Any]: - return self.request("thread/resume", {"threadId": thread_id}) - - def set_goal( - self, - thread_id: str, - *, - objective: str, - mode: str, - token_budget: int | None = None, - ) -> dict[str, Any]: - native_mode = NATIVE_GOAL_MODES.get(mode) - if native_mode is None: - raise ValueError(f"unsupported native KunlunCode goal mode: {mode}") - params: dict[str, Any] = { - "threadId": thread_id, - "objective": objective, - "mode": native_mode, - "requireNoGoal": True, - } - if token_budget is not None: - if token_budget <= 0: - raise ValueError("KunlunCode native goal token budget must be positive") - params["tokenBudget"] = token_budget - return goal_from_result(self.request("thread/goal/set", params)) - - def get_goal( - self, thread_id: str, *, timeout_seconds: float = 15.0 - ) -> dict[str, Any]: - goal = goal_from_result( - self.request( - "thread/goal/get", - {"threadId": thread_id}, - timeout_seconds=timeout_seconds, - ) - ) - if not goal: - raise self._failure("KunlunCode thread/goal/get returned no goal") - return goal - - def start_turn(self, thread_id: str, prompt: str) -> dict[str, Any]: - if not prompt.strip(): - raise ValueError("KunlunCode turn prompt must be non-empty") - return self.request( - "turn/start", - { - "threadId": thread_id, - "input": [{"type": "text", "text": prompt}], - }, - ) - - def wait_for_goal_terminal( - self, - thread_id: str, - *, - timeout_seconds: float, - poll_interval_seconds: float = 0.5, - ) -> dict[str, Any]: - deadline = time.monotonic() + max(0.1, timeout_seconds) - last_goal: dict[str, Any] = {} - while time.monotonic() < deadline: - remaining = max(0.1, deadline - time.monotonic()) - last_goal = self.get_goal( - thread_id, - timeout_seconds=min(15.0, remaining), - ) - status = str(last_goal.get("status") or "") - if status in TERMINAL_GOAL_STATUSES: - return last_goal - wait_until = min( - deadline, time.monotonic() + max(0.05, poll_interval_seconds) - ) - while time.monotonic() < wait_until: - try: - message = self._messages.get( - timeout=max(0.01, wait_until - time.monotonic()) - ) - except queue.Empty: - break - if isinstance(message, EOFError): - raise self._failure( - "KunlunCode app-server exited while the native goal was active" - ) - if isinstance(message, BaseException): - raise self._failure(str(message)) from message - if message.get("method"): - if message.get("id") is not None: - self._send( - { - "jsonrpc": "2.0", - "id": message["id"], - "error": { - "code": -32001, - "message": ( - "LoopX native Goal runs do not service interactive " - "app-server requests" - ), - }, - } - ) - raise self._failure( - "KunlunCode requested interactive input while the native goal was active" - ) - self._handle_notification(message) - continue - raise self._failure( - "KunlunCode returned an unexpected asynchronous response" - ) - compact = compact_goal(last_goal) - raise self._failure( - "timed out while KunlunCode native goal remained non-terminal: " - + json.dumps(compact, ensure_ascii=False, sort_keys=True) - ) - - def close(self) -> None: - process = getattr(self, "process", None) - if process is None or process.poll() is not None: - return - try: - if process.stdin is not None and not process.stdin.closed: - process.stdin.close() - except OSError: - pass - try: - process.wait(timeout=3) - return - except subprocess.TimeoutExpired: - process.terminate() - try: - process.wait(timeout=2) - except subprocess.TimeoutExpired: # pragma: no cover - defensive shutdown - process.kill() - process.wait(timeout=2) +def __dir__() -> list[str]: + return sorted(dir(_target)) diff --git a/loopx/kunluncode_goal_mode/cli.py b/loopx/kunluncode_goal_mode/cli.py index 37d09161d7..f52af8acf2 100644 --- a/loopx/kunluncode_goal_mode/cli.py +++ b/loopx/kunluncode_goal_mode/cli.py @@ -1,761 +1,25 @@ -"""Install, bind, inspect, and run the LoopX KunlunCode adapter.""" +"""Compatibility entrypoint forwarding ``loopx.kunluncode_goal_mode.cli`` to ``loopx.hosts.kunluncode.cli``.""" from __future__ import annotations -import argparse -import importlib.metadata -import json -import os -import shutil -import subprocess -import sys from pathlib import Path -from typing import Any - -from loopx.control_plane.projects.registry_codec import ( - load_project_registry, - mutate_project_registry, - 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 ( - compact_runtime_state, - read_runtime_state, - run_native_goal, -) - - -# Single source for the adapter's `mcp` pin. It is an exact pin: -# 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 -# 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 -# below derive from it. -MCP_SDK_VERSION = "1.28.1" -MCP_REQUIREMENT = f"mcp=={MCP_SDK_VERSION}" -MCP_SCRIPT = Path(__file__).with_name("server.py").resolve() -DEFAULT_MCP_VENV = ( - Path.home() / ".local" / "share" / "loopx" / "kunluncode-mcp" / ".venv" -) - - -def _run( - command: list[str], - *, - cwd: Path | None = None, - timeout: int = 120, -) -> subprocess.CompletedProcess[str]: - return subprocess.run( - command, - cwd=str(cwd) if cwd else None, - capture_output=True, - text=True, encoding="utf-8", errors="replace", - timeout=timeout, - ) - - -def _loopx_prefix() -> list[str]: - executable = shutil.which("loopx") - return [executable] if executable else [sys.executable, "-m", "loopx.cli"] - - -def _venv_python(venv: Path) -> Path: - return venv / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python") - - -def _compatible_python(value: str | Path) -> bool: - probe = _run( - [ - str(value), - "-c", - ( - "from importlib.metadata import version; " - "from mcp.server.fastmcp import FastMCP; " - "import loopx.kunluncode_goal_mode.server; " - f"assert version('mcp') == '{MCP_SDK_VERSION}'" - ), - ], - timeout=30, - ) - return probe.returncode == 0 - - -def _source_root() -> Path | None: - candidate = Path(__file__).resolve().parents[2] - return candidate if (candidate / "pyproject.toml").is_file() else None - - -def provision_mcp_python(*, dry_run: bool = False) -> str: - """Provision the adapter only through uv; never mutate system Python.""" - if _compatible_python(sys.executable): - return sys.executable - uv = shutil.which("uv") - if not uv: - raise RuntimeError("uv is required to provision the KunlunCode MCP environment") - venv_python = _venv_python(DEFAULT_MCP_VENV) - source_root = _source_root() - loopx_requirement = ( - ["-e", str(source_root)] - if source_root is not None - else [f"loopx=={importlib.metadata.version('loopx')}"] - ) - if dry_run: - return str(venv_python) - DEFAULT_MCP_VENV.parent.mkdir(parents=True, exist_ok=True) - if not venv_python.is_file(): - created = _run([uv, "venv", "--python", sys.executable, str(DEFAULT_MCP_VENV)]) - if created.returncode != 0: - raise RuntimeError( - "uv venv failed: " + (created.stdout + created.stderr)[-800:] - ) - installed = _run( - [ - uv, - "pip", - "install", - "--python", - str(venv_python), - *loopx_requirement, - MCP_REQUIREMENT, - ], - timeout=300, - ) - if installed.returncode != 0 or not _compatible_python(venv_python): - raise RuntimeError( - "uv pip install failed: " + (installed.stdout + installed.stderr)[-1200:] - ) - return str(venv_python) - - -def _configured_mcp_servers(kunluncode: str) -> list[dict[str, Any]]: - result = _run([kunluncode, "config", "get", "mcp_servers"]) - if result.returncode != 0: - raise RuntimeError("cannot read KunlunCode MCP configuration") - try: - payload = json.loads(result.stdout or "[]") - except json.JSONDecodeError as exc: - raise RuntimeError("KunlunCode returned invalid mcp_servers JSON") from exc - return [item for item in payload if isinstance(item, dict)] - - -def _is_managed_server(entry: dict[str, Any]) -> bool: - args = list(entry.get("args") or []) - return ( - entry.get("name") == MCP_SERVER_NAME - and len(args) == 1 - and str(args[0]) - .replace("\\", "/") - .endswith("/loopx/kunluncode_goal_mode/server.py") - ) - - -def _mcp_add_command( - kunluncode: str, - *, - name: str, - command: str, - args: list[str], -) -> list[str]: - result = [ - kunluncode, - "mcp", - "add", - name, - "--command", - command, - ] - if args: - result.extend(["--args", *args]) - return result - - -def _restorable_mcp_command( - kunluncode: str, entry: dict[str, Any] -) -> list[str] | None: - command = entry.get("command") - args = entry.get("args", []) - if not isinstance(command, str) or not command.strip() or not isinstance(args, list): - return None - if not all(isinstance(argument, str) for argument in args): - return None - return _mcp_add_command( - kunluncode, - name=str(entry.get("name") or MCP_SERVER_NAME), - command=command, - args=args, - ) - - -def install_mcp(*, python: str | None, dry_run: bool, replace: bool) -> str: - kunluncode = shutil.which("kunluncode") - if not kunluncode: - raise RuntimeError("kunluncode is not on PATH") - if python: - selected_path = Path(python).expanduser() - if not selected_path.is_absolute(): - selected_path = Path.cwd() / selected_path - selected_python = str(selected_path.absolute()) - else: - selected_python = provision_mcp_python(dry_run=dry_run) - if not dry_run and not _compatible_python(selected_python): - raise RuntimeError( - f"{selected_python} must import LoopX and {MCP_REQUIREMENT}; " - "use uv to sync the adapter environment" - ) - existing = next( - ( - item - for item in _configured_mcp_servers(kunluncode) - if item.get("name") == MCP_SERVER_NAME - ), - None, - ) - if existing and not _is_managed_server(existing) and not replace: - raise RuntimeError( - f"KunlunCode MCP server {MCP_SERVER_NAME!r} is user-owned; pass --replace to replace it" - ) - restore_command = ( - _restorable_mcp_command(kunluncode, existing) if existing else None - ) - if existing and restore_command is None: - raise RuntimeError( - f"KunlunCode MCP server {MCP_SERVER_NAME!r} cannot be safely replaced because its " - "registration cannot be restored with `mcp add`; back it up and remove it manually" - ) - if dry_run: - return selected_python - if existing: - removed = _run([kunluncode, "mcp", "remove", MCP_SERVER_NAME]) - if removed.returncode != 0: - raise RuntimeError("failed to remove prior managed KunlunCode MCP entry") - added = _run( - _mcp_add_command( - kunluncode, - name=MCP_SERVER_NAME, - command=selected_python, - args=[str(MCP_SCRIPT)], - ) - ) - if added.returncode != 0: - if restore_command is not None: - restored = _run(restore_command) - if restored.returncode == 0: - raise RuntimeError( - "KunlunCode MCP registration failed; the previous entry was restored: " - + (added.stdout + added.stderr)[-800:] - ) - raise RuntimeError( - "KunlunCode MCP registration failed and automatic restoration of the previous " - "entry also failed; inspect `kunluncode config get mcp_servers` before retrying" - ) - raise RuntimeError( - "KunlunCode MCP registration failed: " - + (added.stdout + added.stderr)[-800:] - ) - return selected_python - - -def uninstall_mcp(*, dry_run: bool) -> bool: - kunluncode = shutil.which("kunluncode") - if not kunluncode: - raise RuntimeError("kunluncode is not on PATH") - existing = next( - ( - item - for item in _configured_mcp_servers(kunluncode) - if item.get("name") == MCP_SERVER_NAME - ), - None, - ) - if existing is None: - return False - if not _is_managed_server(existing): - raise RuntimeError( - f"refusing to remove user-owned MCP server {MCP_SERVER_NAME!r}" - ) - if not dry_run: - removed = _run([kunluncode, "mcp", "remove", MCP_SERVER_NAME]) - if removed.returncode != 0: - raise RuntimeError("failed to remove KunlunCode MCP entry") - return True - - -def _registry_path(project: Path) -> Path: - current = project / ".loopx" / "registry.json" - legacy = project / ".goal-harness" / "registry.json" - return current if current.is_file() or not legacy.is_file() else legacy - - -def _annotate_registry(registry: Path, *, goal_id: str, agent_id: str) -> None: - def reduce(payload: dict[str, Any]) -> None: - goals = payload.get("goals") or [] - if not any( - str(goal.get("id") or "") == goal_id - for goal in goals - if isinstance(goal, dict) - ): - raise RuntimeError(f"goal {goal_id!r} is not registered in {registry}") - backends = payload.setdefault("agent_backends", []) - if "kunluncode" not in backends: - backends.append("kunluncode") - - mutate_project_registry( - registry, - operation="kunluncode_registry_annotate", - reducer=reduce, - ) - write_binding(registry.parent.parent, goal_id=goal_id, agent_id=agent_id) - - -def _registered_agents_for_goal(registry: Path, goal_id: str) -> list[str]: - payload = load_project_registry(registry) - require_runtime_compatible_project_registry( - payload, - operation="KunlunCode Goal adapter", - ) - goal = next( - ( - item - for item in payload.get("goals") or [] - if isinstance(item, dict) and str(item.get("id") or "") == goal_id - ), - None, - ) - if goal is None: - raise RuntimeError(f"goal {goal_id!r} is not registered in {registry}") - return list(registered_agent_ids(goal)) - - -def _bootstrap_if_needed( - project: Path, - *, - goal_id: str, - objective: str | None, - dry_run: bool, -) -> Path: - registry = _registry_path(project) - if registry.is_file(): - return registry - if not objective: - raise RuntimeError( - "project has no LoopX registry; --objective is required for first connect" - ) - command = [ - *_loopx_prefix(), - "bootstrap", - "--project", - str(project), - "--goal-id", - goal_id, - "--objective", - objective, - "--state-file", - f".loopx/goals/{goal_id}/ACTIVE_GOAL_STATE.md", - "--no-global-sync", - ] - if dry_run: - return registry - result = _run(command, cwd=project) - if result.returncode != 0: - raise RuntimeError( - "LoopX bootstrap failed: " + (result.stdout + result.stderr)[-1200:] - ) - return registry - - -def connect_project( - *, - project: Path, - goal_id: str, - agent_id: str, - objective: str | None, - python: str | None, - skip_mcp: bool, - replace: bool, - dry_run: bool, -) -> dict[str, Any]: - project = project.resolve() - registry = _bootstrap_if_needed( - project, goal_id=goal_id, objective=objective, dry_run=dry_run - ) - if not dry_run: - registered_agents = _registered_agents_for_goal(registry, goal_id) - if agent_id not in registered_agents: - registered_agents.append(agent_id) - agent_arguments = [ - argument - for registered_agent in registered_agents - for argument in ("--registered-agent", registered_agent) - ] - configured = _run( - [ - *_loopx_prefix(), - "--registry", - str(registry), - "configure-goal", - "--goal-id", - goal_id, - "--agent-model", - "peer_v1", - *agent_arguments, - "--execute", - ], - cwd=project, - ) - if configured.returncode != 0: - raise RuntimeError( - "LoopX agent registration failed: " - + (configured.stdout + configured.stderr)[-1200:] - ) - _annotate_registry(registry, goal_id=goal_id, agent_id=agent_id) - selected_python = None - if not skip_mcp: - selected_python = install_mcp(python=python, dry_run=dry_run, replace=replace) - return { - "ok": True, - "dry_run": dry_run, - "project": str(project), - "registry": str(registry), - "goal_id": goal_id, - "agent_id": agent_id, - "binding": str(project / ".loopx" / "kunluncode.json"), - "mcp_server": None if skip_mcp else MCP_SERVER_NAME, - "mcp_python": selected_python, - "global_mcp_registration": not skip_mcp, - "native_app_server": True, - "default_run_mode": "goal-pro", - } - - -def add_todo(project: Path, text: str) -> dict[str, Any]: - context = goal_context(project) - if context is None: - raise RuntimeError( - "KunlunCode is not bound; run loopx-kunluncode connect first" - ) - result = _run( - [ - *_loopx_prefix(), - "--registry", - context["registry"], - "--format", - "json", - "todo", - "add", - "--goal-id", - context["goal_id"], - "--role", - "agent", - "--text", - text, - "--claimed-by", - context["agent_id"], - ], - cwd=project, - ) - if result.returncode != 0: - raise RuntimeError( - "todo add failed: " + (result.stdout + result.stderr)[-1000:] - ) - return json.loads(result.stdout) - - -def worker_prompt(agent_id: str) -> str: - return ( - f"You are the LoopX KunlunCode worker bound as agent {agent_id!r}. " - f"Use the {MCP_SERVER_NAME} MCP lifecycle tools; do not use a Claude binding or guess ids. " - "Call should_run first. If should_run is false, report the reason and stop. " - "If true, claim exactly the selected todo with claim_task, perform one bounded segment, " - "verify it with a real check, then call complete_task with the same agent_id and compact " - "public-safe evidence. Supply either next_agent_todo or no_follow_up=true. " - "Leave the unused field empty and never reuse the completed todo_id as next_agent_todo. " - "When the selected todo already names a check, run that check directly instead of exploring unrelated help or files. " - "Re-check should_run once and stop. Stay inside the projected goal boundary; writes, " - "publishing, destructive actions, and production actions still require their existing authority." - ) - - -def run_worker( - project: Path, - *, - permission_mode: str, - max_duration_secs: int, - json_output: bool, - dry_run: bool, - mode: str = "goal-pro", - controller_timeout_secs: int = 3600, - token_budget: int | None = None, -) -> int: - context = goal_context(project) - if context is None: - raise RuntimeError( - "KunlunCode is not bound; run loopx-kunluncode connect first" - ) - kunluncode = shutil.which("kunluncode") - if not kunluncode: - raise RuntimeError("kunluncode is not on PATH") - if mode != "headless": - if dry_run: - command = build_app_server_command( - kunluncode, - project=project, - permission_mode=permission_mode, - max_duration_secs=max_duration_secs, - ) - payload = { - "ok": True, - "dry_run": True, - "mode": mode, - "command": command, - "side_effects": "none", - } - print( - json.dumps(payload, indent=2) - if json_output - else " ".join(command) + " " - ) - return 0 - payload = run_native_goal( - project, - context, - mode=mode, - permission_mode=permission_mode, - max_duration_secs=max_duration_secs, - controller_timeout_secs=controller_timeout_secs, - token_budget=token_budget, - kunluncode_bin=kunluncode, - ) - if json_output: - print(json.dumps(payload, indent=2)) - elif payload.get("status") == "skipped": - print( - "KunlunCode native Goal skipped: " - + str(payload.get("reason") or "not due") - ) - else: - runtime = ( - payload.get("runtime") - if isinstance(payload.get("runtime"), dict) - else {} - ) - print( - f"KunlunCode {mode} committed for todo {runtime.get('todo_id')}; " - "native verification and LoopX writeback completed." - ) - return 0 - command = [ - kunluncode, - "--cwd", - str(project.resolve()), - "--permission-mode", - permission_mode, - "--tool-profile", - "full", - "--max-duration-secs", - str(max_duration_secs), - ] - if json_output: - command.append("--json") - command.append(worker_prompt(context["agent_id"])) - if dry_run: - print(" ".join(command[:-1]) + " ") - return 0 - environment = dict(os.environ) - adapter_bin = str(Path(sys.executable).absolute().parent) - environment["PATH"] = adapter_bin + os.pathsep + environment.get("PATH", "") - return subprocess.run( - command, - cwd=str(project.resolve()), - env=environment, - ).returncode - - -def status(project: Path) -> dict[str, Any]: - context = goal_context(project) - if context is None: - raise RuntimeError( - "KunlunCode is not bound; run loopx-kunluncode connect first" - ) - result = _run( - [ - *_loopx_prefix(), - "--registry", - context["registry"], - "--format", - "json", - "quota", - "should-run", - "--goal-id", - context["goal_id"], - "--agent-id", - context["agent_id"], - "--runtime-profile", - "kunluncode", - "--available-capability", - "shell", - "--available-capability", - "filesystem_write", - ], - cwd=project, - ) - if result.returncode != 0: - raise RuntimeError("status failed: " + (result.stdout + result.stderr)[-1000:]) - payload = json.loads(result.stdout) - payload["kunluncode_native_goal"] = compact_runtime_state( - read_runtime_state(project.resolve()) - ) - return payload - - -def _parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser(prog="loopx-kunluncode") - subparsers = parser.add_subparsers(dest="command", required=True) - - connect = subparsers.add_parser( - "connect", help="Bind one project goal and install the MCP server." - ) - connect.add_argument("--project", default=".") - connect.add_argument("--goal-id", required=True) - connect.add_argument("--agent-id", default=DEFAULT_AGENT_ID) - connect.add_argument("--objective") - connect.add_argument("--python") - connect.add_argument("--skip-mcp", action="store_true") - connect.add_argument("--replace", action="store_true") - connect.add_argument("--dry-run", action="store_true") - - install = subparsers.add_parser( - "install", help="Install the global KunlunCode MCP entry." - ) - install.add_argument("--python") - install.add_argument("--replace", action="store_true") - install.add_argument("--dry-run", action="store_true") +import sys - uninstall = subparsers.add_parser( - "uninstall", help="Remove only the managed KunlunCode MCP entry." - ) - uninstall.add_argument("--dry-run", action="store_true") +if not __package__: + _package_parent = str(Path(__file__).resolve().parents[2]) + if _package_parent not in sys.path: + sys.path.insert(0, _package_parent) - add = subparsers.add_parser( - "add", help="Add and assign one todo to the bound KunlunCode agent." - ) - add.add_argument("text", nargs="+") - add.add_argument("--project", default=".") +from loopx.hosts.kunluncode import cli as _target # noqa: E402 +from loopx.hosts.kunluncode.cli import main # noqa: E402 - run = subparsers.add_parser( - "run", - help="Run a recoverable native KunlunCode Goal (Goal Pro by default).", - ) - run.add_argument("--project", default=".") - run.add_argument( - "--mode", - choices=["goal-pro", "goal", "headless"], - default="goal-pro", - help=( - "goal-pro uses strict independent verification; goal uses native Arrangement; " - "headless preserves the legacy one-turn MCP worker" - ), - ) - run.add_argument( - "--permission-mode", - choices=["ask", "auto", "accept-edits", "dont-ask", "bypass", "yolo"], - default="auto", - ) - run.add_argument("--max-duration-secs", type=int, default=600) - run.add_argument( - "--controller-timeout-secs", - type=int, - default=3600, - help="Overall wait budget across native Goal auto-continuations.", - ) - run.add_argument( - "--token-budget", - type=int, - help="Optional positive KunlunCode native Goal token budget.", - ) - run.add_argument("--json", action="store_true") - run.add_argument("--dry-run", action="store_true") - status_parser = subparsers.add_parser( - "status", help="Read the bound KunlunCode lane status." - ) - status_parser.add_argument("--project", default=".") - return parser +def __getattr__(name: str) -> object: + return getattr(_target, name) -def main(argv: list[str] | None = None) -> int: - args = _parser().parse_args(argv) - try: - if args.command == "connect": - payload = connect_project( - project=Path(args.project), - goal_id=args.goal_id, - agent_id=args.agent_id, - objective=args.objective, - python=args.python, - skip_mcp=args.skip_mcp, - replace=args.replace, - dry_run=args.dry_run, - ) - print(json.dumps(payload, indent=2)) - return 0 - if args.command == "install": - selected = install_mcp( - python=args.python, dry_run=args.dry_run, replace=args.replace - ) - print( - json.dumps( - { - "ok": True, - "mcp_server": MCP_SERVER_NAME, - "python": selected, - "dry_run": args.dry_run, - }, - indent=2, - ) - ) - return 0 - if args.command == "uninstall": - removed = uninstall_mcp(dry_run=args.dry_run) - print( - json.dumps( - {"ok": True, "removed": removed, "dry_run": args.dry_run}, indent=2 - ) - ) - return 0 - if args.command == "add": - print( - json.dumps(add_todo(Path(args.project), " ".join(args.text)), indent=2) - ) - return 0 - if args.command == "run": - return run_worker( - Path(args.project), - permission_mode=args.permission_mode, - max_duration_secs=args.max_duration_secs, - json_output=args.json, - dry_run=args.dry_run, - mode=args.mode, - controller_timeout_secs=args.controller_timeout_secs, - token_budget=args.token_budget, - ) - if args.command == "status": - print(json.dumps(status(Path(args.project)), indent=2)) - return 0 - except ( - OSError, - RuntimeError, - json.JSONDecodeError, - importlib.metadata.PackageNotFoundError, - ) as exc: - print(json.dumps({"ok": False, "error": str(exc)}, indent=2), file=sys.stderr) - return 1 - return 2 +def __dir__() -> list[str]: + return sorted(set(dir(_target)) | {"main"}) if __name__ == "__main__": diff --git a/loopx/kunluncode_goal_mode/context.py b/loopx/kunluncode_goal_mode/context.py index caedf2224a..a3565959ac 100644 --- a/loopx/kunluncode_goal_mode/context.py +++ b/loopx/kunluncode_goal_mode/context.py @@ -1,70 +1,21 @@ -"""KunlunCode-specific LoopX goal and agent binding.""" +"""Compatibility shim forwarding ``loopx.kunluncode_goal_mode.context`` to ``loopx.hosts.kunluncode.context``.""" + from __future__ import annotations -import json from pathlib import Path -from typing import Any - -from loopx.file_lock import exclusive_file_lock -from loopx.goal_mode_context import find_registry, resolve_goal_context -from loopx.registry import atomic_write_json - - -BINDING_SCHEMA_VERSION = "loopx_kunluncode_binding_v0" -BINDING_FILENAME = "kunluncode.json" - - -def binding_path(project_root: str | Path) -> Path: - return Path(project_root) / ".loopx" / BINDING_FILENAME +import sys +if not __package__: + _package_parent = str(Path(__file__).resolve().parents[2]) + if _package_parent not in sys.path: + sys.path.insert(0, _package_parent) -def read_binding(project_root: str | Path) -> dict[str, str] | None: - path = binding_path(project_root) - try: - payload: Any = json.loads(path.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError): - return None - if not isinstance(payload, dict): - return None - if payload.get("schema_version") != BINDING_SCHEMA_VERSION: - return None - goal_id = str(payload.get("goal_id") or "").strip() - agent_id = str(payload.get("agent_id") or "").strip() - if not goal_id or not agent_id: - return None - return {"goal_id": goal_id, "agent_id": agent_id} +from loopx.hosts.kunluncode import context as _target # noqa: E402 -def write_binding( - project_root: str | Path, - *, - goal_id: str, - agent_id: str, -) -> Path: - path = binding_path(project_root) - path.parent.mkdir(parents=True, exist_ok=True) - payload = { - "schema_version": BINDING_SCHEMA_VERSION, - "host": "kunluncode", - "goal_id": goal_id, - "agent_id": agent_id, - } - with exclusive_file_lock(path, operation="kunluncode_binding_write"): - atomic_write_json(path, payload) - return path +def __getattr__(name: str) -> object: + return getattr(_target, name) -def goal_context(cwd: str | Path) -> dict[str, Any] | None: - registry = find_registry(cwd) - if registry is None: - return None - root = registry.parent.parent - binding = read_binding(root) - if binding is None: - return None - return resolve_goal_context( - cwd, - preferred_goal_id=binding["goal_id"], - preferred_agent_id=binding["agent_id"], - require_preferred_binding=True, - ) +def __dir__() -> list[str]: + return sorted(dir(_target)) diff --git a/loopx/kunluncode_goal_mode/control_plane.py b/loopx/kunluncode_goal_mode/control_plane.py index a61cae4d82..177bd74abc 100644 --- a/loopx/kunluncode_goal_mode/control_plane.py +++ b/loopx/kunluncode_goal_mode/control_plane.py @@ -1,235 +1,21 @@ -"""Narrow LoopX CLI seam for the native KunlunCode Goal controller.""" +"""Compatibility shim forwarding ``loopx.kunluncode_goal_mode.control_plane`` to ``loopx.hosts.kunluncode.control_plane``.""" from __future__ import annotations -import json -import shutil -import subprocess -import sys -from collections.abc import Callable, Mapping from pathlib import Path -from typing import Any - -from loopx.control_plane.agents.workspace_guard import capture_delivery_workspace - - -AVAILABLE_CAPABILITIES = ("shell", "filesystem_write") -VERIFIED_CLASSIFICATIONS = { - "goal": "kunluncode_native_goal_verified", - "goal-pro": "kunluncode_native_goal_pro_verified", -} - - -class KunlunNativeGoalRuntimeError(RuntimeError): - """Raised when native Goal execution or LoopX reconciliation fails closed.""" - - -def _default_loopx_prefix() -> list[str]: - executable = shutil.which("loopx") - return [executable] if executable else [sys.executable, "-m", "loopx.cli"] - - -CommandRunner = Callable[..., subprocess.CompletedProcess[str]] - - -def _default_command_runner( - command: list[str], - *, - cwd: Path, - timeout: int = 120, -) -> subprocess.CompletedProcess[str]: - return subprocess.run( - command, - cwd=str(cwd), - capture_output=True, - text=True, encoding="utf-8", errors="replace", - timeout=timeout, - ) - - -class LoopXControlPlane: - """JSON CLI operations used by the native KunlunCode controller.""" - - def __init__( - self, - project: Path, - context: Mapping[str, Any], - *, - command_prefix: list[str] | None = None, - runner: CommandRunner | None = None, - ) -> None: - self.project = project.resolve() - self.registry = str(context.get("registry") or "") - self.goal_id = str(context.get("goal_id") or "") - self.agent_id = str(context.get("agent_id") or "") - if not self.registry or not self.goal_id or not self.agent_id: - raise KunlunNativeGoalRuntimeError( - "KunlunCode binding is missing registry, goal, or agent identity" - ) - self.command_prefix = list(command_prefix or _default_loopx_prefix()) - self.runner = runner or _default_command_runner - - def _run_json(self, arguments: list[str], *, timeout: int = 120) -> dict[str, Any]: - command = [ - *self.command_prefix, - "--registry", - self.registry, - "--format", - "json", - *arguments, - ] - result = self.runner(command, cwd=self.project, timeout=timeout) - try: - payload = json.loads(result.stdout or "{}") - except json.JSONDecodeError as exc: - diagnostic = (result.stderr or result.stdout or "")[-1200:] - raise KunlunNativeGoalRuntimeError( - "LoopX returned non-JSON output" - + (f": {diagnostic}" if diagnostic else "") - ) from exc - if not isinstance(payload, dict): - raise KunlunNativeGoalRuntimeError( - "LoopX returned a non-object JSON payload" - ) - if result.returncode != 0 or payload.get("ok") is False: - reason = payload.get("error") or payload.get("reason") or result.stderr - raise KunlunNativeGoalRuntimeError( - "LoopX control-plane command failed: " - + str(reason or "unknown error")[-1200:] - ) - return payload - - @staticmethod - def _capability_args() -> list[str]: - return [ - argument - for capability in AVAILABLE_CAPABILITIES - for argument in ("--available-capability", capability) - ] - - def should_run(self) -> dict[str, Any]: - return self._run_json( - [ - "quota", - "should-run", - "--goal-id", - self.goal_id, - "--agent-id", - self.agent_id, - "--runtime-profile", - "kunluncode", - *self._capability_args(), - ] - ) +import sys - def claim(self, todo_id: str) -> dict[str, Any]: - return self._run_json( - [ - "todo", - "claim", - "--goal-id", - self.goal_id, - "--todo-id", - todo_id, - "--claimed-by", - self.agent_id, - "--agent-id", - self.agent_id, - ] - ) +if not __package__: + _package_parent = str(Path(__file__).resolve().parents[2]) + if _package_parent not in sys.path: + sys.path.insert(0, _package_parent) - def evidence_since(self, since: str, *, todo_id: str) -> dict[str, Any]: - # Recovery reads its owning persisted event source directly. An agent-facing - # diagnostic command is not a dependency of native writeback reconciliation. - from loopx.history import load_registry - from loopx.paths import resolve_runtime_root - from loopx.rollout_event_log import load_rollout_events, rollout_event_log_path - from loopx.control_plane.runtime.agent_evidence_history import build_agent_scoped_evidence_log +from loopx.hosts.kunluncode import control_plane as _target # noqa: E402 - try: - registry_path = Path(self.registry).expanduser() - if not registry_path.is_absolute(): - registry_path = self.project / registry_path - registry = load_registry(registry_path) - runtime_root = resolve_runtime_root(registry, None, registry_path=registry_path) - events = load_rollout_events(rollout_event_log_path(runtime_root, self.goal_id), limit=400) - return build_agent_scoped_evidence_log( - goal_id=self.goal_id, agent_id=self.agent_id, todo_id=todo_id, - since=since, rollout_events=events, history_runs=[], limit=128, - ) - except (OSError, ValueError, TypeError) as exc: - raise KunlunNativeGoalRuntimeError(f"writeback evidence unavailable: {exc}") from exc - def record_verified_delivery(self, *, mode: str, todo_id: str) -> dict[str, Any]: - workspace_arguments = ( - ["--delivery-workspace-path", str(self.project)] - if capture_delivery_workspace(self.project) - else [] - ) - return self._run_json( - [ - "refresh-state", - "--goal-id", - self.goal_id, - "--todo-id", - todo_id, - "--project", - str(self.project), - "--classification", - VERIFIED_CLASSIFICATIONS[mode], - "--recommended-action", - "Reconcile the verifier-approved KunlunCode todo and continue from LoopX quota.", - "--delivery-batch-scale", - "single_surface", - "--delivery-outcome", - "outcome_progress", - *workspace_arguments, - "--agent-id", - self.agent_id, - "--progress-scope", - "goal", - *self._capability_args(), - "--suppress-external-sinks", - ], - timeout=300, - ) +def __getattr__(name: str) -> object: + return getattr(_target, name) - def complete(self, todo_id: str, *, evidence: str) -> dict[str, Any]: - return self._run_json( - [ - "todo", - "complete", - "--goal-id", - self.goal_id, - "--todo-id", - todo_id, - "--claimed-by", - self.agent_id, - "--agent-id", - self.agent_id, - "--evidence", - evidence, - "--no-follow-up", - ] - ) - def spend(self, *, todo_id: str) -> dict[str, Any]: - return self._run_json( - [ - "quota", - "spend-slot", - "--goal-id", - self.goal_id, - "--todo-id", - todo_id, - "--slots", - "1", - "--source", - "adapter", - "--execute", - "--agent-id", - self.agent_id, - *self._capability_args(), - ], - timeout=300, - ) +def __dir__() -> list[str]: + return sorted(dir(_target)) diff --git a/loopx/kunluncode_goal_mode/guards.py b/loopx/kunluncode_goal_mode/guards.py index 03d15e6a86..fa7a6ece6a 100644 --- a/loopx/kunluncode_goal_mode/guards.py +++ b/loopx/kunluncode_goal_mode/guards.py @@ -1,110 +1,21 @@ -"""Write-ownership guards for a LoopX-controlled native KunlunCode Goal.""" +"""Compatibility shim forwarding ``loopx.kunluncode_goal_mode.guards`` to ``loopx.hosts.kunluncode.guards``.""" from __future__ import annotations -import json -import os -from typing import Any +from pathlib import Path +import sys +if not __package__: + _package_parent = str(Path(__file__).resolve().parents[2]) + if _package_parent not in sys.path: + sys.path.insert(0, _package_parent) -NATIVE_CONTROLLER_ENV = "LOOPX_KUNLUNCODE_OUTER_CONTROLLER" -NATIVE_CONTROLLER_GOAL_ENV = "LOOPX_KUNLUNCODE_OUTER_GOAL_ID" -NATIVE_CONTROLLER_AGENT_ENV = "LOOPX_KUNLUNCODE_OUTER_AGENT_ID" +from loopx.hosts.kunluncode import guards as _target # noqa: E402 -def _native_controller_rejection(operation: str) -> str: - return json.dumps( - { - "ok": False, - "error": ( - f"{operation} is owned by the LoopX outer controller during a native " - "KunlunCode Goal run; wait for verifier-backed terminal writeback" - ), - } - ) +def __getattr__(name: str) -> object: + return getattr(_target, name) -def guard_native_controller_writeback(control_plane: Any) -> None: - """Prevent model-visible MCP tools from committing before native verification.""" - - if os.environ.get(NATIVE_CONTROLLER_ENV) != "1": - return - - def blocked_claim(_todo_id: str, _agent_id: str) -> str: - return _native_controller_rejection("claim_task") - - def blocked_complete(*_args: Any, **_kwargs: Any) -> str: - return _native_controller_rejection("complete_task") - - control_plane.claim_task = blocked_claim - control_plane.complete_task = blocked_complete - - def blocked_vision(*_args: Any, **_kwargs: Any) -> str: - return _native_controller_rejection("review_task_vision") - - control_plane.review_task_vision = blocked_vision - - -def native_controller_cli_write_block(arguments: Any) -> dict[str, Any] | None: - """Block direct model CLI writes to the Goal owned by the outer controller.""" - - if os.environ.get(NATIVE_CONTROLLER_ENV) != "1": - return None - goal_id = str(os.environ.get(NATIVE_CONTROLLER_GOAL_ENV) or "").strip() - if not goal_id: - return None - raw_goal_ids: list[Any] = [] - for attribute in ("goal_id", "goal_ids"): - value = getattr(arguments, attribute, None) - if isinstance(value, (list, tuple, set)): - raw_goal_ids.extend(value) - else: - raw_goal_ids.append(value) - requested_goal_ids = { - str(value).strip() for value in raw_goal_ids if str(value or "").strip() - } - if goal_id not in requested_goal_ids: - return None - - command = str(getattr(arguments, "command", None) or "") - operation: str | None = None - if command == "todo": - todo_command = str(getattr(arguments, "todo_command", None) or "add") - if todo_command not in {"list", "suggest"}: - operation = f"todo {todo_command}" - elif command == "quota": - quota_command = str(getattr(arguments, "quota_command", None) or "status") - if quota_command not in {"status", "plan", "should-run"}: - operation = f"quota {quota_command}" - elif command == "task-lease": - lease_command = str(getattr(arguments, "task_lease_command", None) or "") - if lease_command != "inspect": - operation = f"task-lease {lease_command}".strip() - elif command == "turn" and getattr(arguments, "turn_command", None) == "run-once": - operation = "turn run-once" - elif command == "goal-lifecycle" and getattr(arguments, "execute", False): - operation = f"goal-lifecycle {getattr(arguments, 'operation', '')}".strip() - elif command in { - "archive-runtime", - "configure-goal", - "operator-gate", - "refresh-state", - "register-agent", - "retire-global-goal", - "reward", - }: - operation = command - if operation is None: - return None - return { - "ok": False, - "error_code": "kunluncode_outer_controller_write_owned", - "error": ( - f"{operation} for goal {goal_id!r} is owned by the LoopX outer controller " - "during this native KunlunCode Goal run" - ), - "goal_id": goal_id, - "agent_id": str(os.environ.get(NATIVE_CONTROLLER_AGENT_ENV) or "") or None, - "operation": operation, - "next_action": "wait for verifier-backed terminal writeback", - } +def __dir__() -> list[str]: + return sorted(dir(_target)) diff --git a/loopx/kunluncode_goal_mode/runtime.py b/loopx/kunluncode_goal_mode/runtime.py index ce9b38dfd2..9f37de467c 100644 --- a/loopx/kunluncode_goal_mode/runtime.py +++ b/loopx/kunluncode_goal_mode/runtime.py @@ -1,741 +1,21 @@ -"""Recoverable LoopX controller for KunlunCode native Goal and Goal Pro.""" +"""Compatibility shim forwarding ``loopx.kunluncode_goal_mode.runtime`` to ``loopx.hosts.kunluncode.runtime``.""" from __future__ import annotations -import json -import os -import shutil -import sys -from collections.abc import Callable, Mapping -from datetime import datetime, timezone from pathlib import Path -from typing import Any - -from loopx.file_lock import exclusive_file_lock -from loopx.control_plane.goals.first_party_host_admission import ( - FirstPartyHostGoalAdmission, - capture_first_party_host_goal_ref, -) -from loopx.kunluncode_goal_mode.app_server import ( - NATIVE_GOAL_MODES, - KunlunAppServerClient, - KunlunAppServerError, - build_app_server_command, - compact_goal, - native_goal_success, - stable_text_digest, -) -from loopx.kunluncode_goal_mode.control_plane import ( - VERIFIED_CLASSIFICATIONS, - KunlunNativeGoalRuntimeError, - LoopXControlPlane, -) -from loopx.kunluncode_goal_mode.guards import ( - NATIVE_CONTROLLER_AGENT_ENV, - NATIVE_CONTROLLER_ENV, - NATIVE_CONTROLLER_GOAL_ENV, -) -from loopx.registry import atomic_write_json - - -RUNTIME_STATE_SCHEMA_VERSION = "loopx_kunluncode_runtime_v0" -RUNTIME_STATE_FILENAME = "kunluncode-runtime.json" - - -def _now() -> str: - return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") - - -def runtime_state_path(project: str | Path) -> Path: - return Path(project) / ".loopx" / RUNTIME_STATE_FILENAME - - -def _validate_runtime_state_payload(payload: dict[str, Any]) -> None: - if payload.get("schema_version") != RUNTIME_STATE_SCHEMA_VERSION: - raise KunlunNativeGoalRuntimeError( - "KunlunCode runtime journal has an unsupported schema" - ) - binding = payload.get("binding") - native = payload.get("native") - writeback = payload.get("writeback") - if not isinstance(binding, dict): - raise KunlunNativeGoalRuntimeError( - "KunlunCode runtime journal is missing a binding object" - ) - if not isinstance(native, dict): - raise KunlunNativeGoalRuntimeError( - "KunlunCode runtime journal is missing a native state object" - ) - if not isinstance(writeback, dict): - raise KunlunNativeGoalRuntimeError( - "KunlunCode runtime journal is missing a writeback state object" - ) - if not all(str(binding.get(key) or "").strip() for key in ("goal_id", "agent_id")): - raise KunlunNativeGoalRuntimeError( - "KunlunCode runtime journal has an incomplete goal or agent binding" - ) - if not str(payload.get("todo_id") or "").strip(): - raise KunlunNativeGoalRuntimeError( - "KunlunCode runtime journal is missing its todo identity" - ) - if native.get("mode") not in NATIVE_GOAL_MODES: - raise KunlunNativeGoalRuntimeError( - "KunlunCode runtime journal has an unsupported native goal mode" - ) - objective_digest = str(native.get("objective_sha256") or "") - if len(objective_digest) != 64 or any( - character not in "0123456789abcdef" for character in objective_digest - ): - raise KunlunNativeGoalRuntimeError( - "KunlunCode runtime journal has an invalid objective digest" - ) - for key in ("verification_passed", "verified", "resumed"): - if not isinstance(native.get(key), bool): - raise KunlunNativeGoalRuntimeError( - f"KunlunCode runtime journal native field {key!r} must be boolean" - ) - for key in ("delivery_recorded", "todo_completed", "quota_spent"): - if not isinstance(writeback.get(key), bool): - raise KunlunNativeGoalRuntimeError( - f"KunlunCode runtime journal writeback field {key!r} must be boolean" - ) - if writeback["todo_completed"] and not writeback["delivery_recorded"]: - raise KunlunNativeGoalRuntimeError( - "KunlunCode runtime journal records todo completion before delivery" - ) - if writeback["quota_spent"] and not writeback["todo_completed"]: - raise KunlunNativeGoalRuntimeError( - "KunlunCode runtime journal records quota spend before todo completion" - ) - if any(writeback.values()) and native["verified"] is not True: - raise KunlunNativeGoalRuntimeError( - "KunlunCode runtime journal records writeback before native verification" - ) - if native["verified"] and native.get("status") != "complete": - raise KunlunNativeGoalRuntimeError( - "KunlunCode runtime journal marks a non-complete native goal verified" - ) - if ( - native["verified"] - and native.get("mode") == "goal-pro" - and native["verification_passed"] is not True - ): - raise KunlunNativeGoalRuntimeError( - "KunlunCode Goal Pro runtime journal is verified without verifier proof" - ) - - -def read_runtime_state(project: str | Path) -> dict[str, Any] | None: - path = runtime_state_path(project) - if not path.is_file(): - return None - try: - payload = json.loads(path.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError) as exc: - raise KunlunNativeGoalRuntimeError( - f"KunlunCode runtime journal is unreadable: {path}" - ) from exc - if not isinstance(payload, dict): - raise KunlunNativeGoalRuntimeError( - "KunlunCode runtime journal is not an object" - ) - _validate_runtime_state_payload(payload) - return payload - - -def write_runtime_state(project: str | Path, state: dict[str, Any]) -> Path: - state["updated_at"] = _now() - _validate_runtime_state_payload(state) - path = runtime_state_path(project) - atomic_write_json(path, state) - return path - - -def _writeback_state(state: Mapping[str, Any]) -> dict[str, Any]: - value = state.get("writeback") - return dict(value) if isinstance(value, Mapping) else {} - - -def runtime_phase(state: Mapping[str, Any]) -> str: - native = state.get("native") if isinstance(state.get("native"), Mapping) else {} - writeback = _writeback_state(state) - if writeback.get("quota_spent") is True: - return "committed" - if writeback.get("todo_completed") is True: - return "todo_completed" - if writeback.get("delivery_recorded") is True: - return "delivery_recorded" - if native.get("verified") is True: - return "native_verified" - if native.get("thread_id"): - return "native_active" - return "planned" - - -def compact_runtime_state(state: Mapping[str, Any] | None) -> dict[str, Any] | None: - if not isinstance(state, Mapping): - return None - binding = state.get("binding") if isinstance(state.get("binding"), Mapping) else {} - native = state.get("native") if isinstance(state.get("native"), Mapping) else {} - writeback = _writeback_state(state) - return { - "schema_version": state.get("schema_version"), - "phase": runtime_phase(state), - "goal_id": binding.get("goal_id"), - "agent_id": binding.get("agent_id"), - "todo_id": state.get("todo_id"), - "mode": native.get("mode"), - "thread_id": native.get("thread_id"), - "native_goal_id": native.get("goal_id"), - "native_status": native.get("status"), - "verification_passed": native.get("verification_passed") is True, - "resumed": native.get("resumed") is True, - "delivery_recorded": writeback.get("delivery_recorded") is True, - "todo_completed": writeback.get("todo_completed") is True, - "quota_spent": writeback.get("quota_spent") is True, - "updated_at": state.get("updated_at"), - } - - -def build_native_goal_objective(todo: Mapping[str, Any], *, agent_id: str) -> str: - todo_id = str(todo.get("todo_id") or "").strip() - text = str(todo.get("text") or "").strip() - if not todo_id or not text: - raise KunlunNativeGoalRuntimeError( - "LoopX selected todo must include a stable todo_id and non-empty text" - ) - scopes = [ - str(item).strip() - for item in todo.get("required_write_scopes") or [] - if str(item).strip() - ] - scope_text = ", ".join(scopes) if scopes else "the active LoopX goal boundary" - return ( - f"Complete LoopX todo {todo_id} as bound agent {agent_id}: {text}\n\n" - f"Write boundary: {scope_text}. Preserve all existing repository and user authority gates. " - "Run focused validation for the actual artifact. Continue under this native Goal until the " - "objective is genuinely complete. The LoopX outer controller exclusively owns claim, todo " - "completion, state refresh, and quota accounting; do not call LoopX MCP claim_task or " - "complete_task and do not run LoopX lifecycle write commands. Use KunlunCode's native " - "update_goal lifecycle only after the work and its validation are complete." - ) - - -def native_goal_turn_prompt(mode: str) -> str: - label = "/goal-pro" if mode == "goal-pro" else "/goal" - return ( - f"Work autonomously toward the already-active native KunlunCode {label} objective. " - "Inspect current repository state before editing, stay inside the stated write boundary, " - "and run real focused validation. Do not create a second goal. Do not call LoopX lifecycle " - "write tools; the outer controller will reconcile LoopX only after this native goal reaches " - "an accepted terminal state." - ) - - -def _new_state( - context: Mapping[str, Any], - *, - todo_id: str, - mode: str, - objective_sha256: str, - goal_ref: Mapping[str, str] | None = None, -) -> dict[str, Any]: - timestamp = _now() - binding = { - "goal_id": str(context.get("goal_id") or ""), - "agent_id": str(context.get("agent_id") or ""), - } - if goal_ref is not None: - binding["goal_instance_id"] = goal_ref["goal_instance_id"] - return { - "schema_version": RUNTIME_STATE_SCHEMA_VERSION, - "created_at": timestamp, - "updated_at": timestamp, - "binding": binding, - "todo_id": todo_id, - "native": { - "mode": mode, - "objective_sha256": objective_sha256, - "thread_id": None, - "goal_id": None, - "revision": None, - "status": "planned", - "verification_kind": None, - "verification_passed": False, - "verified": False, - "verified_at": None, - "resumed": False, - "event_counts": {}, - }, - "writeback": { - "delivery_recorded": False, - "todo_completed": False, - "quota_spent": False, - }, - } - - -def _validate_binding(state: Mapping[str, Any], context: Mapping[str, Any]) -> None: - binding = state.get("binding") if isinstance(state.get("binding"), Mapping) else {} - expected = { - "goal_id": str(context.get("goal_id") or ""), - "agent_id": str(context.get("agent_id") or ""), - } - actual = {key: str(binding.get(key) or "") for key in expected} - if actual != expected: - raise KunlunNativeGoalRuntimeError( - "KunlunCode runtime journal belongs to another LoopX goal or agent" - ) - - -def _runtime_goal_ref(state: Mapping[str, Any]) -> object: - binding = state.get("binding") - if not isinstance(binding, Mapping): - return {"malformed": True} - goal_ref = {"goal_id": binding.get("goal_id")} - if "goal_instance_id" in binding: - goal_ref["goal_instance_id"] = binding.get("goal_instance_id") - return goal_ref - - -def _commit_runtime_state( - project: Path, - state: dict[str, Any], - goal_admission: FirstPartyHostGoalAdmission, -) -> Path: - return goal_admission.accept_result(lambda: write_runtime_state(project, state)) - - -def _compact_receipt( - payload: Mapping[str, Any], fields: tuple[str, ...] -) -> dict[str, Any]: - return {key: payload.get(key) for key in fields if key in payload} - - -def _reconcile_writeback_evidence( - project: Path, - state: dict[str, Any], - control: LoopXControlPlane, - goal_admission: FirstPartyHostGoalAdmission, -) -> None: - native = state["native"] - since = str(native.get("verified_at") or "") - if not since: - return - todo_id = str(state.get("todo_id") or "") - goal_admission.require_current() - payload = control.evidence_since(since, todo_id=todo_id) - if payload.get("schema_version") != "agent_scoped_evidence_log_v0" or not isinstance(payload.get("ledger"), list): - raise KunlunNativeGoalRuntimeError("invalid internal writeback evidence schema") - ledger = payload["ledger"] - writeback = state["writeback"] - classification = VERIFIED_CLASSIFICATIONS[str(native.get("mode") or "goal-pro")] - for event in ledger: - if not isinstance(event, Mapping): - continue - event_kind = str(event.get("event_kind") or "") - if str(event.get("todo_id") or "") != todo_id: - continue - if ( - event_kind == "refresh_state" - and event.get("classification") == classification - ): - writeback["delivery_recorded"] = True - if event_kind == "todo_complete" and str(event.get("todo_id") or "") == todo_id: - writeback["todo_completed"] = True - if event_kind in {"quota_spend", "quota_slot_spent"}: - writeback["quota_spent"] = True - _commit_runtime_state(project, state, goal_admission) - - -def _verified_evidence(state: Mapping[str, Any]) -> str: - native = state.get("native") if isinstance(state.get("native"), Mapping) else {} - mode = str(native.get("mode") or "goal-pro") - verification = "passed" if native.get("verification_passed") else "not-required" - digest = str(native.get("objective_sha256") or "")[:16] - native_goal_id = str(native.get("goal_id") or "") - return ( - f"KunlunCode native {mode} terminal accepted; status=complete; " - f"verification={verification}; objective_sha256={digest}; " - f"native_goal_id={native_goal_id}" - ) - - -def _closeout_writeback( - project: Path, - state: dict[str, Any], - control: LoopXControlPlane, - goal_admission: FirstPartyHostGoalAdmission, -) -> None: - goal_admission.require_current() - _reconcile_writeback_evidence(project, state, control, goal_admission) - writeback = state["writeback"] - mode = str(state["native"]["mode"]) - if writeback.get("delivery_recorded") is not True: - goal_admission.require_current() - payload = control.record_verified_delivery( - mode=mode, - todo_id=str(state["todo_id"]), - ) - if payload.get("appended") is not True: - raise KunlunNativeGoalRuntimeError( - "LoopX did not append the verified KunlunCode delivery record" - ) - writeback["delivery_recorded"] = True - writeback["delivery_receipt"] = _compact_receipt( - payload, ("classification", "generated_at", "appended") - ) - _commit_runtime_state(project, state, goal_admission) - if writeback.get("todo_completed") is not True: - goal_admission.require_current() - payload = control.complete( - str(state["todo_id"]), evidence=_verified_evidence(state) - ) - if payload.get("completed") is not True or payload.get("status") != "done": - raise KunlunNativeGoalRuntimeError( - "LoopX did not accept the verified KunlunCode todo completion" - ) - writeback["todo_completed"] = True - writeback["todo_receipt"] = _compact_receipt( - payload, ("todo_id", "status", "status_changed", "changed") - ) - _commit_runtime_state(project, state, goal_admission) - if writeback.get("quota_spent") is not True: - goal_admission.require_current() - payload = control.spend(todo_id=str(state["todo_id"])) - if payload.get("appended") is not True: - raise KunlunNativeGoalRuntimeError( - "LoopX did not append quota accounting for the verified KunlunCode delivery: " - + str(payload.get("reason") or "unknown reason") - ) - writeback["quota_spent"] = True - writeback["quota_receipt"] = _compact_receipt( - payload, ("classification", "generated_at", "appended", "slots") - ) - _commit_runtime_state(project, state, goal_admission) - - -def _update_native_from_goal(state: dict[str, Any], goal: Mapping[str, Any]) -> None: - compact = compact_goal(goal) - native = state["native"] - native["goal_id"] = compact.get("goal_id") - native["revision"] = compact.get("revision") - native["status"] = compact.get("status") - native["verification_kind"] = compact.get("verification_kind") - native["verification_passed"] = compact.get("verification_passed") is True - - -def _validate_native_identity( - state: Mapping[str, Any], - goal: Mapping[str, Any], -) -> None: - native = state["native"] - compact = compact_goal(goal) - expected_goal_id = str(native.get("goal_id") or "") - observed_goal_id = str(compact.get("goal_id") or "") - if expected_goal_id and observed_goal_id != expected_goal_id: - raise KunlunNativeGoalRuntimeError( - "resumed KunlunCode thread contains a different native goal" - ) - objective_sha256 = str(compact.get("objective_sha256") or "") - if objective_sha256 and objective_sha256 != native.get("objective_sha256"): - raise KunlunNativeGoalRuntimeError( - "resumed KunlunCode native goal objective no longer matches the LoopX todo" - ) - expected_mode = NATIVE_GOAL_MODES[str(native.get("mode") or "")] - observed_mode = str(compact.get("mode") or "") - if observed_mode and observed_mode != expected_mode: - raise KunlunNativeGoalRuntimeError( - "resumed KunlunCode native goal mode does not match the runtime journal" - ) - - -def _run_native_host( - project: Path, - state: dict[str, Any], - *, - objective: str, - kunluncode_bin: str, - permission_mode: str, - max_duration_secs: int, - controller_timeout_secs: int, - token_budget: int | None, - scenario: str | None, - client_factory: Callable[..., Any], - goal_admission: FirstPartyHostGoalAdmission, -) -> None: - command = build_app_server_command( - kunluncode_bin, - project=project, - permission_mode=permission_mode, - max_duration_secs=max_duration_secs, - scenario=scenario, - ) - environment = dict(os.environ) - environment[NATIVE_CONTROLLER_ENV] = "1" - environment[NATIVE_CONTROLLER_GOAL_ENV] = str(state["binding"]["goal_id"]) - environment[NATIVE_CONTROLLER_AGENT_ENV] = str(state["binding"]["agent_id"]) - adapter_bin = str(Path(sys.executable).absolute().parent) - environment["PATH"] = adapter_bin + os.pathsep + environment.get("PATH", "") - event_counts: dict[str, int] = {} +import sys - def record_event(message: Mapping[str, Any]) -> None: - method = str(message.get("method") or "") - if method: - event_counts[method] = event_counts.get(method, 0) + 1 +if not __package__: + _package_parent = str(Path(__file__).resolve().parents[2]) + if _package_parent not in sys.path: + sys.path.insert(0, _package_parent) - native = state["native"] - goal_admission.require_current() - with client_factory( - command, - cwd=project, - env=environment, - event_handler=record_event, - ) as client: - client.initialize() - thread_id = str(native.get("thread_id") or "") - resumed = False - goal: dict[str, Any] = {} - if thread_id: - client.resume_thread(thread_id) - resumed = True - if not thread_id: - thread_id = client.start_thread(project) - native["thread_id"] = thread_id - native["status"] = "thread_started" - _commit_runtime_state(project, state, goal_admission) - elif native.get("goal_id"): - goal = client.get_goal(thread_id) - _validate_native_identity(state, goal) - else: - try: - goal = client.get_goal(thread_id) - _validate_native_identity(state, goal) - except KunlunAppServerError: - goal = {} - native["resumed"] = resumed - if not goal: - goal = client.set_goal( - thread_id, - objective=objective, - mode=str(native["mode"]), - token_budget=token_budget, - ) - _validate_native_identity(state, goal) - _update_native_from_goal(state, goal) - _commit_runtime_state(project, state, goal_admission) - else: - _update_native_from_goal(state, goal) - _commit_runtime_state(project, state, goal_admission) +from loopx.hosts.kunluncode import runtime as _target # noqa: E402 - if not native_goal_success(goal, mode=str(native["mode"])): - status = str(goal.get("status") or "") - if status != "active": - raise KunlunNativeGoalRuntimeError( - "KunlunCode native goal stopped without an accepted completion: " - + json.dumps(compact_goal(goal), ensure_ascii=False, sort_keys=True) - ) - client.start_turn( - thread_id, - native_goal_turn_prompt(str(native["mode"])), - ) - goal = client.wait_for_goal_terminal( - thread_id, - timeout_seconds=controller_timeout_secs, - ) - _validate_native_identity(state, goal) - _update_native_from_goal(state, goal) - native["event_counts"] = dict(sorted(event_counts.items())) - if not native_goal_success(goal, mode=str(native["mode"])): - _commit_runtime_state(project, state, goal_admission) - raise KunlunNativeGoalRuntimeError( - "KunlunCode native goal did not reach an accepted terminal state: " - + json.dumps(compact_goal(goal), ensure_ascii=False, sort_keys=True) - ) - native["verified"] = True - native["verified_at"] = native.get("verified_at") or _now() - _commit_runtime_state(project, state, goal_admission) +def __getattr__(name: str) -> object: + return getattr(_target, name) -def run_native_goal( - project: Path, - context: Mapping[str, Any], - *, - mode: str, - permission_mode: str, - max_duration_secs: int, - controller_timeout_secs: int, - token_budget: int | None = None, - scenario: str | None = None, - kunluncode_bin: str | None = None, - control_plane: LoopXControlPlane | None = None, - client_factory: Callable[..., Any] = KunlunAppServerClient, -) -> dict[str, Any]: - if mode not in NATIVE_GOAL_MODES: - raise KunlunNativeGoalRuntimeError( - f"unsupported native KunlunCode goal mode: {mode}" - ) - if max_duration_secs <= 0 or controller_timeout_secs <= 0: - raise KunlunNativeGoalRuntimeError( - "KunlunCode turn and controller timeouts must be positive" - ) - if token_budget is not None and token_budget <= 0: - raise KunlunNativeGoalRuntimeError( - "KunlunCode native goal token budget must be positive" - ) - if permission_mode == "ask": - raise KunlunNativeGoalRuntimeError( - "native app-server runs cannot service interactive approvals; use --permission-mode auto " - "or another explicitly non-interactive KunlunCode mode" - ) - project = project.resolve() - binary = kunluncode_bin or shutil.which("kunluncode") - if not binary: - raise KunlunNativeGoalRuntimeError("kunluncode is not on PATH") - control = control_plane or LoopXControlPlane(project, context) - goal_id = str(context.get("goal_id") or "") - registry_path = Path( - str(context.get("registry") or project / ".loopx" / "registry.json") - ) - goal_ref = capture_first_party_host_goal_ref( - registry_path=registry_path, - goal_id=goal_id, - ) - goal_admission = FirstPartyHostGoalAdmission.for_plan( - registry_path=registry_path, - goal_id=goal_id, - planned_goal_ref=goal_ref, - ) - journal_path = runtime_state_path(project) - with exclusive_file_lock( - journal_path, - agent_id=str(context.get("agent_id") or ""), - operation="kunluncode_native_goal", - ): - state = goal_admission.select_state( - read_state=lambda: read_runtime_state(project), - goal_ref_of=_runtime_goal_ref, - ) - if state is not None: - _validate_binding(state, context) - if ( - state["native"].get("verified") is True - and runtime_phase(state) != "committed" - ): - _closeout_writeback( - project, - state, - control, - goal_admission, - ) - return { - "ok": True, - "status": "committed", - "recovered": True, - "runtime": compact_runtime_state(state), - } - decision = control.should_run() - if decision.get("should_run") is not True: - return { - "ok": True, - "status": "skipped", - "reason": decision.get("reason"), - "runtime": compact_runtime_state(state), - } - todo = decision.get("selected_todo") - if not isinstance(todo, Mapping): - raise KunlunNativeGoalRuntimeError( - "LoopX allowed a KunlunCode turn without selecting an agent todo" - ) - todo_id = str(todo.get("todo_id") or "") - preparation = ( - decision.get("execution_preparation") - if isinstance(decision.get("execution_preparation"), Mapping) - else {} - ) - if preparation.get("state") == "claim_required": - # The Host performs the projected atomic claim before any model - # work. A fresh guard must observe the resulting lease; the - # preview itself never grants execution authority. - goal_admission.require_current() - control.claim(todo_id) - decision = control.should_run() - if decision.get("should_run") is not True: - raise KunlunNativeGoalRuntimeError( - "LoopX did not admit execution after automatic task preparation" - ) - todo = decision.get("selected_todo") - preparation = ( - decision.get("execution_preparation") - if isinstance(decision.get("execution_preparation"), Mapping) - else {} - ) - if ( - not isinstance(todo, Mapping) - or str(todo.get("todo_id") or "") != todo_id - or preparation.get("state") != "ready" - ): - raise KunlunNativeGoalRuntimeError( - "LoopX automatic task preparation did not preserve the selected Todo and current lease" - ) - claimed_by = str(todo.get("claimed_by") or "") - agent_id = str(context.get("agent_id") or "") - if claimed_by and claimed_by != agent_id: - raise KunlunNativeGoalRuntimeError( - "LoopX selected todo is claimed by another agent" - ) - objective = build_native_goal_objective(todo, agent_id=agent_id) - objective_sha256 = stable_text_digest(objective) - if state is not None and str(state.get("todo_id") or "") == todo_id: - native = state["native"] - if native.get("mode") != mode: - raise KunlunNativeGoalRuntimeError( - "unfinished KunlunCode runtime journal uses a different native goal mode" - ) - if native.get("objective_sha256") != objective_sha256: - raise KunlunNativeGoalRuntimeError( - "LoopX selected todo changed after the KunlunCode native goal started" - ) - elif state is not None and runtime_phase(state) != "committed": - raise KunlunNativeGoalRuntimeError( - "unfinished KunlunCode runtime journal belongs to another todo" - ) - else: - state = _new_state( - context, - todo_id=todo_id, - mode=mode, - objective_sha256=objective_sha256, - goal_ref=goal_ref, - ) - _commit_runtime_state(project, state, goal_admission) - if not claimed_by: - goal_admission.require_current() - control.claim(todo_id) - _run_native_host( - project, - state, - objective=objective, - kunluncode_bin=binary, - permission_mode=permission_mode, - max_duration_secs=max_duration_secs, - controller_timeout_secs=controller_timeout_secs, - token_budget=token_budget, - scenario=scenario, - client_factory=client_factory, - goal_admission=goal_admission, - ) - goal_admission.require_current() - _closeout_writeback( - project, - state, - control, - goal_admission, - ) - return { - "ok": True, - "status": "committed", - "recovered": state["native"].get("resumed") is True, - "runtime": compact_runtime_state(state), - } +def __dir__() -> list[str]: + return sorted(dir(_target)) diff --git a/loopx/kunluncode_goal_mode/server.py b/loopx/kunluncode_goal_mode/server.py index 18e629e197..4c4cbec050 100644 --- a/loopx/kunluncode_goal_mode/server.py +++ b/loopx/kunluncode_goal_mode/server.py @@ -1,26 +1,25 @@ -"""KunlunCode stdio MCP entrypoint.""" +"""Compatibility entrypoint forwarding ``loopx.kunluncode_goal_mode.server`` to ``loopx.hosts.kunluncode.server``.""" from __future__ import annotations from pathlib import Path +import sys -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 +if not __package__: + _package_parent = str(Path(__file__).resolve().parents[2]) + if _package_parent not in sys.path: + sys.path.insert(0, _package_parent) +from loopx.hosts.kunluncode import server as _target # noqa: E402 +from loopx.hosts.kunluncode.server import main # noqa: E402 -CONFIG = GoalModeMCPConfig( - server_name="loopx-kunluncode", - runtime_profile="kunluncode", - legacy_host_surface="kunluncode", - setup_hint="run loopx-kunluncode connect --project --goal-id ", -) -mcp, control = create_fastmcp_server(CONFIG, lambda: goal_context(Path.cwd())) -guard_native_controller_writeback(control) +def __getattr__(name: str) -> object: + return getattr(_target, name) -def main() -> None: - mcp.run() + +def __dir__() -> list[str]: + return sorted(set(dir(_target)) | {"main"}) if __name__ == "__main__": 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 bcab2d6828..5d35913aee 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/hosts/dsh/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 2142119bcd..95fd98d6b5 100644 --- a/loopx/slash_command_install.py +++ b/loopx/slash_command_install.py @@ -7,6 +7,7 @@ from collections.abc import Callable, Mapping from enum import Enum from pathlib import Path +from typing import cast from .hosts.agy import ( ANTIGRAVITY_HOOKS_CONFIG_FILENAME, @@ -50,7 +51,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 = { @@ -609,7 +610,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: @@ -644,12 +645,165 @@ def _mcp_command_for_script(script: Path) -> tuple[str, str] | None: def _loopx_mcp_command() -> tuple[str, str] | None: """The shared Claude-profile server Cursor registers.""" try: - from loopx.claude_goal_mode.scripts import install as claude_install + from loopx.hosts.claude.scripts import install as claude_install except ImportError: return None return _mcp_command_for_script(Path(claude_install._p("mcp", "loopx_mcp.py"))) +def _is_within(path: Path, parent: Path) -> bool: + try: + path.expanduser().resolve().relative_to(parent.expanduser().resolve()) + return True + except (OSError, ValueError): + return False + + +def _projects_from_registry_file(registry_file: Path) -> list[Path]: + """Read project directories from one registry JSON file without creating or mutating state.""" + if not registry_file.is_file(): + return [] + try: + from .control_plane.projects.registry_codec import ( + read_activation_upgrade_registry, + ) + + payload_obj: object = read_activation_upgrade_registry(registry_file) + except (OSError, UnicodeDecodeError, ValueError): + return [] + if not isinstance(payload_obj, dict): + return [] + goals_obj = cast(dict[str, object], payload_obj).get("goals") + if not isinstance(goals_obj, list): + return [] + projects: list[Path] = [] + for item in goals_obj: + if not isinstance(item, dict): + continue + goal = cast(dict[str, object], item) + repo_val = goal.get("repo") + if isinstance(repo_val, str) and repo_val.strip(): + projects.append(Path(repo_val).expanduser()) + source_val = goal.get("source_registry") + if isinstance(source_val, str) and source_val.strip(): + src_path = Path(source_val).expanduser() + if src_path.parent.name in {".loopx", ".goal-harness"}: + projects.append(src_path.parent.parent) + return projects + + +def _discover_claude_migration_targets( + *, + claude_root: Path, + claude_home_overridden: bool, + registry_path: str | None, + runtime_root: str | None, +) -> list[tuple[Path, Path | None]]: + """Return unique `(claude_dir, project_dir)` targets to inspect for legacy migration.""" + targets: list[tuple[Path, Path | None]] = [(claude_root, None)] + env_config_dir = os.environ.get("CLAUDE_CONFIG_DIR") if not claude_home_overridden else None + if env_config_dir and env_config_dir.strip(): + targets.append((Path(env_config_dir).expanduser(), None)) + + project_roots: list[Path] = [] + cwd = Path.cwd() + project_roots.append(cwd) + for parent in (cwd, *cwd.parents): + if any((parent / marker / "registry.json").is_file() for marker in (".loopx", ".goal-harness")): + project_roots.append(parent) + break + + registry_files: list[Path] = [] + if registry_path and registry_path.strip(): + registry_files.append(Path(registry_path).expanduser()) + for marker in (".loopx", ".goal-harness"): + local_reg = cwd / marker / "registry.json" + if local_reg.is_file(): + registry_files.append(local_reg) + + explicit_runtime = runtime_root or os.environ.get("LOOPX_RUNTIME_ROOT") + if explicit_runtime and explicit_runtime.strip(): + rt = Path(explicit_runtime).expanduser() + registry_files.extend([rt / "registry.global.json", rt / "registry.json"]) + if not claude_home_overridden or _is_within(claude_root, Path.home()): + home = Path.home() + for rt in (home / ".loopx", home / ".codex" / "loopx"): + registry_files.extend([rt / "registry.global.json", rt / "registry.json"]) + + for reg_file in registry_files: + project_roots.extend(_projects_from_registry_file(reg_file)) + + for proj in project_roots: + targets.append((proj / ".claude", proj)) + + deduped: list[tuple[Path, Path | None]] = [] + seen_dirs: set[Path] = set() + for claude_dir, proj_dir in targets: + try: + key = claude_dir.expanduser().resolve() + except OSError: + key = claude_dir + if key in seen_dirs: + continue + seen_dirs.add(key) + if claude_dir.is_dir() or (proj_dir is not None and (proj_dir / ".mcp.json").is_file()): + deduped.append((claude_dir, proj_dir)) + return deduped + + +def _migrate_legacy_claude_configs( + *, + installed: list[dict[str, object]], + claude_root: Path, + claude_home_overridden: bool, + registry_path: str | None, + runtime_root: str | None, + execute: bool, + extra_notes: list[str] | None = None, +) -> None: + try: + from loopx.hosts.claude.scripts import install as claude_install + except ImportError: + return + for claude_dir, proj_dir in _discover_claude_migration_targets( + claude_root=claude_root, + claude_home_overridden=claude_home_overridden, + registry_path=registry_path, + runtime_root=runtime_root, + ): + for row in claude_install.migrate_legacy_claude_dir( + claude_dir, + project_dir=proj_dir, + execute=execute, + ): + if row.get("note") and extra_notes is not None: + extra_notes.append(str(row["note"])) + if row.get("reason") or row.get("recovery"): + installed.append( + _installed_entry( + surface="claude-code", + host_surfaces=["claude-code"], + mechanism="claude_goal_mode_legacy_migration", + command="/loopx", + path=Path(row["path"]), + status=row["status"], + reason=row.get("reason"), + recovery=row.get("recovery"), + ) + ) + else: + installed.append( + _installed_entry( + surface="claude-code", + host_surfaces=["claude-code"], + mechanism="claude_goal_mode_legacy_migration", + command="/loopx", + path=Path(row["path"]), + status=row["status"], + ) + ) + + def _kiro_cli_mcp_command() -> tuple[str, str] | None: """The Kiro CLI server: same control plane, Kiro runtime profile and session-bound identity.""" @@ -858,6 +1012,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( @@ -885,6 +1041,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( @@ -928,6 +1085,16 @@ def install_slash_commands( uninstall=uninstall, invoke_prefix="/", ) + if not uninstall: + _migrate_legacy_claude_configs( + installed=installed, + claude_root=claude_root, + claude_home_overridden=claude_home is not None, + registry_path=registry_path, + runtime_root=runtime_root, + execute=execute, + extra_notes=migration_notes, + ) if "gemini" in effective_surfaces: # Gemini CLI discovers user skills from GEMINI_HOME/skills. Files are @@ -1239,6 +1406,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/loopx/zcode_goal_mode/__init__.py b/loopx/zcode_goal_mode/__init__.py index 12fb487600..6b2d877517 100644 --- a/loopx/zcode_goal_mode/__init__.py +++ b/loopx/zcode_goal_mode/__init__.py @@ -1,48 +1,19 @@ +"""Compatibility shim forwarding ``loopx.zcode_goal_mode`` to ``loopx.hosts.zcode``.""" + from __future__ import annotations -import os -import shlex -from typing import Any -from pathlib import Path - -ZCODE_INSTALL_SURFACE = "zcode" -ZCODE_HOME_ENV = "ZCODE_HOME" -DEFAULT_ZCODE_HOME = ".zcode" -SKILLS_SUBDIR = "skills" -SKILLS_ROOT_LABEL = "ZCODE_HOME/skills" - - -def zcode_home(value: str | None = None) -> Path: - """ZCode discovers user skills from ZCODE_HOME/skills (default ~/.zcode). - - The default skill entry gates the session turn loop by quota. A separate - native CLI binding is an explicit opt-in and does not change this root. - """ - raw = ( - value - or os.environ.get(ZCODE_HOME_ENV) - or os.environ.get("ZCODE_AGENTS_HOME") - or str(Path.home() / DEFAULT_ZCODE_HOME) - ) - return Path(raw).expanduser() - - -def native_goal_activation( - *, cli_bin: str, runtime_root: str | None, goal_id: str, - agent_id: str | None, activation_allowed: bool, -) -> dict[str, Any]: - """Discover the optional provider; generating commands performs no effects.""" - prefix = [cli_bin] - if runtime_root: - prefix.extend(["--runtime-root", runtime_root]) - commands = { - action: shlex.join([*prefix, "--format", "json", "zcode-goal", action, - "--goal-id", goal_id, "--agent-id", str(agent_id)]) - for action in ("bind", "start", "pause", "resume", "stop", "status") - } if activation_allowed else {} - return { - "default_off": True, "execution_mode": "managed_runtime", "host_surface": "zcode_cli", - "commands": commands, "requires_explicit_host_selection": True, - "quota_boundary": "Admission before start/resume and serial revocation checks during execution; no per-model-call token limit.", - "session_boundary": "One managed app-server session. This does not attach the current Desktop or terminal conversation.", - } +import importlib + +from loopx.hosts import zcode as _target + +_SUBMODULES = frozenset({"api", "bridge", "diagnostics"}) + + +def __getattr__(name: str) -> object: + if name in _SUBMODULES: + return importlib.import_module(f"loopx.hosts.zcode.{name}") + return getattr(_target, name) + + +def __dir__() -> list[str]: + return sorted(set(dir(_target)) | _SUBMODULES) diff --git a/loopx/zcode_goal_mode/api.py b/loopx/zcode_goal_mode/api.py index 6aeb2ad49a..cd73fa8dc4 100644 --- a/loopx/zcode_goal_mode/api.py +++ b/loopx/zcode_goal_mode/api.py @@ -1,78 +1,21 @@ -"""Loopback Chat projection for the explicitly bound ZCode CLI provider.""" -from __future__ import annotations - -from typing import Any -from urllib.parse import unquote, urlparse - -from ..chat import redact_local_paths -from ..status_server import is_loopback_host -from .bridge import ZCodeGoalBridgeError, zcode_goal_operation +"""Compatibility shim forwarding ``loopx.zcode_goal_mode.api`` to ``loopx.hosts.zcode.api``.""" +from __future__ import annotations -def public_zcode_goal_readback(payload: dict[str, Any]) -> dict[str, Any]: - result = {key: payload[key] for key in ("ok", "available", "goal_id", "goal_ref", "goal_creation_operation_id", "identity_scope", "agent_id", "actions") if key in payload} - if "reason" in payload: - result["reason"] = redact_local_paths(str(payload["reason"])) - binding = payload.get("binding") - result["binding"] = {key: binding[key] for key in ("mode", "connected", "cli_path", "protocol") if key in binding} if isinstance(binding, dict) else None - native = payload.get("native") - result["native"] = {key: native[key] for key in ("session_id", "target_id", "status", "raw_status", "session_status", "objective_sha256", "running", "usage", "selected_model", "available_models") if key in native} if isinstance(native, dict) else None - quota = payload.get("quota") - result["quota"] = {key: quota[key] for key in ("should_run", "checked_at") if key in quota} if isinstance(quota, dict) else None - if isinstance(quota, dict) and "reason" in quota: - result["quota"]["reason"] = redact_local_paths(str(quota["reason"])) - return result - +from pathlib import Path +import sys -class ZCodeGoalRequestMixin: - server: Any - path: str +if not __package__: + _package_parent = str(Path(__file__).resolve().parents[2]) + if _package_parent not in sys.path: + sys.path.insert(0, _package_parent) - def _read_json(self) -> dict[str, Any]: - raise NotImplementedError +from loopx.hosts.zcode import api as _target # noqa: E402 - def _require_loopback_origin(self) -> bool: - raise NotImplementedError - def _send_error(self, message: str, **kwargs: Any) -> None: - raise NotImplementedError +def __getattr__(name: str) -> object: + return getattr(_target, name) - def _send_json(self, payload: dict[str, Any], *, status: int = 200) -> None: - raise NotImplementedError - def _dispatch_zcode_goal(self, path: str, *, apply: bool = False) -> bool: - parts = path.strip("/").split("/") - if len(parts) != 6 or parts[:2] != ["api", "goals"] or parts[3] != "agents" or parts[5] != "zcode-goal": - return False - if not is_loopback_host(str(self.server.server_address[0])): - self._send_error("Managed ZCode operations require a loopback server.", status=403, error_code="zcode_goal_loopback_required") - return True - if not self._require_loopback_origin(): - return True - try: - if urlparse(self.path).query: - raise ValueError("ZCode Goal routes do not accept query parameters.") - goal_id, agent_id = unquote(parts[2]), unquote(parts[4]) - body = self._read_json() if apply else {} - if body is None: - return True - if set(body) - {"action", "cli_path", "model_selection", "expected_binding"}: - raise ValueError("ZCode Goal accepts action, expected_binding, optional cli_path and model_selection.") - action = body.get("action") if apply else "status" - if not isinstance(action, str): - raise ValueError("ZCode Goal action must be a string.") - if "cli_path" in body and (not isinstance(body["cli_path"], str) or not body["cli_path"].strip() or len(body["cli_path"]) > 4096): - raise ValueError("cli_path must be a nonempty string of at most 4096 characters.") - if "model_selection" in body and (action != "select_model" or not isinstance(body["model_selection"], dict)): - raise ValueError("model_selection is a selection object accepted only by select_model.") - if apply and not isinstance(body.get("expected_binding"), dict): - raise ValueError("POST requires expected_binding from the current Goal readback.") - payload = zcode_goal_operation( - action=action, registry_path=self.server.registry_path, goal_id=goal_id, agent_id=agent_id, - cli_path=body.get("cli_path"), runtime_root=self.server.runtime_root_override, model_selection=body.get("model_selection"), expected_binding=body.get("expected_binding"), - ) - except (ValueError, OSError) as exc: - self._send_error(redact_local_paths(str(exc)), status=exc.status if isinstance(exc, ZCodeGoalBridgeError) else 400, error_code=getattr(exc, "code", "invalid_zcode_goal_request")) - else: - self._send_json(public_zcode_goal_readback(payload)) - return True +def __dir__() -> list[str]: + return sorted(dir(_target)) diff --git a/loopx/zcode_goal_mode/bridge.py b/loopx/zcode_goal_mode/bridge.py index 8147578f02..e05315db93 100644 --- a/loopx/zcode_goal_mode/bridge.py +++ b/loopx/zcode_goal_mode/bridge.py @@ -1,326 +1,25 @@ -"""ZCode transport and exact Goal/Agent admission; provider decisions live in TS.""" +"""Compatibility entrypoint forwarding ``loopx.zcode_goal_mode.bridge`` to ``loopx.hosts.zcode.bridge``.""" + from __future__ import annotations -import argparse -import hashlib -import json -import os from pathlib import Path -import shutil -import subprocess 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 - -# The bundled provider contract is the single action vocabulary for Python and TS. -ZCODE_GOAL_ACTIONS: tuple[str, ...] = tuple( - json.loads(Path(__file__).with_name("contract.json").read_text(encoding="utf-8"))["actions"] -) -MAX_TRANSPORT_BYTES = 1_048_576 -_UNSET = object() - - -class ZCodeGoalBridgeError(ValueError): - def __init__(self, message: str, *, code: str = "invalid_zcode_goal_request", status: int = 400): - super().__init__(message) - self.code = code - self.status = status - - -def _zcode_host_compatible(profile: dict[str, Any] | None) -> bool: - declared_host = (profile or {}).get("agent_type") or (profile or {}).get("host_surface") - # An advisory profile need not declare a host. Binding remains an explicit choice. - if declared_host is None: - return True - if not isinstance(declared_host, str): - return False - try: - return normalize_agent_type(declared_host) == "zcode" - except ValueError: - return False - - -def zcode_goal_eligible_agent_ids(goal: dict[str, Any]) -> list[str]: - """Project registered actors compatible with this host, without probing it.""" - return [agent_id for agent_id in registered_agent_ids_for_goal(goal) - if _zcode_host_compatible(agent_profile_for_goal(goal, agent_id))] - - -def validate_zcode_binding( - *, registry_path: Path, goal_id: str, agent_id: str, - project: str | Path | None = None, goal_ref: dict[str, str] | None = None, - require_active: bool = True, goal_creation_operation_id: object = _UNSET, -) -> dict[str, Any]: - """Read existing authority only; never create an instance or register an agent.""" - require_goal_id(goal_id) - _, canonical_project, route = resolve_goal_project_route( - registry_path=registry_path, goal_id=goal_id, project_override=project, - ) - source_registry = Path(route["source_registry"]).resolve() - registry = load_registry(source_registry) - matches = [item for item in registry_goals(registry) if item.get("id") == goal_id] - if len(matches) != 1: - raise ZCodeGoalBridgeError("Goal must be registered exactly once.", code="zcode_goal_authority_changed", status=409) - goal = matches[0] - if require_active and (goal_is_stopped(goal) or goal.get("status", "active") != "active"): - raise ZCodeGoalBridgeError("The LoopX Goal is no longer active.", code="zcode_goal_authority_changed", status=409) - # Generic Goal routing already rejects lifecycle-only source-session registries. - # Existing exact identities remain exact; first-party legacy aliases stay compatible. - instance_id = goal.get("goal_instance_id") - if instance_id is not None: - if not isinstance(instance_id, str): - raise ZCodeGoalBridgeError("Goal instance identifier is invalid.") - current_ref = exact_goal_ref(goal_id, instance_id) - identity_scope = "exact_goal_instance" - else: - current_ref = {"goal_id": goal_id} - identity_scope = "legacy_goal_alias" - if goal_ref is not None and goal_ref != current_ref: - raise ZCodeGoalBridgeError("Goal instance changed; inspect the current Goal before binding again.", code="zcode_goal_authority_changed", status=409) - creation_id = goal.get("creation_operation_id") - if creation_id is not None and (not isinstance(creation_id, str) or not creation_id): - raise ZCodeGoalBridgeError("Goal creation witness is invalid.") - if goal_creation_operation_id is not _UNSET and goal_creation_operation_id != creation_id: - raise ZCodeGoalBridgeError("Goal creation witness changed; inspect the current Goal before binding again.", code="zcode_goal_authority_changed", status=409) - normalized_agent = require_registered_agent_id( - registry_path=source_registry, goal_id=goal_id, agent_id=agent_id, field="agent_id", - ) - profile = agent_profile_for_goal(goal, normalized_agent) - if not _zcode_host_compatible(profile): - raise ZCodeGoalBridgeError("The registered Agent explicitly declares a different host.") - if not canonical_project.is_dir(): - raise ZCodeGoalBridgeError("The canonical Goal project is unavailable.") - return { - "ok": True, "goal_id": goal_id, "goal_ref": current_ref, "agent_id": normalized_agent, - "project": str(canonical_project), "registry": str(source_registry), - "runtime_root": str(route["source_runtime_root"]), - "identity_scope": identity_scope, "goal_creation_operation_id": creation_id, - } - - -def _node_command() -> str: - from ..control_plane.effect_runtime import _node_executable, EffectRuntimeStartupError - try: - return _node_executable() - except EffectRuntimeStartupError as exc: - raise ZCodeGoalBridgeError(str(exc), code="zcode_goal_runtime_unavailable", status=503) from exc - - -def _cli_command(cli_path: str | None, node: str) -> list[str]: - requested = cli_path if cli_path is not None else "zcode" - if not isinstance(requested, str) or not requested.strip() or len(requested) > 4096: - raise ZCodeGoalBridgeError("ZCode CLI path must be a nonempty string of at most 4096 characters.") - requested = requested.strip() - resolved = shutil.which(requested) or str(Path(requested).expanduser().resolve()) - path = Path(resolved) - if not path.is_file(): - raise ZCodeGoalBridgeError("ZCode CLI is unavailable. Supply its executable or JS bundle when binding.", code="zcode_cli_unavailable", status=503) - if (path.parent / "resources/glm/zcode.cjs").is_file() or (path.parent / "resources/app.asar").is_file(): - raise ZCodeGoalBridgeError("Select ZCode CLI; a Desktop executable cannot be bound to the managed CLI provider.") - if path.suffix.lower() in {".cmd", ".bat"}: - raise ZCodeGoalBridgeError("Windows shell shims cannot be used by the managed stdio transport. Supply the installed ZCode JS bundle for bind.") - if path.suffix.lower() in {".js", ".cjs", ".mjs"}: - return [node, str(path.resolve()), "app-server"] - return [str(path.resolve()), "app-server"] - - -def _run_json(command: list[str], *, project: str, request: dict[str, Any] | None = None) -> dict[str, Any]: - environment = {**os.environ, "PYTHONUTF8": "1", "PYTHONDONTWRITEBYTECODE": "1"} - try: - completed = subprocess.run( - command, input=json.dumps(request, ensure_ascii=False) if request is not None else None, - cwd=project, env=environment, capture_output=True, text=True, - encoding="utf-8", errors="strict", timeout=45, check=False, - ) - except (OSError, UnicodeError, subprocess.TimeoutExpired) as exc: - raise ZCodeGoalBridgeError("ZCode provider did not return a bounded response. Read status before retrying an operation.", code="zcode_goal_transport_unavailable", status=503) from exc - if len(completed.stdout.encode("utf-8")) > MAX_TRANSPORT_BYTES: - raise ZCodeGoalBridgeError("ZCode provider response exceeded the transport limit.", code="zcode_goal_invalid_readback", status=503) - try: - payload = json.loads(completed.stdout) - except json.JSONDecodeError as exc: - raise ZCodeGoalBridgeError("ZCode provider did not return a JSON readback.", code="zcode_goal_invalid_readback", status=503) from exc - if not isinstance(payload, dict) or not isinstance(payload.get("ok"), bool): - raise ZCodeGoalBridgeError("ZCode provider returned an invalid readback.", code="zcode_goal_invalid_readback", status=503) - if completed.returncode and payload.get("ok") is True: - raise ZCodeGoalBridgeError("ZCode provider failed despite a successful readback.", code="zcode_goal_invalid_readback", status=503) - return payload - - -def _heartbeat_task(binding: dict[str, Any], loopx_command: list[str]) -> str: - payload = _run_json([ - *loopx_command, "--registry", binding["registry"], "--format", "json", - "heartbeat-prompt", "--goal-id", binding["goal_id"], "--agent-id", binding["agent_id"], - "--runtime-profile", "generic_cli", "--thin", - ], project=binding["project"]) - body = payload.get("task_body") - if payload.get("ok") is not True or not isinstance(body, str) or not body.strip(): - raise ZCodeGoalBridgeError("Canonical heartbeat instructions are unavailable. Repair the Goal state before starting ZCode.") - return body - -def _goal_basis(binding: dict[str, Any]) -> dict[str, Any]: - """Read the current criterion/source revisions the native objective must be consumed under. +if not __package__: + _package_parent = str(Path(__file__).resolve().parents[2]) + if _package_parent not in sys.path: + sys.path.insert(0, _package_parent) - This is the Session RFC basis: existing acceptance-contract and explicit - authority-source revisions, not a whole-prompt hash. An unpromoted Goal has - no acceptance owner and reports ``None``; an unreadable owner fails closed so - a stale basis is never presented as current. - """ - registry_path = Path(binding["registry"]) - goal = load_goal_from_registry(registry_path, binding["goal_id"]) - if goal is None: - raise ZCodeGoalBridgeError("Goal must be registered exactly once.", code="zcode_goal_authority_changed", status=409) - sources: list[dict[str, Any]] = [] - for item in goal.get("authority_sources") or []: - if not isinstance(item, dict): - continue - source_id = str(item.get("id") or item.get("source_id") or "") - if not source_id: - continue - revision = item.get("revision") - sources.append({"id": source_id, "revision": revision if isinstance(revision, (int, str)) and not isinstance(revision, bool) else None}) - sources.sort(key=lambda row: row["id"]) - acceptance: dict[str, Any] | None = None - if local_authority_is_promoted(runtime_root=Path(binding["runtime_root"]), goal_id=binding["goal_id"]): - try: - observed = inspect_goal_acceptance(registry_path=registry_path, goal_id=binding["goal_id"], runtime_root=binding["runtime_root"]) - except (ValueError, TypeError, OSError, RuntimeError) as exc: - raise ZCodeGoalBridgeError( - "Current Goal acceptance basis is unavailable. Read status and repair the Goal authority before starting or resuming ZCode.", - code="zcode_goal_basis_unavailable", status=503, - ) from exc - revision = observed.get("revision") - digest = observed.get("contract_digest") - acceptance = { - "revision": revision if isinstance(revision, int) and not isinstance(revision, bool) else None, - "contract_digest": digest if isinstance(digest, str) else None, - } - return {"acceptance": acceptance, "authority_sources": sources} +from loopx.hosts.zcode import bridge as _target # noqa: E402 +from loopx.hosts.zcode.bridge import _validate_main # noqa: E402 -def zcode_goal_operation( - *, action: str, registry_path: Path, goal_id: str, agent_id: str, - project: str | Path | None = None, cli_path: str | None = None, - runtime_root: str | Path | None = None, model_selection: dict[str, Any] | None = None, - expected_binding: dict[str, Any] | None = None, -) -> dict[str, Any]: - if action not in ZCODE_GOAL_ACTIONS: - raise ZCodeGoalBridgeError("Unsupported ZCode Goal operation.") - if model_selection is not None: - if action != "select_model": - raise ZCodeGoalBridgeError("Model selection is supported only by select_model.") - if not isinstance(model_selection, dict) or set(model_selection) - {"providerId", "modelId", "options"}: - raise ZCodeGoalBridgeError("Model selection accepts providerId, modelId and optional reasoning options.") - if any(not isinstance(model_selection.get(key), str) or not model_selection[key].strip() or len(model_selection[key]) > 256 for key in ("providerId", "modelId")): - raise ZCodeGoalBridgeError("Model selection requires bounded providerId and modelId strings.") - options = model_selection.get("options", {}) - if not isinstance(options, dict) or set(options) - {"reasoningLevel"} or ("reasoningLevel" in options and (not isinstance(options["reasoningLevel"], str) or not options["reasoningLevel"].strip() or len(options["reasoningLevel"]) > 128)): - raise ZCodeGoalBridgeError("Model selection options accept only a bounded reasoningLevel.") - elif action == "select_model": - raise ZCodeGoalBridgeError("select_model requires an explicit model_selection.") - if cli_path is not None and action != "bind": - raise ZCodeGoalBridgeError("ZCode CLI selection is supported only by an explicit bind operation.") - expected_ref = None - expected_creation: object = _UNSET - if expected_binding is not None: - if not isinstance(expected_binding, dict) or set(expected_binding) != {"goal_ref", "goal_creation_operation_id"}: - raise ZCodeGoalBridgeError("expected_binding requires goal_ref and goal_creation_operation_id.") - expected_ref = expected_binding["goal_ref"] - if not isinstance(expected_ref, dict) or set(expected_ref) not in ({"goal_id"}, {"goal_id", "goal_instance_id"}): - raise ZCodeGoalBridgeError("expected_binding requires an exact supported Goal reference shape.") - if not isinstance(expected_ref.get("goal_id"), str): - raise ZCodeGoalBridgeError("Expected Goal id must be a string.") - require_goal_id(expected_ref["goal_id"]) - if "goal_instance_id" in expected_ref: - if not isinstance(expected_ref["goal_instance_id"], str): - raise ZCodeGoalBridgeError("Expected Goal instance must be a string.") - exact_goal_ref(expected_ref["goal_id"], expected_ref["goal_instance_id"]) - expected_creation = expected_binding["goal_creation_operation_id"] - if expected_creation is not None and (not isinstance(expected_creation, str) or not expected_creation or len(expected_creation) > 256): - raise ZCodeGoalBridgeError("Expected creation witness must be a bounded string or null.") - require_active = action not in {"status", "pause", "stop"} - binding = validate_zcode_binding( - registry_path=registry_path, goal_id=goal_id, agent_id=agent_id, project=project, - require_active=require_active, goal_ref=expected_ref, goal_creation_operation_id=expected_creation, - ) - node = _node_command() - loopx_command = [sys.executable, "-m", "loopx.cli"] - state_root = Path(runtime_root).expanduser().resolve() if runtime_root is not None else Path(binding["runtime_root"]) - state_key = hashlib.sha256(json.dumps( - [binding["registry"], binding["goal_ref"], binding["goal_creation_operation_id"], binding["agent_id"]], sort_keys=True, - ).encode("utf-8")).hexdigest() - request: dict[str, Any] = { - "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"], - } - if model_selection is not None: - request["model_selection"] = model_selection - if action == "bind": - request["cli_command"] = _cli_command(cli_path, node) - request["cli_path"] = request["cli_command"][-2] - if action in {"bind", "start"}: - request["task_body"] = _heartbeat_task(binding, loopx_command) - if action in {"bind", "start", "resume"}: - request["goal_basis"] = _goal_basis(binding) - payload = _run_json( - [node, "--experimental-strip-types", *node_typescript_flags(), str(Path(__file__).with_name("cli.ts"))], - project=binding["project"], - request=request, - ) - for key in ("goal_id", "goal_ref", "goal_creation_operation_id", "agent_id"): - if key not in payload or payload[key] != binding[key]: - raise ZCodeGoalBridgeError("ZCode readback did not match the exact Goal and Agent requested.", code="zcode_goal_invalid_readback", status=409) - observed = validate_zcode_binding( - registry_path=registry_path, goal_id=goal_id, agent_id=agent_id, - project=binding["project"], goal_ref=binding["goal_ref"], require_active=require_active, - goal_creation_operation_id=binding["goal_creation_operation_id"], - ) - if observed["registry"] != binding["registry"]: - raise ZCodeGoalBridgeError("Canonical Goal authority changed during the operation.", code="zcode_goal_authority_changed", status=409) - return payload +def __getattr__(name: str) -> object: + return getattr(_target, name) -def _validate_main() -> int: - parser = argparse.ArgumentParser(description="Internal read-only ZCode binding admission.") - parser.add_argument("--validate-binding", required=True, action="store_true") - parser.parse_args() - try: - encoded = sys.stdin.buffer.read(MAX_TRANSPORT_BYTES + 1) - if len(encoded) > MAX_TRANSPORT_BYTES: - raise ValueError("binding request exceeded the transport limit") - request = json.loads(encoded) - if not isinstance(request, dict) or not isinstance(request.get("goal_ref"), dict): - raise ValueError("an exact Goal reference is required") - action = request.get("action") - if not isinstance(action, str) or action not in ZCODE_GOAL_ACTIONS: - raise ValueError("an explicit known ZCode operation is required for binding admission") - required = ("registry", "project", "goal_id", "agent_id") - if any(not isinstance(request.get(key), str) or not request[key] for key in required): - raise ValueError("binding identity fields must be nonempty strings") - result = validate_zcode_binding( - registry_path=Path(request["registry"]), project=request["project"], - goal_id=request["goal_id"], agent_id=request["agent_id"], goal_ref=request["goal_ref"], - goal_creation_operation_id=request.get("goal_creation_operation_id", _UNSET), - require_active=action not in {"status", "pause", "stop"}, - ) - payload = {key: result[key] for key in ("ok", "goal_id", "goal_ref", "goal_creation_operation_id", "identity_scope", "agent_id")} - except (ValueError, OSError) as exc: - payload = {"ok": False, "error": str(exc), "error_code": getattr(exc, "code", "invalid_zcode_goal_binding")} - print(json.dumps(payload, ensure_ascii=False)) - return 0 if payload["ok"] else 1 +def __dir__() -> list[str]: + return sorted(set(dir(_target)) | {"_validate_main"}) if __name__ == "__main__": diff --git a/loopx/zcode_goal_mode/diagnostics.py b/loopx/zcode_goal_mode/diagnostics.py index b8ee997d08..88d64ce6c0 100644 --- a/loopx/zcode_goal_mode/diagnostics.py +++ b/loopx/zcode_goal_mode/diagnostics.py @@ -1,358 +1,21 @@ +"""Compatibility shim forwarding ``loopx.zcode_goal_mode.diagnostics`` to ``loopx.hosts.zcode.diagnostics``.""" + from __future__ import annotations -# Local host observations; no control-plane decisions or execution authority. -import json -import os from pathlib import Path -import plistlib -import re -import shutil -import subprocess import sys -import tempfile -import threading -import time -from typing import Any, Literal, TypedDict - -from loopx.extensions.process_runtime import prepare_owned_process_cleanup - -InterfaceStatus = Literal["advertised", "not_advertised", "unverified"] -ProbeStatus = Literal["observed", "failed", "timeout", "unreadable", "output_limit"] - - -class _ProbeReport(TypedDict): - status: ProbeStatus - exit_code: int | None - output: str - - -PROBE_TIMEOUT_SECONDS = 5 -MAX_METADATA_BYTES = 1_048_576 -INTERFACE_PATTERNS = { - "headless_prompt": r"(? dict[str, Any] | None: - try: - if path.stat().st_size > MAX_METADATA_BYTES: - return None - value = json.loads(path.read_text(encoding="utf-8")) - return value if isinstance(value, dict) else None - except (OSError, ValueError): - return None - - -def _run_probe(command: list[str], *, extra_env: dict[str, str] | None = None) -> _ProbeReport: - # Metadata/help only. Shared transport owns the complete isolated tree; - # the reader owns pipe close, which may otherwise wait on a descendant. - disposable = None - try: - disposable = tempfile.TemporaryDirectory(prefix="loopx-zcode-doctor-", ignore_cleanup_errors=True) - env = dict(os.environ) - env.update(extra_env or {}) - for name in ("ZCODE_HOME", "ZCODE_STORAGE_DIR", "ZCODE_DATA_BASE_DIR"): - env[name] = disposable.name - process = subprocess.Popen( - command, cwd=disposable.name, env=env, stdin=subprocess.DEVNULL, - stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=0, - start_new_session=os.name == "posix", - creationflags=(getattr(subprocess, "CREATE_NO_WINDOW") | 4) if os.name == "nt" else 0, - ) - cleanup = prepare_owned_process_cleanup(process) - except OSError: - if disposable is not None: - disposable.cleanup() - return {"status": "unreadable", "exit_code": None, "output": ""} - - deadline = time.monotonic() + PROBE_TIMEOUT_SECONDS - output: list[bytes] = [] - limited = threading.Event() - read_failed = threading.Event() - stream = process.stdout - assert stream is not None - - def capture() -> None: - size = 0 - try: - while chunk := stream.read(4096): - size += len(chunk) - if size > 65536: - limited.set() - break - output.append(chunk) - except (OSError, ValueError): - read_failed.set() - finally: - try: - stream.close() - except OSError: - pass - - reader = threading.Thread(target=capture, daemon=True) - reader.start() - status: ProbeStatus - exit_code = None - while True: - exit_code = process.poll() - if limited.is_set(): - status = "output_limit" - break - if exit_code is not None and not reader.is_alive(): - status = "unreadable" if read_failed.is_set() else "observed" if exit_code == 0 else "failed" - break - if time.monotonic() >= deadline: - status = "timeout" - break - limited.wait(min(.01, max(0, deadline - time.monotonic()))) - try: - # Ownership survives leader exit; the shared transport confirms the - # isolated group is no longer executable before returning a report. - cleanup() - except (OSError, RuntimeError, subprocess.TimeoutExpired): - status = "unreadable" - reader.join(timeout=1) - if reader.is_alive(): - status = "unreadable" - else: - disposable.cleanup() - return { - "status": status, "exit_code": exit_code, - "output": b"".join(output).decode("utf-8", errors="replace") if status in {"observed", "failed"} else "", - } - - - -def _public_probe(probe: _ProbeReport) -> dict[str, Any]: - # Raw output may include private configuration/errors; never project it. - return {"status": probe["status"], "exit_code": probe["exit_code"]} - - -def _version(output: str) -> str | None: - for line in output.splitlines()[:8]: - match = re.fullmatch( - r"\s*(?:ZCode(?: CLI)?(?: version)?[: ]+)?v?(\d+\.\d+\.\d+(?:\.\d+)?(?:[-+][\w.-]+)?)\s*", - line, re.IGNORECASE, - ) - if match: - return match.group(1) - return None - - -def _unknown_interfaces() -> dict[str, dict[str, str]]: - return {name: {"status": "unverified", "evidence": "none"} for name in (*INTERFACE_PATTERNS, "stream_json_syntax")} - - -def _inspect_cli(path: Path | None, *, discovery: str) -> dict[str, Any]: - observation: dict[str, Any] = { - "status": "not_found", "path": str(path) if path else None, - "discovery": discovery, "version": None, "interfaces": _unknown_interfaces(), - "runtime_verified": False, "version_evidence": "unavailable", - "next_action": "Install ZCode CLI or supply --zcode-cli with its executable or existing JS bundle.", - } - if path is None: - return observation - try: - path = path.resolve() - observation["path"] = str(path) - if not path.is_file(): - return observation - except OSError: - observation["status"] = "unreadable" - return observation - if (path.parent / "resources/glm/zcode.cjs").is_file() or (path.parent / "resources/app.asar").is_file(): - observation.update(status="invalid", next_action="This is a Desktop installation. Use --zcode-desktop; the GUI executable is never used for CLI probes.") - return observation - is_js = path.suffix.lower() in {".js", ".cjs", ".mjs"} - node = shutil.which("node") if is_js else None - if is_js and node is None: - observation.update(status="probe_failed", next_action="Make node available on PATH to inspect this JS bundle.") - return observation - command = [node, str(path)] if node else [str(path)] - version = _run_probe([*command, "--version"]) - help_probe = _run_probe([*command, "--help", "--locale", "en-US"]) - observation["probes"] = {"version": _public_probe(version), "help": _public_probe(help_probe)} - if version["status"] == "observed": - observation["version"] = _version(version["output"]) - if observation["version"]: - observation["version_evidence"] = "--version" - identity = help_probe["status"] == "observed" and re.search( - r"(?im)^\s*zcode(?:\s+v?\d+\.\d+\.\d+|\s+\[command\])", - help_probe["output"], - ) is not None - observation["identity_verified"] = identity - if identity: - for name, pattern in INTERFACE_PATTERNS.items(): - status: InterfaceStatus = "advertised" if re.search(pattern, help_probe["output"]) else "not_advertised" - observation["interfaces"][name] = {"status": status, "evidence": "--help --locale en-US"} - # Version short-circuits before sessions/models: parser recognition - # does not verify a runtime stream or execution readiness. - syntax = _run_probe([*command, "--version", "--output-format", "stream-json"]) - invalid_syntax = _run_probe([*command, "--version", "--output-format", "loopx-doctor-invalid"]) - recognized = invalid_syntax["status"] == "failed" and syntax["status"] == "observed" and _version(syntax["output"]) == observation["version"] and observation["version"] is not None - observation["probes"]["stream_json_syntax"] = _public_probe(syntax) - observation["probes"]["invalid_output_format_control"] = _public_probe(invalid_syntax) - observation["interfaces"]["stream_json_syntax"] = { - "status": "advertised" if recognized else "unverified", - "evidence": "--version --output-format stream-json" if recognized else "none", - } - observation["status"] = "available" if identity and observation["version"] else "probe_failed" - observation["next_action"] = ( - "Help/version observed; sessions, models, permissions and native protocol execution remain unverified." - if observation["status"] == "available" else - "Check the CLI path, Node runtime and permissions; failed probes do not prove interface absence." - ) - return observation - - -def _desktop_candidates() -> list[Path]: - if os.name == "nt": - return [ - Path(os.environ[variable]) / suffix - for variable, suffix in ( - ("LOCALAPPDATA", "Programs/ZCode/ZCode.exe"), - ("LOCALAPPDATA", "ZCode/ZCode.exe"), - ("ProgramFiles", "ZCode/ZCode.exe"), - ) if os.environ.get(variable) - ] - if sys.platform == "darwin": - return [Path("/Applications/ZCode.app"), Path.home() / "Applications/ZCode.app"] - return [Path("/opt/ZCode/zcode"), Path("/opt/zcode/zcode")] - - -def _resolve_desktop(path: Path) -> tuple[Path, Path]: - # Locate executable/resources without starting the GUI. - if path.suffix.lower() == ".app": - return path / "Contents/MacOS/ZCode", path / "Contents/Resources" - if path.is_dir(): - return path / ("ZCode.exe" if os.name == "nt" else "zcode"), path / "resources" - if path.parent.name == "MacOS": - return path, path.parent.parent / "Resources" - return path, path.parent / "resources" - - -def _desktop_version(executable: Path, resources: Path) -> dict[str, Any]: - if executable.suffix.lower() == ".exe" and os.name == "nt": - powershell = shutil.which("powershell") or shutil.which("pwsh") - if powershell: - script = "(Get-Item -LiteralPath $env:LOOPX_ZCODE_METADATA_PATH -ErrorAction Stop).VersionInfo | Select-Object ProductVersion,ProductName | ConvertTo-Json -Compress" - probe = _run_probe( - [powershell, "-NoProfile", "-NonInteractive", "-Command", script], - extra_env={"LOOPX_ZCODE_METADATA_PATH": str(executable)}, - ) - try: - metadata = json.loads(probe["output"]) if probe["status"] == "observed" else {} - value = metadata.get("ProductVersion") - if isinstance(value, str) and _version(value): - return {"value": value, "evidence": "executable ProductVersion", "identity_verified": str(metadata.get("ProductName", "")).casefold() == "zcode"} - except (ValueError, AttributeError): - pass - plist_path = resources.parent / "Info.plist" - if plist_path.is_file(): - try: - with plist_path.open("rb") as stream: - value = plistlib.load(stream).get("CFBundleShortVersionString") - if isinstance(value, str): - return {"value": value, "evidence": "Info.plist CFBundleShortVersionString", "identity_verified": resources.parent.parent.name.casefold() == "zcode.app"} - except (OSError, ValueError, plistlib.InvalidFileException): - pass - package = _read_json(resources / "app/package.json") - if package and isinstance(package.get("version"), str): - return {"value": package["version"], "evidence": "installed app/package.json", "identity_verified": str(package.get("name", "")).casefold() == "zcode"} - return {"value": None, "evidence": "unavailable", "identity_verified": False} - - -def _inspect_desktop(path_text: str | None) -> dict[str, Any]: - explicit = path_text or os.environ.get("ZCODE_DESKTOP_PATH") - candidates = [Path(explicit).expanduser()] if explicit else _desktop_candidates() - selected = resources = None - for candidate in candidates: - executable, root = _resolve_desktop(candidate.resolve()) - if executable.is_file(): - selected, resources = executable, root - break - observation: dict[str, Any] = { - "status": "available" if selected else "not_found", - "path": str(selected) if selected else (str(candidates[0]) if explicit else None), - "discovery": "explicit" if explicit else "standard_install_locations", - "version": None, "version_evidence": "unavailable", "runtime_verified": False, - "next_action": "Supply --zcode-desktop with the executable, install directory or .app bundle; inaccessible locations do not prove no installation.", - } - if selected is not None and resources is not None: - metadata = _desktop_version(selected, resources) - identity = metadata.get("identity_verified", False) or (resources / "glm/zcode.cjs").is_file() - observation.update(version=metadata["value"], version_evidence=metadata["evidence"], identity_verified=identity) - if not identity: - observation.update(status="unverified", next_action="The selected file exists but ZCode Desktop identity could not be verified. Check its product metadata or installation resources.") - return observation - observation["bundled_cli"] = _inspect_cli(resources / "glm/zcode.cjs", discovery="desktop_bundle") - observation["next_action"] = "Desktop metadata and bundled CLI are separate; the Desktop UI and Automations have not been exercised." - return observation +if not __package__: + _package_parent = str(Path(__file__).resolve().parents[2]) + if _package_parent not in sys.path: + sys.path.insert(0, _package_parent) -def _inspect_source(path_text: str | None) -> dict[str, Any]: - text = path_text or os.environ.get("ZCODE_SOURCE_ROOT") - if not text: - return {"status": "not_selected", "path": None, "package_version": None} - root = Path(text).expanduser().resolve() - package = _read_json(root / "package.json") - valid = package is not None and str(package.get("name", "")).lower() == "zcode" - observation: dict[str, Any] = { - "status": "available" if valid else "invalid", "path": str(root), - "package_version": package.get("version") if valid and package is not None else None, - "version_evidence": "source package.json; not an installed/runtime version", - } - if valid: - observation["built_cli"] = _inspect_cli(root / "apps/zcode-cli/packages/cli/dist/zcode.cjs", discovery="source_bundle") - else: - observation["next_action"] = "Supply --zcode-source with a ZCode checkout containing its root package.json." - return observation +from loopx.hosts.zcode import diagnostics as _target # noqa: E402 -def collect_zcode_host_diagnostics( - *, cli_path: str | None = None, desktop_path: str | None = None, - source_root: str | None = None, -) -> dict[str, Any]: - explicit_cli = cli_path or os.environ.get("ZCODE_CLI_PATH") - found = shutil.which("zcode") if not explicit_cli else None - resolved_cli = Path(explicit_cli).expanduser() if explicit_cli else (Path(found) if found else None) - return { - "cli": _inspect_cli(resolved_cli, discovery="explicit" if explicit_cli else "PATH"), - "desktop": _inspect_desktop(desktop_path), - "source_checkout": _inspect_source(source_root), - "loopx_binding": {"mode": "skill_facade", "native_goal": "opt_in_managed_cli", "automations": "not_integrated"}, - "probe_boundary": "Isolated help/version only. No Desktop launch, session, model, app-server handshake or credential read. Interface observations do not certify runtime readiness.", - } +def __getattr__(name: str) -> object: + return getattr(_target, name) -def render_zcode_diagnostics_markdown(payload: dict[str, Any]) -> list[str]: - lines = ["", "## ZCode hosts", ""] - hosts = [("CLI", payload["cli"]), ("Desktop", payload["desktop"])] - if payload["desktop"].get("bundled_cli"): - hosts.append(("Desktop bundled CLI", payload["desktop"]["bundled_cli"])) - source = payload["source_checkout"] - lines.append(f"- Source checkout: **{source['status']}**; declared package version: {source.get('package_version') or 'unknown'} (not runtime version).") - if source.get("path"): - lines.append(f" Path: {source['path']}") - if source.get("built_cli"): - hosts.append(("Source built CLI", source["built_cli"])) - for label, host in hosts: - lines.append(f"- {label}: **{host['status']}**; version: {host.get('version') or 'unknown'}; path: {host.get('path') or 'not discovered'}.") - if host.get("version_evidence"): - lines.append(f" Version evidence: {host['version_evidence']}.") - if host.get("interfaces"): - interfaces = ", ".join(f"{name}={row['status']}" for name, row in host["interfaces"].items()) - lines.append(f" Interface observations: {interfaces}.") - if host.get("next_action"): - lines.append(f" {host['next_action']}") - lines.extend(["", payload["probe_boundary"], "LoopX binding: Skill facade by default; managed native CLI Goal requires explicit zcode-goal bind. Desktop attachment and Automations are not integrated."]) - return lines +def __dir__() -> list[str]: + return sorted(dir(_target)) 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 bb3b16e36a..e9cb85e804 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" @@ -104,13 +104,14 @@ include = ["loopx*"] "loopx.extensions.openviking_periodic_report" = ["extension.toml"] "loopx.extensions.openviking_semantic_preference" = ["extension.toml"] "loopx.hosts.agy" = ["README.md"] +"loopx.hosts.claude" = ["README.md", ".claude-plugin/*.json", "commands/*.md", "hooks/*.json", "settings.example.json"] "loopx.hosts.dsh" = ["README.md"] "loopx.hosts.kiro_cli" = ["README.md"] +"loopx.hosts.kunluncode" = ["README.md"] "loopx.hosts.opencode" = ["*.js", "*.mjs", "README.md"] "loopx.hosts.opencode2" = ["*.mjs", "README.md"] "loopx.hosts.pi" = ["*.ts", "*.mjs", "README.md"] -"loopx.kunluncode_goal_mode" = ["README.md"] -"loopx.zcode_goal_mode" = ["README.md", "*.ts", "contract.json", "images/*.png"] +"loopx.hosts.zcode" = ["README.md", "*.ts", "contract.json", "images/*.png"] [tool.setuptools.data-files] "share/loopx/skills/loopx-material" = [ diff --git a/scripts/ci/test_impact_plan.py b/scripts/ci/test_impact_plan.py index bb6b553aef..6bca8179fd 100644 --- a/scripts/ci/test_impact_plan.py +++ b/scripts/ci/test_impact_plan.py @@ -50,7 +50,7 @@ def test_root_readme_locales_are_documents(self): def test_backend_mixed_and_full_risk_tiering(self): for path in ("loopx/cli.py", "loopx/control_plane/goals/vision_checkpoint.ts", - "loopx/claude_goal_mode/commands/loopx.md", "tests/test_ui.py", + "loopx/hosts/claude/commands/loopx.md", "tests/test_ui.py", "AGENTS.md", "docs/build.py", "packages/dsh-loopx-plugin/src/cli.ts", "packages/loopx-ark-turn/tests/test_cli.py", "packages/dsh-loopx-plugin/smoke/dsh-legacy-host.package.json", diff --git a/scripts/install-local.sh b/scripts/install-local.sh index 9681fbf640..2101a11fb9 100755 --- a/scripts/install-local.sh +++ b/scripts/install-local.sh @@ -1015,8 +1015,8 @@ fi # LOOPX_INSTALL_CLAUDE=1 (installs at USER scope: MCP + /loopx command). Add # the optional should_run gate later with `install.py --scope # --harden`. Prefer PROJECT scope: -# `python /loopx/claude_goal_mode/scripts/install.py --scope project`. -claude_installer="$release_dir/loopx/claude_goal_mode/scripts/install.py" +# `python /loopx/hosts/claude/scripts/install.py --scope project`. +claude_installer="$release_dir/loopx/hosts/claude/scripts/install.py" install_claude="${LOOPX_INSTALL_CLAUDE:-0}" claude_line="- loopx Claude adapter: skipped (opt-in; LOOPX_INSTALL_CLAUDE=1, or run install.py --scope project|user)" if [[ "$install_claude" != "0" && -f "$claude_installer" ]]; then diff --git a/scripts/qualify-claude-goal-release.py b/scripts/qualify-claude-goal-release.py index 20a3bcdb4f..fc731bae76 100644 --- a/scripts/qualify-claude-goal-release.py +++ b/scripts/qualify-claude-goal-release.py @@ -121,13 +121,13 @@ def verify_mcp_completions(events: list[dict], expected_todos: set[str] | None = def exercise_host(root: Path, project: Path, launcher: Path, claude: str, timeout: int) -> list[dict]: - from loopx.claude_goal_mode.scripts.goalmode_cmd import write_loop_md + from loopx.hosts.claude.scripts.goalmode_cmd import write_loop_md write_loop_md(project, shared.GOAL, shared.AGENT) config = root / "mcp.json" config.write_text(json.dumps({"mcpServers": {"loopx": { "command": sys.executable, - "args": [str(REPO / "loopx/claude_goal_mode/mcp/loopx_mcp.py")], + "args": [str(REPO / "loopx/hosts/claude/mcp/loopx_mcp.py")], }}})) command = [ claude, "--bare", "--setting-sources", "", "--no-session-persistence", diff --git a/tests/architecture/test_source_session_registry_denial.py b/tests/architecture/test_source_session_registry_denial.py index fb9163403b..2a94fd53ba 100644 --- a/tests/architecture/test_source_session_registry_denial.py +++ b/tests/architecture/test_source_session_registry_denial.py @@ -24,7 +24,7 @@ "loopx/capabilities/manager_context/roundtrip.py", "loopx/capabilities/issue_fix/correction_settlement.py", "loopx/capabilities/native_chat/project_context.py", - "loopx/claude_goal_mode/scripts/connect.py", + "loopx/hosts/claude/scripts/connect.py", "loopx/cli_runtime.py", "loopx/cli_commands/coordination_shadow.py", "loopx/cli_commands/manager_inbox.py", @@ -46,7 +46,7 @@ "loopx/control_plane/projects/registry.py", "loopx/control_plane/quota/execution_preparation.py", "loopx/control_plane/turn_driver/codex_sessions.py", - "loopx/kunluncode_goal_mode/cli.py", + "loopx/hosts/kunluncode/cli.py", "loopx/state_migration.py", "loopx/hosts/managed_service_runtime.py", } diff --git a/tests/cli_commands/test_source_session_lifetime.py b/tests/cli_commands/test_source_session_lifetime.py index c3b48b6e38..2379bd3ee6 100644 --- a/tests/cli_commands/test_source_session_lifetime.py +++ b/tests/cli_commands/test_source_session_lifetime.py @@ -11,7 +11,7 @@ import pytest from loopx.cli import main -from loopx.claude_goal_mode.scripts import connect as claude_connect +from loopx.hosts.claude.scripts import connect as claude_connect from loopx.control_plane.goals import ( source_session_recreation, source_session_registration, diff --git a/tests/control_plane/test_machine_guard_context_contract.py b/tests/control_plane/test_machine_guard_context_contract.py index c700de872a..acbcd9fd4c 100644 --- a/tests/control_plane/test_machine_guard_context_contract.py +++ b/tests/control_plane/test_machine_guard_context_contract.py @@ -10,9 +10,9 @@ import pytest -from loopx.claude_goal_mode.scripts import goalmode_cmd -from loopx.claude_goal_mode.statusline import goal_status -from loopx.claude_goal_mode.hooks import goal_policy +from loopx.hosts.claude.scripts import goalmode_cmd +from loopx.hosts.claude.statusline import goal_status +from loopx.hosts.claude.hooks import goal_policy from loopx.control_plane.host_adapter_settlement import HostTodoSettlementRequest, _prepare from loopx.goal_mode_mcp import GoalModeMCPConfig, GoalModeMCPControlPlane from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime diff --git a/tests/control_plane/test_replan_context_evidence.py b/tests/control_plane/test_replan_context_evidence.py index 4ea36c8a60..7f8405274a 100644 --- a/tests/control_plane/test_replan_context_evidence.py +++ b/tests/control_plane/test_replan_context_evidence.py @@ -445,7 +445,7 @@ def test_unscoped_replan_assignment_ignores_evidence_and_presentation_changes(): def test_native_recovery_reads_its_event_source_without_the_removed_cli(tmp_path: Path): - from loopx.kunluncode_goal_mode.control_plane import LoopXControlPlane + from loopx.hosts.kunluncode.control_plane import LoopXControlPlane runtime = tmp_path / "runtime" registry = tmp_path / "registry.json" diff --git a/tests/control_plane_ts/content_digest_single_owner.test.ts b/tests/control_plane_ts/content_digest_single_owner.test.ts index c959f3f069..585aa95453 100644 --- a/tests/control_plane_ts/content_digest_single_owner.test.ts +++ b/tests/control_plane_ts/content_digest_single_owner.test.ts @@ -195,8 +195,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/host_harness_capabilities.test.ts b/tests/control_plane_ts/host_harness_capabilities.test.ts index 1bc148f4e9..c7f6e55838 100644 --- a/tests/control_plane_ts/host_harness_capabilities.test.ts +++ b/tests/control_plane_ts/host_harness_capabilities.test.ts @@ -428,7 +428,7 @@ test("registry rejects conflicting registrations unless replace=true and stays i const conflicting = defineHostHarnessCapabilities({ host_id: "claude", integration_tier: "boundary_cli", - adapter_module: "loopx.claude_goal_mode", + adapter_module: "loopx.hosts.claude", supported_capabilities: ["verifier_hook", "compact_hook"], hook_events: ["PreToolUse", "PreCompact"], requires_utf8_stdio: true, 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/hosts/test_host_harness_capabilities.py b/tests/hosts/test_host_harness_capabilities.py index 9a2051f0d0..2b9a7996b5 100644 --- a/tests/hosts/test_host_harness_capabilities.py +++ b/tests/hosts/test_host_harness_capabilities.py @@ -113,7 +113,7 @@ def test_flagship_hosts_register_exact_shipped_capabilities() -> None: from loopx.capabilities.native_chat.codex_adapter import ( CODEX_APP_SERVER_HOST_CAPABILITIES as CHAT_ADAPTER_CODEX_APP_SERVER_CAPABILITIES, ) - from loopx.claude_goal_mode import CLAUDE_HOST_CAPABILITIES + from loopx.hosts.claude import CLAUDE_HOST_CAPABILITIES from loopx.codex_app_thread_activity import ( CODEX_APP_HOST_CAPABILITIES as THREAD_ACTIVITY_CODEX_APP_CAPABILITIES, ) @@ -286,7 +286,7 @@ def test_capabilities_lookup_loads_flagship_adapters_lazily_without_cold_import_ assert 'loopx.hosts.agy' not in sys.modules assert 'loopx.hosts.agy.host_runtime' not in sys.modules assert 'loopx.hosts.dsh.turn_host_adapter' not in sys.modules -assert 'loopx.claude_goal_mode' not in sys.modules +assert 'loopx.hosts.claude' not in sys.modules assert 'loopx.hosts.codex_capabilities' not in sys.modules agy = get_host_capabilities('agy') assert agy is not None and agy.integration_tier == 'orchestrated_app' @@ -342,7 +342,7 @@ def test_codex_capabilities_lookup_avoids_heavy_runtime_imports() -> None: for mod in heavy_modules[1:]: assert mod not in sys.modules, f"codex descriptor lookup pulled heavy module {mod}" assert 'loopx.hosts.agy' not in sys.modules -assert 'loopx.claude_goal_mode' not in sys.modules +assert 'loopx.hosts.claude' not in sys.modules assert 'loopx.hosts.dsh.turn_host_adapter' not in sys.modules """ completed = subprocess.run( @@ -409,7 +409,7 @@ def test_default_registry_enforces_builtin_conflict_in_both_orders_preserving_la conflicting_claude = HostHarnessCapabilities( host_id='claude', integration_tier='boundary_cli', - adapter_module='loopx.claude_goal_mode', + adapter_module='loopx.hosts.claude', supported_capabilities=('verifier_hook',), hook_events=('PreToolUse',), requires_utf8_stdio=True, @@ -420,12 +420,12 @@ def test_default_registry_enforces_builtin_conflict_in_both_orders_preserving_la with pytest.raises(ValueError, match='conflicting host capabilities registration for claude'): register_host_capabilities(conflicting_claude) -assert 'loopx.claude_goal_mode' in sys.modules +assert 'loopx.hosts.claude' in sys.modules assert 'loopx.hosts.agy' not in sys.modules assert 'loopx.hosts.agy.host_runtime' not in sys.modules assert 'loopx.hosts.dsh.turn_host_adapter' not in sys.modules -import loopx.claude_goal_mode as claude_mod +import loopx.hosts.claude as claude_mod assert get_host_capabilities('claude') == claude_mod.CLAUDE_HOST_CAPABILITIES assert register_host_capabilities(claude_mod.CLAUDE_HOST_CAPABILITIES) == claude_mod.CLAUDE_HOST_CAPABILITIES """ @@ -440,7 +440,7 @@ def test_default_registry_enforces_builtin_conflict_in_both_orders_preserving_la override_claude = HostHarnessCapabilities( host_id='claude', integration_tier='boundary_cli', - adapter_module='loopx.claude_goal_mode', + adapter_module='loopx.hosts.claude', supported_capabilities=('verifier_hook',), hook_events=('PreToolUse',), requires_utf8_stdio=True, @@ -454,7 +454,7 @@ def test_default_registry_enforces_builtin_conflict_in_both_orders_preserving_la assert 'loopx.hosts.agy.host_runtime' not in sys.modules assert 'loopx.hosts.dsh.turn_host_adapter' not in sys.modules -import loopx.claude_goal_mode as claude_mod +import loopx.hosts.claude as claude_mod assert claude_mod.CLAUDE_HOST_CAPABILITIES != override_claude assert get_host_capabilities('claude') == override_claude """ @@ -472,7 +472,7 @@ def test_default_registry_enforces_builtin_conflict_in_both_orders_preserving_la conflicting_claude = HostHarnessCapabilities( host_id='claude', integration_tier='boundary_cli', - adapter_module='loopx.claude_goal_mode', + adapter_module='loopx.hosts.claude', supported_capabilities=('verifier_hook',), hook_events=('PreToolUse',), requires_utf8_stdio=True, @@ -511,7 +511,7 @@ def test_concurrent_first_builtin_load_blocks_conflict_without_blocking_other_bu builtin_claude = HostHarnessCapabilities( host_id="claude", integration_tier="boundary_cli", - adapter_module="loopx.claude_goal_mode", + adapter_module="loopx.hosts.claude", supported_capabilities=("verifier_hook",), hook_events=("PreToolUse",), requires_utf8_stdio=True, @@ -533,7 +533,7 @@ def test_concurrent_first_builtin_load_blocks_conflict_without_blocking_other_bu conflicting_claude = HostHarnessCapabilities( host_id="claude", integration_tier="boundary_cli", - adapter_module="loopx.claude_goal_mode", + adapter_module="loopx.hosts.claude", supported_capabilities=("verifier_hook",), hook_events=("PreToolUse",), requires_utf8_stdio=True, @@ -707,7 +707,7 @@ def run_concurrent_conflict_register() -> None: assert "conflicting host capabilities registration for dsh" in str(t3_error) assert "loopx.hosts.agy" not in sys.modules assert "loopx.hosts.agy.host_runtime" not in sys.modules -assert "loopx.claude_goal_mode" not in sys.modules +assert "loopx.hosts.claude" not in sys.modules """ completed = subprocess.run( [sys.executable, "-c", script], @@ -1005,7 +1005,7 @@ def test_flagship_wiring_preserves_default_runtime_behavior(tmp_path: Path) -> N ) == {} ) - hook_path = REPO_ROOT / "loopx" / "claude_goal_mode" / "hooks" / "goal_policy.py" + hook_path = REPO_ROOT / "loopx" / "hosts" / "claude" / "hooks" / "goal_policy.py" hook_result = subprocess.run( [sys.executable, str(hook_path)], cwd=tmp_path, @@ -1032,7 +1032,7 @@ def test_isolated_registry_loads_real_builtins_in_cold_and_warm_processes( ) assert 'loopx.hosts.agy' not in sys.modules -assert 'loopx.claude_goal_mode' not in sys.modules +assert 'loopx.hosts.claude' not in sys.modules assert 'loopx.hosts.codex_capabilities' not in sys.modules assert 'loopx.hosts.dsh.turn_host_adapter' not in sys.modules @@ -1041,7 +1041,7 @@ def test_isolated_registry_loads_real_builtins_in_cold_and_warm_processes( assert agy is not None and agy.host_id == 'agy' assert 'loopx.hosts.agy' in sys.modules assert 'loopx.hosts.agy.host_runtime' not in sys.modules -assert 'loopx.claude_goal_mode' not in sys.modules +assert 'loopx.hosts.claude' not in sys.modules assert 'loopx.hosts.codex_capabilities' not in sys.modules assert 'loopx.hosts.dsh.turn_host_adapter' not in sys.modules assert get_host_capabilities('agy') == agy @@ -1049,7 +1049,7 @@ def test_isolated_registry_loads_real_builtins_in_cold_and_warm_processes( conflicting_claude = HostHarnessCapabilities( host_id='claude', integration_tier='boundary_cli', - adapter_module='loopx.claude_goal_mode', + adapter_module='loopx.hosts.claude', supported_capabilities=('verifier_hook',), hook_events=('PreToolUse',), requires_utf8_stdio=True, @@ -1079,7 +1079,7 @@ def test_isolated_registry_loads_real_builtins_in_cold_and_warm_processes( warm_and_override_isolated_script = """ import sys import loopx.hosts.agy as agy_mod -import loopx.claude_goal_mode as claude_mod +import loopx.hosts.claude as claude_mod import loopx.hosts.codex_capabilities as codex_mod import loopx.hosts.dsh.turn_host_adapter as dsh_mod from loopx.hosts.capabilities import ( @@ -1093,7 +1093,7 @@ def test_isolated_registry_loads_real_builtins_in_cold_and_warm_processes( override_claude = HostHarnessCapabilities( host_id='claude', integration_tier='boundary_cli', - adapter_module='loopx.claude_goal_mode', + adapter_module='loopx.hosts.claude', supported_capabilities=('verifier_hook',), hook_events=('PreToolUse',), requires_utf8_stdio=True, @@ -1165,7 +1165,7 @@ def test_isolated_registry_loads_real_builtins_in_cold_and_warm_processes( explicit_fake = HostHarnessCapabilities( host_id="claude", integration_tier="boundary_cli", - adapter_module="loopx.claude_goal_mode", + adapter_module="loopx.hosts.claude", supported_capabilities=("verifier_hook",), hook_events=("PreToolUse",), requires_utf8_stdio=True, 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 5b09145d59..0c22ee6006 100644 --- a/tests/test_audit_cli_and_runtime_fixes.py +++ b/tests/test_audit_cli_and_runtime_fixes.py @@ -211,7 +211,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..88c51a0d7e --- /dev/null +++ b/tests/test_hosts_goal_mode_batch2_consolidation.py @@ -0,0 +1,884 @@ +"""Contracts protecting Batch 2 host consolidation and thin compatibility shims.""" + +from __future__ import annotations + +import ast +import importlib +import importlib.util +from importlib.util import resolve_name +import json +import os +from pathlib import Path +import subprocess +import sys +import tomllib +import venv +import zipfile + +from loopx import __version__ as loopx_version +from loopx.hosts.kunluncode import cli as kunlun_cli + +REPO_ROOT = Path(__file__).resolve().parents[1] +PACKAGE_ROOT = REPO_ROOT / "loopx" + +SHIM_TARGETS: dict[str, tuple[set[str], str]] = { + "claude_goal_mode": ( + { + "__init__.py", + "hooks/goal_policy.py", + "hooks/goal_state.py", + "hooks/stdio_utf8.py", + "mcp/loopx_mcp.py", + "scripts/connect.py", + "scripts/goalmode_cmd.py", + "scripts/install.py", + "statusline/goal_status.py", + }, + "loopx.hosts.claude", + ), + "kunluncode_goal_mode": ( + { + "__init__.py", + "app_server.py", + "cli.py", + "context.py", + "control_plane.py", + "guards.py", + "runtime.py", + "server.py", + }, + "loopx.hosts.kunluncode", + ), + "zcode_goal_mode": ( + { + "__init__.py", + "api.py", + "bridge.py", + "diagnostics.py", + }, + "loopx.hosts.zcode", + ), +} + + +def _module_name(path: Path) -> str: + relative = path.relative_to(PACKAGE_ROOT).with_suffix("") + parts = list(relative.parts) + if parts[-1] == "__init__": + parts.pop() + return ".".join(("loopx", *parts)) + + +def _resolved_imports(path: Path) -> set[str]: + module_name = _module_name(path) + package_name = module_name if path.name == "__init__.py" else module_name.rpartition(".")[0] + tree = ast.parse(path.read_bytes(), filename=str(path)) + imports: set[str] = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + imports.update(alias.name for alias in node.names) + elif isinstance(node, ast.ImportFrom): + module = node.module or "" + if node.level: + module = resolve_name("." * node.level + module, package_name) + if module: + imports.add(module) + if module == "loopx" or module.startswith("loopx."): + rel_parts = module.split(".")[1:] + for alias in node.names: + if alias.name == "*": + continue + candidate_path = PACKAGE_ROOT.joinpath(*rel_parts, alias.name) + if candidate_path.with_suffix(".py").is_file() or candidate_path.is_dir(): + imports.add(f"{module}.{alias.name}") + return imports + + +def _build_pure_loopx_wheel(out_dir: Path) -> Path: + version = loopx_version + metadata = f"loopx-{version}.dist-info" + contents: dict[str, bytes] = {} + for file_path in sorted(PACKAGE_ROOT.rglob("*")): + if not file_path.is_file(): + continue + rel = file_path.relative_to(REPO_ROOT).as_posix() + if "/__pycache__/" in rel or rel.startswith("loopx/web/") or rel.endswith(".pyc"): + continue + if file_path.suffix not in {".py", ".json", ".ts", ".toml", ".md", ".png", ".js", ".mjs"}: + continue + contents[rel] = file_path.read_bytes() + + contents[f"{metadata}/METADATA"] = ( + f"Metadata-Version: 2.1\nName: loopx\nVersion: {version}\n".encode("utf-8") + ) + contents[f"{metadata}/WHEEL"] = ( + b"Wheel-Version: 1.0\nGenerator: test\nRoot-Is-Purelib: true\nTag: py3-none-any\n" + ) + contents[f"{metadata}/RECORD"] = "".join( + f"{name},,\n" for name in [*contents, f"{metadata}/RECORD"] + ).encode("utf-8") + + wheel_path = out_dir / f"loopx-{version}-py3-none-any.whl" + with zipfile.ZipFile(wheel_path, "w") as archive: + for name, data in contents.items(): + archive.writestr(name, data) + return wheel_path + + +def _build_pre_consolidation_stub_wheel(out_dir: Path) -> Path: + meta = "loopx-0.0.0.dist-info" + contents: dict[str, bytes] = { + "loopx/__init__.py": b'__version__ = "0.0.0"\n', + f"{meta}/METADATA": b"Metadata-Version: 2.1\nName: loopx\nVersion: 0.0.0\n", + f"{meta}/WHEEL": ( + b"Wheel-Version: 1.0\nGenerator: test\nRoot-Is-Purelib: true\nTag: py3-none-any\n" + ), + } + for pkg_name, (rel_files, _) in SHIM_TARGETS.items(): + for rel in rel_files: + contents[f"loopx/{pkg_name}/{rel}"] = ( + b"raise RuntimeError('stale pre-consolidation stub was not replaced')\n" + if rel != "__init__.py" + else b"STALE = True\n" + ) + contents[f"{meta}/RECORD"] = "".join( + f"{name},,\n" for name in [*contents, f"{meta}/RECORD"] + ).encode("utf-8") + wheel_path = out_dir / "loopx-0.0.0-py3-none-any.whl" + with zipfile.ZipFile(wheel_path, "w") as archive: + for name, data in contents.items(): + archive.writestr(name, data) + return wheel_path + + +def test_batch2_hosts_packages_and_pyproject_package_data() -> None: + for host_dir in ("claude", "kunluncode", "zcode"): + assert (PACKAGE_ROOT / "hosts" / host_dir / "__init__.py").is_file() + assert (PACKAGE_ROOT / "hosts" / host_dir / "README.md").is_file() + + for asset in ( + "claude/.claude-plugin/plugin.json", + "claude/commands/loopx.md", + "claude/hooks/hooks.json", + "claude/hooks/goal_policy.py", + "claude/hooks/goal_state.py", + "claude/hooks/stdio_utf8.py", + "claude/mcp/loopx_mcp.py", + "claude/scripts/connect.py", + "claude/scripts/goalmode_cmd.py", + "claude/scripts/install.py", + "claude/settings.example.json", + "claude/statusline/goal_status.py", + "kunluncode/app_server.py", + "kunluncode/cli.py", + "kunluncode/context.py", + "kunluncode/control_plane.py", + "kunluncode/guards.py", + "kunluncode/runtime.py", + "kunluncode/server.py", + "zcode/api.py", + "zcode/app-server.ts", + "zcode/bridge.py", + "zcode/cli.ts", + "zcode/contract.json", + "zcode/contract.ts", + "zcode/diagnostics.py", + "zcode/guard.ts", + "zcode/images/native-error-mobile.png", + "zcode/images/native-quota-desktop.png", + "zcode/runtime.ts", + ): + assert (PACKAGE_ROOT / "hosts" / asset).is_file(), asset + + pyproject = tomllib.loads((REPO_ROOT / "pyproject.toml").read_text(encoding="utf-8")) + assert pyproject["project"]["scripts"]["loopx-kunluncode"] == "loopx.hosts.kunluncode.cli:main" + package_data = pyproject["tool"]["setuptools"]["package-data"] + for legacy_pkg in ("loopx.claude_goal_mode", "loopx.kunluncode_goal_mode", "loopx.zcode_goal_mode"): + assert legacy_pkg not in package_data + assert package_data["loopx.hosts.claude"] == [ + "README.md", + ".claude-plugin/*.json", + "commands/*.md", + "hooks/*.json", + "settings.example.json", + ] + assert package_data["loopx.hosts.kunluncode"] == ["README.md"] + assert package_data["loopx.hosts.zcode"] == [ + "README.md", + "*.ts", + "contract.json", + "images/*.png", + ] + + +def test_no_internal_loopx_production_module_imports_legacy_batch2_shims() -> None: + legacy_prefixes = ( + "loopx.claude_goal_mode", + "loopx.kunluncode_goal_mode", + "loopx.zcode_goal_mode", + ) + offenders: list[tuple[str, str]] = [] + for py_path in sorted(PACKAGE_ROOT.rglob("*.py")): + rel = py_path.relative_to(PACKAGE_ROOT).as_posix() + if rel.startswith(("claude_goal_mode/", "kunluncode_goal_mode/", "zcode_goal_mode/")): + continue + for imported in sorted(_resolved_imports(py_path)): + for prefix in legacy_prefixes: + if imported == prefix or imported.startswith(prefix + "."): + offenders.append((rel, imported)) + assert offenders == [], ( + f"Internal modules must import loopx.hosts.{{claude,kunluncode,zcode}}: {offenders}" + ) + + +def test_legacy_batch2_packages_are_thin_forwarding_shims_only(tmp_path: Path) -> None: + for pkg_name, (expected_files, target_prefix) in SHIM_TARGETS.items(): + pkg_dir = PACKAGE_ROOT / pkg_name + assert pkg_dir.is_dir(), pkg_name + actual_files = { + path.relative_to(pkg_dir).as_posix() + for path in pkg_dir.rglob("*") + if path.is_file() and "__pycache__" not in path.parts + } + assert actual_files == expected_files, f"{pkg_name}: {actual_files}" + + for rel_name in sorted(expected_files): + py_path = pkg_dir / rel_name + tree = ast.parse(py_path.read_text(encoding="utf-8"), filename=str(py_path)) + classes = [node.name for node in tree.body if isinstance(node, ast.ClassDef)] + functions = [ + node.name + for node in tree.body + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) + ] + assert classes == [], f"{pkg_name}/{rel_name} defines classes: {classes}" + assert set(functions) <= {"__getattr__", "__dir__"}, ( + f"{pkg_name}/{rel_name} defines logic functions: {functions}" + ) + imported = _resolved_imports(py_path) + assert any( + mod == target_prefix or mod.startswith(target_prefix + ".") + for mod in imported + ), f"{pkg_name}/{rel_name} does not delegate to {target_prefix}: {imported}" + + from loopx.claude_goal_mode import CLAUDE_HOST_CAPABILITIES as legacy_claude_cap + from loopx.hosts.claude import CLAUDE_HOST_CAPABILITIES as canonical_claude_cap + from loopx.kunluncode_goal_mode import DEFAULT_AGENT_ID as legacy_kunlun_agent + from loopx.hosts.kunluncode import DEFAULT_AGENT_ID as canonical_kunlun_agent + from loopx.zcode_goal_mode import zcode_home as legacy_zcode_home + from loopx.hosts.zcode import zcode_home as canonical_zcode_home + + assert legacy_claude_cap is canonical_claude_cap + assert legacy_kunlun_agent == canonical_kunlun_agent + assert legacy_zcode_home is canonical_zcode_home + + # Direct file-path execution of runnable legacy shims without PYTHONPATH works identically. + env = {key: value for key, value in os.environ.items() if key != "PYTHONPATH"} + hook_event = json.dumps({"cwd": str(tmp_path), "tool_name": "Bash"}) + for script_path in ( + PACKAGE_ROOT / "hosts" / "claude" / "hooks" / "goal_policy.py", + PACKAGE_ROOT / "claude_goal_mode" / "hooks" / "goal_policy.py", + ): + proc = subprocess.run( + [sys.executable, str(script_path)], + cwd=tmp_path, + env=env, + input=hook_event, + capture_output=True, + text=True, + check=False, + ) + assert proc.returncode == 0, f"{script_path}: {proc.stderr}" + assert json.loads(proc.stdout) == {} + + for help_script in ( + PACKAGE_ROOT / "claude_goal_mode" / "scripts" / "install.py", + PACKAGE_ROOT / "claude_goal_mode" / "scripts" / "connect.py", + PACKAGE_ROOT / "kunluncode_goal_mode" / "cli.py", + PACKAGE_ROOT / "zcode_goal_mode" / "bridge.py", + ): + proc = subprocess.run( + [sys.executable, str(help_script), "--help"], + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + check=False, + ) + assert proc.returncode == 0, f"{help_script} --help: {proc.stderr}" + + +def test_kunluncode_source_root_and_core_prepare_stage_canonical_and_shims( + tmp_path: Path, +) -> None: + assert kunlun_cli._source_root() == REPO_ROOT + + spec = importlib.util.spec_from_file_location( + "batch2_core_prepare", REPO_ROOT / "packages" / "loopx-core" / "prepare.py" + ) + assert spec is not None and spec.loader is not None + prepare_mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(prepare_mod) + + staged = prepare_mod.prepare_core_source(tmp_path / "core-stage") + for rel in ( + "loopx/hosts/claude/__init__.py", + "loopx/hosts/claude/hooks/goal_policy.py", + "loopx/hosts/kunluncode/cli.py", + "loopx/hosts/zcode/bridge.py", + "loopx/claude_goal_mode/__init__.py", + "loopx/claude_goal_mode/hooks/goal_policy.py", + "loopx/claude_goal_mode/scripts/install.py", + "loopx/kunluncode_goal_mode/__init__.py", + "loopx/kunluncode_goal_mode/cli.py", + "loopx/zcode_goal_mode/__init__.py", + "loopx/zcode_goal_mode/bridge.py", + ): + assert (staged / rel).is_file(), rel + + +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 = PACKAGE_ROOT / "hosts" / "claude" + + for base_dir in (expected_plugin, PACKAGE_ROOT / "claude_goal_mode"): + for rel, check_plugin in ( + ("hooks/goal_state.py", False), + ("mcp/loopx_mcp.py", False), + ("scripts/install.py", True), + ("scripts/connect.py", True), + ): + script = base_dir / 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"{script}: {completed.stderr}{completed.stdout}" + + +def test_isolated_wheel_upgrade_preserves_batch2_shims_and_scripts( + tmp_path: Path, +) -> None: + pre_wheel = _build_pre_consolidation_stub_wheel(tmp_path) + wheel = _build_pure_loopx_wheel(tmp_path) + venv_dir = tmp_path / "isolated-venv" + venv.EnvBuilder(with_pip=True, symlinks=os.name != "nt").create(venv_dir) + py_bin = venv_dir / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python") + + for cmd in ( + [ + str(py_bin), + "-I", + "-m", + "pip", + "install", + "--no-index", + "--no-deps", + "--disable-pip-version-check", + str(pre_wheel), + ], + [ + str(py_bin), + "-I", + "-m", + "pip", + "install", + "--no-index", + "--no-deps", + "--disable-pip-version-check", + "--upgrade", + str(wheel), + ], + ): + subprocess.run(cmd, check=True, capture_output=True, text=True, timeout=60) + + work_dir = tmp_path / "work" + work_dir.mkdir() + probe = subprocess.run( + [ + str(py_bin), + "-I", + "-c", + ( + "import importlib.resources as r\n" + "from loopx.claude_goal_mode import CLAUDE_HOST_CAPABILITIES as LC\n" + "from loopx.claude_goal_mode.hooks.goal_policy import decide as LD\n" + "from loopx.claude_goal_mode.hooks.goal_state import active_context as LA\n" + "from loopx.claude_goal_mode.hooks.stdio_utf8 import pin_utf8_stdio as LP\n" + "from loopx.claude_goal_mode.scripts.install import _rewrite_legacy_claude_command as LR\n" + "from loopx.claude_goal_mode.statusline.goal_status import _clip as LCLIP\n" + "from loopx.hosts.claude import CLAUDE_HOST_CAPABILITIES as CC\n" + "from loopx.hosts.claude.hooks.goal_policy import decide as CD\n" + "from loopx.hosts.claude.hooks.goal_state import active_context as CA\n" + "from loopx.hosts.claude.hooks.stdio_utf8 import pin_utf8_stdio as CP\n" + "from loopx.hosts.claude.scripts.install import _rewrite_legacy_claude_command as CR\n" + "from loopx.hosts.claude.statusline.goal_status import _clip as CCLIP\n" + "from loopx.kunluncode_goal_mode import DEFAULT_AGENT_ID as LK_AGENT\n" + "from loopx.kunluncode_goal_mode.cli import main as LK_MAIN\n" + "from loopx.kunluncode_goal_mode.runtime import run_native_goal as LK_RUN\n" + "from loopx.hosts.kunluncode import DEFAULT_AGENT_ID as CK_AGENT\n" + "from loopx.hosts.kunluncode.cli import main as CK_MAIN\n" + "from loopx.hosts.kunluncode.runtime import run_native_goal as CK_RUN\n" + "from loopx.zcode_goal_mode import zcode_home as LZ_HOME\n" + "from loopx.zcode_goal_mode.bridge import _validate_main as LZ_VAL\n" + "from loopx.zcode_goal_mode.diagnostics import INTERFACE_PATTERNS as LZ_PATTERNS\n" + "from loopx.hosts.zcode import zcode_home as CZ_HOME\n" + "from loopx.hosts.zcode.bridge import _validate_main as CZ_VAL\n" + "from loopx.hosts.zcode.diagnostics import INTERFACE_PATTERNS as CZ_PATTERNS\n" + "assert LC is CC and LD is CD and LA is CA and LP is CP and LR is CR and LCLIP is CCLIP\n" + "assert LK_AGENT == CK_AGENT and LK_MAIN is CK_MAIN and LK_RUN is CK_RUN\n" + "assert LZ_HOME is CZ_HOME and LZ_VAL is CZ_VAL and LZ_PATTERNS is CZ_PATTERNS\n" + "assert '/loopx' in r.files('loopx.hosts.claude').joinpath('commands/loopx.md').read_text(encoding='utf-8')\n" + "assert 'PreToolUse' in r.files('loopx.hosts.claude').joinpath('hooks/hooks.json').read_text(encoding='utf-8')\n" + "assert 'actions' in r.files('loopx.hosts.zcode').joinpath('contract.json').read_text(encoding='utf-8')\n" + "assert 'KunlunCode' in r.files('loopx.hosts.kunluncode').joinpath('README.md').read_text(encoding='utf-8')\n" + ), + ], + cwd=work_dir, + capture_output=True, + text=True, + check=False, + ) + assert probe.returncode == 0, probe.stderr + + site_pkg_raw = subprocess.check_output( + [str(py_bin), "-I", "-c", "import loopx, pathlib; print(pathlib.Path(loopx.__file__).parent)"], + cwd=work_dir, + text=True, + ).strip() + site_loopx = Path(site_pkg_raw) + + # Direct file-path execution of legacy scripts in the upgraded venv (as Claude hooks/statusline invoke). + for shim_rel, canonical_rel in ( + ("claude_goal_mode/hooks/goal_policy.py", "hosts/claude/hooks/goal_policy.py"), + ("claude_goal_mode/statusline/goal_status.py", "hosts/claude/statusline/goal_status.py"), + ): + outputs: list[str] = [] + for rel in (shim_rel, canonical_rel): + res = subprocess.run( + [str(py_bin), "-I", str(site_loopx / rel)], + cwd=work_dir, + input=json.dumps({"cwd": str(work_dir), "tool_name": "Bash"}), + capture_output=True, + text=True, + check=False, + ) + assert res.returncode == 0, f"{rel}: {res.stderr}" + outputs.append(res.stdout) + assert outputs[0] == outputs[1] + + for args, shim_rel, canonical_rel in ( + (["--help"], "claude_goal_mode/scripts/install.py", "hosts/claude/scripts/install.py"), + (["--help"], "claude_goal_mode/scripts/connect.py", "hosts/claude/scripts/connect.py"), + (["--help"], "kunluncode_goal_mode/cli.py", "hosts/kunluncode/cli.py"), + (["--validate-binding"], "zcode_goal_mode/bridge.py", "hosts/zcode/bridge.py"), + ): + outputs = [] + for rel in (shim_rel, canonical_rel): + stdin_payload = "{}" if "--validate-binding" in args else None + res = subprocess.run( + [str(py_bin), "-I", str(site_loopx / rel), *args], + cwd=work_dir, + input=stdin_payload, + capture_output=True, + text=True, + check=False, + ) + expected_rc = 1 if "--validate-binding" in args else 0 + assert res.returncode == expected_rc, f"{rel}: rc={res.returncode} stderr={res.stderr}" + if "--validate-binding" in args: + payload = json.loads(res.stdout) + assert payload["error_code"] == "invalid_zcode_goal_binding" + outputs.append(res.stdout) + if "--validate-binding" in args: + assert outputs[0] == outputs[1] + else: + assert all("usage:" in out for out in outputs) + + for args, shim_mod, canonical_mod in ( + (["--help"], "loopx.claude_goal_mode.scripts.install", "loopx.hosts.claude.scripts.install"), + (["--help"], "loopx.kunluncode_goal_mode.cli", "loopx.hosts.kunluncode.cli"), + (["--validate-binding"], "loopx.zcode_goal_mode.bridge", "loopx.hosts.zcode.bridge"), + ): + mod_outputs: list[str] = [] + for mod in (shim_mod, canonical_mod): + stdin_payload = "{}" if "--validate-binding" in args else None + res = subprocess.run( + [str(py_bin), "-I", "-m", mod, *args], + cwd=work_dir, + input=stdin_payload, + capture_output=True, + text=True, + check=False, + ) + expected_rc = 1 if "--validate-binding" in args else 0 + assert res.returncode == expected_rc, f"{mod}: rc={res.returncode} stderr={res.stderr}" + mod_outputs.append(res.stdout) + if "--validate-binding" in args: + assert mod_outputs[0] == mod_outputs[1] + else: + assert all("usage:" in out for out in mod_outputs) + + +def _build_pre_consolidation_claude_wheel(out_dir: Path) -> Path: + """Build a baseline-layout wheel without ``loopx/hosts/claude/``.""" + version = "0.0.0" + metadata = f"loopx-{version}.dist-info" + contents: dict[str, bytes] = {} + excluded_prefixes = ( + "loopx/hosts/claude/", + "loopx/claude_goal_mode/", + "loopx/web/", + ) + for file_path in sorted(PACKAGE_ROOT.rglob("*")): + if not file_path.is_file(): + continue + rel = file_path.relative_to(REPO_ROOT).as_posix() + if "/__pycache__/" in rel or rel.endswith(".pyc") or rel.startswith(excluded_prefixes): + continue + if file_path.suffix not in {".py", ".json", ".ts", ".toml", ".md", ".png", ".js", ".mjs"}: + continue + if rel == "loopx/__init__.py": + text = file_path.read_text(encoding="utf-8") + contents[rel] = text.replace(loopx_version, version, 1).encode("utf-8") + elif rel == "loopx/hosts/capabilities.py": + text = file_path.read_text(encoding="utf-8") + contents[rel] = text.replace( + '"claude": "loopx.hosts.claude"', + '"claude": "loopx.claude_goal_mode"', + ).encode("utf-8") + elif rel == "loopx/goal_mode_mcp.py": + text = file_path.read_text(encoding="utf-8") + contents[rel] = text.replace( + "from .hosts.claude.scripts.goalmode_cmd import", + "from .claude_goal_mode.scripts.goalmode_cmd import", + ).encode("utf-8") + elif rel == "loopx/slash_command_install.py": + text = file_path.read_text(encoding="utf-8") + text = text.replace( + "from loopx.hosts.claude.scripts import install as claude_install", + "from loopx.claude_goal_mode.scripts import install as claude_install", + ) + marker = " try:\n from loopx.claude_goal_mode.scripts import install as claude_install" + assert marker in text + text = text.replace(marker, " return\n" + marker, 1) + contents[rel] = text.encode("utf-8") + else: + contents[rel] = file_path.read_bytes() + + claude_root = PACKAGE_ROOT / "hosts" / "claude" + for file_path in sorted(claude_root.rglob("*")): + if not file_path.is_file(): + continue + sub_rel = file_path.relative_to(claude_root).as_posix() + if "/__pycache__/" in sub_rel or sub_rel.endswith(".pyc"): + continue + rel = f"loopx/claude_goal_mode/{sub_rel}" + if file_path.suffix in {".py", ".json", ".md"}: + text = file_path.read_text(encoding="utf-8") + if sub_rel == "__init__.py": + text = text.replace("from ..capabilities", "from ..hosts.capabilities") + text = text.replace('adapter_module="loopx.hosts.claude"', 'adapter_module="loopx.claude_goal_mode"') + elif sub_rel in { + "hooks/goal_state.py", + "mcp/loopx_mcp.py", + "scripts/connect.py", + "scripts/install.py", + }: + text = text.replace("parents[4]", "parents[3]") + contents[rel] = text.encode("utf-8") + else: + contents[rel] = file_path.read_bytes() + + contents[f"{metadata}/METADATA"] = ( + f"Metadata-Version: 2.1\nName: loopx\nVersion: {version}\n".encode("utf-8") + ) + contents[f"{metadata}/WHEEL"] = ( + b"Wheel-Version: 1.0\nGenerator: test\nRoot-Is-Purelib: true\nTag: py3-none-any\n" + ) + contents[f"{metadata}/RECORD"] = "".join( + f"{name},,\n" for name in [*contents, f"{metadata}/RECORD"] + ).encode("utf-8") + + wheel_path = out_dir / f"loopx-{version}-py3-none-any.whl" + with zipfile.ZipFile(wheel_path, "w") as archive: + for name, data in contents.items(): + archive.writestr(name, data) + return wheel_path + + +def test_two_wheel_claude_upgrade_migration_and_rollback_cycle( + tmp_path: Path, +) -> None: + """5-stage wheel cycle: baseline -> upgrade -> default migrate -> downgrade -> baseline reinstall.""" + baseline_wheel = _build_pre_consolidation_claude_wheel(tmp_path) + candidate_wheel = _build_pure_loopx_wheel(tmp_path) + venv_dir = tmp_path / "rollback-venv" + venv.EnvBuilder(with_pip=True, symlinks=os.name != "nt").create(venv_dir) + py_bin = venv_dir / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python") + bin_dir = py_bin.parent + + home = tmp_path / "home" + user_claude = home / ".claude" + user_claude.mkdir(parents=True) + 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-rb", + "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-rb", + "repo": str(proj), + "source_registry": str(proj / ".loopx" / "registry.json"), + } + ], + } + ), + encoding="utf-8", + ) + proj_claude.mkdir(parents=True) + (proj_claude / "loop.md").write_text( + '\n', + encoding="utf-8", + ) + + isolated_env = { + "PATH": f"{bin_dir}:/usr/bin:/bin", + "HOME": str(home), + "CLAUDE_HOME": str(user_claude), + "LOOPX_RUNTIME_ROOT": str(runtime_root), + "LOOPX_GOAL_FORCE": "1", + } + + def pip_install(wheel: Path, *extra: str) -> None: + subprocess.run( + [ + str(py_bin), + "-I", + "-m", + "pip", + "install", + "--no-index", + "--no-deps", + "--disable-pip-version-check", + *extra, + str(wheel), + ], + check=True, + capture_output=True, + text=True, + timeout=60, + ) + + def site_loopx_dir() -> Path: + raw = subprocess.check_output( + [str(py_bin), "-I", "-c", "import loopx, pathlib; print(pathlib.Path(loopx.__file__).parent)"], + cwd=tmp_path, + text=True, + ).strip() + return Path(raw) + + def replay_all(stage: str) -> None: + settings_data = json.loads((proj_claude / "settings.json").read_text(encoding="utf-8")) + assert settings_data["permissions"] == {"deny": ["Read(~/.ssh/**)"]}, stage + pre_hooks = [ + h["command"] + for g in settings_data["hooks"]["PreToolUse"] + for h in g["hooks"] + ] + assert "echo user-hook-keep" in pre_hooks, stage + + sl_cmd = settings_data["statusLine"]["command"] + sl_proc = subprocess.run( + ["/bin/sh", "-c", sl_cmd], + cwd=proj, + input=json.dumps({"cwd": str(proj)}), + capture_output=True, + text=True, + env=isolated_env, + check=False, + ) + assert sl_proc.returncode == 0, f"{stage} statusLine rc={sl_proc.returncode}: {sl_proc.stderr}" + assert "cc-rb" in sl_proc.stdout, f"{stage} statusLine stdout={sl_proc.stdout!r}" + + cmd_text = (proj_claude / "commands" / "loopx.md").read_text(encoding="utf-8") + assert "" in cmd_text, stage + bang_lines = [ + line.strip() + for line in cmd_text.splitlines() + if line.strip().startswith("!`") and line.strip().endswith("`") + ] + assert len(bang_lines) == 1, f"{stage}: {cmd_text!r}" + slash_cmd = bang_lines[0][2:-1].replace("$ARGUMENTS", "status") + slash_proc = subprocess.run( + ["/bin/sh", "-c", slash_cmd], + cwd=proj, + capture_output=True, + text=True, + env=isolated_env, + check=False, + ) + assert slash_proc.returncode == 0, f"{stage} /loopx status rc={slash_proc.returncode}: {slash_proc.stderr}" + assert "goal : cc-rb" in slash_proc.stdout, f"{stage} /loopx stdout={slash_proc.stdout!r}" + + hook_cmds = [c for c in pre_hooks if "goal_policy.py" in c] + assert len(hook_cmds) == 1, stage + hook_proc = subprocess.run( + ["/bin/sh", "-c", hook_cmds[0]], + cwd=proj, + input=json.dumps({"cwd": str(proj), "tool_name": "Read", "tool_input": {"file_path": "README.md"}}), + capture_output=True, + text=True, + env=isolated_env, + check=False, + ) + assert hook_proc.returncode == 0, f"{stage} PreToolUse rc={hook_proc.returncode}: {hook_proc.stderr}" + + mcp_data = json.loads((proj / ".mcp.json").read_text(encoding="utf-8")) + assert Path(mcp_data["mcpServers"]["loopx"]["args"][0]).is_file(), stage + + # Stage 1: baseline install + pip_install(baseline_wheel) + site_base = site_loopx_dir() + assert not (site_base / "hosts" / "claude").exists() + inst = subprocess.run( + [ + str(py_bin), + "-I", + str(site_base / "claude_goal_mode" / "scripts" / "install.py"), + "--scope", + "project", + "--project", + str(proj), + "--skip-mcp", + "--harden", + ], + cwd=proj, + env=isolated_env, + capture_output=True, + text=True, + check=False, + ) + assert inst.returncode == 0, inst.stderr + inst.stdout + settings = json.loads((proj_claude / "settings.json").read_text(encoding="utf-8")) + settings["permissions"] = {"deny": ["Read(~/.ssh/**)"]} + settings["hooks"]["PreToolUse"].insert( + 0, + {"matcher": "Bash", "hooks": [{"type": "command", "command": "echo user-hook-keep"}]}, + ) + (proj_claude / "settings.json").write_text(json.dumps(settings, indent=2), encoding="utf-8") + loopx_md = proj_claude / "commands" / "loopx.md" + loopx_md.write_text(loopx_md.read_text(encoding="utf-8") + "\n\n", encoding="utf-8") + (proj / ".mcp.json").write_text( + json.dumps( + { + "mcpServers": { + "loopx": { + "command": str(py_bin), + "args": [str(site_base / "claude_goal_mode" / "mcp" / "loopx_mcp.py")], + } + } + } + ), + encoding="utf-8", + ) + replay_all("stage1_baseline") + + # Stage 2: upgrade to candidate wheel before running slash-commands --install + pip_install(candidate_wheel, "--upgrade") + assert (site_loopx_dir() / "hosts" / "claude").is_dir() + replay_all("stage2_upgraded_before_migrate") + + # Stage 3: candidate default slash-commands --install preserves cross-version shim launchers + cand_install = subprocess.run( + [ + str(py_bin), + "-I", + "-m", + "loopx.cli", + "--format", + "json", + "slash-commands", + "--install", + "--codex-home", + str(home / ".codex"), + "--opencode-home", + str(home / ".config" / "opencode"), + ], + cwd=proj, + env=isolated_env, + capture_output=True, + text=True, + check=False, + ) + assert cand_install.returncode == 0, cand_install.stderr + cand_install.stdout + assert json.loads(cand_install.stdout)["ok"] is True + replay_all("stage3_after_candidate_default_install") + + # Stage 4: downgrade back to baseline wheel -> entries stay runnable with zero missing-script errors + pip_install(baseline_wheel, "--force-reinstall") + assert not (site_loopx_dir() / "hosts" / "claude").exists() + replay_all("stage4_downgraded_to_baseline") + + # Stage 5: baseline rollback reinstall command continues working cleanly + base_reinstall = subprocess.run( + [ + str(py_bin), + "-I", + "-m", + "loopx.cli", + "slash-commands", + "--install", + "--codex-home", + str(home / ".codex"), + "--opencode-home", + str(home / ".config" / "opencode"), + ], + cwd=proj, + env=isolated_env, + capture_output=True, + text=True, + check=False, + ) + assert base_reinstall.returncode == 0, base_reinstall.stderr + base_reinstall.stdout + replay_all("stage5_after_baseline_reinstall") diff --git a/tests/test_kiro_cli_mcp.py b/tests/test_kiro_cli_mcp.py index 59e5fbdabf..78732f360b 100644 --- a/tests/test_kiro_cli_mcp.py +++ b/tests/test_kiro_cli_mcp.py @@ -392,7 +392,7 @@ def test_default_install_migrates_stale_managed_kiro_mcp_and_preserves_other_ent ) -> None: """Default `slash-commands --install` (`surfaces=all`, what `self-update` runs) migrates a sidecar-verified Kiro MCP registration whose server path moved.""" - from loopx.claude_goal_mode.scripts import install as claude_install + from loopx.hosts.claude.scripts import install as claude_install provision_calls = 0 diff --git a/tests/test_kunluncode_goal_mode.py b/tests/test_kunluncode_goal_mode.py index afac67688a..d1b349da74 100644 --- a/tests/test_kunluncode_goal_mode.py +++ b/tests/test_kunluncode_goal_mode.py @@ -11,7 +11,7 @@ from loopx import goal_mode_mcp from loopx import cli as loopx_cli -from loopx.claude_goal_mode.hooks.goal_state import goal_context as claude_context +from loopx.hosts.claude.hooks.goal_state import goal_context as claude_context from loopx.goal_mode_mcp import ( GoalModeMCPConfig, GoalModeMCPControlPlane, @@ -26,26 +26,26 @@ source_session_registry_transaction, ) from loopx.file_lock import exclusive_cross_runtime_file_lock -from loopx.kunluncode_goal_mode import cli -from loopx.kunluncode_goal_mode.app_server import ( +from loopx.hosts.kunluncode import cli +from loopx.hosts.kunluncode.app_server import ( NATIVE_GOAL_MODES, KunlunAppServerError, native_goal_success, stable_text_digest, ) -from loopx.kunluncode_goal_mode.context import ( +from loopx.hosts.kunluncode.context import ( goal_context as kunluncode_context, write_binding, ) -from loopx.kunluncode_goal_mode.control_plane import LoopXControlPlane -from loopx.kunluncode_goal_mode.guards import ( +from loopx.hosts.kunluncode.control_plane import LoopXControlPlane +from loopx.hosts.kunluncode.guards import ( NATIVE_CONTROLLER_AGENT_ENV, NATIVE_CONTROLLER_ENV, NATIVE_CONTROLLER_GOAL_ENV, guard_native_controller_writeback, native_controller_cli_write_block, ) -from loopx.kunluncode_goal_mode.runtime import ( +from loopx.hosts.kunluncode.runtime import ( RUNTIME_STATE_SCHEMA_VERSION, KunlunNativeGoalRuntimeError, build_native_goal_objective, @@ -1178,7 +1178,7 @@ def _native_todo(*, claimed: bool = False) -> dict[str, object]: "todo_id": "todo-native-1", "text": "Implement and verify the native Goal Pro adapter.", "claimed_by": "kunlun" if claimed else "", - "required_write_scopes": ["loopx/kunluncode_goal_mode/**"], + "required_write_scopes": ["loopx/hosts/kunluncode/**"], } @@ -1829,3 +1829,89 @@ def test_mcp_pin_has_one_source_of_truth() -> None: assert cli.MCP_REQUIREMENT.startswith("mcp==") assert cli.MCP_SDK_VERSION not in probe_source assert "MCP_SDK_VERSION" in probe_source + + +@pytest.mark.parametrize( + "legacy_script", + ( + "/opt/loopx/loopx/kunluncode_goal_mode/server.py", + r"C:\loopx\loopx\kunluncode_goal_mode\server.py", + ), +) +def test_install_connect_and_uninstall_accept_legacy_kunluncode_goal_mode_server( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + legacy_script: str, +) -> None: + registry = _registry(tmp_path) + calls: list[list[str]] = [] + configured = [ + { + "name": cli.MCP_SERVER_NAME, + "command": "/old/python", + "args": [legacy_script], + } + ] + monkeypatch.setattr(cli.shutil, "which", lambda name: f"/usr/bin/{name}") + monkeypatch.setattr(cli, "_compatible_python", lambda _python: True) + monkeypatch.setattr(cli, "_configured_mcp_servers", lambda _binary: configured) + monkeypatch.setattr(cli, "_loopx_prefix", lambda: ["loopx"]) + + def capture(command: list[str], **_kwargs) -> subprocess.CompletedProcess[str]: + calls.append(command) + return subprocess.CompletedProcess(command, 0, '{"ok": true}', "") + + monkeypatch.setattr(cli, "_run", capture) + + selected = cli.install_mcp( + python="/managed/.venv/bin/python", + dry_run=False, + replace=False, + ) + assert selected == "/managed/.venv/bin/python" + assert calls[0] == ["/usr/bin/kunluncode", "mcp", "remove", cli.MCP_SERVER_NAME] + assert calls[1][-1] == str(cli.MCP_SCRIPT) + + calls.clear() + connected = cli.connect_project( + project=tmp_path, + goal_id="shared-goal", + agent_id="kunlun", + objective=None, + python="/managed/.venv/bin/python", + skip_mcp=False, + replace=False, + dry_run=False, + ) + assert connected["mcp_python"] == "/managed/.venv/bin/python" + assert any( + cmd[:3] == ["/usr/bin/kunluncode", "mcp", "remove"] for cmd in calls + ) + assert json.loads(registry.read_text(encoding="utf-8"))["agent_backends"] == [ + "kunluncode" + ] + + calls.clear() + removed = cli.uninstall_mcp(dry_run=False) + assert removed is True + assert calls == [["/usr/bin/kunluncode", "mcp", "remove", cli.MCP_SERVER_NAME]] + + +def test_uninstall_mcp_still_refuses_user_owned_server( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(cli.shutil, "which", lambda name: f"/usr/bin/{name}") + monkeypatch.setattr( + cli, + "_configured_mcp_servers", + lambda _binary: [ + { + "name": cli.MCP_SERVER_NAME, + "command": "/usr/bin/python3", + "args": ["/home/user/custom/server.py"], + } + ], + ) + + with pytest.raises(RuntimeError, match="user-owned"): + cli.uninstall_mcp(dry_run=False) diff --git a/tests/test_runtime_subprocess_utf8.py b/tests/test_runtime_subprocess_utf8.py index e10400df2c..10e5666d23 100644 --- a/tests/test_runtime_subprocess_utf8.py +++ b/tests/test_runtime_subprocess_utf8.py @@ -16,7 +16,7 @@ from pathlib import Path from loopx.capabilities.change_quality import scope -from loopx.claude_goal_mode.scripts import goalmode_cmd +from loopx.hosts.claude.scripts import goalmode_cmd REPO_ROOT = Path(__file__).resolve().parents[1] diff --git a/tests/test_slash_command_install.py b/tests/test_slash_command_install.py index aa0962a575..3e1bde95a6 100644 --- a/tests/test_slash_command_install.py +++ b/tests/test_slash_command_install.py @@ -1388,3 +1388,1033 @@ def test_antigravity_resident_guidance_is_isolated_to_antigravity_surfaces(tmp_p codex_text = (codex_home / "skills" / "loopx" / "SKILL.md").read_text(encoding="utf-8") assert "Antigravity App fixed resident session" not in codex_text assert "--with-agy-hooks" not in codex_text + + +def _seed_legacy_claude_dir( + claude_dir: Path, + *, + legacy_root: str = "/opt/old-loopx/loopx/claude_goal_mode", + include_custom_statusline: bool = False, +) -> tuple[Path, Path]: + cmd_dir = claude_dir / "commands" + cmd_dir.mkdir(parents=True, exist_ok=True) + cmd_path = cmd_dir / "loopx.md" + cmd_path.write_text( + "---\n" + "description: loopx goal-mode setup. `/loopx ` sets up a goal + writes .claude/loop.md; " + "drive the loop with native /loop. bare /loopx = arm; off | status.\n" + "argument-hint: | (no args = arm) | off | status\n" + "allowed-tools: Bash('/old/python3':*)\n" + "---\n\n" + "Run the loopx setup helper and read its output:\n\n" + f"!`'/old/python3' '{legacy_root}/scripts/goalmode_cmd.py' $ARGUMENTS`\n\n" + "Show it to the user VERBATIM and STOP.\n", + encoding="utf-8", + ) + settings_path = claude_dir / "settings.json" + settings_payload: dict[str, object] = { + "permissions": {"allow": ["Bash(ls:*)"], "deny": ["Read(~/.ssh/**)"]}, + "env": {"CUSTOM_FLAG": "keep"}, + "model": "sonnet", + "hooks": { + "PreToolUse": [ + { + "matcher": "Bash", + "hooks": [{"type": "command", "command": "echo user-owned-hook"}], + }, + { + "matcher": "*", + "hooks": [ + { + "type": "command", + "command": f"/old/python3 '{legacy_root}/hooks/goal_policy.py'", + "timeout": 10, + } + ], + }, + ] + }, + "statusLine": ( + {"type": "command", "command": "custom-user-statusline.sh"} + if include_custom_statusline + else { + "type": "command", + "command": f"/old/python3 '{legacy_root}/statusline/goal_status.py'", + } + ), + } + settings_path.write_text(json.dumps(settings_payload, indent=2), encoding="utf-8") + return cmd_path, settings_path + + +def test_default_install_migrates_legacy_claude_project_and_user_preserving_config( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + import shlex + import subprocess + import sys + + home = tmp_path / "home" + user_claude = home / ".claude" + proj = tmp_path / "proj" + proj_claude = proj / ".claude" + (proj / ".loopx").mkdir(parents=True) + (proj / ".loopx" / "registry.json").write_text( + json.dumps( + { + "schema_version": "0.1", + "goals": [ + { + "id": "cc-proj", + "repo": str(proj), + "coordination": {"agent_model": "peer_v1", "registered_agents": ["cc"]}, + } + ], + } + ), + encoding="utf-8", + ) + runtime_root = home / ".loopx" + runtime_root.mkdir(parents=True) + (runtime_root / "registry.global.json").write_text( + json.dumps( + { + "schema_version": "0.1", + "goals": [ + { + "id": "cc-proj", + "repo": str(proj), + "source_registry": str(proj / ".loopx" / "registry.json"), + } + ], + } + ), + encoding="utf-8", + ) + + user_cmd, user_settings = _seed_legacy_claude_dir(user_claude, include_custom_statusline=True) + proj_cmd, proj_settings = _seed_legacy_claude_dir(proj_claude, include_custom_statusline=False) + proj_mcp = proj / ".mcp.json" + proj_mcp.write_text( + json.dumps( + { + "mcpServers": { + "other": {"command": "other-bin", "args": ["--serve"]}, + "loopx": { + "command": "/old/python3", + "args": ["/opt/old-loopx/loopx/claude_goal_mode/mcp/loopx_mcp.py"], + }, + } + } + ), + encoding="utf-8", + ) + + # Dry-run reports planned migrations without writing any file. + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("CLAUDE_HOME", str(user_claude)) + monkeypatch.delenv("LOOPX_RUNTIME_ROOT", raising=False) + monkeypatch.chdir(tmp_path) + + before_proj_cmd = proj_cmd.read_text(encoding="utf-8") + before_proj_settings = proj_settings.read_text(encoding="utf-8") + dry_payload = install_slash_commands( + execute=False, + codex_home=str(home / ".codex"), + opencode_home=str(home / ".config" / "opencode"), + ) + assert dry_payload["ok"] is True + assert proj_cmd.read_text(encoding="utf-8") == before_proj_cmd + assert proj_settings.read_text(encoding="utf-8") == before_proj_settings + migrated_dry = [ + row + for row in dry_payload["installed"] # type: ignore[attr-defined] + if isinstance(row, dict) and row.get("mechanism") == "claude_goal_mode_legacy_migration" + ] + assert {row["status"] for row in migrated_dry} == {"would_write"} + assert len(migrated_dry) == 5 + + # Default install migrates both user and project entries cleanly while preserving user config. + applied = install_slash_commands( + execute=True, + codex_home=str(home / ".codex"), + opencode_home=str(home / ".config" / "opencode"), + ) + assert applied["ok"] is True + migrated = [ + row + for row in applied["installed"] # type: ignore[attr-defined] + if isinstance(row, dict) and row.get("mechanism") == "claude_goal_mode_legacy_migration" + ] + assert {row["status"] for row in migrated} == {"updated"} + assert len(migrated) == 5 + + # Idempotent on repeated default install. + second = install_slash_commands( + execute=True, + codex_home=str(home / ".codex"), + opencode_home=str(home / ".config" / "opencode"), + ) + assert not any( + isinstance(row, dict) and row.get("mechanism") == "claude_goal_mode_legacy_migration" + for row in second["installed"] # type: ignore[attr-defined] + ) + + user_settings_data = json.loads(user_settings.read_text(encoding="utf-8")) + assert user_settings_data["statusLine"] == {"type": "command", "command": "custom-user-statusline.sh"} + assert "/loopx/hosts/claude/commands/" not in user_cmd.read_text(encoding="utf-8") + assert "/loopx/hosts/claude/scripts/goalmode_cmd.py" in user_cmd.read_text(encoding="utf-8") + + proj_settings_data = json.loads(proj_settings.read_text(encoding="utf-8")) + assert proj_settings_data["permissions"] == {"allow": ["Bash(ls:*)"], "deny": ["Read(~/.ssh/**)"]} + assert proj_settings_data["env"] == {"CUSTOM_FLAG": "keep"} + assert proj_settings_data["model"] == "sonnet" + hooks_cmds = [ + h["command"] + for g in proj_settings_data["hooks"]["PreToolUse"] + for h in g["hooks"] + ] + assert "echo user-owned-hook" in hooks_cmds + assert any("/loopx/hosts/claude/hooks/goal_policy.py" in c for c in hooks_cmds) + assert "/loopx/hosts/claude/statusline/goal_status.py" in proj_settings_data["statusLine"]["command"] + + mcp_data = json.loads(proj_mcp.read_text(encoding="utf-8")) + assert mcp_data["mcpServers"]["other"] == {"command": "other-bin", "args": ["--serve"]} + assert mcp_data["mcpServers"]["loopx"]["args"][0].endswith("/loopx/hosts/claude/mcp/loopx_mcp.py") + + # Execute the migrated /loopx status command and statusLine command verbatim against proj. + cmd_lines = [ + line.strip() + for line in proj_cmd.read_text(encoding="utf-8").splitlines() + if line.strip().startswith("!`") and line.strip().endswith("`") + ] + assert len(cmd_lines) == 1 + status_tokens = shlex.split(cmd_lines[0][2:-1].replace("$ARGUMENTS", "status")) + status_run = subprocess.run( + status_tokens, + cwd=str(proj), + capture_output=True, + text=True, + env={**slash_command_install.os.environ, "HOME": str(home), "PYTHONPATH": str(Path(__file__).resolve().parents[1])}, + check=False, + ) + assert status_run.returncode == 0, status_run.stderr + status_run.stdout + assert "goal : cc-proj" in status_run.stdout + + sl_tokens = shlex.split(proj_settings_data["statusLine"]["command"]) + sl_run = subprocess.run( + sl_tokens, + input=json.dumps({"cwd": str(proj)}), + capture_output=True, + text=True, + env={**slash_command_install.os.environ, "HOME": str(home), "PYTHONPATH": str(Path(__file__).resolve().parents[1])}, + check=False, + ) + assert sl_run.returncode == 0, sl_run.stderr + sl_run.stdout + assert sys.executable + + +def test_claude_legacy_migration_skips_targeted_uninstall_and_unowned_or_corrupt_files( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + home = tmp_path / "home" + user_claude = home / ".claude" + _seed_legacy_claude_dir(user_claude) + user_cmd = user_claude / "commands" / "loopx.md" + user_settings = user_claude / "settings.json" + before_cmd = user_cmd.read_bytes() + before_settings = user_settings.read_bytes() + + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("CLAUDE_HOME", str(user_claude)) + monkeypatch.chdir(tmp_path) + + # 1. Explicit --surface codex never probes or modifies Claude configs. + monkeypatch.setattr( + slash_command_install, + "_migrate_legacy_claude_configs", + lambda **_kw: pytest.fail("explicit --surface codex must not probe legacy Claude configs"), + ) + codex_payload = install_slash_commands( + execute=True, + surfaces=["codex"], + codex_home=str(home / ".codex"), + ) + assert codex_payload["ok"] is True + assert user_cmd.read_bytes() == before_cmd + assert user_settings.read_bytes() == before_settings + + # 2. --uninstall never migrates legacy Claude configs. + monkeypatch.undo() + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("CLAUDE_HOME", str(user_claude)) + monkeypatch.chdir(tmp_path) + uninstall_payload = install_slash_commands( + execute=True, + uninstall=True, + codex_home=str(home / ".codex"), + opencode_home=str(home / ".config" / "opencode"), + ) + assert uninstall_payload["ok"] is True + assert user_cmd.read_bytes() == before_cmd + assert user_settings.read_bytes() == before_settings + + # 3. Unowned commands/loopx.md and non-UTF-8 settings.json / global registry fail closed cleanly. + user_cmd.write_text("---\ndescription: user custom loopx\n---\n!`echo custom`\n", encoding="utf-8") + custom_cmd_bytes = user_cmd.read_bytes() + user_settings.write_bytes(b"\xff\xfe\x00not-utf8-settings") + corrupt_settings_bytes = user_settings.read_bytes() + (home / ".loopx").mkdir(parents=True, exist_ok=True) + (home / ".loopx" / "registry.global.json").write_bytes(b"\xff\xfe\x00bad-registry") + + default_payload = install_slash_commands( + execute=True, + codex_home=str(home / ".codex"), + opencode_home=str(home / ".config" / "opencode"), + ) + assert default_payload["ok"] is True + assert user_cmd.read_bytes() == custom_cmd_bytes + assert user_settings.read_bytes() == corrupt_settings_bytes + + +def test_claude_legacy_migration_preserves_wrapped_commands_and_reads_v2_envelope( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + import hashlib + import sys + + from loopx.control_plane.projects.registry_codec import ( + SOURCE_SESSION_PROFILE_ID, + SOURCE_SESSION_SCHEMA_VERSION, + SOURCE_SESSION_WRITER_PROTOCOL, + ) + from loopx.hosts.claude.scripts import install as claude_install + + home = tmp_path / "home" + user_claude = home / ".claude" + user_claude.mkdir(parents=True) + proj = tmp_path / "proj-v2" + (proj / ".loopx").mkdir(parents=True) + payload = { + "schema_version": "0.1", + "profile_id": SOURCE_SESSION_PROFILE_ID, + "goals": [{"id": "cc-v2", "repo": str(proj)}], + } + digest = "sha256:" + hashlib.sha256( + json.dumps( + payload, + ensure_ascii=False, + allow_nan=False, + sort_keys=True, + separators=(",", ":"), + ).encode("utf-8") + ).hexdigest() + (proj / ".loopx" / "registry.json").write_text( + json.dumps( + [ + { + "schema_version": SOURCE_SESSION_SCHEMA_VERSION, + "minimum_writer_protocol": SOURCE_SESSION_WRITER_PROTOCOL, + "payload_sha256": digest, + }, + payload, + ], + ensure_ascii=False, + allow_nan=False, + indent=2, + ) + + "\n", + encoding="utf-8", + ) + + proj_claude = proj / ".claude" + proj_claude.mkdir(parents=True) + proj_settings = proj_claude / "settings.json" + proj_settings.write_text( + json.dumps( + { + "hooks": { + "PreToolUse": [ + { + "matcher": "*", + "hooks": [ + { + "type": "command", + "command": ( + "env FOO=bar /old/python3 " + "/opt/old/loopx/claude_goal_mode/hooks/goal_policy.py --flag" + ), + "timeout": 10, + }, + { + "type": "command", + "command": ( + "sh -c 'BAR=\"a b\" /old/python3 -I " + "\"/opt/old/loopx/claude_goal_mode/hooks/goal_policy.py\" --inner'" + ), + }, + ], + } + ] + }, + "statusLine": { + "type": "command", + "command": ( + "env BAZ='x y' /old/python3 -u " + "\"/opt/old/loopx/claude_goal_mode/statusline/goal_status.py\" --compact" + ), + }, + } + ), + encoding="utf-8", + ) + + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("CLAUDE_HOME", str(user_claude)) + monkeypatch.delenv("LOOPX_RUNTIME_ROOT", raising=False) + elsewhere = tmp_path / "elsewhere" + elsewhere.mkdir() + monkeypatch.chdir(elsewhere) + + assert slash_command_install._projects_from_registry_file(proj / ".loopx" / "registry.json") == [proj] + + result = install_slash_commands( + execute=True, + registry_path=str(proj / ".loopx" / "registry.json"), + codex_home=str(home / ".codex"), + opencode_home=str(home / ".config" / "opencode"), + ) + assert result["ok"] is True + + migrated = json.loads(proj_settings.read_text(encoding="utf-8")) + hook_cmds = [h["command"] for h in migrated["hooks"]["PreToolUse"][0]["hooks"]] + assert hook_cmds[0].startswith("env FOO=bar ") + assert "/old/python3" not in hook_cmds[0] + assert sys.executable in hook_cmds[0] + assert "/loopx/hosts/claude/hooks/goal_policy.py" in hook_cmds[0] + assert hook_cmds[0].endswith(" --flag") + + assert "BAR=\"a b\"" in hook_cmds[1] + assert "/loopx/hosts/claude/hooks/goal_policy.py" in hook_cmds[1] + assert hook_cmds[1].endswith("--inner'") + + sl_cmd = migrated["statusLine"]["command"] + assert sl_cmd.startswith("env BAZ='x y' ") + assert " -u " in sl_cmd + assert "/loopx/hosts/claude/statusline/goal_status.py" in sl_cmd + assert sl_cmd.endswith(" --compact") + + # Idempotent after migration. + assert claude_install._migrated_settings_payload(migrated, py_exe=sys.executable) is None + + # PowerShell wrapped command preserves `&`, prefix, and flags. + ps_migrated = claude_install._rewrite_legacy_claude_command( + "& 'C:\\old\\python.exe' 'C:\\old\\loopx\\claude_goal_mode\\hooks\\goal_policy.py' --flag", + legacy_suffix=claude_install._LEGACY_POLICY_HOOK_SUFFIX, + new_script=claude_install._p("hooks", "goal_policy.py"), + py_exe="/new/python.exe", + powershell=True, + ) + assert ps_migrated is not None + assert ps_migrated.startswith("& '/new/python.exe' ") + assert ps_migrated.endswith(" --flag") + assert "& &" not in ps_migrated + + +def test_claude_legacy_migration_command_position_and_operator_boundaries( + tmp_path: Path, +) -> None: + import shlex + import subprocess + import sys + + from loopx.hosts.claude.scripts import install as claude_install + + home = tmp_path / "home" + user_claude = home / ".claude" + user_claude.mkdir(parents=True) + proj = tmp_path / "proj-cmd-pos" + (proj / ".loopx").mkdir(parents=True) + (proj / ".loopx" / "registry.json").write_text( + json.dumps( + { + "schema_version": "0.1", + "goals": [ + { + "id": "cc-pos", + "repo": str(proj), + "coordination": {"agent_model": "peer_v1", "registered_agents": ["cc"]}, + } + ], + } + ), + encoding="utf-8", + ) + runtime_root = home / ".loopx" + runtime_root.mkdir(parents=True) + (runtime_root / "registry.global.json").write_text( + json.dumps( + { + "schema_version": "0.1", + "goals": [ + { + "id": "cc-pos", + "repo": str(proj), + "source_registry": str(proj / ".loopx" / "registry.json"), + } + ], + } + ), + encoding="utf-8", + ) + + legacy_status = "/opt/old dir/loopx/claude_goal_mode/statusline/goal_status.py" + legacy_hook = "/opt/old/loopx/claude_goal_mode/hooks/goal_policy.py" + new_status = claude_install._p("statusline", "goal_status.py") + new_hook = claude_install._p("hooks", "goal_policy.py") + + # Data-argument, query, redirection, and non-script Python invocations stay untouched. + untouched_commands = [ + f"printf '%s\\n' {shlex.quote(legacy_status)}", + f"echo {shlex.quote(legacy_status)}", + f"FOO=1 env BAR=2 printf '%s\\n' {shlex.quote(legacy_status)}", + f"command -v {shlex.quote(legacy_status)}", + f"cat <{shlex.quote(legacy_status)}", + f"echo hi>{shlex.quote(legacy_status)}", + f"/old/python3 -c \"print('{legacy_status}')\"", + f"/old/python3 -m user_tool {shlex.quote(legacy_status)}", + f"/old/python3 /user/custom_tool.py {shlex.quote(legacy_status)}", + f"sh -c 'printf \"%s\\n\" \"{legacy_status}\"'", + f"FOO={shlex.quote(legacy_status)} printf '%s\\n' ok", + ] + for raw in untouched_commands: + assert ( + claude_install._rewrite_legacy_claude_command( + raw, + legacy_suffix=claude_install._LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=new_status, + py_exe=sys.executable, + powershell=False, + ) + is None + ), raw + + # Executed commands right before adjacent unquoted shell operators migrate cleanly. + adjacent_status = f"/old/python3 -u {shlex.quote(legacy_status)}&&echo AFTER_STATUS" + migrated_adj = claude_install._rewrite_legacy_claude_command( + adjacent_status, + legacy_suffix=claude_install._LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=new_status, + py_exe=sys.executable, + powershell=False, + ) + assert migrated_adj is not None + assert migrated_adj.endswith("&&echo AFTER_STATUS") + assert "/old/python3" not in migrated_adj + assert " -u " in migrated_adj + assert new_status in migrated_adj + + # Direct adjacent operator with no interpreter prefix and pipe/semicolon/or-else boundaries. + for sep in ("&&", "||", ";", "|"): + direct_cmd = f"/opt/old{legacy_hook.removeprefix('/opt/old')}{sep}cat" + migrated_direct = claude_install._rewrite_legacy_claude_command( + direct_cmd, + legacy_suffix=claude_install._LEGACY_POLICY_HOOK_SUFFIX, + new_script=new_hook, + py_exe=sys.executable, + powershell=False, + ) + assert migrated_direct is not None, sep + assert migrated_direct.endswith(f"{sep}cat") + assert new_hook in migrated_direct + assert "/claude_goal_mode/" not in migrated_direct + + # Mixed print-then-execute leaves the printed data arg intact and upgrades only the launcher. + print_then_run_adj = f"printf '%s\\n' {shlex.quote(legacy_status)}&&/old/python3 {shlex.quote(legacy_status)}" + migrated_mix = claude_install._rewrite_legacy_claude_command( + print_then_run_adj, + legacy_suffix=claude_install._LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=new_status, + py_exe=sys.executable, + powershell=False, + ) + assert migrated_mix is not None + head_part, tail_part = migrated_mix.split("&&", 1) + assert head_part == f"printf '%s\\n' {shlex.quote(legacy_status)}" + assert "/old/python3" not in tail_part + assert new_status in tail_part + + # Nested sh -c with both print-data segment and adjacent executed launcher. + nested_mix = f"env WRAP=1 sh -ec 'printf \"%s\\n\" \"{legacy_status}\"&&/old/python3 \"{legacy_status}\"'" + migrated_nested = claude_install._rewrite_legacy_claude_command( + nested_mix, + legacy_suffix=claude_install._LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=new_status, + py_exe=sys.executable, + powershell=False, + ) + assert migrated_nested is not None + assert legacy_status in migrated_nested + assert new_status in migrated_nested + assert "/old/python3" not in migrated_nested + + # PowerShell mixed literal arg + executed command keeps literal arg and `&`. + ps_mix = ( + "printf '%s' 'C:\\old\\loopx\\claude_goal_mode\\statusline\\goal_status.py'; " + "& 'C:\\old\\python.exe' 'C:\\old\\loopx\\claude_goal_mode\\statusline\\goal_status.py'" + ) + migrated_ps_mix = claude_install._rewrite_legacy_claude_command( + ps_mix, + legacy_suffix=claude_install._LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=new_status, + py_exe="/new/python.exe", + powershell=True, + ) + assert migrated_ps_mix is not None + assert migrated_ps_mix.startswith( + "printf '%s' 'C:\\old\\loopx\\claude_goal_mode\\statusline\\goal_status.py'; & '/new/python.exe' " + ) + + # Full migrate_legacy_claude_dir + actual /bin/sh execution for print-only, adjacent-&&, and print-then-launch. + env_exec = { + **slash_command_install.os.environ, + "HOME": str(home), + "LOOPX_RUNTIME_ROOT": str(runtime_root), + "LOOPX_GOAL_FORCE": "1", + "PYTHONPATH": str(Path(__file__).resolve().parents[1]), + "PATH": f"{Path(sys.executable).parent}:{slash_command_install.os.environ.get('PATH', '')}", + } + proj_claude = proj / ".claude" + proj_claude.mkdir(parents=True) + (proj_claude / "loop.md").write_text("\n", encoding="utf-8") + proj_settings = proj_claude / "settings.json" + cases = [ + ("print_only", f"printf '%s\\n' {shlex.quote(legacy_status)}", legacy_status, False), + ("adjacent_and", f"/old/python3 {shlex.quote(legacy_status)}&&echo CHAIN_OK", "CHAIN_OK", True), + ( + "print_then_launch", + f"printf '%s\\n' {shlex.quote(legacy_status)}&&/old/python3 {shlex.quote(legacy_status)}", + legacy_status, + True, + ), + ] + for name, raw_cmd, expected_line, expect_status_output in cases: + proj_settings.write_text( + json.dumps({"statusLine": {"type": "command", "command": raw_cmd}}), + encoding="utf-8", + ) + res = claude_install.migrate_legacy_claude_dir(proj_claude, project_dir=proj, execute=True) + if expect_status_output: + assert res == [{"path": str(proj_settings), "status": "updated"}], name + else: + assert res == [], name + updated_cmd = json.loads(proj_settings.read_text(encoding="utf-8"))["statusLine"]["command"] + proc = subprocess.run( + ["/bin/sh", "-c", updated_cmd], + input=json.dumps({"cwd": str(proj)}), + capture_output=True, + text=True, + env=env_exec, + check=False, + ) + assert proc.returncode == 0, f"{name}: {proc.stderr} {proc.stdout}" + assert expected_line in proc.stdout, (name, proc.stdout) + if expect_status_output: + assert "cc-pos" in proc.stdout, (name, proc.stdout) + # Idempotent on repeat run. + assert claude_install.migrate_legacy_claude_dir(proj_claude, project_dir=proj, execute=True) == [] + + +def test_claude_legacy_migration_heredocs_compound_clauses_and_manual_diagnostics( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + import shlex + import subprocess + import sys + + from loopx.hosts.claude.scripts import install as claude_install + + home = tmp_path / "home" + user_claude = home / ".claude" + user_claude.mkdir(parents=True) + proj = tmp_path / "proj-compound" + (proj / ".loopx").mkdir(parents=True) + (proj / ".loopx" / "registry.json").write_text( + json.dumps( + { + "schema_version": "0.1", + "goals": [ + { + "id": "cc-comp", + "repo": str(proj), + "coordination": {"agent_model": "peer_v1", "registered_agents": ["cc"]}, + } + ], + } + ), + encoding="utf-8", + ) + runtime_root = home / ".loopx" + runtime_root.mkdir(parents=True) + (runtime_root / "registry.global.json").write_text( + json.dumps( + { + "schema_version": "0.1", + "goals": [ + { + "id": "cc-comp", + "repo": str(proj), + "source_registry": str(proj / ".loopx" / "registry.json"), + } + ], + } + ), + encoding="utf-8", + ) + + legacy_status = "/opt/old dir/loopx/claude_goal_mode/statusline/goal_status.py" + legacy_hook = "/opt/old/loopx/claude_goal_mode/hooks/goal_policy.py" + new_status = claude_install._p("statusline", "goal_status.py") + new_hook = claude_install._p("hooks", "goal_policy.py") + + # 1. Quoted/tab-stripped here-document bodies remain byte-verbatim (even with unmatched quotes), + # while executable launchers on the header line or after the closing delimiter migrate. + heredoc_only = f"cat <<'EOF'\n{legacy_status}\nEOF" + assert claude_install._inspect_legacy_claude_command( + heredoc_only, + legacy_suffix=claude_install._LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=new_status, + py_exe=sys.executable, + powershell=False, + ) == (None, None) + + heredoc_and_post = ( + f"cat <<'EOF'\n{legacy_status}\nit's raw text\nEOF\n" + f"/old/python3 {shlex.quote(legacy_status)}" + ) + migrated_hd, hd_reason = claude_install._inspect_legacy_claude_command( + heredoc_and_post, + legacy_suffix=claude_install._LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=new_status, + py_exe=sys.executable, + powershell=False, + ) + assert hd_reason is None + assert migrated_hd is not None + hd_prefix, hd_tail = migrated_hd.split("\nEOF\n", 1) + assert hd_prefix == f"cat <<'EOF'\n{legacy_status}\nit's raw text" + assert "/old/python3" not in hd_tail + assert new_status in hd_tail + + tab_heredoc = ( + f"cat <<-EOF && echo ok\n\t{legacy_status}\n\tEOF\n" + f"{legacy_hook}" + ) + migrated_tab = claude_install._rewrite_legacy_claude_command( + tab_heredoc, + legacy_suffix=claude_install._LEGACY_POLICY_HOOK_SUFFIX, + new_script=new_hook, + py_exe=sys.executable, + powershell=False, + ) + assert migrated_tab is not None + assert migrated_tab.startswith(f"cat <<-EOF && echo ok\n\t{legacy_status}\n\tEOF\n") + assert migrated_tab.endswith(shlex.quote(new_hook)) + + # 2. Compound POSIX control clauses migrate executed positions while skipping loop lists, + # case patterns, and quoted keyword literals. + if_cmd = f"if [ -n \"$HOME\" ]; then /old/python3 {shlex.quote(legacy_status)}; fi" + migrated_if = claude_install._rewrite_legacy_claude_command( + if_cmd, + legacy_suffix=claude_install._LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=new_status, + py_exe=sys.executable, + powershell=False, + ) + assert migrated_if is not None + assert migrated_if.startswith("if [ -n \"$HOME\" ]; then ") + assert migrated_if.endswith("; fi") + assert new_status in migrated_if and "/old/python3" not in migrated_if + + elif_else_cmd = ( + f"if {legacy_hook}; then echo a; elif {legacy_hook}; then echo b; " + f"else /old/python3 {legacy_hook}; fi" + ) + migrated_branch = claude_install._rewrite_legacy_claude_command( + elif_else_cmd, + legacy_suffix=claude_install._LEGACY_POLICY_HOOK_SUFFIX, + new_script=new_hook, + py_exe=sys.executable, + powershell=False, + ) + assert migrated_branch is not None + assert "/claude_goal_mode/" not in migrated_branch + assert migrated_branch.count(new_hook) == 3 + + brace_subshell_while = ( + f"while {legacy_hook}; do {{ /old/python3 {legacy_hook}; }}; done && ( {legacy_hook} )" + ) + migrated_complex = claude_install._rewrite_legacy_claude_command( + brace_subshell_while, + legacy_suffix=claude_install._LEGACY_POLICY_HOOK_SUFFIX, + new_script=new_hook, + py_exe=sys.executable, + powershell=False, + ) + assert migrated_complex is not None + assert "/claude_goal_mode/" not in migrated_complex + assert migrated_complex.count(new_hook) == 3 + + # Non-command positions in for/case/quoted-'then' stay intact; case arm body updates. + for_non_exec = f"for s in {shlex.quote(legacy_status)}; do echo \"$s\"; done" + assert claude_install._rewrite_legacy_claude_command( + for_non_exec, + legacy_suffix=claude_install._LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=new_status, + py_exe=sys.executable, + powershell=False, + ) is None + assert claude_install._rewrite_legacy_claude_command( + f"'then' {shlex.quote(legacy_status)}", + legacy_suffix=claude_install._LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=new_status, + py_exe=sys.executable, + powershell=False, + ) is None + + case_cmd = ( + f"case \"$MODE\" in {shlex.quote(legacy_status)}) echo pat;; " + f"run) /old/python3 {shlex.quote(legacy_status)};; esac" + ) + migrated_case = claude_install._rewrite_legacy_claude_command( + case_cmd, + legacy_suffix=claude_install._LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=new_status, + py_exe=sys.executable, + powershell=False, + ) + assert migrated_case is not None + first_arm, second_arm = migrated_case.split(";;", 1) + assert shlex.quote(legacy_status) in first_arm + assert new_status in second_arm and "/old/python3" not in second_arm + + # 3. Execute real migrated heredoc-then-launch and if/then statusLine commands via /bin/sh. + env_exec = { + **slash_command_install.os.environ, + "HOME": str(home), + "LOOPX_RUNTIME_ROOT": str(runtime_root), + "LOOPX_GOAL_FORCE": "1", + "PYTHONPATH": str(Path(__file__).resolve().parents[1]), + "PATH": f"{Path(sys.executable).parent}:{slash_command_install.os.environ.get('PATH', '')}", + } + proj_claude = proj / ".claude" + proj_claude.mkdir(parents=True) + (proj_claude / "loop.md").write_text("\n", encoding="utf-8") + proj_settings = proj_claude / "settings.json" + for label, raw_cmd, expected_verbatim in ( + ("heredoc_then_launch", heredoc_and_post, f"{legacy_status}\nit's raw text\n"), + ("if_then_branch", if_cmd, ""), + ): + proj_settings.write_text( + json.dumps({"statusLine": {"type": "command", "command": raw_cmd}}), + encoding="utf-8", + ) + mig = claude_install.migrate_legacy_claude_dir(proj_claude, project_dir=proj, execute=True) + assert mig == [{"path": str(proj_settings), "status": "updated"}], label + updated_cmd = json.loads(proj_settings.read_text(encoding="utf-8"))["statusLine"]["command"] + proc = subprocess.run( + ["/bin/sh", "-c", updated_cmd], + input=json.dumps({"cwd": str(proj)}), + capture_output=True, + text=True, + env=env_exec, + check=False, + ) + assert proc.returncode == 0, f"{label}: {proc.stderr} {proc.stdout}" + if expected_verbatim: + assert proc.stdout.startswith(expected_verbatim), (label, proc.stdout) + assert "cc-comp" in proc.stdout, (label, proc.stdout) + + # 4. Uncertifiable dynamic syntax (`eval` / `env -S` / unterminated heredoc) stays untouched + # and reports `manual_migration_required` with explicit recovery guidance through install_slash_commands. + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("CLAUDE_HOME", str(user_claude)) + monkeypatch.setenv("LOOPX_RUNTIME_ROOT", str(runtime_root)) + monkeypatch.chdir(tmp_path) + + for bad_cmd in ( + f"eval '/old/python3 {shlex.quote(legacy_status)}'", + f"env -S '/old/python3 {shlex.quote(legacy_status)}'", + f"cat <`.\n" + f"allowed-tools: Bash({shlex.quote(sys.executable)}:*)\n" + "---\n" + f"!`{shlex.quote(sys.executable)} {shlex.quote(live_cmd_shim)} $ARGUMENTS`\n" + "\n" + ) + assert claude_install._migrated_command_md_text(live_md, py_exe=sys.executable) is None + + broken_py_live_md = live_md.replace(shlex.quote(sys.executable), "'/old/python3'") + migrated_broken_md = claude_install._migrated_command_md_text(broken_py_live_md, py_exe=sys.executable) + assert migrated_broken_md is not None + assert "/loopx/hosts/claude/scripts/goalmode_cmd.py" in migrated_broken_md + assert "" in migrated_broken_md + + assert claude_install._inspect_legacy_claude_command( + f"{shlex.quote(sys.executable)} {shlex.quote(live_status_shim)}", + legacy_suffix=claude_install._LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=new_status, + py_exe=sys.executable, + powershell=False, + ) == (None, None) + + mixed_live_and_stale = ( + f"{shlex.quote(sys.executable)} {shlex.quote(live_status_shim)} && " + f"/old/python3 {shlex.quote(legacy_status)}" + ) + migrated_mixed, mixed_reason = claude_install._inspect_legacy_claude_command( + mixed_live_and_stale, + legacy_suffix=claude_install._LEGACY_STATUSLINE_SCRIPT_SUFFIX, + new_script=new_status, + py_exe=sys.executable, + powershell=False, + ) + assert mixed_reason is None + assert migrated_mixed is not None + assert migrated_mixed.startswith(f"{shlex.quote(sys.executable)} {shlex.quote(live_status_shim)} && ") + assert new_status in migrated_mixed and "/old/python3" not in migrated_mixed + + assert claude_install._migrated_mcp_json_payload( + {"mcpServers": {"loopx": {"command": sys.executable, "args": [live_mcp_shim]}}} + ) is None + assert claude_install._migrated_mcp_json_payload( + {"mcpServers": {"loopx": {"command": "/old/python3", "args": [live_mcp_shim]}}} + )["mcpServers"]["loopx"]["args"][0].endswith("/loopx/hosts/claude/mcp/loopx_mcp.py") + assert claude_install._inspect_legacy_claude_command( + f"/old/python3 {shlex.quote(live_hook_shim)}", + legacy_suffix=claude_install._LEGACY_POLICY_HOOK_SUFFIX, + new_script=new_hook, + py_exe=sys.executable, + powershell=False, + )[0] is not None diff --git a/tests/test_slash_command_install_equivalence.py b/tests/test_slash_command_install_equivalence.py index f378406639..c17f4ef6a3 100644 --- a/tests/test_slash_command_install_equivalence.py +++ b/tests/test_slash_command_install_equivalence.py @@ -47,12 +47,16 @@ def _load_baseline_module( module.__file__ = str(REPOSITORY_ROOT / relpath) module.__package__ = "loopx" # Historical commit e5d5945f6 imported kiro_cli_goal_mode, opencode_goal_mode, - # and pi_goal_mode before those packages moved under loopx/hosts/; agy_goal_mode - # continues resolving via its compatibility shim. + # pi_goal_mode, zcode_goal_mode, and claude_goal_mode before those packages + # moved under loopx/hosts/; agy_goal_mode continues resolving via its + # compatibility shim. compiled_source = ( source.replace("from .kiro_cli_goal_mode", "from .hosts.kiro_cli") .replace("from .opencode_goal_mode", "from .hosts.opencode") .replace("from .pi_goal_mode", "from .hosts.pi") + .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 ) 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 45cf9059b5..efa5bbbab4 100644 --- a/tsconfig.control-plane.json +++ b/tsconfig.control-plane.json @@ -17,7 +17,7 @@ "tests/control_plane_ts/session_binding.test.ts", "tests/control_plane_ts/host_failure_policy.test.ts", "tests/control_plane_ts/host_harness_capabilities.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",