From 6650ff7ff48a3d861518cf16633da3013705bb41 Mon Sep 17 00:00:00 2001 From: masongyan Date: Fri, 30 Oct 2026 10:48:11 +0800 Subject: [PATCH] feat: add OpenCode host support Add a first-class OpenCode V2 Host Kit and plugin package that registers HelixHarness commands, method skills and subagent roles from the canonical resources instead of copying Markdown into .opencode/. - add hosts/opencode manifest, runtime, subagent, UT, lifecycle, project config and installer resources - add opencode/index.ts + core.ts with Host Context injection, argument substitution, native subagent mappings and repo_root binding for skills - add Bun unit, registration and real-server E2E tests - add Python Host Kit, detector, telemetry/update and feedback coverage - document OpenCode installation, verification and Workspace depth setup --- .claude-plugin/marketplace.json | 4 +- README.md | 19 +- README.zh-CN.md | 19 +- docs/installation.md | 33 +- docs/user-guide.md | 26 +- docs/user-guide.zh-CN.md | 26 +- docs/workflow-architecture.md | 13 +- examples/README.md | 2 +- helixharness/.claude-plugin/marketplace.json | 4 +- helixharness/.claude-plugin/plugin.json | 2 +- helixharness/.gitignore | 2 + helixharness/AGENTS.md | 2 +- helixharness/PLUGIN_USAGE.md | 6 +- helixharness/README.md | 8 +- .../hosts/opencode/command-projection.json | 15 + helixharness/hosts/opencode/host.json | 50 ++ helixharness/hosts/opencode/installer.md | 72 ++ helixharness/hosts/opencode/lifecycle.md | 19 + .../hosts/opencode/project-hooks.json | 8 + helixharness/hosts/opencode/project.json | 6 + helixharness/hosts/opencode/runtime.md | 75 ++ helixharness/hosts/opencode/subagent.md | 102 +++ helixharness/hosts/opencode/ut.md | 51 ++ .../hosts/opencode/workflow-transition.md | 14 + helixharness/opencode/core.ts | 748 ++++++++++++++++++ helixharness/opencode/index.ts | 18 + helixharness/opencode/tests/core.test.ts | 200 +++++ helixharness/opencode/tests/e2e.test.ts | 174 ++++ helixharness/opencode/tests/plugin.test.ts | 184 +++++ helixharness/package.json | 23 + helixharness/reference/eval-protocol.md | 11 +- .../reference/eval-supplement-protocol.md | 2 +- helixharness/reference/host-api.md | 14 +- .../reference/host-runtime-protocol.md | 16 +- .../reference/ut-business-protocol.md | 2 +- .../reference/version-update-protocol.md | 4 +- .../reference/workflow-projection-protocol.md | 5 +- helixharness/scripts/feedback_submit.py | 13 +- .../scripts/tests/test_feedback_submit.py | 5 + .../scripts/tests/test_opencode_host.py | 213 +++++ .../tests/test_public_workflow_router.py | 2 +- helixharness/scripts/update_hosts/opencode.py | 19 + helixharness/skills/feedback/SKILL.md | 8 +- helixharness/tsconfig.json | 13 + 44 files changed, 2170 insertions(+), 82 deletions(-) create mode 100644 helixharness/hosts/opencode/command-projection.json create mode 100644 helixharness/hosts/opencode/host.json create mode 100644 helixharness/hosts/opencode/installer.md create mode 100644 helixharness/hosts/opencode/lifecycle.md create mode 100644 helixharness/hosts/opencode/project-hooks.json create mode 100644 helixharness/hosts/opencode/project.json create mode 100644 helixharness/hosts/opencode/runtime.md create mode 100644 helixharness/hosts/opencode/subagent.md create mode 100644 helixharness/hosts/opencode/ut.md create mode 100644 helixharness/hosts/opencode/workflow-transition.md create mode 100644 helixharness/opencode/core.ts create mode 100644 helixharness/opencode/index.ts create mode 100644 helixharness/opencode/tests/core.test.ts create mode 100644 helixharness/opencode/tests/e2e.test.ts create mode 100644 helixharness/opencode/tests/plugin.test.ts create mode 100644 helixharness/package.json create mode 100644 helixharness/scripts/tests/test_opencode_host.py create mode 100644 helixharness/scripts/update_hosts/opencode.py create mode 100644 helixharness/tsconfig.json diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 7e0e045..24846e6 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -4,12 +4,12 @@ "name": "HelixHarness contributors" }, "metadata": { - "description": "Plugin marketplace for the HelixHarness repository, exposing the helixharness workflow plugin for Claude Code and Codex" + "description": "Plugin marketplace for the HelixHarness repository, exposing the helixharness workflow plugin for Claude Code, Codex and OpenCode" }, "plugins": [ { "name": "helix", - "description": "HelixHarness workflow plugin for Claude Code and Codex with commands and reusable skills", + "description": "HelixHarness workflow plugin for Claude Code, Codex and OpenCode with commands and reusable skills", "source": "./helixharness", "version": "1.0.0", "license": "Apache-2.0" diff --git a/README.md b/README.md index a70cb12..21018a7 100644 --- a/README.md +++ b/README.md @@ -6,11 +6,11 @@ > > Your team's engineering DNA, carried into AI development. -**HelixHarness helps your team build its own AI coding harness on Codex and Claude Code.** It brings your business knowledge, engineering rules and development workflow into the agent's work—from requirements through implementation, tests, review and archive. Verified lessons stay with the project, ready for the next feature. +**HelixHarness helps your team build its own AI coding harness on Codex, Claude Code and OpenCode.** It brings your business knowledge, engineering rules and development workflow into the agent's work—from requirements through implementation, tests, review and archive. Verified lessons stay with the project, ready for the next feature. Start with the plugin. When you want to improve the harness itself, the optional **helixharness-platform** lets maintainers observe usage, compare framework versions and evaluate candidate improvements before adopting them. -**9 commands · Codex / Claude Code · Single repo / multi-repo Workspace · Apache-2.0** +**9 commands · Codex / Claude Code / OpenCode · Single repo / multi-repo Workspace · Apache-2.0** [Quick start](#quick-start) · [The name](#the-story-behind-the-name) · [Why HelixHarness](#why-helixharness) · [Framework iteration platform](#a-platform-for-iterating-on-helixharness) · [User guide](docs/user-guide.md) @@ -63,7 +63,7 @@ Knowledge accumulates as **reviewable repository documents**. You control what b ### 1. Install the plugin -Requirements: Python 3.10+, Git and a plugin-capable Codex or Claude Code installation. Make sure the host is signed in or has its model configuration set up and is working normally. +Requirements: Python 3.10+, Git and a plugin-capable Codex, Claude Code or OpenCode installation. OpenCode requires v2.2+. Make sure the host is signed in or has its model configuration set up and is working normally. After the repository is public, run the commands for your host in a terminal. No manual source clone is needed: @@ -79,13 +79,18 @@ claude plugin marketplace add https://github.com/didi/helixharness.git claude plugin install helix@helixharness-marketplace ``` -The root marketplace installs the `helixharness/` plugin, not the platform. For testing before publication or modifying the plugin, use [developer installation from local source](docs/installation.md#developer-installation). See [hook verification, updates and uninstall](docs/installation.md). +```bash +# OpenCode v2.2+ +opencode plugin add 'github:didi/helixharness::path:helixharness' +``` + +The root marketplace installs the `helixharness/` plugin, not the platform. OpenCode installs the same plugin package directly. For testing before publication or modifying the plugin, use [developer installation from local source](docs/installation.md#developer-installation). See [hook verification, updates and uninstall](docs/installation.md). ### 2. Run a small feature The product name is **HelixHarness**; its plugin ID and command namespace are **`helix`**. -Open a new agent session in the **application repository** you want to develop. Review the plugin hooks through the host's native interface, then enter these commands in the conversation: +Open a new agent session in the **application repository** you want to develop. Codex and Claude Code users review the plugin hooks through the host's native interface; OpenCode registers its commands, skills and agents from the plugin package. Then enter these commands in the conversation: ```text /helix:init @@ -184,10 +189,10 @@ Report community bugs through [GitHub Issues](https://github.com/didi/helixharne Two planned directions will help more teams shape HelixHarness around their development practices: -- **More coding agents.** Extend support beyond Codex and Claude Code so teams can use HelixHarness with more of their preferred tools. +- **More coding agents.** Extend support beyond Codex, Claude Code and OpenCode so teams can use HelixHarness with more of their preferred tools. - **Configurable workflows.** Let teams configure workflow stages and their order to fit their development process. -These are planned capabilities. The current release supports Codex and Claude Code with the Propose → Apply → Archive workflow. Share concrete use cases through the [contribution guide](CONTRIBUTING.md) to help shape these directions. +These are planned capabilities. The current release supports Codex, Claude Code and OpenCode with the Propose → Apply → Archive workflow. Share concrete use cases through the [contribution guide](CONTRIBUTING.md) to help shape these directions. ## Documentation and contribution diff --git a/README.zh-CN.md b/README.zh-CN.md index c408c26..990ff44 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -6,11 +6,11 @@ > > 为适配而生,为进化而设计。让团队的工程 DNA,融入 AI 研发。 -**HelixHarness 帮助团队在 Codex 和 Claude Code 上构建专属的 AI Coding Harness。** 将你的业务知识、工程规范与研发工作流带入 Agent 的工作过程,从需求分析、实现、测试、评审到归档,让 AI 按团队的方式开展研发,并将经验证的经验留在项目中,供下一个需求复用。 +**HelixHarness 帮助团队在 Codex、Claude Code 和 OpenCode 上构建专属的 AI Coding Harness。** 将你的业务知识、工程规范与研发工作流带入 Agent 的工作过程,从需求分析、实现、测试、评审到归档,让 AI 按团队的方式开展研发,并将经验证的经验留在项目中,供下一个需求复用。 从插件开始即可。当你希望改进 Harness 本身时,可选的 **helixharness-platform** 帮助框架维护者观测使用过程、对比框架版本,并在采纳候选改进前验证效果。 -**9 个命令 · Codex / Claude Code · 单仓 / 多仓 Workspace · Apache-2.0** +**9 个命令 · Codex / Claude Code / OpenCode · 单仓 / 多仓 Workspace · Apache-2.0** [快速开始](#快速开始) · [命名故事](#名字背后的故事) · [框架亮点](#框架亮点) · [框架迭代平台](#围绕-helixharness-框架的迭代平台) · [使用指南](docs/user-guide.zh-CN.md) @@ -63,7 +63,7 @@ Knowledge 与 Harness 通过索引引导上下文加载,Specs 保存每个需 ### 1. 安装插件 -需要 Python 3.10+、Git,以及支持插件市场的 Codex 或 Claude Code。先确保宿主已完成登录或模型配置,能够正常使用。 +需要 Python 3.10+、Git,以及 Codex、Claude Code 或 OpenCode。OpenCode 需 v2.2+。先确保宿主已完成登录或模型配置,能够正常使用。 仓库公开后,在终端选择对应宿主安装,无需先手动克隆源码: @@ -79,11 +79,16 @@ claude plugin marketplace add https://github.com/didi/helixharness.git claude plugin install helix@helixharness-marketplace ``` -根市场会安装 `helixharness/` 插件,不会安装平台。发布前测试或修改插件时,使用[开发者安装(本地源码)](docs/installation.md#developer-installation)。详见[hooks 检查、更新与卸载](docs/installation.md)。 +```bash +# OpenCode v2.2+ +opencode plugin add 'github:didi/helixharness::path:helixharness' +``` + +根市场会安装 `helixharness/` 插件,不会安装平台;OpenCode 直接安装同一插件包。发布前测试或修改插件时,使用[开发者安装(本地源码)](docs/installation.md#developer-installation)。详见[hooks 检查、更新与卸载](docs/installation.md)。 ### 2. 完成一个小需求 -在要开发的**业务仓库**新开 Agent 会话,通过宿主原生界面审阅插件 hooks,然后在对话中输入: +在要开发的**业务仓库**新开 Agent 会话。Codex/Claude Code 通过宿主原生界面审阅插件 hooks;OpenCode 由插件包注册命令、Skill 和子任务角色。然后在对话中输入: ```text /helix:init @@ -182,10 +187,10 @@ python -m web_ui.demo --port 7860 接下来计划围绕两个方向,让更多团队按自己的研发方式使用 HelixHarness: -- **支持更多 Coding Agent**:在 Codex 和 Claude Code 之外扩展宿主适配,让团队能在更多熟悉的工具中使用 HelixHarness。 +- **支持更多 Coding Agent**:在 Codex、Claude Code 和 OpenCode 之外扩展宿主适配,让团队能在更多熟悉的工具中使用 HelixHarness。 - **支持工作流配置**:允许团队配置工作流阶段及其顺序,适配自身的研发流程。 -以上为规划能力。当前版本支持 Codex 和 Claude Code,采用 Propose → Apply → Archive 工作流。欢迎通过[贡献指南](CONTRIBUTING.md)分享具体使用场景,帮助完善这些方向。 +以上为规划能力。当前版本支持 Codex、Claude Code 和 OpenCode,采用 Propose → Apply → Archive 工作流。欢迎通过[贡献指南](CONTRIBUTING.md)分享具体使用场景,帮助完善这些方向。 ## 文档与贡献 diff --git a/docs/installation.md b/docs/installation.md index 4f3856c..64081b0 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -4,7 +4,7 @@ ## Requirements -Python 3.10+, Git and a Codex or Claude Code installation supporting plugin marketplaces are required. Make sure the host is signed in or has its model configuration set up and is working normally. The platform is optional. +Python 3.10+, Git and a Codex, Claude Code or OpenCode installation are required. Codex and Claude Code need a client that supports plugin marketplaces; OpenCode needs v2.2+ with plugin support. Make sure the host is signed in or has its model configuration set up and is working normally. The platform is optional. The examples use Bash/Zsh. `didi/helixharness` is the planned public repository; remote commands become usable after its publication. For testing before publication or modifying the plugin, use [developer installation](#developer-installation). @@ -26,7 +26,12 @@ claude plugin marketplace add https://github.com/didi/helixharness.git claude plugin install helix@helixharness-marketplace ``` -The repository root contains `.claude-plugin/marketplace.json`, whose `./helixharness` source points to the plugin. Both hosts consume this compatible marketplace format. The platform is not installed by these commands. +```bash +# OpenCode v2.2+ +opencode plugin add 'github:didi/helixharness::path:helixharness' +``` + +The repository root contains `.claude-plugin/marketplace.json`, whose `./helixharness` source points to the plugin. Codex and Claude Code consume this compatible marketplace format. OpenCode installs the `helixharness/` package directly; its `package.json` exports `opencode/index.ts`. The platform is not installed by these commands. Sources: [OpenAI plugin packaging](https://developers.openai.com/plugins/build/plugins#marketplace-metadata), [Claude Code marketplaces](https://code.claude.com/docs/en/plugin-marketplaces). Host commands and trust screens can vary with client version; use a version providing the listed commands. @@ -48,13 +53,24 @@ claude plugin marketplace add "$HELIXHARNESS_SOURCE" claude plugin install helix@helixharness-marketplace ``` +For OpenCode, point the `plugins` array at the plugin subdirectory instead: + +```jsonc +{ + "$schema": "https://opencode.ai/config.json", + "plugins": ["/absolute/path/to/helixharness/helixharness"] +} +``` + A standalone plugin copy can still use the absolute path to `helixharness/`; its nested marketplace points to `.`. Register only one source under `helixharness-marketplace` at a time. When switching sources, remove the old marketplace using the host's plugin management first. ## Verify installation Open a new host session in the application repository you want to develop. Confirm the nine public commands: `init`, `propose`, `apply`, `archive`, `bug-fix`, `ut`, `update`, `status`, `config`. -Review and trust the plugin's hooks through the host's native interface. Confirm SessionStart identifies the host and installed plugin path. Command visibility alone does not prove hooks executed. Then run `/helix:init`; check generated project hooks and project documentation before creating a feature. Repeated init should preserve unrelated host settings. For single-repository Init, required project files include nonempty `docs/harness/index.md`, `docs/knowledge/index.md` and `docs/knowledge/project-context.md`; also check the other outputs required for the detected project type. A final completion message is not a substitute for those checks. +Codex and Claude Code review and trust the plugin's hooks through the host's native interface. Confirm SessionStart identifies the host and installed plugin path. Command visibility alone does not prove hooks executed. OpenCode registers `helix:` commands, `helix-` method skills and `helix-` subagent roles from its plugin package; it has no SessionStart hook, so run `/helix:status` once and confirm the admitted text contains `canonical_host_id: opencode`, the current `plugin_root` and `repo_root`. + +Then run `/helix:init`; check generated project hooks and project documentation before creating a feature. Repeated init should preserve unrelated host settings. For single-repository Init, required project files include nonempty `docs/harness/index.md`, `docs/knowledge/index.md` and `docs/knowledge/project-context.md`; also check the other outputs required for the detected project type. A final completion message is not a substitute for those checks. If an entrypoint reports `plugin_source_mismatch`, its executing copy differs from the source bound to the session. Check the active marketplace and installed plugin, keep the intended source selected, and start a new session. Use resources from that installation; do not mix another checkout or cached version into the workflow. @@ -62,19 +78,20 @@ If an entrypoint reports `plugin_source_mismatch`, its executing copy differs fr Run `/helix:update` in the host conversation. The plugin checks the configured marketplace, shows an available update and uses the host adapter after authorization. -- **Git source:** the host refreshes the configured repository; use the same marketplace for later versions. +- **Codex / Claude Code Git source:** the host refreshes the configured repository; use the same marketplace for later versions. +- **OpenCode:** `plugin_update=unsupported`, so `/helix:update` returns `continue_silently`. Update with `opencode plugin update`, or re-run `opencode plugin add` for a pinned revision. - **Local source:** update the source copy yourself first, then check for updates. The plugin does not pull an arbitrary local checkout automatically. If the copy was cloned, review its working tree and update it using your normal Git workflow. - Start a new host session after updating; review changed hooks when the host requests it. ## Uninstall -Use the host's plugin management to uninstall `helix@helixharness-marketplace`. Generated project knowledge, requirements and business code are retained. Review project hook settings separately if you no longer want the host to invoke HelixHarness in that application repository. +Use the host's plugin management to uninstall `helix@helixharness-marketplace`. For OpenCode use `opencode plugin remove helixharness-opencode` or remove the directory from `plugins`. Generated project knowledge, requirements and business code are retained. Review project hook settings separately if you no longer want the host to invoke HelixHarness in that application repository. ## 中文说明 -需要 Python 3.10+、Git,以及支持插件市场的 Codex 或 Claude Code。先确保宿主已完成登录或模型配置,能够正常使用。平台不是安装插件的前置条件。 +需要 Python 3.10+、Git,以及 Codex、Claude Code 或 OpenCode。Codex/Claude Code 需支持插件市场;OpenCode 需 v2.2+ 并支持插件。先确保宿主已完成登录或模型配置,能够正常使用。平台不是安装插件的前置条件。 -正式发布后使用上面的 GitHub 安装命令,无需先手动克隆源码。发布前测试或修改插件时,使用[开发者安装(本地源码)](#developer-installation):先下载或克隆源码,再从**包含两个子项目的根目录**添加本地市场。根市场指向 `./helixharness`,不会安装平台。独立插件副本仍可添加插件目录本身;同名市场只保留一个来源。 +正式发布后使用上面的 GitHub 安装命令,无需先手动克隆源码。发布前测试或修改插件时,使用[开发者安装(本地源码)](#developer-installation):先下载或克隆源码,再从**包含两个子项目的根目录**添加本地市场。根市场指向 `./helixharness`,不会安装平台。独立插件副本仍可添加插件目录本身;同名市场只保留一个来源。OpenCode 直接把 `helixharness/` 插件目录加入 `plugins` 数组。 -安装后新开会话,确认九个命令可见、插件 hooks 已审阅并实际执行,再在业务仓库运行 `/helix:init` 并检查项目 hooks。单仓 Init 还需检查非空的 `docs/harness/index.md`、`docs/knowledge/index.md`、`docs/knowledge/project-context.md` 及对应项目类型要求的其他产物,不能只看“已完成”回复。若出现 `plugin_source_mismatch`,先核对市场来源与当前安装插件,选定正确来源并新开会话,避免混用其他 checkout 或缓存版本。更新使用 `/helix:update`;本地来源需先自行更新源码,不能把版本识别成功当作已完成跨版本升级。 +安装后新开会话,确认九个命令可见、插件 hooks 已审阅并实际执行,再在业务仓库运行 `/helix:init` 并检查项目 hooks。OpenCode 没有 SessionStart hook:确认 `helix:*` 命令、`helix-*` 方法 Skill 和子任务角色可见,并执行一次 `/helix:status`,检查正文包含 `canonical_host_id: opencode`、当前 `plugin_root` 与 `repo_root`。单仓 Init 还需检查非空的 `docs/harness/index.md`、`docs/knowledge/index.md`、`docs/knowledge/project-context.md` 及对应项目类型要求的其他产物,不能只看“已完成”回复。若出现 `plugin_source_mismatch`,先核对市场来源与当前安装插件,选定正确来源并新开会话,避免混用其他 checkout 或缓存版本。更新使用 `/helix:update`;本地来源需先自行更新源码,不能把版本识别成功当作已完成跨版本升级。OpenCode 的 `/helix:update` 返回 `continue_silently`,请使用 `opencode plugin update` 手动更新。 diff --git a/docs/user-guide.md b/docs/user-guide.md index cd65ead..16481cb 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -4,7 +4,7 @@ Source version: **HelixHarness 1.0.0 · helixharness-platform 1.0.0**. -**A development workflow for Codex and Claude Code, with a companion platform for usage dashboards, version evaluation and evolution.** +**A development workflow for Codex, Claude Code and OpenCode, with a companion platform for usage dashboards, version evaluation and evolution.** Take a requirement through to a verified code change: define the scope, break it into tasks, implement, test, review, and archive the result. HelixHarness gives your coding agent a reusable workflow. Requirements and progress stay in the repository so you can inspect them and resume unfinished work. @@ -14,7 +14,7 @@ Propose → Apply → Archive └─ Tests + code review + verification evidence ``` -**9 public commands · 3 core stages · Codex / Claude Code · Single repo / multi-repo Workspace · Apache-2.0** +**9 public commands · 3 core stages · Codex / Claude Code / OpenCode · Single repo / multi-repo Workspace · Apache-2.0** Install **HelixHarness** for everyday development. Add **helixharness-platform** to observe usage and evaluate or improve **the HelixHarness framework itself**. Scenario results provide evidence about framework behavior; this is not a general business-code grading service. @@ -49,7 +49,7 @@ Install **HelixHarness** for everyday development. Add **helixharness-platform** | Use case | Requirements | | --- | --- | -| HelixHarness plugin | Python 3.10+, Git, and a plugin-capable Codex or Claude Code installation that is signed in or has its model configuration set up and works normally | +| HelixHarness plugin | Python 3.10+, Git, and a plugin-capable Codex, Claude Code or OpenCode installation that is signed in or has its model configuration set up and works normally. OpenCode requires v2.2+. | | Platform demo or usage dashboard | Python 3.10+, Git, and the platform's `server` dependencies | | Real version evaluation | Platform dependencies, a working Codex execution environment, model credentials, accessible Git repositories, and the build/test tools required by each Case | | Frontend previews and visual verification | Your project's Node.js, package manager, and browser tools; configure design services as needed | @@ -74,7 +74,13 @@ claude plugin marketplace add https://github.com/didi/helixharness.git claude plugin install helix@helixharness-marketplace ``` -After installation, open a new agent session in the application repository you want to develop. Check that the nine public HelixHarness commands are available. See the [Codex installation guide](../helixharness/hosts/codex/installer.md) or [Claude Code installation guide](../helixharness/hosts/claude-code/installer.md) for the host-specific setup. +**OpenCode v2.2+** + +```bash +opencode plugin add 'github:didi/helixharness::path:helixharness' +``` + +After installation, open a new agent session in the application repository you want to develop. Check that the nine public HelixHarness commands are available. See the [Codex installation guide](../helixharness/hosts/codex/installer.md), [Claude Code installation guide](../helixharness/hosts/claude-code/installer.md) or [OpenCode installation guide](../helixharness/hosts/opencode/installer.md) for the host-specific setup. ### 2. Build Your First Feature @@ -86,7 +92,7 @@ Initialize your application repository: /helix:init ``` -Initialization writes project documentation and host project settings. Allow the host to write the current project's settings directory when prompted. Automated runs need an explicit permission response too: Claude Code's `acceptEdits` mode alone does not approve `.claude/settings.json`, and a sandbox protecting `.codex/` can leave Codex hooks incomplete. Check the initialization result before starting a requirement. +Codex and Claude Code write project documentation and host project settings. Allow the host to write the current project's settings directory when prompted. Automated runs need an explicit permission response too: Claude Code's `acceptEdits` mode alone does not approve `.claude/settings.json`, and a sandbox protecting `.codex/` can leave Codex hooks incomplete. OpenCode has no project settings hook contract, so Init merges `AGENTS.md` and does not create `.opencode/` settings. Check the initialization result before starting a requirement. Create a small, concrete requirement: @@ -149,7 +155,7 @@ python -m web_ui.demo --port 7860 --data-dir /path/to/demo-runtime | Project | Who it is for | What it does | Where it runs | | --- | --- | --- | --- | -| [`helixharness/`](../helixharness/README.md) | Developers using AI coding agents | Project initialization, requirements, implementation, testing, review, and archiving | Codex / Claude Code sessions and application repositories | +| [`helixharness/`](../helixharness/README.md) | Developers using AI coding agents | Project initialization, requirements, implementation, testing, review, and archiving | Codex / Claude Code / OpenCode sessions and application repositories | | [`helixharness-platform/`](../helixharness-platform/README.md) | Maintainers observing and improving the HelixHarness framework | Usage dashboards, version evaluation and evolution | A separate Python web service and evaluation Workers | ```mermaid @@ -398,7 +404,7 @@ Paths below are relative to your platform's base URL: ### Model Configuration -For everyday plugin use, configure models in Codex / Claude Code. The platform's own model configuration applies to evaluation, analysis, and other jobs it starts. +For everyday plugin use, configure models in Codex / Claude Code / OpenCode. The platform's own model configuration applies to evaluation, analysis, and other jobs it starts. See [`helixharness-platform/.env.example`](../helixharness-platform/.env.example) for the template. The service reads **process environment variables and does not automatically load `.env.example`**. Inject real values into the environments running both the web service and Workers. @@ -610,7 +616,7 @@ The repository contains two independently installable projects: ├── helixharness/ │ ├── commands/ # Nine public command entrypoints │ ├── workflows/ # single/ execution and workspace/ coordination -│ ├── hosts/ # Codex / Claude Code adapters +│ ├── hosts/ # Codex / Claude Code / OpenCode adapters │ ├── skills/ # Reusable workflow methods │ └── scripts/ # Routing, artifact validation, and telemetry └── helixharness-platform/ @@ -633,7 +639,7 @@ The repository contains two independently installable projects: | [`systematic-debugging`](../helixharness/skills/systematic-debugging/SKILL.md) | Reproduce failures, test hypotheses, identify causes, and verify fixes | Standalone, explicitly invoked by the user | | [`feedback`](../helixharness/skills/feedback/SKILL.md) | Submit HelixHarness usage issues | Standalone; requires a running platform and configured destination | -Codex installs these eight method skills alongside the nine public entry skills; Claude Code discovers the root `skills/` directly. The four lifecycle commands still use the workflow router; `status` and `config` do not advance development stages. Auxiliary skills do not add development stages; formal Spec/Tasks, progress tracking, and completion checks remain owned by those stages. +Codex installs these eight method skills alongside the nine public entry skills; Claude Code discovers the root `skills/` directly; OpenCode registers them as `helix-` from the same root files. The four lifecycle commands still use the workflow router; `status` and `config` do not advance development stages. Auxiliary skills do not add development stages; formal Spec/Tasks, progress tracking, and completion checks remain owned by those stages. `git-diff-impact` requires no Init, active feature, or platform service. For example: “Use HelixHarness git-diff-impact to analyze uncommitted changes, --no-save.” You may instead specify two commits or branches and optional `--req` / `--design` documents. Markdown reports default to `diff-impact-reports/`; `--out` selects another location. The skill does not fix code or change review verdicts. @@ -658,6 +664,8 @@ Validate the plugin from `helixharness/`: ```bash python3 scripts/run_tests.py python3 scripts/host_runtime_cli.py list +bun test opencode/tests +bun run typecheck ``` Validate the platform from `helixharness-platform/` with its virtual environment active: diff --git a/docs/user-guide.zh-CN.md b/docs/user-guide.zh-CN.md index 012896f..d0b8056 100644 --- a/docs/user-guide.zh-CN.md +++ b/docs/user-guide.zh-CN.md @@ -4,7 +4,7 @@ 当前版本:**HelixHarness 1.0.0 · helixharness-platform 1.0.0**。 -**面向 Codex 与 Claude Code 的研发工作流,以及提供数据看板、版本评测与自进化的配套平台。** +**面向 Codex、Claude Code 与 OpenCode 的研发工作流,以及提供数据看板、版本评测与自进化的配套平台。** 从一个需求到有验证依据的代码变更:明确边界、拆分任务、实现、测试、评审,再把结果归档到项目中。HelixHarness 将这些步骤作为可复用的工作流交给编码助手,需求和执行进度保存在仓库里,便于检查和续跑。 @@ -14,7 +14,7 @@ Propose → Apply → Archive └─ 测试 + 代码评审 + 验证依据 ``` -**9 个公开命令 · 3 个核心阶段 · Codex / Claude Code · 单仓 / 多仓 Workspace · Apache-2.0** +**9 个公开命令 · 3 个核心阶段 · Codex / Claude Code / OpenCode · 单仓 / 多仓 Workspace · Apache-2.0** 只做日常开发,安装 **HelixHarness** 即可。需要观测使用情况、评测和改进 **HelixHarness 框架本身**,再运行 **helixharness-platform**。开发场景的结果用于判断框架行为,平台不是通用的业务代码评分服务。 @@ -50,7 +50,7 @@ Propose → Apply → Archive | 用途 | 要求 | | --- | --- | -| 使用 HelixHarness | Python 3.10+、Git,以及支持插件的 Codex 或 Claude Code;宿主已完成登录或模型配置,能够正常使用 | +| 使用 HelixHarness | Python 3.10+、Git,以及支持插件的 Codex、Claude Code 或 OpenCode;OpenCode 需 v2.2+;宿主已完成登录或模型配置,能够正常使用 | | 运行平台 Demo / 使用看板 | Python 3.10+、Git;安装平台 `server` 依赖 | | 真实版本评测 | 平台依赖、可用的 Codex 执行环境、模型凭据、可访问的 Git 仓库,以及 Case 所需的构建与测试工具 | | 前端预览与视觉验证 | 项目自身的 Node.js、包管理器及浏览器工具;设计服务按实际使用情况配置 | @@ -75,7 +75,13 @@ claude plugin marketplace add https://github.com/didi/helixharness.git claude plugin install helix@helixharness-marketplace ``` -安装后,在你要开发的业务仓库中新开宿主会话,确认能找到 `helixharness` 的九个公开命令。宿主适配说明见 [Codex 安装指南](../helixharness/hosts/codex/installer.md) 和 [Claude Code 安装指南](../helixharness/hosts/claude-code/installer.md)。 +**OpenCode v2.2+** + +```bash +opencode plugin add 'github:didi/helixharness::path:helixharness' +``` + +安装后,在你要开发的业务仓库中新开宿主会话,确认能找到 `helixharness` 的九个公开命令。宿主适配说明见 [Codex 安装指南](../helixharness/hosts/codex/installer.md)、[Claude Code 安装指南](../helixharness/hosts/claude-code/installer.md) 和 [OpenCode 安装指南](../helixharness/hosts/opencode/installer.md)。 ### 2. 完成第一个需求 @@ -87,7 +93,7 @@ claude plugin install helix@helixharness-marketplace /helix:init ``` -初始化会写入项目文档和宿主项目配置。宿主提示当前项目配置目录的写权限时,确认本项目后授权。自动化运行也需显式响应授权:Claude Code 的 `acceptEdits` 模式不会自动批准 `.claude/settings.json`,保护 `.codex/` 的沙箱也可能使 Codex hooks 未完成。开始需求前先检查初始化结果。 +Codex 和 Claude Code 会写入项目文档和宿主项目配置。宿主提示当前项目配置目录的写权限时,确认本项目后授权。自动化运行也需显式响应授权:Claude Code 的 `acceptEdits` 模式不会自动批准 `.claude/settings.json`,保护 `.codex/` 的沙箱也可能使 Codex hooks 未完成。OpenCode 没有项目 settings hook 契约,Init 只合并 `AGENTS.md`,不创建 `.opencode/` 设置。开始需求前先检查初始化结果。 再创建一个范围清晰的需求: @@ -150,7 +156,7 @@ python -m web_ui.demo --port 7860 --data-dir /path/to/demo-runtime | 项目 | 面向谁 | 负责什么 | 运行位置 | | --- | --- | --- | --- | -| [`helixharness/`](../helixharness/README.md) | 日常使用 AI 编码的开发者 | 初始化项目、收敛需求、实现、测试、评审、归档 | Codex / Claude Code 会话及业务仓库 | +| [`helixharness/`](../helixharness/README.md) | 日常使用 AI 编码的开发者 | 初始化项目、收敛需求、实现、测试、评审、归档 | Codex / Claude Code / OpenCode 会话及业务仓库 | | [`helixharness-platform/`](../helixharness-platform/README.md) | 观测和改进 HelixHarness 框架的维护者 | 数据看板、版本评测、自进化 | 独立 Python Web 服务与评测 Worker | ```mermaid @@ -399,7 +405,7 @@ DEFAULT_FEEDBACK_ENDPOINT = "" ### 模型配置 -日常使用插件时,模型由 Codex / Claude Code 宿主配置。平台自身的模型配置用于平台发起的评测、分析等任务。 +日常使用插件时,模型由 Codex / Claude Code / OpenCode 宿主配置。平台自身的模型配置用于平台发起的评测、分析等任务。 配置模板见 [`helixharness-platform/.env.example`](../helixharness-platform/.env.example)。服务读取**进程环境变量,不会自动加载 `.env.example`**;将真实值注入启动 Web 和 Worker 的环境。 @@ -611,7 +617,7 @@ Candidate 生成在普通用户(包括 macOS 本地用户)下默认使用 Co ├── helixharness/ │ ├── commands/ # 九个公共命令入口和路由 │ ├── workflows/ # single/ 单仓执行,workspace/ 多仓协调 -│ ├── hosts/ # Codex / Claude Code 适配 +│ ├── hosts/ # Codex / Claude Code / OpenCode 适配 │ ├── skills/ # 工作流复用的方法 │ └── scripts/ # 路由、工件校验与遥测 └── helixharness-platform/ @@ -634,7 +640,7 @@ Candidate 生成在普通用户(包括 macOS 本地用户)下默认使用 Co | [`systematic-debugging`](../helixharness/skills/systematic-debugging/SKILL.md) | 复现异常、验证假设、定位根因与验证修复 | 由用户明确调用,独立使用 | | [`feedback`](../helixharness/skills/feedback/SKILL.md) | 提交 HelixHarness 使用问题 | 独立辅助能力;需启动平台并配置地址 | -Codex 安装目录包含九个公开入口 Skill 和上述八个方法 Skill;Claude Code 直接发现根 `skills/`。四个生命周期命令继续使用工作流路由;`status`、`config` 与辅助 Skill 不增加研发阶段。正式 Spec/Tasks、执行进度和完成验证仍由对应研发阶段负责。 +Codex 安装目录包含九个公开入口 Skill 和上述八个方法 Skill;Claude Code 直接发现根 `skills/`;OpenCode 从同一批根文件注册为 `helix-`。四个生命周期命令继续使用工作流路由;`status`、`config` 与辅助 Skill 不增加研发阶段。正式 Spec/Tasks、执行进度和完成验证仍由对应研发阶段负责。 `git-diff-impact` 无需 Init、活跃 feature 或平台服务。示例:“使用 HelixHarness git-diff-impact,分析当前未提交改动,--no-save”;也可明确提供两个提交或分支,以及 `--req` / `--design` 文档。默认保存 Markdown 到 `diff-impact-reports/`,`--out` 可指定位置。它不自动修复代码,也不改变评审结论。 @@ -659,6 +665,8 @@ Codex 安装目录包含九个公开入口 Skill 和上述八个方法 Skill;C ```bash python3 scripts/run_tests.py python3 scripts/host_runtime_cli.py list +bun test opencode/tests +bun run typecheck ``` 平台验证,在 `helixharness-platform/` 的虚拟环境中执行: diff --git a/docs/workflow-architecture.md b/docs/workflow-architecture.md index a340e01..2fef6d8 100644 --- a/docs/workflow-architecture.md +++ b/docs/workflow-architecture.md @@ -22,11 +22,13 @@ Workspace 子任务从公共入口进入 Single 正文,根目录不写子仓 ## 宿主边界 [`Host API`](../helixharness/reference/host-api.md) 定义 manifest 和适配器合同。 -Claude Code 使用原生命令,Codex 使用 Skill 投影;宿主机制由 `hosts/{host-id}/` 提供。 -两个原生插件清单显式选择各自的 hook 配置。宿主入口负责固定身份和事件转换, -共享生命周期逻辑不得根据平台名称、环境变量或缓存目录猜测宿主。 +Claude Code 使用原生命令,Codex 使用 Skill 投影,OpenCode 在 V2 插件中注册原生命令、方法 +Skill 和子任务角色;宿主机制由 `hosts/{host-id}/` 提供。Claude Code 与 Codex 的原生插件清单 +显式选择各自的 hook 配置;OpenCode 不发布 hook 清单,而在插件 `setup` 中注入 Host Context。 +宿主入口负责固定身份和事件转换,共享生命周期逻辑不得根据平台名称、环境变量或缓存目录猜测宿主。 -Codex Init 入口加载 `project_config`、`project_hooks`;UT 入口加载 `ut`。 +Codex Init 入口加载 `project_config`、`project_hooks`;UT 入口加载 `ut`。OpenCode Init 使用 +`AGENTS.md` 且 `settings_file=null`,不创建 `.opencode/` 设置。 单仓 Init 必须实际生成并校验当前 Host Kit 的项目 hooks,重复初始化保留用户配置并去重。 业务阶段显式记录 start/finish;会话 Stop 不是业务完成证据。 @@ -40,6 +42,7 @@ Codex Init 入口加载 `project_config`、`project_hooks`;UT 入口加载 `ut ## 验证 -统一回归入口为 `python3 scripts/run_tests.py`,另执行 Host Kit 和 Codex 投影校验。 +统一回归入口为 `python3 scripts/run_tests.py`,另执行 Host Kit、Codex 投影校验和 OpenCode 插件 +的 `bun test` / `bun run typecheck`;真实 OpenCode 验收使用 `HELIXHARNESS_OPENCODE_E2E=1 bun test opencode/tests/e2e.test.ts`。 原生客户端验收分别核查插件装载、启动身份、真实子任务、测试和覆盖率、 完整工件、归档状态与清理;单测通过、命令退出成功或模型回复完成均不能单独证明闭环通过。 diff --git a/examples/README.md b/examples/README.md index 8b3514b..cf34c52 100644 --- a/examples/README.md +++ b/examples/README.md @@ -23,7 +23,7 @@ The baseline has two passing tests. It returns all titles but does not yet accep ## 2. Run HelixHarness -Open Codex or Claude Code in the `$TASK_FILTER_DEMO` directory (run `pwd` in that terminal to see its path) and enter: +Open Codex, Claude Code or OpenCode in the `$TASK_FILTER_DEMO` directory (run `pwd` in that terminal to see its path) and enter: ```text /helix:init diff --git a/helixharness/.claude-plugin/marketplace.json b/helixharness/.claude-plugin/marketplace.json index f11670e..1e9b024 100644 --- a/helixharness/.claude-plugin/marketplace.json +++ b/helixharness/.claude-plugin/marketplace.json @@ -4,12 +4,12 @@ "name": "helixharness-marketplace" }, "metadata": { - "description": "Plugin marketplace for the HelixHarness repository, exposing the helixharness workflow plugin for Claude Code and Codex" + "description": "Plugin marketplace for the HelixHarness repository, exposing the helixharness workflow plugin for Claude Code, Codex and OpenCode" }, "plugins": [ { "name": "helix", - "description": "HelixHarness workflow plugin for Claude Code and Codex with commands and reusable skills", + "description": "HelixHarness workflow plugin for Claude Code, Codex and OpenCode with commands and reusable skills", "source": ".", "version": "1.0.0" } diff --git a/helixharness/.claude-plugin/plugin.json b/helixharness/.claude-plugin/plugin.json index 6b70e3a..b249fa8 100644 --- a/helixharness/.claude-plugin/plugin.json +++ b/helixharness/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "helix", - "description": "HelixHarness 面向 Agent 的双宿主研发工作流插件,提供命令与可复用技能。", + "description": "HelixHarness 面向 Agent 的多宿主研发工作流插件,提供命令与可复用技能。", "author": { "name": "HelixHarness contributors" }, diff --git a/helixharness/.gitignore b/helixharness/.gitignore index 2b22ac5..aa7019f 100644 --- a/helixharness/.gitignore +++ b/helixharness/.gitignore @@ -7,6 +7,8 @@ .venv/ node_modules/ *.egg-info/ +bun.lock +bun.lockb # Python and test caches __pycache__/ diff --git a/helixharness/AGENTS.md b/helixharness/AGENTS.md index 8616fa5..9dc8bc8 100644 --- a/helixharness/AGENTS.md +++ b/helixharness/AGENTS.md @@ -4,4 +4,4 @@ 修改后运行相关 Python unittest、Host Kit 装载和路径引用检查。不得加入凭据、真实会话、私有 URL 或运行数据。不要自动推送或部署。 -测试文件统一放在 `scripts/tests/`,通过 `python3 scripts/run_tests.py` 运行完整测试集;`scripts/` 根目录不放 `test_*.py`。 +测试文件统一放在 `scripts/tests/`,通过 `python3 scripts/run_tests.py` 运行完整测试集;`scripts/` 根目录不放 `test_*.py`。OpenCode 插件测试位于 `opencode/tests/`,使用 `bun test opencode/tests` 和 `bun run typecheck`;真实客户端验收使用 `HELIXHARNESS_OPENCODE_E2E=1 bun test opencode/tests/e2e.test.ts`。 diff --git a/helixharness/PLUGIN_USAGE.md b/helixharness/PLUGIN_USAGE.md index ac7f204..33750c5 100644 --- a/helixharness/PLUGIN_USAGE.md +++ b/helixharness/PLUGIN_USAGE.md @@ -1,6 +1,6 @@ # HelixHarness -面向 Codex 与 Claude Code 的 HelixHarness 研发工作流。通过项目约束、知识库、Spec、任务和验证证据完成研发。 +面向 Codex、Claude Code 与 OpenCode 的 HelixHarness 研发工作流。通过项目约束、知识库、Spec、任务和验证证据完成研发。 ## 命令 @@ -15,7 +15,7 @@ ## 安装 -需要 Python 3.10+、Git,以及 Codex 或 Claude Code。将本目录作为本地 marketplace 添加。宿主具体命令见 `hosts/codex/installer.md` 或 `hosts/claude-code/installer.md`。 +需要 Python 3.10+、Git,以及 Codex、Claude Code 或 OpenCode。Codex/Claude Code 将本目录作为本地 marketplace 添加;OpenCode 将本目录加入 `plugins` 数组。宿主具体命令见 `hosts/codex/installer.md`、`hosts/claude-code/installer.md` 或 `hosts/opencode/installer.md`。 ## 项目结构 @@ -33,6 +33,8 @@ ```bash PYTHONPATH=scripts python3 -m unittest discover -s scripts/tests -p 'test_*.py' python3 scripts/host_runtime_cli.py list +bun test opencode/tests +bun run typecheck ``` 此发行版仅维护当前 HelixHarness 合同,不迁移其他工作流历史。循环不包含发布或部署。 diff --git a/helixharness/README.md b/helixharness/README.md index 4176733..bd6fb2c 100644 --- a/helixharness/README.md +++ b/helixharness/README.md @@ -2,7 +2,7 @@ 当前版本:**1.0.0**。 -面向 Codex 与 Claude Code 的 HelixHarness 研发工作流。通过项目约束、知识库、Spec、任务和验证证据完成研发。 +面向 Codex、Claude Code 与 OpenCode 的 HelixHarness 研发工作流。通过项目约束、知识库、Spec、任务和验证证据完成研发。 ## 命令 @@ -19,7 +19,7 @@ ## 安装 -需要 Python 3.10+、Git,以及 Codex 或 Claude Code。将本目录作为本地 marketplace 添加。宿主具体命令见 `hosts/codex/installer.md` 或 `hosts/claude-code/installer.md`。 +需要 Python 3.10+、Git,以及 Codex、Claude Code 或 OpenCode。Codex/Claude Code 将本目录作为本地 marketplace 添加;OpenCode 将本目录加入 `plugins` 数组。宿主具体命令见 `hosts/codex/installer.md`、`hosts/claude-code/installer.md` 或 `hosts/opencode/installer.md`。 ## 独立方案探索与调试 @@ -30,7 +30,7 @@ 有代码库时结合相关实现探索方案;没有代码库时先澄清想法与约束。Skill 交付讨论摘要或调试结果后结束;用户可自行将结果作为后续需求输入。两项 Skill 不创建 feature、Spec/Tasks 或 eval-log,不推进研发阶段。 -这两项是辅助 Skill,不增加研发阶段,公开入口另含 status 与 config。Codex 使用生成的宿主入口,Claude Code 直接发现根 `skills/`;详细示例见[使用指南](../docs/user-guide.zh-CN.md#从想法或异常开始)。 +这两项是辅助 Skill,不增加研发阶段,公开入口另含 status 与 config。Codex 使用生成的宿主入口,Claude Code 直接发现根 `skills/`,OpenCode 注册为 `helix-`;详细示例见[使用指南](../docs/user-guide.zh-CN.md#从想法或异常开始)。 可选的 [git-diff-impact](skills/git-diff-impact/SKILL.md) 可独立分析 Git 改动的调用链、业务影响和兼容性。显式要求“使用 HelixHarness git-diff-impact,分析当前未提交改动,--no-save”即可,无需 Init 或 feature。默认保存 Markdown 报告到 `diff-impact-reports/`;日常 Apply 不自动调用,也不改变评审状态。`code-review` / `tdd` 当前仍依赖 HelixHarness 的 Spec 和执行上下文,没有独立模式。 @@ -77,6 +77,8 @@ feedback 使用相同结构,地址为实际平台的 `/feedback/report`。** ```bash python3 scripts/run_tests.py python3 scripts/host_runtime_cli.py list +bun test opencode/tests +bun run typecheck ``` 此发行版仅维护当前 HelixHarness 合同,不迁移其他工作流历史。循环不包含发布或部署。 diff --git a/helixharness/hosts/opencode/command-projection.json b/helixharness/hosts/opencode/command-projection.json new file mode 100644 index 0000000..b7a7ef4 --- /dev/null +++ b/helixharness/hosts/opencode/command-projection.json @@ -0,0 +1,15 @@ +{ + "projection_version": "1.0", + "surface": "native-command", + "entrypoints": { + "apply": ["commands/apply.md", "commands/apply.md"], + "archive": ["commands/archive.md", "commands/archive.md"], + "bug-fix": ["commands/bug-fix.md", "commands/bug-fix.md"], + "config": ["commands/config.md", "commands/config.md"], + "init": ["commands/init.md", "commands/init.md"], + "propose": ["commands/propose.md", "commands/propose.md"], + "status": ["commands/status.md", "commands/status.md"], + "update": ["commands/update.md", "commands/update.md"], + "ut": ["commands/ut.md", "commands/ut.md"] + } +} diff --git a/helixharness/hosts/opencode/host.json b/helixharness/hosts/opencode/host.json new file mode 100644 index 0000000..c72ad96 --- /dev/null +++ b/helixharness/hosts/opencode/host.json @@ -0,0 +1,50 @@ +{ + "host_id": "opencode", + "host_api_version": "1.1", + "aliases": [], + "support": { + "level": "preview", + "display_name": "OpenCode", + "evidence": null, + "limitations": [ + "No native session-start, session-end, stop or failure hooks; the plugin injects Host Context when a command executes or a method skill loads.", + "Telemetry and plugin-update adapters are unsupported; HelixHarness scripts return unsupported_host or continue_silently while business work continues.", + "OpenCode has no native plan tool; update_plan falls back to the current Feature tasks.md.", + "Project hooks are unsupported because OpenCode has no project settings hook contract; Init uses AGENTS.md and settings_file is null.", + "Workspace Apply RepoJobs use delegation_policy=may_delegate; OpenCode defaults to subagent depth 1, so set experimental.subagent_depth to at least 2.", + "The d-d2c Claude skill-scoped Stop/PreToolUse guards are not active; run that skill in its no-hook/--bare semantics without claiming guard enforcement." + ] + }, + "capabilities": { + "command_surface": "native", + "skill_discovery": "native", + "session_start": "emulated", + "stop_hook": "unsupported", + "failure_hook": "unsupported", + "command_lifecycle": "native", + "workflow_transition": "emulated", + "subagents": "native", + "unit_test_workflow": "native", + "task_tracking": "unsupported", + "project_hooks": "unsupported", + "session_events": "unsupported", + "telemetry": "unsupported", + "plugin_install": "native", + "plugin_update": "unsupported", + "session_end": "unsupported" + }, + "adapters": { + "detector": "python:update_hosts.opencode:detect_host", + "distribution": "resource:package.json", + "installer": "resource:hosts/opencode/installer.md", + "command_projection": "resource:hosts/opencode/command-projection.json", + "runtime": "resource:hosts/opencode/runtime.md", + "subagent_protocol": "resource:hosts/opencode/subagent.md", + "workflow_transition": "resource:hosts/opencode/workflow-transition.md", + "project_config": "resource:hosts/opencode/project.json", + "project_hooks": "resource:hosts/opencode/project-hooks.json", + "ut": "resource:hosts/opencode/ut.md", + "lifecycle": "resource:hosts/opencode/lifecycle.md", + "telemetry_protocol": "resource:hosts/shared/telemetry.md" + } +} diff --git a/helixharness/hosts/opencode/installer.md b/helixharness/hosts/opencode/installer.md new file mode 100644 index 0000000..d697c11 --- /dev/null +++ b/helixharness/hosts/opencode/installer.md @@ -0,0 +1,72 @@ +# 安装与更新 + +完整步骤见[安装指南](../../../docs/installation.md)。当前单仓源码使用插件目录的绝对路径; +公开发布后也可使用 `https://github.com/didi/helixharness.git`,记为 `HELIXHARNESS_SOURCE`。 +OpenCode V2 使用插件包根目录(本仓库的 `helixharness/`)中的 `package.json` 和 +`opencode/index.ts`。 + +## 从 Git 安装 + +```bash +opencode plugin add 'github:didi/helixharness::path:helixharness' +``` + +Git 安装支持分支、Tag 和完整提交;需要固定版本时使用完整提交或 npm 版本。安装后 OpenCode +加载 `package.json` 的 `exports["."]`;插件只使用 Bun 内置模块和 OpenCode 提供的插件上下文, +没有运行时 npm 依赖,因此本地源码副本也无需先执行 `bun install`。开发时运行 +`bun install` 只是为了 `bun test` 和 `tsc` 的类型检查。 + +## 本地源码 + +本地插件目录必须配置为目录,不能指向单个 `.ts` 文件。将绝对路径加入项目或全局 +`opencode.json(c)`: + +```jsonc +{ + "$schema": "https://opencode.ai/config.json", + "plugins": ["/absolute/path/to/helixharness"] +} +``` + +本地源码修改后按 OpenCode 要求重启服务或重新加载插件。 + +## 多仓 Workspace + +OpenCode 默认子代理嵌套深度为一。Workspace Apply 的 RepoJob 使用 +`delegation_policy=may_delegate`,需要允许 child 继续派发 Single Apply 的只读评审角色。在该项目 +或全局 `opencode.json(c)` 中设置: + +```jsonc +{ + "experimental": { + "subagent_depth": 2 + } +} +``` + +不设置时 Single 仓流程仍可运行,但 Workspace Apply 必须如实报告深度不足并停止该 RepoJob,不能 +降级内联或伪造完成。 + +## 验收 + +新开 OpenCode 会话并确认: + +- 九个公开命令可见:`helix:init`、`helix:propose`、`helix:apply`、`helix:archive`、 + `helix:bug-fix`、`helix:ut`、`helix:update`、`helix:status`、`helix:config`; +- 方法 Skill 以 `helix-` 出现在原生 skill 列表; +- 子任务角色以 `helix-` 出现在 subagent 列表; +- 直接执行 `/helix:status` 时正文包含 `canonical_host_id: opencode`、当前 `plugin_root` 和 + `repo_root`。 + +仅命令可见不能证明 Host Context 注入成功;必须检查一次命令展开后的正文。 + +## 更新与卸载 + +- Git 来源:使用 `opencode plugin update`,或重新执行 `opencode plugin add` 并指定目标版本。 +- 本地来源:先自行更新源码,再重启或重新加载 OpenCode。 +- 卸载:使用 `opencode plugin remove`,或在 `plugins` 数组中移除该目录。插件卸载不删除业务 + 仓库中的 `docs/harness/`、`docs/knowledge/`、`docs/specs/` 或业务代码。 + +`/helix:update` 在 OpenCode 上返回 `continue_silently`,因为当前 `plugin_update=unsupported`; +这不影响手动更新。OpenCode 不会创建 `.opencode/` 项目设置或项目 hooks;Init 只合并 +`AGENTS.md`。 diff --git a/helixharness/hosts/opencode/lifecycle.md b/helixharness/hosts/opencode/lifecycle.md new file mode 100644 index 0000000..c2b9790 --- /dev/null +++ b/helixharness/hosts/opencode/lifecycle.md @@ -0,0 +1,19 @@ +# opencode 生命周期适配 + +OpenCode 不需要 plugin hook manifest。`opencode/index.ts` 的 `setup` 在插件装载时注册命令、 +方法 Skill 和子任务角色,并在 `tool.execute.after` 为方法 Skill 绑定当前会话 `repo_root`。 + +- 不注册 SessionStart、SessionEnd、Stop 或 Failure 业务钩子;`session_start` 由命令执行和 + Skill 加载时的 Host Context 注入等价实现。 +- 阶段开始、完成与失败仍由公共命令显式调用 HelixHarness 生命周期脚本;会话空闲或结束不代表 + 阶段完成。 +- `session_events`、`session_end`、`stop_hook` 和 `failure_hook` 声明为 `unsupported`,不得 + 虚构事件或模拟清理。 +- 项目 hooks 由 `project-hooks.json` 独立声明为 `unsupported`;Init 不创建 `.opencode/` + 设置或替代 hook 文件。 +- `telemetry=unsupported`:统计关闭不改变工作流完成门禁,脚本返回 `unsupported_host` 后继续 + 业务。 +- 插件更新由 OpenCode 的插件管理完成;`plugin_update=unsupported` 时 `/helix:update` 只返回 + `continue_silently`,不调用其他宿主的安装命令。 +- 修改插件源码或局部依赖后按 OpenCode 要求重启服务或重新加载会话;更新后新开会话确认九个 + `helix:*` 命令、`helix-*` 方法 Skill 和子任务角色可见。 diff --git a/helixharness/hosts/opencode/project-hooks.json b/helixharness/hosts/opencode/project-hooks.json new file mode 100644 index 0000000..4766cf5 --- /dev/null +++ b/helixharness/hosts/opencode/project-hooks.json @@ -0,0 +1,8 @@ +{ + "project_hooks_version": "1.0", + "owner": "parent", + "settings_file": null, + "merge_strategy": "unsupported", + "dedupe_key": null, + "payload": null +} diff --git a/helixharness/hosts/opencode/project.json b/helixharness/hosts/opencode/project.json new file mode 100644 index 0000000..8e4c298 --- /dev/null +++ b/helixharness/hosts/opencode/project.json @@ -0,0 +1,6 @@ +{ + "entry_file": "AGENTS.md", + "entry_template": "templates/project-entry.md.tpl", + "workspace_entry_template": "templates/workspace-entry.md.tpl", + "settings_file": null +} diff --git a/helixharness/hosts/opencode/runtime.md b/helixharness/hosts/opencode/runtime.md new file mode 100644 index 0000000..b8b3cd1 --- /dev/null +++ b/helixharness/hosts/opencode/runtime.md @@ -0,0 +1,75 @@ +# OpenCode 宿主运行时 + +本 Host Kit 面向 OpenCode V2(`@opencode/plugin` 2.2.x)。插件包在本安装的 `opencode/index.ts` +中一次性注册全部宿主表面,不把 canonical Markdown 复制到项目的 `.opencode/`: + +- 公开命令注册为 `helix:`,执行时加载同一插件内的唯一 `commands/.md`; +- 方法 Skill 注册为 `helix-`,正文仍来自根 `skills//SKILL.md`; +- 子任务角色注册为 `helix-`,正文仍来自根 `agents/.md`。 + +命令执行与 Skill 加载时由插件注入预绑定 Host Context(`canonical_host_id=opencode`、 +`plugin_root`、`repo_root`、`host_manifest`、`capabilities` 和全部资源绝对路径)。这等价实现 +`session_start=emulated`;不得从环境变量、项目文件或其他插件缓存重新识别宿主。直接调用方法 +Skill 时,`repo_root` 由 `tool.execute.after` 按当前会话目录绑定。 + +| 逻辑动作 | OpenCode 行为 | +|---|---| +| `read_file` | 使用原生 `read` 工具读取确定路径 | +| `edit_file` | 使用原生 `edit`、`write` 或 `patch`,并保留当前写域与单写者约束 | +| `run_command` | 使用原生 `shell` 工具并保留真实退出状态;需要时显式设置 `workdir`、`timeout` 或 `background` | +| `invoke_skill` | 使用原生 `skill` 工具;把 `invoke_skill(name)` 映射为 `helix-` | +| `spawn_job` | 使用原生 `subagent` 工具,按 `resources.subagent_protocol` 传入 `helix-`、`helix-worker` 或内建 `general` | +| `wait_job` | 前台 `subagent` 直接等待真实结果;后台任务等待原生完成通知,再校验结果与产物 | +| `ask_user` | 使用原生 `question` 工具并等待真实回答 | +| `update_plan` | OpenCode 无原生计划工具,更新当前 Feature 的 `tasks.md` | +| `stage_finish` | 在命令内按真实终态显式调用 HelixHarness 生命周期脚本 | +| `project_entry` | 生成或合并根 `AGENTS.md` | +| `project_hooks` | OpenCode 无项目 settings hook 契约;声明 `unsupported`,不创建替代文件 | + +## 命令与参数 + +OpenCode 原生命令执行器收到的是用户输入的原始参数字符串。插件把它作为 `$ARGUMENTS` 注入 +`commands/.md`,并替换 `{plugin_root}`、`{repo_root}`、`{canonical_host_id}`、 +`{current_platform}` 和 `{SHELL_QUOTED_ARGUMENTS}`。替换只发生一次,用户参数中的同名文本保持 +字面值。命令通过 `session.prompt` 提交展开后的正文,不递归调用 `session.command`,避免重复 +命令生命周期。 + +用户附件、agent mention 和 skill mention 原样转发到展开后的 prompt;`delivery` 保持调用方 +给定的 `steer|queue`。`metadata` 只记录逻辑命令名,不进入业务事实。 + +## 用户决策与等待 + +- `question` 必须取得真实回答;取消、空结果或超时不等于默认选项。 +- 需要文本选择时按公共命令要求展示完整问题和选项,并交还控制等待回答。 +- 子代理内部使用 `question` 时保持 `interaction_mode=host_native`;若 child 无法直接交互, + 返回具体缺口,由父流程按命令的 blocked 语义处理。 + +## 命令入口与资源加载 + +命令入口已经是公共 contract,不需要额外薄入口。插件在启动时读取并校验一次: + +- `hosts/opencode/host.json` 的 `host_id`、`host_api_version=1.1`、能力和全部资源引用; +- 九个 `commands/*.md`、根 `skills/*/SKILL.md` 和 `agents/*.md`。 + +资源缺失、越界、宿主 ID 或 API 版本不一致时插件装载失败;不得扫描其他插件副本或降级到 +Claude Code/Codex。Skill 与 Agent 的 canonical 正文只在本插件内解析,不读取项目中的同名 +`.opencode/skills` 或 `.opencode/agents`。 + +## Python 与统计 + +OpenCode 插件本身使用 TypeScript,不依赖 Python 启动。业务命令仍按 `reference/runtime-preflight.md` +执行 Python preflight。`telemetry=unsupported` 时统计脚本返回 `unsupported_host`,业务继续; +不读写其他宿主的 consent、eval-log 或私有缓存。`plugin_update=unsupported` 时版本检查返回 +`continue_silently`,不得调用 Claude Code/Codex 的安装命令。 + +## d-d2c guard 边界 + +`skills/d-d2c/SKILL.md` 中的 Claude skill-scoped `Stop` / `PreToolUse:AskUserQuestion` guard 不会在 +OpenCode 中执行,因为 OpenCode Host Kit 不注册 skill hooks。按该 Skill 的 `--bare` / 无 hook +语义执行:业务步骤、阶段确认和用户授权门禁仍由 Skill 正文与当前命令负责,但不得声称确定性 +guard 已运行,也不得用 guard 缺失跳过视觉验收或完成条件。 + +## 项目配置 + +`resources.project_config` 固定 `entry_file=AGENTS.md`、`settings_file=null`。Init 只合并 +`AGENTS.md` 并生成公共工件,不创建 `.opencode/` 设置或虚构 hook 配置。 diff --git a/helixharness/hosts/opencode/subagent.md b/helixharness/hosts/opencode/subagent.md new file mode 100644 index 0000000..0948551 --- /dev/null +++ b/helixharness/hosts/opencode/subagent.md @@ -0,0 +1,102 @@ +# OpenCode 子代理适配 + +本适配器把公共 Subagent 协议映射到 OpenCode V2 的原生 `subagent` 工具,不新增业务任务、依赖、 +写域、产物或完成条件。 + +```text +apply_shared_write_mode: child_scoped_write +ut_experience_write_mode: parent_finalize +result_encoding: native_agent_result +dispatch_mode: native_job +``` + +## 派发与等待 + +- 每个逻辑 job 使用一次 `subagent` 调用。普通 leaf job 使用内建 `general` agent;明确声明 + `delegation_policy=may_delegate` 的通用 job(当前为 Workspace Apply RepoJob)使用 + `helix-worker`;Init 角色和 UT worker 使用本插件注册的 `helix-` agent。业务角色正文由 + `prompt_source` 决定,agent ID 只负责选择运行配置。 +- 每次派发的 prompt 必须完整包含当前 Host Context、当前命令的 Dispatch Contract、已解析的 + `read_scope`/`write_scope`/`forbidden_scope`、`delegation_policy=leaf` 和 + `interaction_mode=host_native`。child 不得继续派生子代理;OpenCode 默认嵌套深度为一。 +- `subagent` 默认前台执行:父流程等待真实返回结果。需要并行的互斥只读或写域互斥 job 使用 + `background: true` 同时派发;不得用固定轮询或文件出现代替终态。 +- `helix-worker` 是 Host Kit 注册的通用运行角色,只执行 dispatch prompt,不承载业务步骤。 + 内建 `general` 默认禁止 `subagent`,因此不能用于 `may_delegate` 的 RepoJob。插件为所有 + canonical `helix-*` 角色追加 `subagent` deny 权限,强制公共协议默认的 `leaf`;只有 + `helix-worker` 保留派发能力。- 后台 child 完成时由 OpenCode 向父会话发送原生完成通知。父流程收到通知后读取该 child 的 + 真实结果;返回值中的 `sessionID` 只用于继续同一 child 会话,不作为业务工件或跨会话 handle。 +- 只把仍为 running 的 child 计入并发预算。OpenCode 不提供固定 slot/queue 计数;容量暂满、 + 等待中或单个 job 失败不得触发内联重试。 +- child 原生失败、取消或等待超时按 `BLOCKED: agent_failed` 收口,不自动转内联。只有当前 + 运行时明确没有暴露且无法发现 `subagent` 能力,并且命令 Dispatch Contract 允许时,才按同一 + prompt 串行内联一次。 + +## 工作区深化 + +OpenCode 默认子代理嵌套深度为一。Workspace Apply 的 RepoJob 明确声明 +`delegation_policy=may_delegate`,需要在当前 `opencode.json(c)` 中设置: + +```jsonc +{ + "experimental": { + "subagent_depth": 2 + } +} +``` + +该设置只允许 RepoJob child 继续派发其 Single Apply 所需的只读评审角色。未设置或深度不足时, +child 必须返回具体缺口并由父流程按 blocked 语义处理,不得把 depth 限制当作“subagent 不可用” +而降级内联,也不得虚构已完成的 Single Apply。Single 仓流程、Propose、Archive 和 UT 的默认 +`leaf` 语义不受影响。 + +## 写入所有权 + +- Apply 及通用子任务使用 `child_scoped_write`:child 只能写 Dispatch Contract 显式授权的 + 路径;共享索引、计划、checkpoint 和最终报告仍由父流程串行写入。 +- UT worker 使用 `parent_finalize`:worker 不写 `unittest-experience.md` 等共享文件,只在 + 结果中返回有界经验摘要;父流程验证后串行、原子合并。 +- 并行 job 的写域不得重叠。父流程必须校验真实 diff、写域和产物,文本自报不等于完成。 + +## 结果与验证 + +- 保持 OpenCode 原生 agent result,不要求 child 输出其他宿主的文本 marker。 +- 父流程从原生 result 映射 `completed|blocked|failed`、写入路径、验证结果和错误,并独立读取 + 关键产物。只读 job 通过命令约定的结构化结果返回,不写共享报告。 +- `result_reencode_budget=1` 只适用于 `helixharness_structured_text`;本宿主使用 + `native_agent_result`,不进入该分支。 + +## Init 原生角色映射 + +仅当当前会话实际列出下列 agent ID,且其正文来自本次 Host Context 绑定的同一插件安装时,Init +使用对应角色;否则使用内建 `general` 并在 prompt 中完整指定同一 `prompt_source`。不得搜索或 +猜测其他 agent 类型。 + +| Init job_id | OpenCode agent ID | +|---|---| +| `init_scan_tech` | `helix-scan-tech` | +| `init_scan_db` | `helix-scan-db` | +| `init_scan_api` | `helix-scan-api` | +| `init_scan_service` | `helix-scan-service` | +| `init_scan_boundary` | `helix-scan-boundary` | +| `init_scan_service_meta` | `helix-scan-service-meta` | +| `init_scan_frontend_meta` | `helix-scan-frontend-meta` | +| `init_scan_frontend_api` | `helix-scan-frontend-api` | +| `init_scan_frontend_routes` | `helix-scan-frontend-routes` | +| `init_scan_frontend_state` | `helix-scan-frontend-state` | +| `init_scan_frontend_components` | `helix-scan-frontend-components` | +| `init_scan_frontend_tracking` | `helix-scan-frontend-tracking` | +| `init_service_bootstrap` | `helix-init-service-bootstrap` | +| `init_frontend_bootstrap` | `helix-init-frontend-bootstrap` | +| `init_workspace_bootstrap` | `helix-init-workspace-bootstrap` | + +原生角色仍是直接执行 `prompt_source` 的 leaf。完整派发 message、唯一 job handle、依赖 DAG、 +授权写域和父流程产物验证保持不变;工具调用成功或角色自报不能代替这些门禁。 + +## 读取边界与恢复 + +- `read_scope` 是完整读取授权清单;父流程传入规范化绝对路径和 `ownership_root`。child 不得从 + workspace 根或父目录发起宽泛搜索,也不得跟随链接读取范围外内容。 +- 跨会话只持久化逻辑 job 状态、输入摘要和产物路径,不持久化 child sessionID。恢复时重新派发 + 没有可验证终态的 `in_progress` job。 +- child 的关闭和资源回收由 OpenCode 管理;公共命令不假设存在 close 工具。 diff --git a/helixharness/hosts/opencode/ut.md b/helixharness/hosts/opencode/ut.md new file mode 100644 index 0000000..892def6 --- /dev/null +++ b/helixharness/hosts/opencode/ut.md @@ -0,0 +1,51 @@ +# OpenCode UT 运行适配 + +本资源只把 [公共 UT 命令](../../commands/ut.md) 的 Claude 兼容工具语义映射到 OpenCode;不复制 +参数、扫描、6 Loop、重试、统一验证或报告步骤。子代理的通用派发、容量、等待、终态和回退完整 +服从当前 `resources.subagent_protocol`。 + +```text +dispatch_mode: native_job +experience_write_mode: parent_finalize +runtime_handle_in_queue: false +permission_prepare: host_approval +permission_cleanup: not_required +``` + +## 权限与工具映射 + +- 不读取、创建或修改其他宿主配置,不自动批准权限,不绕过 OpenCode permission 规则,也不修改 + 全局 `opencode.json(c)`。 +- `Read/Write/Edit/Bash` 使用当前运行时真实工具:`read`、`edit`/`write`/`patch`、`shell`。 +- `permission_prepare` 只验证当前工作区、临时目录和必要构建命令是否可用;需要额外权限时使用 + OpenCode 原生审批流程。未获得时保存证据并按公共命令标记 blocked/failed。 +- `permission_cleanup` 固定返回 `not_required`,因为本适配器不写项目权限文件。 + +## Worker Dispatch Contract + +每个逻辑 Worker ID 建立 `ut_worker_` job: + +| 字段 | 映射 | +|---|---| +| `prompt_source` | `agents/unit-test-worker.md`,worker 首个业务动作前完整读取 | +| `agent` | `helix-unit-test-worker`;不可用时使用内建 `general` 并传入同一完整 prompt | +| `depends_on` | 目标测试路径或共享 fixture 写域冲突时依赖前一 job | +| `write_scope` | worker 临时目录、自己的 result/defects、唯一目标测试文件 | +| `forbidden_scope` | 业务源码、构建配置、共享 queue/session/summary/experience、其他 worker 路径 | +| `expected_artifacts` | result;成功时目标测试文件;有缺陷时 defects | +| `validation` | 原生终态、公共 final、写域、结果结构、6 Loop、测试和覆盖率 | +| `unavailable_fallback` | 仅确认子代理能力不可用时,父流程按同一 prompt 串行内联 | + +- `dispatch_worker` 映射为 `subagent`。需要并发时使用 `background: true` 并行派发 ready job; + 不假定固定并发上限,不预计算 slot,不把容量暂满当不可用。 +- runtime handle 只保存在当前调用内存,不写业务工件;队列 `Agent ID` 列写 `-`。 +- `wait_worker` 使用前台结果或后台 child 的原生完成通知,不按固定频率轮询文件,不因静默自动 + 中断或重试。收到终态后父流程再校验 result/defects、目标测试文件和 write scope。 +- 原生失败、取消、越界写入或非法产物停止新任务准入,等待已派发 job 安全收口并输出部分结果。 +- 重新执行只恢复逻辑队列和已验证产物;旧 `in_progress` 无可验证终态时重置为 `pending`。 +- worker 使用 `parent_finalize`:不写共享经验,在 final 返回有界经验摘要,由父流程验证后串行、 + 原子合并。 + +结构合法的 worker 业务失败(包括高危 Bug)仍按公共 UT 状态机处理,不等同于宿主原生 job 失败。 +只有确认当前运行时没有暴露且无法发现 `subagent` 能力时才允许 inline fallback,并记录 +`WARN:opencode_subagent_unavailable`;容量暂满、等待中、单个 job 失败或取消不得触发 fallback。 diff --git a/helixharness/hosts/opencode/workflow-transition.md b/helixharness/hosts/opencode/workflow-transition.md new file mode 100644 index 0000000..051cd61 --- /dev/null +++ b/helixharness/hosts/opencode/workflow-transition.md @@ -0,0 +1,14 @@ +# OpenCode 工作流跳转 + +模式:`inline`。Propose `--loop` 按 Router 返回值,在当前主会话中依次执行 +`workflows/single/` 或 `workflows/workspace/` 下的唯一阶段正文。已路由的内部阶段复用保留 +feature、execution_scope 与 trigger,跳过重复入口路由,不递归调用 `session.command` 或其他 +`/helix:*` 命令。 + +Apply 的双轴评审完整执行 `skills/code-review/SKILL.md`,通过原生 `skill` 工具加载 +`helix-code-review`,按当前子代理协议派发 Standards 与 Spec 两个独立只读角色。评审属于同一个 +Apply Stage,不创建独立 Review 阶段,也不提前 finish coding entry。 + +当前阶段的 start、trace-event、finish 均以所选工作流及 `resources.telemetry_protocol` 为准。 +OpenCode 的 `telemetry=unsupported`,统计脚本返回 `unsupported_host` 时跳过统计并继续业务; +不得因此跳过评审、验证或完成门禁。 diff --git a/helixharness/opencode/core.ts b/helixharness/opencode/core.ts new file mode 100644 index 0000000..8a3c5b0 --- /dev/null +++ b/helixharness/opencode/core.ts @@ -0,0 +1,748 @@ +/** + * HelixHarness OpenCode plugin core. + * + * The canonical resources live at the plugin package root (`commands/`, + * `skills/`, `agents/` and `hosts/`). This module reads them at startup and + * renders deterministic registration payloads. It intentionally has no + * dependency on the OpenCode runtime so it can be unit tested with plain Bun. + */ + +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +export const HOST_ID = "opencode"; +export const HOST_API_VERSION = "1.1"; +export const PLUGIN_ID = "helixharness"; +export const REPO_ROOT_TOKEN = "@@HELIXHARNESS_REPO_ROOT@@"; +export const WORKER_AGENT_ID = "helix-worker"; + +export const COMMAND_NAMES = [ + "init", + "propose", + "apply", + "archive", + "bug-fix", + "ut", + "update", + "status", + "config", +] as const; + +export type CommandName = (typeof COMMAND_NAMES)[number]; + +export const REQUIRED_RESOURCE_ADAPTERS = [ + "command_projection", + "distribution", + "installer", + "lifecycle", + "project_config", + "project_hooks", + "runtime", + "subagent_protocol", + "telemetry_protocol", + "ut", + "workflow_transition", +] as const; + +const CAPABILITY_LEVELS = new Set(["native", "emulated", "unsupported"]); + +export interface HostManifest { + host_id: string; + host_api_version: string; + aliases: string[]; + capabilities: Record; + adapters: Record; + support?: { + level?: string; + display_name?: string; + evidence?: string | null; + limitations?: string[]; + }; +} + +export interface MarkdownDocument { + path: string; + frontmatter: Record; + body: string; +} + +export interface CommandSource extends MarkdownDocument { + name: CommandName; + description: string; +} + +export interface SkillSource extends MarkdownDocument { + id: string; + skillName: string; + description: string; + autoinvoke: boolean; +} + +export interface AgentSource extends MarkdownDocument { + id: string; + agentName: string; + description: string; +} + +export interface LoadedPlugin { + pluginRoot: string; + manifest: HostManifest; + resources: Record; + commands: CommandSource[]; + skills: SkillSource[]; + agents: AgentSource[]; + capabilities: Record; +} + +export interface HostContext { + canonicalHostId: string; + pluginRoot: string; + repoRoot?: string; + hostManifest: string; + hostApiVersion: string; + capabilities: Record; + resources: Record; +} + +export interface CommandInvocation { + sessionID: string; + prompt: { + text: string; + files?: unknown[]; + agents?: unknown[]; + skills?: unknown[]; + metadata?: Record; + }; + delivery?: "steer" | "queue"; +} + +export interface AgentDraft { + name: string; + description?: string; + system?: string; + mode: "subagent" | "primary" | "all"; + hidden: boolean; + permissions: Array<{ + action: string; + resource: string; + effect: "allow" | "ask" | "deny"; + }>; +} + +export interface ToolContent { + type: "text" | "file"; + text?: string; + uri?: string; + mime?: string; + name?: string; +} + +export interface ToolAfterEvent { + tool: string; + sessionID: string; + status: "completed" | "error"; + result?: { content?: string | ReadonlyArray }; +} + +/** + * The subset of the OpenCode plugin context used by this package. Keeping the + * shape structural makes the registration logic testable without a server. + */ +export interface PluginContext { + location: { directory: string }; + command: { + transform( + callback: (editor: { + add(definition: { + name: string; + description?: string; + execute(input: CommandInvocation): Promise; + }): void; + }) => void, + ): Promise; + }; + skill: { + transform( + callback: (editor: { + add(skill: { + id: string; + name: string; + description?: string; + autoinvoke?: boolean; + path: string; + content: string; + }): void; + }) => void, + ): Promise; + }; + agent: { + transform( + callback: (editor: { + update(id: string, update: (agent: AgentDraft) => void): void; + }) => void, + ): Promise; + }; + tool?: { + hook( + name: "execute.after", + callback: (event: ToolAfterEvent) => Promise | void, + ): Promise; + }; + session: { + get(input: { sessionID: string }): Promise<{ location?: { directory?: string } }>; + prompt(input: { + sessionID: string; + text: string; + files?: unknown[]; + agents?: unknown[]; + skills?: unknown[]; + metadata?: Record; + delivery?: "steer" | "queue"; + }): Promise; + }; +} + +export interface RegisterOptions { + pluginRoot?: string; +} + +export function pluginRootFromModule(moduleUrl: string = import.meta.url): string { + return path.resolve(path.dirname(fileURLToPath(moduleUrl)), ".."); +} + +function realpath(value: string): string { + return fs.realpathSync(value); +} + +function assertInside(root: string, candidate: string, label: string): string { + const resolved = path.resolve(candidate); + const relative = path.relative(root, resolved); + if ( + relative === "" || + (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)) + ) { + return resolved; + } + throw new Error(`${label} escapes the plugin root: ${resolved}`); +} + +function requireFile(filePath: string, label: string): string { + let stat: fs.Stats; + try { + stat = fs.statSync(filePath); + } catch { + throw new Error(`${label} does not exist: ${filePath}`); + } + if (!stat.isFile()) { + throw new Error(`${label} is not a file: ${filePath}`); + } + return filePath; +} + +function unquote(value: string): string { + const text = value.trim(); + if (text.length >= 2 && text.startsWith('"') && text.endsWith('"')) { + try { + const parsed = JSON.parse(text); + if (typeof parsed === "string") return parsed; + } catch { + // Fall through to the simple quote stripping below. + } + return text.slice(1, -1); + } + if (text.length >= 2 && text.startsWith("'") && text.endsWith("'")) { + return text.slice(1, -1).replaceAll("''", "'"); + } + return text; +} + +function parseScalar(value: string): string | boolean { + const text = value.trim(); + if (text === "true") return true; + if (text === "false") return false; + if (text === "null" || text === "~") return ""; + return unquote(text); +} + +/** + * Parses the flat frontmatter keys used by HelixHarness commands, skills and + * agents. Nested YAML is intentionally ignored; only top-level scalar fields + * are part of the host projection contract. + */ +export function parseFrontmatter(frontmatter: string): Record { + const result: Record = {}; + for (const line of frontmatter.split(/\r?\n/)) { + if (!line || /^\s/.test(line) || line.trimStart().startsWith("#")) continue; + const match = /^([A-Za-z0-9_-]+):(.*)$/.exec(line); + if (!match) continue; + const [, key, rawValue] = match; + const value = rawValue.trim(); + if (!value || value === ">" || value === ">-" || value === "|" || value === "|-") { + // Block scalars and nested maps are not used as scalar projection fields. + continue; + } + result[key] = parseScalar(value); + } + return result; +} + +export function parseMarkdown(source: string, filePath: string): MarkdownDocument { + const text = source.replace(/^\uFEFF/, ""); + const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text); + if (!match) { + return { path: filePath, frontmatter: {}, body: text }; + } + return { + path: filePath, + frontmatter: parseFrontmatter(match[1]), + body: text.slice(match[0].length), + }; +} + +export function loadManifest(pluginRoot: string): { + manifest: HostManifest; + resources: Record; +} { + const root = realpath(pluginRoot); + const manifestPath = path.join(root, "hosts", HOST_ID, "host.json"); + requireFile(manifestPath, "OpenCode host manifest"); + const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8")) as HostManifest; + if (manifest.host_id !== HOST_ID) { + throw new Error( + `OpenCode host manifest ID mismatch: ${String(manifest.host_id)} != ${HOST_ID}`, + ); + } + if (manifest.host_api_version !== HOST_API_VERSION) { + throw new Error( + `Unsupported OpenCode Host API version: ${String(manifest.host_api_version)}`, + ); + } + if (!manifest.capabilities || typeof manifest.capabilities !== "object") { + throw new Error("OpenCode host manifest is missing capabilities"); + } + for (const [name, level] of Object.entries(manifest.capabilities)) { + if (!CAPABILITY_LEVELS.has(level)) { + throw new Error(`Invalid OpenCode capability level: ${name}=${level}`); + } + } + if (!manifest.adapters || typeof manifest.adapters !== "object") { + throw new Error("OpenCode host manifest is missing adapters"); + } + + const resources: Record = {}; + for (const [name, reference] of Object.entries(manifest.adapters)) { + if (!reference.startsWith("resource:")) continue; + const target = reference.slice("resource:".length); + if (!target || path.isAbsolute(target)) { + throw new Error(`Invalid OpenCode resource adapter: ${name}`); + } + const resolved = assertInside(root, path.join(root, target), `OpenCode resource ${name}`); + resources[name] = requireFile(resolved, `OpenCode resource ${name}`); + } + + for (const name of REQUIRED_RESOURCE_ADAPTERS) { + if (!resources[name]) { + throw new Error(`OpenCode host manifest is missing required resource: ${name}`); + } + } + + return { manifest, resources }; +} + +export function loadCommands(pluginRoot: string): CommandSource[] { + const root = realpath(pluginRoot); + return COMMAND_NAMES.map((name) => { + const filePath = requireFile( + path.join(root, "commands", `${name}.md`), + `HelixHarness command ${name}`, + ); + const document = parseMarkdown(fs.readFileSync(filePath, "utf8"), filePath); + const description = + typeof document.frontmatter.description === "string" && + document.frontmatter.description.trim() + ? document.frontmatter.description.trim() + : `HelixHarness ${name}`; + return { ...document, name, description }; + }); +} + +export function loadSkills(pluginRoot: string): SkillSource[] { + const root = realpath(pluginRoot); + const skillsRoot = path.join(root, "skills"); + const entries = fs + .readdirSync(skillsRoot, { withFileTypes: true }) + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name) + .sort((left, right) => left.localeCompare(right)); + const skills: SkillSource[] = []; + for (const directory of entries) { + const filePath = path.join(skillsRoot, directory, "SKILL.md"); + if (!fs.existsSync(filePath)) continue; + const document = parseMarkdown(fs.readFileSync(filePath, "utf8"), filePath); + const description = + typeof document.frontmatter.description === "string" && + document.frontmatter.description.trim() + ? document.frontmatter.description.trim() + : `HelixHarness ${directory} skill`; + skills.push({ + ...document, + id: `helix-${directory}`, + skillName: directory, + description, + autoinvoke: document.frontmatter["disable-model-invocation"] !== true, + }); + } + return skills; +} + +export function loadAgents(pluginRoot: string): AgentSource[] { + const root = realpath(pluginRoot); + const agentsRoot = path.join(root, "agents"); + const files = fs + .readdirSync(agentsRoot, { withFileTypes: true }) + .filter((entry) => entry.isFile() && entry.name.endsWith(".md")) + .map((entry) => entry.name) + .sort((left, right) => left.localeCompare(right)); + return files.map((file) => { + const filePath = path.join(agentsRoot, file); + const document = parseMarkdown(fs.readFileSync(filePath, "utf8"), filePath); + const agentName = file.slice(0, -".md".length); + const description = + typeof document.frontmatter.description === "string" && + document.frontmatter.description.trim() + ? document.frontmatter.description.trim() + : `HelixHarness ${agentName} agent`; + return { + ...document, + id: `helix-${agentName}`, + agentName, + description, + }; + }); +} + +export function loadPluginResources(pluginRoot: string = pluginRootFromModule()): LoadedPlugin { + const root = realpath(pluginRoot); + const { manifest, resources } = loadManifest(root); + return { + pluginRoot: root, + manifest, + resources, + capabilities: { ...manifest.capabilities }, + commands: loadCommands(root), + skills: loadSkills(root), + agents: loadAgents(root), + }; +} + +export function hostContextFor( + plugin: LoadedPlugin, + repoRoot?: string, +): HostContext { + return { + canonicalHostId: plugin.manifest.host_id, + pluginRoot: plugin.pluginRoot, + repoRoot, + hostManifest: path.join(plugin.pluginRoot, "hosts", HOST_ID, "host.json"), + hostApiVersion: plugin.manifest.host_api_version, + capabilities: plugin.capabilities, + resources: plugin.resources, + }; +} + +function renderCapabilities(capabilities: Record): string[] { + const lines = ["| capability | level |", "| --- | --- |"]; + for (const name of Object.keys(capabilities).sort()) { + lines.push(`| \`${name}\` | ${capabilities[name]} |`); + } + return lines; +} + +function renderResources(resources: Record): string[] { + const lines = ["| resource | absolute path |", "| --- | --- |"]; + for (const name of Object.keys(resources).sort()) { + lines.push(`| \`${name}\` | \`${resources[name]}\` |`); + } + return lines; +} + +export function renderHostContext(context: HostContext): string { + const lines = [ + "# HelixHarness Host Context", + "", + "This context is pre-bound by the installed HelixHarness OpenCode plugin. Use these values directly; do not search for another plugin copy or another version.", + "", + `- canonical_host_id: \`${context.canonicalHostId}\``, + `- host_api_version: \`${context.hostApiVersion}\``, + `- plugin_root: \`${context.pluginRoot}\``, + ]; + if (context.repoRoot) { + lines.push(`- repo_root: \`${context.repoRoot}\``); + } + lines.push(`- host_manifest: \`${context.hostManifest}\``); + lines.push("", "## Capabilities", "", ...renderCapabilities(context.capabilities)); + lines.push("", "## Resolved resources", "", ...renderResources(context.resources)); + lines.push( + "", + "## OpenCode runtime bindings", + "", + "- `read_file` uses the native `read` tool.", + "- `edit_file` uses native `edit`, `write` or `patch` while preserving the current write scope and single-writer rule.", + "- `run_command` uses the native `shell` tool and keeps the real exit status.", + "- `invoke_skill(name)` loads the native skill ID `helix-`. Direct method-skill invocation is also registered as `helix-`.", + "- `spawn_job` uses the native `subagent` tool. Registered roles use `helix-`; generic jobs use the built-in `general` agent. Set `background: true` only when the command needs parallel work.", + "- `wait_job` uses the foreground subagent result, or the native background-completion notice for a background subagent, and then validates the returned result and artifacts.", + "- `ask_user` uses the native `question` tool and waits for a real answer.", + "- `update_plan` has no native OpenCode plan tool; update the current Feature `tasks.md` instead.", + "- `workflow_transition` is `inline`: execute the routed workflow body in this same session instead of recursively invoking another slash command.", + "- `stage_finish` calls the HelixHarness lifecycle scripts from the command body. OpenCode telemetry is `unsupported`, so telemetry steps return `unsupported_host` and business work continues.", + "- OpenCode plugin update is `unsupported`; `/helix:update` reports `continue_silently` and the user updates through OpenCode plugin management.", + "", + "Follow `resources.runtime`, `resources.subagent_protocol`, `resources.workflow_transition`, `resources.ut`, `resources.project_config`, `resources.project_hooks` and `resources.telemetry_protocol` for the complete host contract.", + ); + return lines.join("\n"); +} + +export function shellQuote(value: string): string { + if (value === "") return "''"; + return `'${value.replaceAll("'", "'\\''")}'`; +} + +export function substitutePlaceholders( + text: string, + context: HostContext, + argumentsText: string, +): string { + const replacements: Record = { + "{plugin_root}": context.pluginRoot, + "{repo_root}": context.repoRoot ?? "{repo_root}", + "{canonical_host_id}": context.canonicalHostId, + "{current_platform}": context.canonicalHostId, + "{SHELL_QUOTED_ARGUMENTS}": shellQuote(argumentsText), + $ARGUMENTS: argumentsText, + }; + return text.replace( + /\{plugin_root\}|\{repo_root\}|\{canonical_host_id\}|\{current_platform\}|\{SHELL_QUOTED_ARGUMENTS\}|\$ARGUMENTS/g, + (match) => replacements[match] ?? match, + ); +} + +/** + * Method skills are loaded by the native `skill` tool, which has no argument + * channel. Keep `$ARGUMENTS` literal so the model can interpret the user's + * message as the skill input, while still binding the plugin and host paths. + */ +export function substituteSkillPlaceholders( + text: string, + context: HostContext, +): string { + const replacements: Record = { + "{plugin_root}": context.pluginRoot, + "{repo_root}": context.repoRoot ?? "{repo_root}", + "{canonical_host_id}": context.canonicalHostId, + "{current_platform}": context.canonicalHostId, + }; + return text.replace( + /\{plugin_root\}|\{repo_root\}|\{canonical_host_id\}|\{current_platform\}/g, + (match) => replacements[match] ?? match, + ); +} + +export function buildCommandPrompt( + command: CommandSource, + context: HostContext, + argumentsText: string, +): string { + return [ + `# HelixHarness command /helix:${command.name}`, + "", + renderHostContext(context), + "", + "---", + "", + substitutePlaceholders(command.body, context, argumentsText).trimEnd(), + "", + ].join("\n"); +} + +export function buildSkillContent(skill: SkillSource, plugin: LoadedPlugin): string { + const context = hostContextFor(plugin, REPO_ROOT_TOKEN); + return [ + renderHostContext(context), + "", + "---", + "", + substituteSkillPlaceholders(skill.body, context).trimEnd(), + "", + ].join("\n"); +} + +export function buildAgentSystem(agent: AgentSource, plugin: LoadedPlugin): string { + const context = hostContextFor(plugin); + return [ + renderHostContext(context), + "", + "The dispatch prompt supplies the authoritative `repo_root` and the command-local Dispatch Contract.", + "", + "---", + "", + substituteSkillPlaceholders(agent.body, context).trimEnd(), + "", + ].join("\n"); +} + +/** + * Host-only role for generic jobs that legitimately declare + * `delegation_policy=may_delegate` (currently the Workspace Apply RepoJob). + * The built-in `general` agent cannot spawn subagents; this role carries the + * same complete dispatch prompt and only changes that host capability. + */ +export function buildWorkerSystem(plugin: LoadedPlugin): string { + const context = hostContextFor(plugin); + return [ + renderHostContext(context), + "", + "You execute one dispatched HelixHarness job described by the prompt.", + "", + "- Read the complete dispatch prompt before acting: `job_id`, `prompt_source`, `read_scope`, `write_scope`, `forbidden_scope`, `delegation_policy`, `interaction_mode`, expected artifacts and validation.", + "- Follow the current command contract and `prompt_source`; the Host Context above and the routed workflow body are the only business sources.", + "- When `delegation_policy=may_delegate`, delegate only the independent review roles required by the routed Single Apply through the native `subagent` tool. Otherwise stay a leaf and do not spawn children.", + "- If the native nesting depth does not permit the required delegation, return the concrete gap and `BLOCKED` reason to the parent instead of inlining or inventing the missing review.", + "- Do not write shared indexes, plans, checkpoints or final reports owned by the parent.", + ].join("\n"); +} + +export function replaceRepoRootToken( + content: string, + repoRoot: string, +): string { + return content.replaceAll(REPO_ROOT_TOKEN, repoRoot); +} + +function replaceToolResultContent( + result: ToolAfterEvent["result"], + repoRoot: string, +): void { + if (!result || result.content === undefined) return; + if (typeof result.content === "string") { + result.content = replaceRepoRootToken(result.content, repoRoot); + return; + } + result.content = result.content.map((item) => + item.type === "text" && item.text !== undefined + ? { ...item, text: replaceRepoRootToken(item.text, repoRoot) } + : item, + ); +} + +async function resolveRepoRoot( + ctx: PluginContext, + sessionID: string, + fallback: string, +): Promise { + try { + const session = await ctx.session.get({ sessionID }); + const directory = session.location?.directory; + return typeof directory === "string" && directory ? directory : fallback; + } catch { + return fallback; + } +} + +/** + * Registers every HelixHarness command, method skill and subagent role with an + * OpenCode plugin context. Commands execute the canonical `commands/*.md` + * contract with a pre-bound Host Context instead of copying Markdown into a + * project `.opencode/` directory. + */ +export async function registerHelixHarness( + ctx: PluginContext, + options: RegisterOptions = {}, +): Promise { + const plugin = loadPluginResources(options.pluginRoot ?? pluginRootFromModule()); + const fallbackRepoRoot = ctx.location.directory; + + await ctx.command.transform((editor) => { + for (const command of plugin.commands) { + editor.add({ + name: `helix:${command.name}`, + description: command.description, + async execute(input) { + const repoRoot = await resolveRepoRoot(ctx, input.sessionID, fallbackRepoRoot); + const context = hostContextFor(plugin, repoRoot); + const text = buildCommandPrompt( + command, + context, + input.prompt.text ?? "", + ); + await ctx.session.prompt({ + sessionID: input.sessionID, + text, + ...(input.prompt.files ? { files: input.prompt.files } : {}), + ...(input.prompt.agents ? { agents: input.prompt.agents } : {}), + ...(input.prompt.skills ? { skills: input.prompt.skills } : {}), + metadata: { "helixharness.command": command.name }, + ...(input.delivery ? { delivery: input.delivery } : {}), + }); + }, + }); + } + }); + + await ctx.skill.transform((editor) => { + for (const skill of plugin.skills) { + editor.add({ + id: skill.id, + name: `HelixHarness ${skill.skillName}`, + description: skill.description, + autoinvoke: skill.autoinvoke, + path: skill.path, + content: buildSkillContent(skill, plugin), + }); + } + }); + + await ctx.agent.transform((editor) => { + for (const agent of plugin.agents) { + editor.update(agent.id, (draft) => { + draft.name = `HelixHarness ${agent.agentName}`; + draft.description = agent.description; + draft.mode = "subagent"; + draft.hidden = false; + draft.system = buildAgentSystem(agent, plugin); + // Public contracts default to leaf delegation for canonical roles. + // Only the host-only worker role may spawn the Workspace Apply review + // agents when the dispatch declares may_delegate. + draft.permissions.push({ + action: "subagent", + resource: "*", + effect: "deny", + }); + if (agent.agentName === "unit-test-worker") { + draft.permissions.push({ + action: "question", + resource: "*", + effect: "deny", + }); + } + }); + } + editor.update(WORKER_AGENT_ID, (draft) => { + draft.name = "HelixHarness Worker"; + draft.description = + "Executes one dispatched HelixHarness job. Use for generic jobs that declare delegation_policy=may_delegate."; + draft.mode = "subagent"; + draft.hidden = false; + draft.system = buildWorkerSystem(plugin); + }); + }); + + if (ctx.tool) { + await ctx.tool.hook("execute.after", async (event) => { + if (event.tool !== "skill" || event.status !== "completed") return; + const repoRoot = await resolveRepoRoot(ctx, event.sessionID, fallbackRepoRoot); + replaceToolResultContent(event.result, repoRoot); + }); + } +} diff --git a/helixharness/opencode/index.ts b/helixharness/opencode/index.ts new file mode 100644 index 0000000..04d1b2a --- /dev/null +++ b/helixharness/opencode/index.ts @@ -0,0 +1,18 @@ +import type { Plugin } from "@opencode/plugin"; + +import { + PLUGIN_ID, + type PluginContext, + registerHelixHarness, +} from "./core.ts"; + +const helixharness: Plugin.Plugin = { + id: PLUGIN_ID, + async setup(ctx) { + // The real context is a superset of the structural surface used by the + // host-agnostic registration core. + await registerHelixHarness(ctx as unknown as PluginContext); + }, +}; + +export default helixharness; diff --git a/helixharness/opencode/tests/core.test.ts b/helixharness/opencode/tests/core.test.ts new file mode 100644 index 0000000..46d6287 --- /dev/null +++ b/helixharness/opencode/tests/core.test.ts @@ -0,0 +1,200 @@ +import { describe, expect, test } from "bun:test"; +import path from "node:path"; + +import { + COMMAND_NAMES, + HOST_ID, + REPO_ROOT_TOKEN, + buildAgentSystem, + buildCommandPrompt, + buildSkillContent, + buildWorkerSystem, + hostContextFor, + loadPluginResources, + parseFrontmatter, + parseMarkdown, + replaceRepoRootToken, + shellQuote, + substitutePlaceholders, + substituteSkillPlaceholders, +} from "../core.ts"; + +const PLUGIN_ROOT = path.resolve(import.meta.dir, "../.."); + +describe("frontmatter", () => { + test("parses flat scalar fields and ignores nested maps", () => { + const source = [ + "---", + 'name: "example"', + "description: 'single quoted'", + "disable-model-invocation: true", + "hooks:", + " PreToolUse:", + " - matcher: AskUserQuestion", + "---", + "", + "# Body", + "", + ].join("\n"); + const document = parseMarkdown(source, "/tmp/example.md"); + expect(document.frontmatter).toEqual({ + name: "example", + description: "single quoted", + "disable-model-invocation": true, + }); + expect(document.body).toStartWith("\n# Body"); + }); + + test("returns the whole document when frontmatter is absent", () => { + expect(parseFrontmatter("description: plain")).toEqual({ + description: "plain", + }); + }); +}); + +describe("plugin resources", () => { + test("loads every public command, skill and agent from the package root", () => { + const plugin = loadPluginResources(PLUGIN_ROOT); + + expect(plugin.pluginRoot).toBe(PLUGIN_ROOT); + expect(plugin.manifest.host_id).toBe(HOST_ID); + expect(plugin.manifest.host_api_version).toBe("1.1"); + expect(plugin.commands.map((command) => command.name)).toEqual([ + ...COMMAND_NAMES, + ]); + expect(plugin.commands.every((command) => command.description.length > 0)).toBe( + true, + ); + expect(plugin.skills.map((skill) => skill.id)).toContain("helix-code-review"); + expect(plugin.skills.map((skill) => skill.id)).toContain("helix-feedback"); + expect(plugin.agents.map((agent) => agent.id)).toContain("helix-scan-tech"); + expect(plugin.agents.map((agent) => agent.id)).toContain( + "helix-unit-test-worker", + ); + expect(plugin.skills.length).toBeGreaterThanOrEqual(8); + expect(plugin.agents.length).toBeGreaterThanOrEqual(16); + }); + + test("resolves required resources to absolute files inside the plugin", () => { + const plugin = loadPluginResources(PLUGIN_ROOT); + for (const [name, resource] of Object.entries(plugin.resources)) { + expect(path.isAbsolute(resource), name).toBe(true); + expect(resource.startsWith(PLUGIN_ROOT), name).toBe(true); + } + expect(plugin.resources.runtime).toBe( + path.join(PLUGIN_ROOT, "hosts/opencode/runtime.md"), + ); + expect(plugin.resources.telemetry_protocol).toBe( + path.join(PLUGIN_ROOT, "hosts/shared/telemetry.md"), + ); + expect(plugin.capabilities.command_surface).toBe("native"); + expect(plugin.capabilities.subagents).toBe("native"); + expect(plugin.capabilities.telemetry).toBe("unsupported"); + expect(plugin.capabilities.plugin_update).toBe("unsupported"); + }); + + test("maps disable-model-invocation to OpenCode autoinvoke=false", () => { + const plugin = loadPluginResources(PLUGIN_ROOT); + const brainstorming = plugin.skills.find( + (skill) => skill.id === "helix-brainstorming", + ); + const codeReview = plugin.skills.find( + (skill) => skill.id === "helix-code-review", + ); + expect(brainstorming?.autoinvoke).toBe(false); + expect(codeReview?.autoinvoke).toBe(true); + }); +}); + +describe("rendering", () => { + test("renders a pre-bound context with every capability and resource", () => { + const plugin = loadPluginResources(PLUGIN_ROOT); + const context = hostContextFor(plugin, "/repo"); + const text = buildCommandPrompt( + plugin.commands.find((command) => command.name === "apply")!, + context, + "--feature demo", + ); + + expect(text).toContain("# HelixHarness Host Context"); + expect(text).toContain("canonical_host_id: `opencode`"); + expect(text).toContain(`plugin_root: \`${PLUGIN_ROOT}\``); + expect(text).toContain("repo_root: `/repo`"); + expect(text).toContain("`helix-`"); + expect(text).toContain("`workflow_transition` is `inline`"); + expect(text).toContain("`update_plan` has no native OpenCode plan tool"); + expect(text).toContain("HelixHarness 公共命令唯一契约"); + expect(text).toContain("--arguments='--feature demo'"); + }); + + test("substitutes command placeholders once and keeps user arguments literal", () => { + const plugin = loadPluginResources(PLUGIN_ROOT); + const context = hostContextFor(plugin, "/repo"); + const literal = "--note {plugin_root} $ARGUMENTS"; + + expect(substitutePlaceholders("$ARGUMENTS", context, literal)).toBe(literal); + expect( + substitutePlaceholders( + "python3 {plugin_root}/scripts/x.py --repo-root {repo_root} {SHELL_QUOTED_ARGUMENTS}", + context, + literal, + ), + ).toBe( + `python3 ${PLUGIN_ROOT}/scripts/x.py --repo-root /repo ${shellQuote(literal)}`, + ); + }); + + test("shell quoting is single-argument safe", () => { + expect(shellQuote("")).toBe("''"); + expect(shellQuote("plain")).toBe("'plain'"); + expect(shellQuote("it's")).toBe("'it'\\''s'"); + }); + + test("method skills carry a repo-root marker until the tool hook binds the session", () => { + const plugin = loadPluginResources(PLUGIN_ROOT); + const skill = plugin.skills.find((item) => item.id === "helix-feedback")!; + const content = buildSkillContent(skill, plugin); + + expect(content).toContain(REPO_ROOT_TOKEN); + expect(content).toContain("canonical_host_id: `opencode`"); + expect(content).toContain("$ARGUMENTS"); + expect(content).toContain("`opencode`"); + expect(replaceRepoRootToken(content, "/work/repo")).toContain( + "repo_root: `/work/repo`", + ); + expect(replaceRepoRootToken(content, "/work/repo")).not.toContain( + REPO_ROOT_TOKEN, + ); + }); + + test("skill placeholder substitution keeps the skill argument convention", () => { + const plugin = loadPluginResources(PLUGIN_ROOT); + const context = hostContextFor(plugin, "/repo"); + expect( + substituteSkillPlaceholders( + "$ARGUMENTS {plugin_root} {repo_root} {current_platform}", + context, + ), + ).toBe(`$ARGUMENTS ${PLUGIN_ROOT} /repo opencode`); + }); + + test("agent systems bind the plugin and resources but leave repo_root to dispatch", () => { + const plugin = loadPluginResources(PLUGIN_ROOT); + const agent = plugin.agents.find((item) => item.id === "helix-scan-tech")!; + const system = buildAgentSystem(agent, plugin); + + expect(system).toContain("canonical_host_id: `opencode`"); + expect(system).toContain("The dispatch prompt supplies the authoritative `repo_root`"); + expect(system).not.toContain("repo_root: `"); + expect(system).toContain("任务:生成项目技术栈与架构全景文档"); + }); + + test("the delegating worker role stays leaf unless the dispatch allows delegation", () => { + const plugin = loadPluginResources(PLUGIN_ROOT); + const system = buildWorkerSystem(plugin); + + expect(system).toContain("canonical_host_id: `opencode`"); + expect(system).toContain("`delegation_policy=may_delegate`"); + expect(system).toContain("Do not write shared indexes"); + }); +}); diff --git a/helixharness/opencode/tests/e2e.test.ts b/helixharness/opencode/tests/e2e.test.ts new file mode 100644 index 0000000..d35eaeb --- /dev/null +++ b/helixharness/opencode/tests/e2e.test.ts @@ -0,0 +1,174 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +const PLUGIN_ROOT = path.resolve(import.meta.dir, "../.."); +const ENABLED = process.env.HELIXHARNESS_OPENCODE_E2E === "1"; +const PASSWORD = "helix-e2e-password"; + +function authorization(): string { + return `Basic ${btoa(`opencode:${PASSWORD}`)}`; +} + +async function request( + port: number, + route: string, + init: RequestInit = {}, +): Promise { + return fetch(`http://127.0.0.1:${port}${route}`, { + ...init, + headers: { + authorization: authorization(), + "content-type": "application/json", + ...(init.headers ?? {}), + }, + }); +} + +async function waitForServer(port: number): Promise { + const deadline = Date.now() + 30_000; + let lastError: unknown; + while (Date.now() < deadline) { + try { + // The agent registry request also activates the location's plugins. + const response = await request(port, "/api/agent"); + if (response.ok) return; + lastError = new Error(`HTTP ${response.status}`); + } catch (error) { + lastError = error; + } + await new Promise((resolve) => setTimeout(resolve, 250)); + } + throw new Error(`OpenCode server did not become ready: ${String(lastError)}`); +} + +describe.skipIf(!ENABLED)("installed OpenCode plugin", () => { + let directory = ""; + let port = 0; + let server: ReturnType | undefined; + + beforeAll(async () => { + directory = fs.mkdtempSync(path.join(os.tmpdir(), "helix-opencode-e2e-")); + fs.writeFileSync( + path.join(directory, "opencode.json"), + `${JSON.stringify( + { + $schema: "https://opencode.ai/config.json", + plugins: [PLUGIN_ROOT], + }, + null, + 2, + )}\n`, + ); + port = 5200 + Math.floor(Math.random() * 300); + server = Bun.spawn( + ["opencode", "serve", "--port", String(port), "--print-logs"], + { + cwd: directory, + env: { ...process.env, OPENCODE_PASSWORD: PASSWORD }, + stdout: "ignore", + stderr: "ignore", + }, + ); + await waitForServer(port); + }, 45_000); + + afterAll(() => { + server?.kill(); + if (directory) fs.rmSync(directory, { recursive: true, force: true }); + }); + + test("registers commands, method skills and subagent roles", async () => { + const commands = (await (await request(port, "/api/command")).json()) as { + data: Array<{ name: string }>; + }; + expect(commands.data.map((command) => command.name)).toEqual( + expect.arrayContaining([ + "helix:init", + "helix:propose", + "helix:apply", + "helix:archive", + "helix:bug-fix", + "helix:ut", + "helix:update", + "helix:status", + "helix:config", + ]), + ); + + const skills = (await (await request(port, "/api/skill")).json()) as { + data: Array<{ id: string; path: string; content: string }>; + }; + const feedback = skills.data.find((skill) => skill.id === "helix-feedback"); + expect(feedback).toBeDefined(); + expect(feedback?.path).toBe(path.join(PLUGIN_ROOT, "skills/feedback/SKILL.md")); + expect(feedback?.content).toContain("canonical_host_id: `opencode`"); + + const agents = (await (await request(port, "/api/agent")).json()) as { + data: Array<{ id: string; mode: string }>; + }; + const agentIds = agents.data.map((agent) => agent.id); + expect(agentIds).toEqual( + expect.arrayContaining([ + "helix-scan-tech", + "helix-scan-db", + "helix-init-service-bootstrap", + "helix-unit-test-worker", + "helix-worker", + ]), + ); + expect( + agents.data.filter((agent) => agent.id.startsWith("helix-")).every( + (agent) => agent.mode === "subagent", + ), + ).toBe(true); + }, 20_000); + + test("a native command admits the canonical contract with Host Context", async () => { + const sessionResponse = await request(port, "/api/session", { + method: "POST", + body: JSON.stringify({ + title: "helix-e2e", + model: { providerID: "mock", id: "none" }, + }), + }); + const session = (await sessionResponse.json()) as { + data: { id: string }; + }; + + const commandResponse = await request( + port, + `/api/session/${session.data.id}/command`, + { + method: "POST", + body: JSON.stringify({ name: "helix:status", text: "--help" }), + }, + ); + expect(commandResponse.ok).toBe(true); + + const context = (await ( + await request(port, `/api/session/${session.data.id}/context`) + ).json()) as { + data: Array<{ + type?: string; + metadata?: Record; + text?: string; + }>; + }; + const user = context.data.find( + (message) => message.metadata?.["helixharness.command"] === "status", + ); + expect(user?.text).toBeDefined(); + expect(user?.text).toContain("# HelixHarness command /helix:status"); + expect(user?.text).toContain("canonical_host_id: `opencode`"); + expect(user?.text).toContain(`plugin_root: \`${PLUGIN_ROOT}\``); + expect(user?.text).toContain(`repo_root: \`${fs.realpathSync(directory)}\``); + expect(user?.text).toContain("--help"); + expect(user?.text).toContain("HelixHarness 公共命令唯一契约"); + expect(user?.text).not.toContain("$ARGUMENTS"); + expect(user?.text).not.toContain("{plugin_root}"); + expect(user?.text).not.toContain("{repo_root}"); + expect(user?.text).not.toContain("{SHELL_QUOTED_ARGUMENTS}"); + }, 30_000); +}); diff --git a/helixharness/opencode/tests/plugin.test.ts b/helixharness/opencode/tests/plugin.test.ts new file mode 100644 index 0000000..1fd2f52 --- /dev/null +++ b/helixharness/opencode/tests/plugin.test.ts @@ -0,0 +1,184 @@ +import { describe, expect, test } from "bun:test"; +import path from "node:path"; + +import { + REPO_ROOT_TOKEN, + type PluginContext, + registerHelixHarness, +} from "../core.ts"; + +const PLUGIN_ROOT = path.resolve(import.meta.dir, "../.."); + +interface Captured { + commands: Array>; + skills: Array>; + agents: Array<{ id: string; draft: Record }>; + prompts: Array>; + toolHooks: Array<(event: any) => Promise | void>; +} + +function createContext(options: { + location?: string; + sessionDirectory?: string; +} = {}): { ctx: PluginContext; captured: Captured } { + const captured: Captured = { + commands: [], + skills: [], + agents: [], + prompts: [], + toolHooks: [], + }; + const ctx = { + location: { directory: options.location ?? "/project" }, + command: { + async transform(callback: (editor: any) => void) { + callback({ add: (command: any) => captured.commands.push(command) }); + }, + }, + skill: { + async transform(callback: (editor: any) => void) { + callback({ add: (skill: any) => captured.skills.push(skill) }); + }, + }, + agent: { + async transform(callback: (editor: any) => void) { + callback({ + update: (id: string, update: (draft: any) => void) => { + const draft: Record = { + name: id, + mode: "primary", + hidden: false, + permissions: [], + }; + update(draft); + captured.agents.push({ id, draft }); + }, + }); + }, + }, + tool: { + async hook(_name: string, callback: (event: any) => Promise | void) { + captured.toolHooks.push(callback); + }, + }, + session: { + async get() { + return { + location: { directory: options.sessionDirectory ?? "/session-repo" }, + }; + }, + async prompt(input: Record) { + captured.prompts.push(input); + }, + }, + }; + return { ctx: ctx as unknown as PluginContext, captured }; +} + +describe("OpenCode registration", () => { + test("registers nine commands, all method skills and all subagent roles", async () => { + const { ctx, captured } = createContext(); + await registerHelixHarness(ctx, { pluginRoot: PLUGIN_ROOT }); + + expect(captured.commands.map((command) => command.name)).toEqual([ + "helix:init", + "helix:propose", + "helix:apply", + "helix:archive", + "helix:bug-fix", + "helix:ut", + "helix:update", + "helix:status", + "helix:config", + ]); + expect(captured.commands.every((command) => command.description)).toBe(true); + expect(captured.skills.map((skill) => skill.id)).toContain("helix-code-review"); + expect(captured.skills.every((skill) => path.isAbsolute(skill.path))).toBe(true); + expect(captured.agents.map((agent) => agent.id)).toContain("helix-scan-tech"); + expect(captured.agents.map((agent) => agent.id)).toContain("helix-worker"); + expect(captured.agents.every((agent) => agent.draft.mode === "subagent")).toBe( + true, + ); + const canonicalAgents = captured.agents.filter( + (agent) => agent.id !== "helix-worker", + ); + expect( + canonicalAgents.every((agent) => + agent.draft.permissions.some( + (rule: Record) => + rule.action === "subagent" && + rule.resource === "*" && + rule.effect === "deny", + ), + ), + ).toBe(true); + const worker = captured.agents.find((agent) => agent.id === "helix-worker")!; + expect( + worker.draft.permissions.some( + (rule: Record) => rule.action === "subagent", + ), + ).toBe(false); + expect(captured.toolHooks).toHaveLength(1); + }); + + test("command execution injects Host Context and the canonical contract", async () => { + const { ctx, captured } = createContext(); + await registerHelixHarness(ctx, { pluginRoot: PLUGIN_ROOT }); + const init = captured.commands.find((command) => command.name === "helix:init")!; + + await init.execute({ + sessionID: "ses_test", + prompt: { text: "--workspace --knowledge", files: [{ uri: "file:///x" }] }, + delivery: "queue", + }); + + expect(captured.prompts).toHaveLength(1); + const prompt = captured.prompts[0]; + expect(prompt.sessionID).toBe("ses_test"); + expect(prompt.delivery).toBe("queue"); + expect(prompt.files).toEqual([{ uri: "file:///x" }]); + expect(prompt.metadata).toEqual({ "helixharness.command": "init" }); + expect(prompt.text).toContain("# HelixHarness command /helix:init"); + expect(prompt.text).toContain("canonical_host_id: `opencode`"); + expect(prompt.text).toContain("repo_root: `/session-repo`"); + expect(prompt.text).toContain("--workspace --knowledge"); + expect(prompt.text).toContain("HelixHarness 公共命令唯一契约"); + expect(prompt.text).not.toContain("$ARGUMENTS"); + }); + + test("the skill result hook binds repo_root to the requesting session", async () => { + const { ctx, captured } = createContext(); + await registerHelixHarness(ctx, { pluginRoot: PLUGIN_ROOT }); + + const result = { + content: `repo_root: \`${REPO_ROOT_TOKEN}\``, + }; + await captured.toolHooks[0]({ + tool: "skill", + sessionID: "ses_test", + status: "completed", + result, + }); + expect(result.content).toBe("repo_root: `/session-repo`"); + + const arrayResult = { + content: [{ type: "text" as const, text: `x ${REPO_ROOT_TOKEN}` }], + }; + await captured.toolHooks[0]({ + tool: "skill", + sessionID: "ses_test", + status: "completed", + result: arrayResult, + }); + expect(arrayResult.content[0].text).toBe("x /session-repo"); + + const untouched = { content: "no marker" }; + await captured.toolHooks[0]({ + tool: "read", + sessionID: "ses_test", + status: "completed", + result: untouched, + }); + expect(untouched.content).toBe("no marker"); + }); +}); diff --git a/helixharness/package.json b/helixharness/package.json new file mode 100644 index 0000000..a4f4b39 --- /dev/null +++ b/helixharness/package.json @@ -0,0 +1,23 @@ +{ + "name": "helixharness-opencode", + "version": "1.0.0", + "description": "HelixHarness workflow plugin for OpenCode, with commands, method skills and subagent roles", + "type": "module", + "license": "Apache-2.0", + "author": { + "name": "HelixHarness contributors" + }, + "exports": { + ".": "./opencode/index.ts" + }, + "scripts": { + "test": "bun test opencode/tests", + "typecheck": "tsc --noEmit" + }, + "devDependencies": { + "@opencode/plugin": "^2.2.2", + "@types/node": "^22.0.0", + "bun-types": "^1.3.0", + "typescript": "^5.9.0" + } +} diff --git a/helixharness/reference/eval-protocol.md b/helixharness/reference/eval-protocol.md index c85bc8f..f14632a 100644 --- a/helixharness/reference/eval-protocol.md +++ b/helixharness/reference/eval-protocol.md @@ -25,15 +25,18 @@ Claude Code: ${CLAUDE_CONFIG_DIR:-$HOME/.claude}/helixharness/telemetry-consent- Codex: ${CODEX_HOME:-$HOME/.codex}/helixharness/telemetry-consent-cache.json ``` +OpenCode 的 `telemetry=unsupported`,没有 consent 缓存路径;统计脚本返回 `unsupported_host` +后继续业务,不读写上述文件。 + 用户主动查询和修改配置使用 `/helix:config`,通过 `scripts/user_config.py` 复用本协议 API;默认查看不触发 CLI resolve 的清理副作用,显式修改仍由既有授权 API 管理 scope、epoch 和清理。 缓存必须由 plugin 捆绑的 `scripts/telemetry_consent.py` 读写,命令或 Agent 不得自行构造、修改 JSON,也不得自行猜测项目指纹。调用方式: ```text -python3 {plugin_root}/scripts/telemetry_consent.py --repo-root {repo_root} --platform {claude-code|codex} resolve -python3 {plugin_root}/scripts/telemetry_consent.py --repo-root {repo_root} --platform {claude-code|codex} set --scope {project|user} --mode disabled -python3 {plugin_root}/scripts/telemetry_consent.py --repo-root {repo_root} --platform {claude-code|codex} set --scope {project|user} --mode enabled --source {interactive-user|explicit-command} --user-confirmed -python3 {plugin_root}/scripts/telemetry_consent.py --repo-root {repo_root} --platform {claude-code|codex} choose --action {allowed_action.id} --user-confirmed +python3 {plugin_root}/scripts/telemetry_consent.py --repo-root {repo_root} --platform {canonical_host_id} resolve +python3 {plugin_root}/scripts/telemetry_consent.py --repo-root {repo_root} --platform {canonical_host_id} set --scope {project|user} --mode disabled +python3 {plugin_root}/scripts/telemetry_consent.py --repo-root {repo_root} --platform {canonical_host_id} set --scope {project|user} --mode enabled --source {interactive-user|explicit-command} --user-confirmed +python3 {plugin_root}/scripts/telemetry_consent.py --repo-root {repo_root} --platform {canonical_host_id} choose --action {allowed_action.id} --user-confirmed ``` 授权与异步地址分别判断:`telemetry_consent.py resolve` 正常按授权缓存和提醒周期返回 `prompt_due` 与 `allowed_actions`,没有地址或地址无效也不抑制开启/续期问询。地址诊断与 Runtime 共用 `telemetry_async.endpoint_status`:优先读取 `${HELIXHARNESS_TELEMETRY_HOME:-~/.helixharness/telemetry}/config.json` 的非空 `endpoint`,否则使用 `scripts/reporting_config.py` 的 `DEFAULT_REPORT_ENDPOINT` 发布默认值(当前为空);地址环境变量不再参与解析,只校验配置,不探测服务在线状态。未配置时附带 `reason=endpoint_unconfigured`;地址或文件无效时附带 `reason=endpoint_invalid` 和 `WARN:telemetry_endpoint_invalid`。这些字段仅说明异步通路不可用,不能作为跳过授权交互的条件。`resolve` 不改写授权缓存和提醒时间,用户确认后由 `choose` 正常更新。 `endpoint_unconfigured` 仅供内部诊断,正常授权交互、选择结果和阶段摘要不显示地址缺失或未异步上报提示,也不主动提醒配置;仅在用户主动查询或排障时解释。地址无效的 warning 保留。 diff --git a/helixharness/reference/eval-supplement-protocol.md b/helixharness/reference/eval-supplement-protocol.md index 65c9555..f3fd623 100644 --- a/helixharness/reference/eval-supplement-protocol.md +++ b/helixharness/reference/eval-supplement-protocol.md @@ -29,7 +29,7 @@ Telemetry consent 只授权记录和上报,不单独授权 Git commit 或 push 统计开启且 Archive 成功记账后,finish CLI 返回 `NOTICE:lite_telemetry_delivery_required`,工作流在最终交付选择前原样展示一次:过程统计 Supplement 自动异步上报,但最终 eval-log 必须提交并随功能分支 push 才能完成平台关联。同一需求的本次交付已经提醒时,恢复、继续执行或复用已有授权均不重复展示。`commit-ledger` 成功或幂等跳过时不返回该 NOTICE;工作流也不重复展示旧版 CLI 返回的同名提示。用户选择后的最终回执只报告实际提交/推送结果:有效最终 Ledger 已提交并随远端 HEAD 验证成功时说明“平台可继续关联统计”;未提交或未推送时说明对应待完成动作及“平台暂时无法关联”;失败时说明真实原因,不把选择等同于执行成功,也不重复通用 NOTICE。 -业务合同与统计支持集相互独立:业务正文和三工件不记录宿主,同一需求可以跨宿主继续;`current_platform` 只用于本次 Telemetry Adapter 选择。当前只有 Claude Code 与 Codex 注册 Adapter。CLI 输入对大小写和宿主包装标签宽松:只要包含 `claude` 或 `codex` 子串,就分别规范化为 `claude-code` 或 `codex`;同时包含两类子串时因歧义拒绝,公开 Ledger 与 Supplement 始终只落 canonical ID。其他未注册统计宿主按 `unsupported_host` 跳过统计,但业务必须继续。新增统计宿主只在 `scripts/telemetry_hosts/` 实现并注册 `HostAdapter`(含统一 Supplement 窗口),不得修改业务正文,也不得在 Ledger、Collector 或 Schema 中增加平台分支。 +业务合同与统计支持集相互独立:业务正文和三工件不记录宿主,同一需求可以跨宿主继续;`current_platform` 只用于本次 Telemetry Adapter 选择。当前只有 Claude Code 与 Codex 注册 Adapter;OpenCode 明确声明 `telemetry=unsupported`,按未注册统计宿主处理。CLI 输入对大小写和宿主包装标签宽松:只要包含 `claude` 或 `codex` 子串,就分别规范化为 `claude-code` 或 `codex`;同时包含两类子串时因歧义拒绝,公开 Ledger 与 Supplement 始终只落 canonical ID。其他未注册统计宿主(包括 OpenCode)按 `unsupported_host` 跳过统计,但业务必须继续。新增统计宿主只在 `scripts/telemetry_hosts/` 实现并注册 `HostAdapter`(含统一 Supplement 窗口),不得修改业务正文,也不得在 Ledger、Collector 或 Schema 中增加平台分支。 同一 feature 允许跨宿主接力。Ledger 的每个 entry 独立记录本次实际 `platform` 与 locator;不同 entry 可以来自不同已注册 Adapter,Supplement 仍按 `entry_id` 精确关联。未注册宿主只缺少该次统计,不阻塞业务。 diff --git a/helixharness/reference/host-api.md b/helixharness/reference/host-api.md index 2030825..2afb2be 100644 --- a/helixharness/reference/host-api.md +++ b/helixharness/reference/host-api.md @@ -1,6 +1,6 @@ # HelixHarness Host API 1.1 -HelixHarness 当前只发布 Claude Code 与 Codex 两个 Host Kit。公共业务契约与宿主运行机制保持解耦: +HelixHarness 当前发布 Claude Code、Codex 与 OpenCode 三个 Host Kit。公共业务契约与宿主运行机制保持解耦: `commands/`、`workflows/`、共享 `skills/`、`agents/` 和 `templates/` 定义业务结果,`hosts/{host-id}/` 只定义如何在某个宿主中安装、发现和执行。 @@ -13,10 +13,12 @@ HelixHarness 当前只发布 Claude Code 与 Codex 两个 Host Kit。公共业 当前 Registry 必须只发现: - `claude-code`:原生命令、Hook 生命周期、原生 Agent、Claude marketplace; -- `codex`:Skill 命令投影、独立启动/结束 Hook 与命令驱动阶段生命周期、Codex subagent、Codex marketplace。 +- `codex`:Skill 命令投影、独立启动/结束 Hook 与命令驱动阶段生命周期、Codex subagent、Codex marketplace; +- `opencode`:原生命令/Skill/Agent 注册、插件内 Host Context 注入、原生 subagent、OpenCode plugin 分发。 -两者使用 Host API 1.1,支持等级均为 Stable。仓库不提供其他平台的 manifest、安装器、分发清单、 -运行时适配器或入口文件。未知宿主必须关闭失败,不能回退到 Claude Code 或借用 Codex 资源。 +三者使用 Host API 1.1。Claude Code 与 Codex 的支持等级为 Stable;OpenCode 为 Preview,明确声明 +`telemetry` 与 `plugin_update` 为 `unsupported`,不提供其他平台的 manifest、安装器、分发清单、 +运行时适配器或入口文件。未知宿主必须关闭失败,不能回退到 Claude Code 或借用其他 Host Kit 资源。 ## 共享核心与 Host Kit @@ -119,8 +121,10 @@ Context,不在每条命令中启动 Python 重新识别。 ## 插件 Hook 分发 -两个宿主的原生 plugin manifest 都必须显式声明 `hosts/{host-id}/hooks.json`。 +Claude Code 与 Codex 的原生 plugin manifest 必须显式声明 `hosts/{host-id}/hooks.json`。 不得发布根目录默认 `hooks/hooks.json`,以免客户端自动装载另一个宿主的入口。 +OpenCode 不发布 hook manifest,而是在 `opencode/index.ts` 的 `setup` 中注册 surface,并按 +`hosts/opencode/lifecycle.md` 声明 `session_start=emulated` 和 `session_events=unsupported`。 Hook 入口位于对应 Host Kit,绑定自身安装目录的规范 manifest,转换宿主事件与环境持久化。 共享 `scripts/lifecycle_service.py` 只消费显式 HostManifest 和规范事件,不猜平台。 项目级检查 hooks 独立使用 `project_hooks` 合同;单仓 Init 的实际 settings 缺失或重复必须阻断。 diff --git a/helixharness/reference/host-runtime-protocol.md b/helixharness/reference/host-runtime-protocol.md index 5d2128a..3d01b7b 100644 --- a/helixharness/reference/host-runtime-protocol.md +++ b/helixharness/reference/host-runtime-protocol.md @@ -10,13 +10,15 @@ Host Context 在 command/Skill 进入业务工作流前由安装分发或宿主 启动 Python 进程重新识别: 1. Claude Code 的 `commands/{entry}.md` plugin command 表面绑定 `hosts/claude-code/host.json`; -2. Codex 的 `hosts/codex/skills/{entry}/SKILL.md` plugin Skill 表面绑定 `hosts/codex/host.json`。 +2. Codex 的 `hosts/codex/skills/{entry}/SKILL.md` plugin Skill 表面绑定 `hosts/codex/host.json`; +3. OpenCode 的 `opencode/index.ts` 注册的原生命令或 Skill 表面绑定 `hosts/opencode/host.json`。 “分发表面绑定”是一种确定性入口绑定,不要求宿主额外设置环境变量或在目标项目 生成 settings:当前产品加载 `resources.command_projection` 已声明的原生命令或宿主 Skill 入口时,产品身份与该入口所属插件分发表面已经唯一确定 Host Context。Claude Code 原生命令以 `commands/{entry}.md` 为入口和公共 contract;Codex 命令以宿主 Skill 为入口、以同一 -`commands/{entry}.md` 为公共 contract。根 `skills/{name}/SKILL.md` 只保存非命令的方法能力; +`commands/{entry}.md` 为公共 contract;OpenCode 通过插件命令执行器加载同一 contract 并注入 +Host Context。根 `skills/{name}/SKILL.md` 只保存非命令的方法能力; 在已绑定 workflow 内调用时继承当前 Host Context,直接调用时由当前插件分发表面绑定。 入口使用自身实际路径和 projection 声明的固定资源定位插件根;宿主私有路径换算只写在对应 Host Kit,不得假定所有入口都位于根 `skills/{entry}/`。这一确定性路径换算不属于宿主发现; @@ -34,7 +36,8 @@ Host Kit,不得假定所有入口都位于根 `skills/{entry}/`。这一确定 `scripts/host_runtime_cli.py resolve` 保留为安装器、开发诊断和契约测试工具;正常业务命令不得为了 识别宿主调用它。这样 Python 不可用且 telemetry 关闭时,原本不依赖 Python 的 Claude Code/Codex -业务动作不会因 Host Registry 新增阻断或工具调用。 +业务动作不会因 Host Registry 新增阻断或工具调用;OpenCode 插件同样只用 TypeScript 完成注册与 +Host Context 注入。 当前产品与插件分发表面无法共同确定唯一宿主、规范 ID 含路径分隔符或 `..`、清单不匹配、版本 不支持、资源越过插件根目录时,立即返回 `BLOCKED: helixharness_host_unavailable`。不得从 PATH 中 @@ -65,7 +68,7 @@ Host Kit,不得假定所有入口都位于根 `skills/{entry}/`。这一确定 command 中的 `Read`、`Write`、`Edit`、`Bash`、`AskUserQuestion`、`TodoWrite`、 `Skill`、`Agent` 和 `Task` 属于 HelixHarness Tool Semantics 的 Claude Code 兼容拼写。 -Codex 不得虚构同名工具,必须按 Host Kit 映射为上述逻辑动作。 +Codex 与 OpenCode 不得虚构同名工具,必须按 Host Kit 映射为上述逻辑动作。 ## 3. 能力选择规则 @@ -99,7 +102,8 @@ Codex 不得虚构同名工具,必须按 Host Kit 映射为上述逻辑动作 ## 5. 未来宿主扩展契约 -当前仓库不发布其他 Host Kit。未来重新接入新宿主时,正常改动范围应限制为: +当前仓库发布 Claude Code、Codex 与 OpenCode Host Kit,其中 OpenCode 的 telemetry 和 +plugin_update 明确为 `unsupported`。未来重新接入新宿主时,正常改动范围应限制为: - `hosts/{host-id}/host.json`; - 该 Host Kit 引用的分发、安装、入口投影、启动、工具映射、生命周期、项目配置、遥测或更新适配器; @@ -107,5 +111,5 @@ Codex 不得虚构同名工具,必须按 Host Kit 映射为上述逻辑动作 如果接入必须修改 `commands/`、共享 `skills/`、`scripts/metrics.py`、 `scripts/version_update.py` 或 Host Registry 中的平台列表,说明 Host API 缺少通用能力。此时只能 -先以版本化、宿主无关的方式扩展 Host API,并为 Claude Code、Codex 补齐兼容测试;禁止加入 +先以版本化、宿主无关的方式扩展 Host API,并为现有宿主补齐兼容测试;禁止加入 按平台名称选择业务流程的核心分支。 diff --git a/helixharness/reference/ut-business-protocol.md b/helixharness/reference/ut-business-protocol.md index c94d935..b5b01c5 100644 --- a/helixharness/reference/ut-business-protocol.md +++ b/helixharness/reference/ut-business-protocol.md @@ -17,7 +17,7 @@ adapter 必须声明 `dispatch_mode`、`experience_write_mode`、`runtime_handle - 支持 `--packages `、`-p` 与无参数交互入口;参数缺失或非法时不退出,由父流程在进入扫描前展示候选包清单与候选类计数,用户选择包并指定并发后与显式传入等价。继续执行模式沿用已有队列,不重新选包,但必须按包展示队列内任务的完成状态,使已在任务列表中的包可区分;显式传入的包不在队列中时仅提示,不自动转增量。 - 有残留 session/queue/worker 文件时展示状态,由用户选择继续、全新开始或增量补充。 - 增量补充必须最终确定包名(显式提供或交互选择均可),按源文件路径与已有队列去重;无残留时直接全新开始。 -- 只在模式选择、恢复确认、参数补全(包选择与并发确认)和全新任务清单确认这些业务门禁询问用户;worker 不询问用户;两个宿主使用相同的纯文本编号清单交互,不依赖任何结构化选择器。 +- 只在模式选择、恢复确认、参数补全(包选择与并发确认)和全新任务清单确认这些业务门禁询问用户;worker 不询问用户;各宿主使用相同的纯文本编号清单交互,不依赖任何结构化选择器。 ## 2. 不变量 diff --git a/helixharness/reference/version-update-protocol.md b/helixharness/reference/version-update-protocol.md index 6df817d..36bcb89 100644 --- a/helixharness/reference/version-update-protocol.md +++ b/helixharness/reference/version-update-protocol.md @@ -17,7 +17,9 @@ update 与 eval 分别使用动态 Host Registry,并保持独立 capability、cache 和生命周期。update 是否 可用只看当前 Host Kit 的 `plugin_update=native|emulated|unsupported`;公共协议不维护宿主白名单。 -当前内置 Claude Code/Codex adapter 都提供正式更新能力。任何未注册宿主执行 update `check` 时固定返回 +当前内置 Claude Code/Codex adapter 都提供正式更新能力;OpenCode Host Kit 明确声明 +`plugin_update=unsupported`,因此 update `check` 返回 `continue_silently`,由用户通过 OpenCode +插件管理手动更新。任何未注册宿主执行 update `check` 时固定返回 `state=unsupported, reason=unsupported_host, next_action=continue_silently`,不读取或写入 版本缓存、不提示更新、不创建 authorization,也不执行任何 plugin 命令。 diff --git a/helixharness/reference/workflow-projection-protocol.md b/helixharness/reference/workflow-projection-protocol.md index 7211e63..6bf2e29 100644 --- a/helixharness/reference/workflow-projection-protocol.md +++ b/helixharness/reference/workflow-projection-protocol.md @@ -10,7 +10,8 @@ `resources.runtime` 和 `resources.command_projection`。 3. `resources.command_projection` 必须声明当前公开入口及其唯一 command contract;未声明的入口关闭失败。 4. Skill 与原生命令入口先执行 projection 声明的 `commands/{command}.md`;Claude Code 允许入口与 - contract 是同一个 command 文件,Codex 等 Skill 表面使用宿主薄入口加载该 contract。需要阶段正文时,完整读取 Router 返回的唯一 workflow,保留身份、scope 和 trigger,不叠加另一套正文。Host Kit + contract 是同一个 command 文件,Codex 等 Skill 表面使用宿主薄入口加载该 contract,OpenCode + 的原生命令执行器直接加载该 contract 并注入 Host Context。需要阶段正文时,完整读取 Router 返回的唯一 workflow,保留身份、scope 和 trigger,不叠加另一套正文。Host Kit 资源只能映射执行机制,不得成为第二份业务事实源。 5. 仅当 command contract 声明 Agent/Task 逻辑 job 时,才在首次派发前读取 `reference/subagent-runtime-protocol.md` 与当前 `resources.subagent_protocol`;无子任务命令不得 @@ -36,6 +37,8 @@ - Codex 方法薄入口必须先绑定 `hosts/codex/host.json`、公共 Host Runtime/Tool Semantics 与 `resources.runtime`,然后才执行 canonical 正文;正文首次派发 Agent/Task 时再按需读取公共协议和 `resources.subagent_protocol`。直接调用方法 Skill 与从公共 command 调用时使用同一能力映射。 +- OpenCode 插件在命令执行和 Skill 加载时注入含绝对路径的 Host Context;正文直接使用这些路径, + 不读取项目 `.opencode/` 下的同名副本,也不枚举安装目录。 - Host Context、projection 和 manifest 已给出的资源路径必须直接使用;不得枚举或搜索 plugin 根目录、 安装目录或 cache 来重新发现同名资源,也不得用 `find/rg/ls/wc/stat` 试探已绑定资源的位置或长度。 - 固定且互不依赖的资源可在宿主支持时合并为一个有界读取批次;生命周期协议要求独占工具轮次的动作 diff --git a/helixharness/scripts/feedback_submit.py b/helixharness/scripts/feedback_submit.py index fa5d627..c0b683c 100755 --- a/helixharness/scripts/feedback_submit.py +++ b/helixharness/scripts/feedback_submit.py @@ -27,6 +27,7 @@ import eval_schema import reporting_config import telemetry_consent_state +from host_runtime import HostRegistry from telemetry_hosts import get_host_adapter, normalize_host_id from telemetry_ledger import PLUGIN_VERSION, _git from telemetry_ledger import LedgerError as TelemetryError @@ -109,6 +110,16 @@ def _resolve_platform(value: Any) -> str: return "unknown" +def _registered_host(platform: str) -> str | None: + """Return a canonical installed host ID without requiring a telemetry adapter.""" + + try: + registry = HostRegistry.discover(PLUGIN_ROOT / "hosts") + except Exception: + return None + return registry.resolve_id(platform) + + def _feedback_id(text: str, created_at: str, project: str, session: str) -> str: identity = { "algorithm": "helixharness-feedback-v1", @@ -362,7 +373,7 @@ def _build_document(repo: Path, payload: dict[str, Any]) -> tuple[dict[str, Any] created_at = _now() project = telemetry_consent_state.project_fingerprint(repo) adapter = get_host_adapter(platform) - if adapter is None: + if adapter is None and _registered_host(platform) is None: # Unregistered hosts still may submit; the schema only admits # registered host ids plus the explicit "unknown" marker. platform = "unknown" diff --git a/helixharness/scripts/tests/test_feedback_submit.py b/helixharness/scripts/tests/test_feedback_submit.py index f5945d5..a697393 100644 --- a/helixharness/scripts/tests/test_feedback_submit.py +++ b/helixharness/scripts/tests/test_feedback_submit.py @@ -85,6 +85,11 @@ def test_registered_future_host_can_prepare_feedback(self): draft = self.prepare(platform="future-host") self.assertEqual("future-host", draft["item"]["document"]["host"]) + def test_registered_host_without_telemetry_adapter_keeps_its_identity(self): + draft = self.prepare(platform="opencode") + self.assertEqual("opencode", draft["item"]["document"]["host"]) + self.assertEqual("unknown", draft["item"]["document"]["session"]) + def test_offline_queue_is_bound_to_original_endpoint(self): draft = self.prepare() with mock.patch.object(feedback, "_post_item", return_value="unreachable"): diff --git a/helixharness/scripts/tests/test_opencode_host.py b/helixharness/scripts/tests/test_opencode_host.py new file mode 100644 index 0000000..8b0c123 --- /dev/null +++ b/helixharness/scripts/tests/test_opencode_host.py @@ -0,0 +1,213 @@ +#!/usr/bin/env python3 +"""OpenCode Host Kit and plugin package contracts.""" + +from __future__ import annotations + +import json +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +from host_runtime import HostRegistry +from host_runtime.command_projection import load_command_projection +from host_runtime.project_config import load_project_config +from host_runtime.project_hooks import load_project_hooks +from telemetry_hosts import get_host_adapter, normalize_host_id +from update_hosts.opencode import detect_host + +PLUGIN_ROOT = Path(__file__).resolve().parents[2] +HOST_ROOT = PLUGIN_ROOT / "hosts" / "opencode" +COMMANDS = { + "init", + "propose", + "apply", + "archive", + "bug-fix", + "ut", + "update", + "status", + "config", +} + + +class OpenCodeHostKitTest(unittest.TestCase): + def setUp(self) -> None: + self.registry = HostRegistry.discover(PLUGIN_ROOT / "hosts") + self.manifest = self.registry.require("opencode") + + def test_manifest_is_discovered_with_expected_capabilities(self) -> None: + self.assertEqual(self.manifest.host_id, "opencode") + self.assertEqual(self.manifest.host_api_version, "1.1") + self.assertEqual(self.manifest.support_level, "preview") + self.assertEqual(self.manifest.display_name, "OpenCode") + + expected = { + "command_surface": "native", + "skill_discovery": "native", + "session_start": "emulated", + "stop_hook": "unsupported", + "failure_hook": "unsupported", + "command_lifecycle": "native", + "workflow_transition": "emulated", + "subagents": "native", + "unit_test_workflow": "native", + "task_tracking": "unsupported", + "project_hooks": "unsupported", + "session_events": "unsupported", + "telemetry": "unsupported", + "plugin_install": "native", + "plugin_update": "unsupported", + "session_end": "unsupported", + } + self.assertEqual(self.manifest.capabilities, expected) + + def test_command_projection_is_the_canonical_native_surface(self) -> None: + projection = load_command_projection(self.manifest) + self.assertEqual(projection.surface, "native-command") + self.assertEqual(set(projection.entrypoints), COMMANDS) + for command, (entry, contract) in projection.entrypoints.items(): + self.assertEqual(entry, f"commands/{command}.md") + self.assertEqual(contract, f"commands/{command}.md") + text = (PLUGIN_ROOT / contract).read_text(encoding="utf-8") + self.assertIn("HelixHarness 公共命令唯一契约", text) + + def test_project_config_uses_agents_md_without_settings(self) -> None: + project = load_project_config(self.manifest) + self.assertEqual(project.entry_file, "AGENTS.md") + self.assertIsNone(project.settings_file) + self.assertEqual(project.entry_template, "templates/project-entry.md.tpl") + self.assertEqual( + project.workspace_entry_template, + "templates/workspace-entry.md.tpl", + ) + + def test_project_hooks_are_explicitly_unsupported(self) -> None: + hooks = load_project_hooks(self.manifest) + self.assertEqual(hooks.merge_strategy, "unsupported") + self.assertIsNone(hooks.settings_file) + self.assertIsNone(hooks.dedupe_key) + self.assertIsNone(hooks.payload) + + def test_all_required_resources_resolve_to_files(self) -> None: + for name in ( + "command_projection", + "distribution", + "installer", + "lifecycle", + "project_config", + "project_hooks", + "runtime", + "subagent_protocol", + "telemetry_protocol", + "ut", + "workflow_transition", + ): + resource = self.manifest.resolve_resource_adapter(name) + self.assertTrue(resource.is_file(), name) + self.assertTrue(resource.is_relative_to(PLUGIN_ROOT), name) + self.assertEqual( + self.manifest.resolve_resource_adapter("distribution"), + (PLUGIN_ROOT / "package.json").resolve(), + ) + self.assertEqual( + self.manifest.resolve_resource_adapter("telemetry_protocol"), + (PLUGIN_ROOT / "hosts/shared/telemetry.md").resolve(), + ) + + def test_package_manifest_exports_the_opencode_plugin(self) -> None: + package = json.loads((PLUGIN_ROOT / "package.json").read_text(encoding="utf-8")) + self.assertEqual(package["type"], "module") + self.assertEqual(package["exports"]["."], "./opencode/index.ts") + self.assertIn("@opencode/plugin", package["devDependencies"]) + self.assertEqual(package.get("dependencies", {}), {}) + self.assertTrue((PLUGIN_ROOT / "opencode/index.ts").is_file()) + self.assertTrue((PLUGIN_ROOT / "opencode/core.ts").is_file()) + self.assertTrue((PLUGIN_ROOT / "opencode/tests/core.test.ts").is_file()) + self.assertTrue((PLUGIN_ROOT / "opencode/tests/plugin.test.ts").is_file()) + self.assertTrue((PLUGIN_ROOT / "opencode/tests/e2e.test.ts").is_file()) + + def test_plugin_source_registers_prefixed_surfaces_and_host_context(self) -> None: + core = (PLUGIN_ROOT / "opencode/core.ts").read_text(encoding="utf-8") + self.assertIn("helix:${command.name}", core) + self.assertIn("id: `helix-${directory}`", core) + self.assertIn("id: `helix-${agentName}`", core) + self.assertIn("WORKER_AGENT_ID", core) + self.assertIn('action: "subagent"', core) + self.assertIn('effect: "deny"', core) + self.assertIn("canonical_host_id", core) + self.assertIn("resources.subagent_protocol", core) + self.assertIn('ctx.tool.hook("execute.after"', core) + self.assertIn("session.prompt", core) + + def test_detector_requires_explicit_opencode_markers(self) -> None: + self.assertEqual(detect_host({"OPENCODE_SESSION_ID": "ses_x"}), 100) + self.assertEqual(detect_host({"OPENCODE": "1"}), 80) + self.assertIsNone(detect_host({})) + self.assertIsNone(detect_host({"CODEX_THREAD_ID": "thread"})) + + def test_telemetry_and_update_are_declared_unsupported(self) -> None: + self.assertEqual(normalize_host_id("opencode"), "opencode") + self.assertIsNone(get_host_adapter("opencode")) + + with tempfile.TemporaryDirectory() as directory: + result = subprocess.run( + [ + sys.executable, + str(PLUGIN_ROOT / "scripts/version_update.py"), + "--platform", + "opencode", + "--repo-root", + directory, + "check", + ], + capture_output=True, + text=True, + check=False, + cwd=PLUGIN_ROOT / "scripts", + ) + self.assertEqual(result.returncode, 0, result.stderr) + payload = json.loads(result.stdout) + self.assertEqual(payload["state"], "unsupported") + self.assertEqual(payload["reason"], "unsupported_host") + self.assertEqual(payload["next_action"], "continue_silently") + + def test_host_context_cli_resolves_the_installed_plugin(self) -> None: + result = subprocess.run( + [ + sys.executable, + str(PLUGIN_ROOT / "scripts/host_runtime_cli.py"), + "resolve", + "--platform", + "opencode", + "--expected-plugin-root", + str(PLUGIN_ROOT), + ], + capture_output=True, + text=True, + check=False, + cwd=PLUGIN_ROOT / "scripts", + ) + self.assertEqual(result.returncode, 0, result.stderr) + payload = json.loads(result.stdout) + self.assertEqual(payload["status"], "resolved") + self.assertEqual(payload["host_id"], "opencode") + self.assertEqual(payload["plugin_root"], str(PLUGIN_ROOT.resolve())) + self.assertEqual(payload["capabilities"]["telemetry"], "unsupported") + self.assertEqual( + payload["resources"]["runtime"], "hosts/opencode/runtime.md" + ) + + def test_host_kit_does_not_duplicate_public_business_contracts(self) -> None: + self.assertFalse((HOST_ROOT / "commands").exists()) + self.assertFalse((HOST_ROOT / "skills").exists()) + self.assertFalse((HOST_ROOT / "hooks.json").exists()) + self.assertEqual( + {path.stem for path in (PLUGIN_ROOT / "commands").glob("*.md")}, + COMMANDS, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/helixharness/scripts/tests/test_public_workflow_router.py b/helixharness/scripts/tests/test_public_workflow_router.py index 607fd97..9e195c1 100644 --- a/helixharness/scripts/tests/test_public_workflow_router.py +++ b/helixharness/scripts/tests/test_public_workflow_router.py @@ -238,4 +238,4 @@ def test_hosts_expose_exact_public_command_set(self): for key in host.adapters: if host.adapter_reference(key).kind=='python': host.load_python_adapter(key) - self.assertEqual(set(registry.supported_ids()),{'codex','claude-code'}) + self.assertEqual(set(registry.supported_ids()),{'codex','claude-code','opencode'}) diff --git a/helixharness/scripts/update_hosts/opencode.py b/helixharness/scripts/update_hosts/opencode.py new file mode 100644 index 0000000..f46359c --- /dev/null +++ b/helixharness/scripts/update_hosts/opencode.py @@ -0,0 +1,19 @@ +"""OpenCode host detection for optional diagnostics. + +OpenCode currently declares ``telemetry`` and ``plugin_update`` as +``unsupported``, so this module intentionally exposes only a detector. Business +commands bind their Host Context through the installed plugin; the detector is +used only by development diagnostics and the Host Context CLI. +""" + +from __future__ import annotations + +from typing import Any + + +def detect_host(environment: Any) -> int | None: + """Return a confidence score only for explicit OpenCode runtime markers.""" + + if environment.get("OPENCODE_SESSION_ID"): + return 100 + return 80 if environment.get("OPENCODE") else None diff --git a/helixharness/skills/feedback/SKILL.md b/helixharness/skills/feedback/SKILL.md index c17ad53..4fef873 100644 --- a/helixharness/skills/feedback/SKILL.md +++ b/helixharness/skills/feedback/SKILL.md @@ -97,7 +97,7 @@ $ARGUMENTS ### Step 3: 准备、确认并发送 -`{plugin_root}` 必须来自当前 plugin skill resource(Claude 可用 `${CLAUDE_PLUGIN_ROOT}`,Codex 使用当前 plugin resource root),不得搜索安装目录。`{current_platform}` 必须使用 canonical host ID:Claude Code 固定为 `claude-code`,Codex 固定为 `codex`。 +`{plugin_root}` 必须来自当前 plugin skill resource(Claude 可用 `${CLAUDE_PLUGIN_ROOT}`,Codex 使用当前 plugin resource root,OpenCode 使用 Host Context 的 `plugin_root`),不得搜索安装目录。`{current_platform}` 必须使用 Host Context 的 canonical host ID,不得根据操作系统或客户端名称猜测。 先准备草稿,不发送。参数必须安全转义: @@ -136,10 +136,10 @@ python3 "{plugin_root}/scripts/feedback_submit.py" send --draft "{draft_path}" - **平台拒绝(`status: "rejected"`)**:尚未送达,保留草稿并报告原因,不改写内容重发。用户要求重试时可执行 `feedback_submit.py retry --confirmed`,仅补投已确认且与当前配置地址一致的待发记录。 -## 双宿主说明 +## 宿主说明 -- Claude Code 与 Codex 使用同一 CLI(`feedback_submit.py`),反馈流程本身无 hook 参与、无 consent 流程 -- 会话上下文采集当前仅支持 claude-code 会话;Codex 宿主仍可上报反馈元数据(`transcript_stats.supported=false`),不是错误 +- Claude Code、Codex 与 OpenCode 使用同一 CLI(`feedback_submit.py`),反馈流程本身无 hook 参与、无 consent 流程 +- 会话上下文采集当前仅支持 claude-code 会话;Codex、OpenCode 宿主仍可上报反馈元数据(`transcript_stats.supported=false`),不是错误 - 未注册宿主(`{current_platform}` 无法给出 canonical ID 时):`--platform unknown` 仍可上报,文档中 `host` 记为 `unknown` ## 注意事项 diff --git a/helixharness/tsconfig.json b/helixharness/tsconfig.json new file mode 100644 index 0000000..218a95b --- /dev/null +++ b/helixharness/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "allowImportingTsExtensions": true, + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "types": ["bun-types", "node"] + }, + "include": ["opencode/**/*.ts"] +}