From f213db5d581e5a295bb3e05ea032a9d21c4259bb Mon Sep 17 00:00:00 2001 From: acderchenjunwei Date: Fri, 20 Nov 2026 16:24:34 +0800 Subject: [PATCH 01/37] feat(cursor): add native plugin support and workflow integration Add Cursor marketplace manifests, slash-command skills, native and managed installers, identity hooks, scoped cleanup, consent-based telemetry and updates. Harden Init completion and command guidance, shared usage accounting and D2C whitespace checks while preserving Claude Code and Codex compatibility. Document supported capabilities, installation paths and accepted limitations. Remove unused code and imports, normalize Cursor installation transaction paths, and reject non-commit Git objects during native source verification. Validation: 727 plugin cases covered (one sandbox-blocked case passed an isolated retry); 132 related platform cases passed; D2C 13 groups passed and 2 skipped for missing optional dependencies. Skill projections, Ruff and document links passed. Retain the documented pre-existing original-host update and cache-usage findings. --- .cursor-plugin/marketplace.json | 14 + README.md | 29 +- README.zh-CN.md | 29 +- docs/claude-testing.md | 42 ++ docs/codex-testing.md | 40 ++ docs/cursor-testing.md | 57 ++ docs/installation.md | 38 +- docs/user-guide.md | 26 +- docs/user-guide.zh-CN.md | 26 +- docs/workflow-architecture.md | 9 +- helixharness-platform/README.md | 10 + helixharness-platform/eval/runtime_health.py | 2 +- .../eval/stage_supplements.py | 24 + .../eval/telemetry_materialization.py | 64 +- .../eval/tests/test_runtime_health.py | 15 +- .../eval/tests/test_usage_loader.py | 47 +- .../eval/tests/test_usage_materialization.py | 88 +++ helixharness-platform/eval/usage_loader.py | 112 ++- .../templates/eval/feedback_detail.html | 2 +- .../test_claude_usage_precision_pipeline.py | 141 ++++ .../test_cursor_native_usage_pipeline.py | 155 ++++ .../web_ui/tests/test_feedback_report.py | 17 + .../web_ui/tests/test_telemetry_report.py | 22 + .../tests/test_usage_precision_pipeline.py | 188 +++++ helixharness/.cursor-plugin/marketplace.json | 14 + helixharness/.cursor-plugin/plugin.json | 12 + helixharness/PLUGIN_USAGE.md | 10 +- helixharness/README.md | 8 +- .../agents/init-frontend-bootstrap.md | 60 +- helixharness/agents/init-service-bootstrap.md | 54 +- .../agents/init-workspace-bootstrap.md | 31 + helixharness/agents/scan-db.md | 14 +- helixharness/commands/config.md | 11 +- helixharness/commands/init.md | 76 +- helixharness/commands/propose.md | 6 +- helixharness/commands/update.md | 14 +- helixharness/hosts/cursor/cleanup_worker.py | 87 +++ .../hosts/cursor/command-projection.json | 15 + helixharness/hosts/cursor/d2c_gate.cjs | 163 +++++ helixharness/hosts/cursor/hook_bootstrap.sh | 45 ++ helixharness/hosts/cursor/hook_entry.py | 130 ++++ helixharness/hosts/cursor/hooks.json | 24 + helixharness/hosts/cursor/host.json | 53 ++ helixharness/hosts/cursor/installer.md | 154 ++++ helixharness/hosts/cursor/lifecycle.md | 67 ++ helixharness/hosts/cursor/project-hooks.json | 16 + helixharness/hosts/cursor/project.json | 6 + helixharness/hosts/cursor/runtime.md | 120 ++++ helixharness/hosts/cursor/skill-entry.md | 56 ++ .../hosts/cursor/skills/helix-apply/SKILL.md | 11 + .../cursor/skills/helix-archive/SKILL.md | 11 + .../skills/helix-brainstorming/SKILL.md | 11 + .../cursor/skills/helix-bug-fix/SKILL.md | 11 + .../cursor/skills/helix-code-review/SKILL.md | 11 + .../hosts/cursor/skills/helix-config/SKILL.md | 11 + .../hosts/cursor/skills/helix-d-d2c/SKILL.md | 13 + .../helix-d2c-fidelity-evaluator/SKILL.md | 11 + .../cursor/skills/helix-feedback/SKILL.md | 11 + .../skills/helix-git-diff-impact/SKILL.md | 11 + .../hosts/cursor/skills/helix-init/SKILL.md | 11 + .../cursor/skills/helix-propose/SKILL.md | 11 + .../hosts/cursor/skills/helix-status/SKILL.md | 11 + .../helix-systematic-debugging/SKILL.md | 11 + .../hosts/cursor/skills/helix-tdd/SKILL.md | 11 + .../hosts/cursor/skills/helix-update/SKILL.md | 11 + .../hosts/cursor/skills/helix-ut/SKILL.md | 11 + helixharness/hosts/cursor/subagent.md | 40 ++ helixharness/hosts/cursor/ut.md | 26 + .../hosts/cursor/workflow-transition.md | 10 + .../hosts/host-manifest-v1.schema.json | 4 +- helixharness/reference/eval-protocol.md | 11 +- .../reference/eval-supplement-protocol.md | 4 +- helixharness/reference/host-api.md | 40 +- .../reference/host-runtime-protocol.md | 23 +- .../reference/project-type-detection.md | 12 +- helixharness/reference/runtime-preflight.md | 6 + .../reference/ut-business-protocol.md | 2 +- .../reference/version-update-protocol.md | 36 +- .../reference/workflow-projection-protocol.md | 4 + .../scripts/cursor_managed_install.py | 35 + helixharness/scripts/cursor_native_install.py | 300 ++++++++ .../scripts/cursor_skill_projection.py | 230 ++++++ helixharness/scripts/host_runtime/__init__.py | 4 +- .../scripts/host_runtime/project_hooks.py | 49 +- helixharness/scripts/init_guidance.py | 206 ++++++ helixharness/scripts/init_state.py | 225 ++++++ helixharness/scripts/lifecycle_service.py | 49 +- helixharness/scripts/metrics.py | 59 +- helixharness/scripts/project_hooks_cli.py | 36 +- helixharness/scripts/runtime_preflight.sh | 7 +- helixharness/scripts/telemetry_async.py | 32 +- helixharness/scripts/telemetry_collector.py | 22 + .../scripts/telemetry_consent_state.py | 91 ++- .../scripts/telemetry_hosts/__init__.py | 81 +++ .../scripts/telemetry_hosts/cursor.py | 548 +++++++++++++++ .../telemetry_hosts/supplement_parsers.py | 15 +- helixharness/scripts/telemetry_ledger.py | 24 +- helixharness/scripts/telemetry_session.py | 5 + .../tests/test_claude_command_scenarios.py | 317 +++++++++ .../tests/test_claude_lifecycle_scenarios.py | 316 +++++++++ .../tests/test_claude_supplement_parser.py | 96 +++ .../tests/test_claude_update_scenarios.py | 279 ++++++++ .../tests/test_codex_command_scenarios.py | 373 ++++++++++ .../tests/test_codex_lifecycle_scenarios.py | 297 ++++++++ .../tests/test_codex_update_scenarios.py | 346 +++++++++ .../test_cursor_acceptance_regressions.py | 113 +++ .../tests/test_cursor_bundle_update.py | 133 ++++ .../tests/test_cursor_cleanup_recovery.py | 228 ++++++ .../tests/test_cursor_command_scenarios.py | 316 +++++++++ .../tests/test_cursor_entry_repairs.py | 205 ++++++ .../scripts/tests/test_cursor_hook_budget.py | 429 +++++++++++ .../tests/test_cursor_hook_fastpath.py | 144 ++++ .../scripts/tests/test_cursor_hooks.py | 207 ++++++ .../tests/test_cursor_initial_recovery.py | 323 +++++++++ .../scripts/tests/test_cursor_integration.py | 275 ++++++++ .../tests/test_cursor_lifecycle_scenarios.py | 343 +++++++++ .../tests/test_cursor_managed_update.py | 350 +++++++++ .../tests/test_cursor_native_install.py | 169 +++++ .../tests/test_cursor_native_update.py | 64 ++ .../scripts/tests/test_cursor_projection.py | 493 +++++++++++++ .../tests/test_cursor_prompt_context.py | 101 +++ .../scripts/tests/test_cursor_telemetry.py | 430 +++++++++++ .../tests/test_cursor_update_scenarios.py | 138 ++++ .../tests/test_host_runtime_registry.py | 62 ++ .../scripts/tests/test_init_guidance.py | 248 +++++++ helixharness/scripts/tests/test_init_state.py | 408 +++++++++++ helixharness/scripts/tests/test_metrics.py | 2 +- .../scripts/tests/test_project_hooks.py | 113 +++ .../tests/test_public_workflow_router.py | 3 +- .../scripts/tests/test_reporting_config.py | 20 + .../scripts/tests/test_telemetry_ledger.py | 2 +- .../tests/test_update_marketplace_contract.py | 98 +++ .../scripts/tests/test_update_resume.py | 172 +++++ .../scripts/tests/test_user_commands.py | 18 +- .../scripts/tests/test_user_config_notice.py | 273 +++++++ .../tests/test_workspace_init_registry.py | 2 + helixharness/scripts/update_hosts/base.py | 82 ++- .../scripts/update_hosts/claude_code.py | 1 + helixharness/scripts/update_hosts/codex.py | 1 + helixharness/scripts/update_hosts/cursor.py | 665 ++++++++++++++++++ helixharness/scripts/user_config.py | 61 +- helixharness/scripts/validate_init_outputs.py | 6 + helixharness/scripts/version_update.py | 152 +++- .../skills/d-d2c/rules/d-d2c-generate.md | 7 +- .../scripts/lib/d2c-geometry-check-core.cjs | 63 +- .../d-d2c/scripts/lib/dsl-layout-core.cjs | 10 +- .../tests/d2c-whitespace-fidelity.test.cjs | 69 ++ helixharness/skills/feedback/SKILL.md | 8 +- helixharness/templates/project-entry.md.tpl | 22 +- helixharness/templates/workspace-entry.md.tpl | 19 +- helixharness/workflows/single/apply.md | 2 +- helixharness/workflows/single/archive.md | 2 +- helixharness/workflows/single/propose.md | 2 +- 153 files changed, 13597 insertions(+), 349 deletions(-) create mode 100644 .cursor-plugin/marketplace.json create mode 100644 docs/claude-testing.md create mode 100644 docs/codex-testing.md create mode 100644 docs/cursor-testing.md create mode 100644 helixharness-platform/eval/tests/test_usage_materialization.py create mode 100644 helixharness-platform/web_ui/tests/test_claude_usage_precision_pipeline.py create mode 100644 helixharness-platform/web_ui/tests/test_cursor_native_usage_pipeline.py create mode 100644 helixharness-platform/web_ui/tests/test_usage_precision_pipeline.py create mode 100644 helixharness/.cursor-plugin/marketplace.json create mode 100644 helixharness/.cursor-plugin/plugin.json create mode 100644 helixharness/hosts/cursor/cleanup_worker.py create mode 100644 helixharness/hosts/cursor/command-projection.json create mode 100644 helixharness/hosts/cursor/d2c_gate.cjs create mode 100644 helixharness/hosts/cursor/hook_bootstrap.sh create mode 100644 helixharness/hosts/cursor/hook_entry.py create mode 100644 helixharness/hosts/cursor/hooks.json create mode 100644 helixharness/hosts/cursor/host.json create mode 100644 helixharness/hosts/cursor/installer.md create mode 100644 helixharness/hosts/cursor/lifecycle.md create mode 100644 helixharness/hosts/cursor/project-hooks.json create mode 100644 helixharness/hosts/cursor/project.json create mode 100644 helixharness/hosts/cursor/runtime.md create mode 100644 helixharness/hosts/cursor/skill-entry.md create mode 100644 helixharness/hosts/cursor/skills/helix-apply/SKILL.md create mode 100644 helixharness/hosts/cursor/skills/helix-archive/SKILL.md create mode 100644 helixharness/hosts/cursor/skills/helix-brainstorming/SKILL.md create mode 100644 helixharness/hosts/cursor/skills/helix-bug-fix/SKILL.md create mode 100644 helixharness/hosts/cursor/skills/helix-code-review/SKILL.md create mode 100644 helixharness/hosts/cursor/skills/helix-config/SKILL.md create mode 100644 helixharness/hosts/cursor/skills/helix-d-d2c/SKILL.md create mode 100644 helixharness/hosts/cursor/skills/helix-d2c-fidelity-evaluator/SKILL.md create mode 100644 helixharness/hosts/cursor/skills/helix-feedback/SKILL.md create mode 100644 helixharness/hosts/cursor/skills/helix-git-diff-impact/SKILL.md create mode 100644 helixharness/hosts/cursor/skills/helix-init/SKILL.md create mode 100644 helixharness/hosts/cursor/skills/helix-propose/SKILL.md create mode 100644 helixharness/hosts/cursor/skills/helix-status/SKILL.md create mode 100644 helixharness/hosts/cursor/skills/helix-systematic-debugging/SKILL.md create mode 100644 helixharness/hosts/cursor/skills/helix-tdd/SKILL.md create mode 100644 helixharness/hosts/cursor/skills/helix-update/SKILL.md create mode 100644 helixharness/hosts/cursor/skills/helix-ut/SKILL.md create mode 100644 helixharness/hosts/cursor/subagent.md create mode 100644 helixharness/hosts/cursor/ut.md create mode 100644 helixharness/hosts/cursor/workflow-transition.md create mode 100644 helixharness/scripts/cursor_managed_install.py create mode 100644 helixharness/scripts/cursor_native_install.py create mode 100644 helixharness/scripts/cursor_skill_projection.py create mode 100644 helixharness/scripts/init_guidance.py create mode 100644 helixharness/scripts/init_state.py create mode 100644 helixharness/scripts/telemetry_hosts/cursor.py create mode 100644 helixharness/scripts/telemetry_session.py create mode 100644 helixharness/scripts/tests/test_claude_command_scenarios.py create mode 100644 helixharness/scripts/tests/test_claude_lifecycle_scenarios.py create mode 100644 helixharness/scripts/tests/test_claude_supplement_parser.py create mode 100644 helixharness/scripts/tests/test_claude_update_scenarios.py create mode 100644 helixharness/scripts/tests/test_codex_command_scenarios.py create mode 100644 helixharness/scripts/tests/test_codex_lifecycle_scenarios.py create mode 100644 helixharness/scripts/tests/test_codex_update_scenarios.py create mode 100644 helixharness/scripts/tests/test_cursor_acceptance_regressions.py create mode 100644 helixharness/scripts/tests/test_cursor_bundle_update.py create mode 100644 helixharness/scripts/tests/test_cursor_cleanup_recovery.py create mode 100644 helixharness/scripts/tests/test_cursor_command_scenarios.py create mode 100644 helixharness/scripts/tests/test_cursor_entry_repairs.py create mode 100644 helixharness/scripts/tests/test_cursor_hook_budget.py create mode 100644 helixharness/scripts/tests/test_cursor_hook_fastpath.py create mode 100644 helixharness/scripts/tests/test_cursor_hooks.py create mode 100644 helixharness/scripts/tests/test_cursor_initial_recovery.py create mode 100644 helixharness/scripts/tests/test_cursor_integration.py create mode 100644 helixharness/scripts/tests/test_cursor_lifecycle_scenarios.py create mode 100644 helixharness/scripts/tests/test_cursor_managed_update.py create mode 100644 helixharness/scripts/tests/test_cursor_native_install.py create mode 100644 helixharness/scripts/tests/test_cursor_native_update.py create mode 100644 helixharness/scripts/tests/test_cursor_projection.py create mode 100644 helixharness/scripts/tests/test_cursor_prompt_context.py create mode 100644 helixharness/scripts/tests/test_cursor_telemetry.py create mode 100644 helixharness/scripts/tests/test_cursor_update_scenarios.py create mode 100644 helixharness/scripts/tests/test_init_guidance.py create mode 100644 helixharness/scripts/tests/test_init_state.py create mode 100644 helixharness/scripts/tests/test_update_marketplace_contract.py create mode 100644 helixharness/scripts/tests/test_update_resume.py create mode 100644 helixharness/scripts/tests/test_user_config_notice.py create mode 100644 helixharness/scripts/update_hosts/cursor.py create mode 100644 helixharness/skills/d-d2c/scripts/tests/d2c-whitespace-fidelity.test.cjs diff --git a/.cursor-plugin/marketplace.json b/.cursor-plugin/marketplace.json new file mode 100644 index 0000000..4dd3987 --- /dev/null +++ b/.cursor-plugin/marketplace.json @@ -0,0 +1,14 @@ +{ + "name": "helixharness-marketplace", + "owner": {"name": "HelixHarness contributors"}, + "metadata": {"description": "HelixHarness Cursor marketplace"}, + "plugins": [ + { + "name": "helix", + "description": "HelixHarness workflow skills for Cursor", + "source": "./helixharness", + "version": "1.0.0", + "license": "Apache-2.0" + } + ] +} diff --git a/README.md b/README.md index a70cb12..710eb6c 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 Cursor.** 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 / Cursor · 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,9 +63,9 @@ 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.9+, Git and a plugin-capable Codex, Claude Code or Cursor installation. 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: +After the repository is public, install Codex and Claude Code plugins with the terminal commands below. Cursor uses the marketplace UI described afterward. These routes do not require a manual source clone: ```bash # Codex @@ -79,24 +79,37 @@ claude plugin marketplace add https://github.com/didi/helixharness.git claude plugin install helix@helixharness-marketplace ``` +Cursor users install `helix` from their Cursor marketplace through **Customize → helix → Install**, then reload the window and open a new Agent. A team administrator first imports the published release repository into the team's marketplace. Cursor uses `/helix-init`, `/helix-propose`, etc. See [marketplace setup, optional Local installation and capability limits](docs/installation.md#cursor-preview). + 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). ### 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. Review the plugin hooks through the host's native interface, then enter the commands for your host in the conversation. + +Codex / Claude Code: ```text /helix:init /helix:propose task-filter ./requirements/task-filter.md --loop ``` +Cursor: + +```text +/helix-init +/helix-propose task-filter ./requirements/task-filter.md --loop +``` + +Cursor uses `/helix-` throughout; Codex and Claude Code use `/helix:`. Command arguments and workflows are the same. + Use the [self-contained task-filter example](examples/README.md) to get a starter project, requirement and acceptance check. `--loop` runs Propose → Apply → Archive, pausing for decisions or blockers. It does not publish or deploy your code. You can also run `/helix:propose`, `/helix:apply` and `/helix:archive` separately. See [all nine commands](docs/user-guide.md#commands). -Use `/helix:status` to inspect progress and blockers, and `/helix:config` to view or change telemetry consent and reporting addresses. +Use `/helix:status` (Cursor: `/helix-status`) to inspect progress and blockers, and `/helix:config` (Cursor: `/helix-config`) to view or change telemetry consent and reporting addresses. ## How it relates to Superpowers and OpenSpec @@ -184,10 +197,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 to more hosts beyond Codex, Claude Code and Cursor 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 source supports Codex, Claude Code and Cursor, using the Propose → Apply → Archive workflow. Cursor native-client acceptance is tracked separately from automated contract tests. 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..8757d0b 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 和 Cursor上构建专属的 AI Coding Harness。** 将你的业务知识、工程规范与研发工作流带入 Agent 的工作过程,从需求分析、实现、测试、评审到归档,让 AI 按团队的方式开展研发,并将经验证的经验留在项目中,供下一个需求复用。 从插件开始即可。当你希望改进 Harness 本身时,可选的 **helixharness-platform** 帮助框架维护者观测使用过程、对比框架版本,并在采纳候选改进前验证效果。 -**9 个命令 · Codex / Claude Code · 单仓 / 多仓 Workspace · Apache-2.0** +**9 个命令 · Codex / Claude Code / Cursor · 单仓 / 多仓 Workspace · Apache-2.0** [快速开始](#快速开始) · [命名故事](#名字背后的故事) · [框架亮点](#框架亮点) · [框架迭代平台](#围绕-helixharness-框架的迭代平台) · [使用指南](docs/user-guide.zh-CN.md) @@ -63,9 +63,9 @@ Knowledge 与 Harness 通过索引引导上下文加载,Specs 保存每个需 ### 1. 安装插件 -需要 Python 3.10+、Git,以及支持插件市场的 Codex 或 Claude Code。先确保宿主已完成登录或模型配置,能够正常使用。 +需要 Python 3.9+、Git,以及支持插件的 Codex、Claude Code 或 Cursor。先确保宿主已完成登录或模型配置,能够正常使用。 -仓库公开后,在终端选择对应宿主安装,无需先手动克隆源码: +仓库公开后,Codex 和 Claude Code 使用下方终端命令,Cursor 使用随后说明的市场界面安装;这些方式无需先手动克隆源码: ```bash # Codex @@ -79,22 +79,35 @@ claude plugin marketplace add https://github.com/didi/helixharness.git claude plugin install helix@helixharness-marketplace ``` +Cursor 用户通过 **Customize → helix → Install** 从市场安装,随后重载窗口并新建 Agent。团队管理员需先将已发布的发行仓库导入团队市场。Cursor 使用 `/helix-init`、`/helix-propose` 等入口,详见[市场安装、可选 Local 安装及能力限制](docs/installation.md#cursor-preview)。 + 根市场会安装 `helixharness/` 插件,不会安装平台。发布前测试或修改插件时,使用[开发者安装(本地源码)](docs/installation.md#developer-installation)。详见[hooks 检查、更新与卸载](docs/installation.md)。 ### 2. 完成一个小需求 -在要开发的**业务仓库**新开 Agent 会话,通过宿主原生界面审阅插件 hooks,然后在对话中输入: +在要开发的**业务仓库**新开 Agent 会话,通过宿主原生界面审阅插件 hooks,然后在对话中输入对应宿主的命令。 + +Codex / Claude Code: ```text /helix:init /helix:propose task-filter ./requirements/task-filter.md --loop ``` +Cursor: + +```text +/helix-init +/helix-propose task-filter ./requirements/task-filter.md --loop +``` + +Cursor 全部使用 `/helix-`,Codex 和 Claude Code 使用 `/helix:`;命令参数和工作流相同。 + [任务筛选示例](examples/README.md)提供起始项目、需求和独立验收脚本,可直接跟着操作。`--loop` 串联 Propose → Apply → Archive,遇到需要决策的问题或阻断时暂停,不包含代码发布或部署。 也可分别执行 `/helix:propose`、`/helix:apply` 和 `/helix:archive`。详见[九个公开命令](docs/user-guide.zh-CN.md#命令参考)。 -产品名称为 **HelixHarness**,插件 ID 和命令前缀使用 **`helix`**。使用 `/helix:status` 查看进度与阻塞,使用 `/helix:config` 查看或修改统计授权和上报地址。 +产品名称为 **HelixHarness**,插件 ID 和命令前缀使用 **`helix`**。使用 `/helix:status`(Cursor:`/helix-status`)查看进度与阻塞,使用 `/helix:config`(Cursor:`/helix-config`)查看或修改统计授权和上报地址。 ## 与 Superpowers、OpenSpec 的侧重点 @@ -182,10 +195,10 @@ python -m web_ui.demo --port 7860 接下来计划围绕两个方向,让更多团队按自己的研发方式使用 HelixHarness: -- **支持更多 Coding Agent**:在 Codex 和 Claude Code 之外扩展宿主适配,让团队能在更多熟悉的工具中使用 HelixHarness。 +- **支持更多 Coding Agent**:在 Codex、Claude Code 和 Cursor 的基础上继续扩展宿主适配,让团队能在更多熟悉的工具中使用 HelixHarness。 - **支持工作流配置**:允许团队配置工作流阶段及其顺序,适配自身的研发流程。 -以上为规划能力。当前版本支持 Codex 和 Claude Code,采用 Propose → Apply → Archive 工作流。欢迎通过[贡献指南](CONTRIBUTING.md)分享具体使用场景,帮助完善这些方向。 +以上为规划方向。当前源码支持 Codex、Claude Code 和 Cursor,采用 Propose → Apply → Archive 工作流。Cursor 原生客户端验收与自动化合同测试分别记录。欢迎通过[贡献指南](CONTRIBUTING.md)分享具体使用场景,帮助完善这些方向。 ## 文档与贡献 diff --git a/docs/claude-testing.md b/docs/claude-testing.md new file mode 100644 index 0000000..128b4c9 --- /dev/null +++ b/docs/claude-testing.md @@ -0,0 +1,42 @@ +# Claude Code compatibility verification / Claude Code 兼容验证 + +## Scope and evidence / 范围与证据 + +Cursor integration shares command contracts, Init output validation and update infrastructure with Claude Code. Focused command, lifecycle, update and shared Init regression passed in the recorded runs. The latest productization suite and accepted Cursor release scope are summarized in the [Cursor report](cursor-testing.md). Historical source versions and overlapping test counts are kept in local evidence. + +Cursor 接入与 Claude Code 共用命令合同、Init 产物校验和更新基础设施。已记录的命令、生命周期、更新及共享 Init 定向回归通过。最近产品化测试及 Cursor 发布范围见 [Cursor 报告](cursor-testing.md)。历史源码版本与重叠测试数量保留在本地证据。 + +Native samples on Claude Code 2.1.252 covered plugin discovery, selected status/config execution and visible-notice enable/disable. Earlier isolated Hook tests and authenticated command tests used different execution setups, so those samples do not establish a complete Hook-to-model chain. Some earlier interaction attempts timed out or stopped at `notice_required`; later successful samples retain that history. + +Claude Code 2.1.252 的实机样例覆盖插件发现、所选 status/config 执行、可见说明后的统计开启/关闭。早期隔离 Hook 与已认证命令使用不同执行配置,不能据此认定完整 Hook 到模型链路通过。部分早期交互超时或停在 `notice_required`,后续成功样例保留这些历史结果。 + +## Historical diagnostic findings / 历史诊断问题 + +- Update probes found that a synthetic host returning success without installing the approved version, or installing a later version, could produce a success result and consume authorization. Both outcomes also reproduced on the original baseline. / 更新探测发现,合成宿主返回成功却未安装批准版本、或实际安装更高版本时,包装脚本可能误报成功并消费授权;两种情况也在原基线复现。 +- A synthetic native usage probe found omitted cache-read/write fields and an incorrectly precise total. Cache semantics must be normalized in the Claude adapter because other hosts may already include cache in input totals. / 合成原生用量探测发现缓存读写字段遗漏并错误标记精确总量;应在 Claude 适配层归一化缓存语义,其他宿主的 input 可能已包含缓存。 + +These are retained historical findings, not new Cursor defects. The 2026-11-20 pre-merge review reran both independent probes: the two abnormal update outcomes still failed, and the native cache-usage probe still omitted cache fields on both the current parser and the original baseline. These explicitly selected diagnostics are not included in standard-suite pass counts. + +这些是保留的历史发现,不是 Cursor 新引入缺陷。2026-11-20 合并前评审重跑两项独立探针:两类异常升级结果仍失败,原生缓存用量探针在当前解析器和原基线仍遗漏缓存字段。这些显式诊断不包含在常规测试通过数量中。 + +## Reproduce / 复跑 + +Run from the combined repository root. Use synthetic projects and keep runtime evidence in ignored `output/` directories. Native testing should authenticate normally without copying credentials. Synthetic routing/state tests do not establish model-generated code quality or every native interaction path. + +在组合仓库根执行,使用合成项目,将运行证据保存在忽略的 `output/` 中。原生测试通过正常机制认证,不复制凭据。合成路由/状态测试不证明模型生成质量或全部原生交互路径。 + +```bash +PYTHONPATH=helixharness/scripts:helixharness/scripts/tests \ +python3 -m unittest test_claude_command_scenarios test_claude_lifecycle_scenarios \ + test_claude_update_scenarios test_claude_local_update + +# Independent historical failure probes / 独立历史失败探针 +python3 helixharness/scripts/tests/test_claude_update_scenarios.py --probe-postconditions +python3 helixharness/scripts/tests/test_claude_update_scenarios.py --probe-postconditions --baseline +PYTHONPATH=helixharness/scripts:helixharness/scripts/tests \ +python3 helixharness/scripts/tests/test_claude_lifecycle_scenarios.py --probe-native-cache +``` + +The probes exit nonzero while their modeled failure remains. Full plugin reproduction and environment requirements are in the [Cursor verification guide](cursor-testing.md#reproduce--复跑). See the [Claude Code installer](../helixharness/hosts/claude-code/installer.md) for normal installation. + +探测问题仍存在时返回非零。插件全量复跑与环境要求见 [Cursor 验证说明](cursor-testing.md#reproduce--复跑),正常安装见 [Claude Code 安装指南](../helixharness/hosts/claude-code/installer.md)。 diff --git a/docs/codex-testing.md b/docs/codex-testing.md new file mode 100644 index 0000000..f02b79c --- /dev/null +++ b/docs/codex-testing.md @@ -0,0 +1,40 @@ +# Codex compatibility verification / Codex 兼容验证 + +## Scope and evidence / 范围与证据 + +Cursor integration shares workflow contracts, Init validation and update infrastructure with Codex. Recorded command, lifecycle, update and shared Init regression passed. The latest productization suite and accepted Cursor release scope are summarized in the [Cursor report](cursor-testing.md). Tests use synthetic repositories, artifacts, host outcomes and consent choices. + +Cursor 接入与 Codex 共用流程合同、Init 校验和更新基础设施。已记录的命令、生命周期、更新及共享 Init 定向回归通过。最近产品化回归和 Cursor 发布范围见 [Cursor 报告](cursor-testing.md)。测试使用合成仓库、产物、宿主结果及授权选择。 + +Native Codex CLI 0.144.3 samples covered source resolution and entry loading. A later visible-notice enable/disable sequence completed with independent readback, while an initial unavailable readback and native error events remained unexplained. An earlier bounded status/config attempt reached its deadline before business execution. Those samples retain their limited scope and do not establish zero-anomaly native compatibility. + +Codex CLI 0.144.3 的实机样例覆盖来源解析和入口加载。后续可见说明后的统计开启/关闭完成并有独立读回,但首次 unavailable 读回及原生错误事件未完成归因。更早的有界 status/config 尝试在业务执行前到达期限。各样例保留原范围,不据此认定全部原生交互无异常。 + +## Historical update findings / 历史更新问题 + +Independent probes reproduced two outcomes on both the current source at that time and the original baseline: the native updater returned success but left the old version installed, or installed a higher version than approved after its source advanced. The wrapper reported success and consumed authorization. Normal successful-update tests passed. The finding concerns validation of abnormal native outcomes. + +独立探针在当时源码和原基线均复现两类结果:原生更新器返回成功但仍保留旧版,或来源推进后安装了高于批准版本的版本。包装脚本误报成功并消费授权,正常升级用例通过。问题在于异常原生结果的安装后校验。 + +The 2026-11-20 pre-merge review reran the probe against the current source: both abnormal update outcomes still failed. Standard-suite pass counts exclude this explicitly selected diagnostic. Reassess the current [Codex adapter](../helixharness/scripts/update_hosts/codex.py) and [shared updater](../helixharness/scripts/version_update.py) with the commands below. Installed-version checks must consider versioned-cache switching rather than assuming the executing old plugin directory has changed. + +2026-11-20 合并前评审在当前源码重跑探针,两类异常升级结果仍失败;常规测试通过数量不包含这项显式诊断。通过下方命令复核当前 [Codex 适配器](../helixharness/scripts/update_hosts/codex.py) 和[公共更新器](../helixharness/scripts/version_update.py)。安装结果校验需考虑版本缓存切换,不能假定正在执行的旧插件目录已变为新版。 + +## Reproduce / 复跑 + +Run from the combined repository root. Use synthetic projects and keep raw runtime evidence in ignored `output/`. The deterministic workflow tests supply prepared Spec/Tasks/review receipts; they verify routing, persistence and gates. They do not prove native discovery, model implementation quality or complete UT worker behavior. + +在组合仓库根运行,使用合成项目,原始运行证据保存在忽略的 `output/` 中。确定性流程测试预置 Spec/Tasks/评审收据,验证路由、持久状态和门禁,不证明原生发现、模型实现质量或完整 UT worker 行为。 + +```bash +PYTHONPATH=helixharness/scripts:helixharness/scripts/tests \ +python3 -m unittest test_codex_command_scenarios test_codex_lifecycle_scenarios \ + test_codex_update_scenarios test_codex_local_update + +# Independent historical failure probe / 独立历史失败探针 +python3 helixharness/scripts/tests/test_codex_update_scenarios.py --probe-postconditions +``` + +The probe exits nonzero while its modeled failure remains. Full reproduction and environment requirements are in the [Cursor verification guide](cursor-testing.md#reproduce--复跑). See the [Codex installer](../helixharness/hosts/codex/installer.md) for normal installation. + +探测问题仍存在时返回非零。插件全量复跑与环境要求见 [Cursor 验证说明](cursor-testing.md#reproduce--复跑),正常安装见 [Codex 安装指南](../helixharness/hosts/codex/installer.md)。 diff --git a/docs/cursor-testing.md b/docs/cursor-testing.md new file mode 100644 index 0000000..d0c243e --- /dev/null +++ b/docs/cursor-testing.md @@ -0,0 +1,57 @@ +# Cursor support and verification / Cursor 支持与验证 + +## Release scope / 发布范围 + +Cursor desktop support is `stable` and release-ready within the documented limits. On 2026-11-20 the project owner accepted the remaining verification gaps for this release. Commands use `/helix-xxx`. Single-repository and Workspace workflows, unit-test generation, status/configuration and consent-based statistics are implemented. Managed Local automatic updates require a registered installation. Installation options are documented in the [installation guide](installation.md#cursor-preview). + +Cursor 桌面接入按已声明的能力边界标记为 `stable`、可发布。项目负责人于 2026-11-20 接受本次剩余验证缺口。命令使用 `/helix-xxx`,已实现单仓与 Workspace 流程、单测生成、状态/配置管理及授权后统计。托管 Local 自动升级需要已登记的安装。安装方式见[安装指南](installation.md#cursor-preview)。 + +| Capability / 能力 | Evidence and boundary / 证据与边界 | +| --- | --- | +| Commands and workflows / 命令与流程 | Synthetic contract tests cover all nine entries. Native samples cover Single and Workspace implementation/archive, active Single BugFix, frontend Init and Java UT. / 合同测试覆盖九个入口;实机样例覆盖单仓及多仓实施/归档、活跃单仓 BugFix、前端 Init 和 Java UT。 | +| Recorded Local candidate / 已验 Local 候选 | 387 reviewed files matched the installed package. Two identity rounds and normal status/preflight on Python 3.9.6 passed. The unregistered Local updater returned the expected source warning. / 387 个审核文件与安装包匹配;两轮身份、Python 3.9.6 下的 status/预检及未登记 Local 更新警告通过。 | +| Native fixed source / 原生固定来源 | An earlier candidate was fetched by Cursor with 386 matching files; status, identity and partial statistics passed. / 较早候选由 Cursor 获取,386 文件匹配,status、身份及有限统计通过。 | +| Managed Local upgrade / 托管 Local 升级 | A synthetic 1.0.0 → 1.0.1 native upgrade and post-reload version recognition passed. Abnormal installation outcomes are covered by automated checks. / 合成版本原生升级及重载后识别通过,安装异常结果由自动化检查覆盖。 | +| Statistics and cleanup / 统计与清理 | Real tool events, one loopback acknowledgment, repeat-collection deduplication and consent-revocation cleanup passed in isolation. Usage remained partial. / 隔离环境真实工具事件、本机接收、重复采集去重与关闭授权清理通过,usage 为 partial。 | +| D2C | A synthetic local page and owner-bound checkpoint gate passed selected checks. The full MasterGo-to-delivery workflow remains unaccepted. / 合成本地页面与 owner checkpoint 门禁通过所选检查,完整 MasterGo 到交付流程未完整验收。 | + +The 2026-11-20 pre-merge regression ran 727 plugin tests: 726 passed, and one process-inspection case was blocked by the sandbox's `ps` restriction; that case passed an authorized isolated retry. All 132 related platform tests passed. Cursor and Codex Skill projections and platform Ruff checks passed. These results cover the cleaned source; native candidate results above refer to earlier recorded packages. Native replies were partly supplied by the user; installed hashes and selected artifacts were independently checked. + +2026-11-20 合并前回归运行 727 项插件测试,726 项通过,1 项因沙箱禁止 `ps` 而报错;该用例获准单独重跑后通过。相关平台测试 132 项全部通过,Cursor/Codex Skill 投影与平台 Ruff 检查通过。这些结果覆盖清理后的源码,上方实机结果对应此前记录的候选包。部分原生回复由用户提供,安装哈希及所选产物独立核验。 + +## Accepted limitations and follow-up / 已接受限制与跟进项 + +- Native fixed-SHA automatic upgrades, colon-prefix completion, Cloud Agents and native Skill-scoped stop/question interception are outside this release's capabilities. / 原生固定 SHA 自动升级、冒号补全、Cloud Agents 及原生 Skill 级停止/提问拦截不在本期能力范围。 +- Token attribution can remain partial/unavailable. Full token precision, default background delivery and production statistics ingestion have not completed native acceptance. / Token 可为 partial/unavailable;完整精度、默认后台投递与生产统计入库未完成实机验收。 +- Window-close cleanup is best effort. Explicit consent revocation cleans the current repository; later startup can retry scoped cleanup. / 关窗清理尽力执行,主动关闭授权清理当前仓库,后续启动可补扫。 +- Fresh remote loading of the productized candidate, native update-entry behavior, invalid-source/recovery and the general marketplace UI flow remain accepted follow-up verification. / 产品化候选的新一轮远程加载、原生更新入口、错误来源/恢复及普通市场 UI 完整流程作为已接受的后续验证。 +- Cursor Agent CLI, full D2C and all native cancellation/concurrency boundaries remain outside complete acceptance. / Cursor Agent CLI、完整 D2C 及全部原生取消/并发边界未完整验收。 +- Mixed imported/Local copies can select different Skill and Hook roots. Resolve source conflicts without bypassing binding checks. Imported Claude hooks may duplicate checks. / 混合导入与 Local 副本可能选中不同 Skill/Hook 来源,需解决来源冲突并保留绑定检查;导入 Claude hooks 可能重复检查。 + +Historical failures remain recorded in local evidence. Earlier Hook timeouts, missing identity and empty-cwd tool accounting led to repairs and subsequent focused/native checks. Earlier upgrade runs also exposed a test-launcher lock issue and a model's failure-to-stop deviation; successful final installation does not erase those observations. Original-host historical diagnostics are summarized in the [Claude Code](claude-testing.md) and [Codex](codex-testing.md) reports. + +历史失败保留在本地证据中。此前 Hook 超时、身份缺失和空 cwd 工具计数问题促成修复,并有后续定向/实机复验。升级历史还记录了测试 launcher 锁识别问题及模型未遵守失败停止的偏差,最终安装成功不会覆盖这些观察。原宿主历史诊断见 [Claude Code](claude-testing.md) 与 [Codex](codex-testing.md)。 + +## Reproduce / 复跑 + +Run from the combined repository root with Python, Git and Node.js. The process-timeout fixture needs permission to inspect its own child process. Use synthetic projects and keep raw runtime evidence in ignored `output/` directories. + +在组合仓库根运行,需要 Python、Git 和 Node.js。进程超时夹具需能检查自身子进程。使用合成项目,将原始运行证据保存在忽略的 `output/` 中。 + +```bash +GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null \ +GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=core.hooksPath GIT_CONFIG_VALUE_0=/dev/null \ +python3 helixharness/scripts/run_tests.py + +PYTHONPATH=helixharness/scripts:helixharness/scripts/tests \ +python3 -m unittest test_cursor_command_scenarios test_cursor_lifecycle_scenarios \ + test_cursor_native_install test_cursor_native_update test_cursor_managed_update + +python3 helixharness/scripts/cursor_skill_projection.py --check +python3 helixharness/scripts/codex_skill_projection.py --check +python3 helixharness/scripts/host_runtime_cli.py list +``` + +Automated contract tests supply synthetic workflow artifacts. They verify routing, persistence, isolation and gates; native model behavior and external service delivery require their own recorded evidence. Read the [Host API](../helixharness/reference/host-api.md) for the capability contract. + +自动化合同测试提供合成流程产物,验证路由、持久状态、隔离与门禁;原生模型行为和外部投递需各自的实际证据。能力合同见 [Host API](../helixharness/reference/host-api.md)。 diff --git a/docs/installation.md b/docs/installation.md index 4f3856c..b0aaf70 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -4,15 +4,15 @@ ## 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.9+, Git and a plugin-capable Codex, Claude Code or Cursor installation are required. Make sure the host is signed in or has its model configuration set up and is working normally. The platform is optional. Cursor desktop support follows the release scope and limitations below. 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). -This edition uses only the HelixHarness identifiers: `helix@helixharness-marketplace`, `/helix:*`, `.helixharness/`, `helixharness.workspace.yaml`, and `HELIXHARNESS_*` environment variables. It does not recognize or migrate identifiers, configuration or runtime data from previous branding. Initialize a fresh application copy when validating this edition. +This edition uses only the HelixHarness identifiers: `helix@helixharness-marketplace`, logical `/helix:*` commands (Cursor: `/helix-{command}`), `.helixharness/`, `helixharness.workspace.yaml`, and `HELIXHARNESS_*` environment variables. It does not recognize or migrate identifiers, configuration or runtime data from previous branding. Initialize a fresh application copy when validating this edition. ## Install from GitHub after publication -Choose your host and run its commands in a terminal. No manual source clone is needed: +For Codex and Claude Code, run the following terminal commands. For Cursor, use the [marketplace flow](#cursor). These marketplace routes do not require a manual source clone: ```bash # Codex @@ -58,9 +58,33 @@ Review and trust the plugin's hooks through the host's native interface. Confirm 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. + + +## Cursor + +Cursor desktop support uses `/helix-xxx` Skills. The default distribution route is a Cursor marketplace. After the release repository is available, a team administrator imports it through **Dashboard → Plugins & MCPs → Add Marketplace → Import from Repo**. Users then open **Customize → helix → Install** and select project or user scope. Follow Cursor's repository-provider and account-permission prompts. Helix has the required marketplace manifests; a public Cursor Marketplace listing requires submission and review. See [Cursor's marketplace documentation](https://cursor.com/docs/plugins). + +Cursor 桌面支持使用 `/helix-xxx` Skill,默认通过 Cursor 市场分发。发行仓库可访问后,团队管理员通过 **Dashboard → Plugins & MCPs → Add Marketplace → Import from Repo** 导入;用户在 **Customize → helix → Install** 选择项目或用户范围。仓库和账号权限按 Cursor 提示配置。Helix 已具备市场清单,公共市场上架需单独提交审核。 + +Reload the window, start a new Agent and select `/helix-status` from `/helix-` completion. Verify the selected plugin root and runtime preflight, then use `/helix-init` in the application repository. The nine command names and arguments follow the shared workflow contracts. Existing native acceptance covers a fixed remote source; the general marketplace UI flow remains an accepted verification gap for this release. + +安装后重载窗口,新建 Agent,从 `/helix-` 补全选择 `/helix-status`,核对插件来源及运行预检,再在业务仓库运行 `/helix-init`。九个命令的名称与参数沿用公共流程合同。已有原生实机证据覆盖固定远程来源;普通市场 UI 完整流程保留为本次接受的验证缺口。 + +The [Cursor installer contract](../helixharness/hosts/cursor/installer.md) documents advanced fixed-SHA project configuration, optional Helix-managed Local installation and recovery. Fixed-SHA configuration lets Cursor obtain the package without a source checkout. Registered managed-local installations on macOS/Linux support `/helix-update`; native marketplace installations use Cursor's update controls. A manually copied Local package has no managed registration. + +[Cursor 安装合同](../helixharness/hosts/cursor/installer.md)提供高级固定 SHA 项目配置、可选的 Helix 托管 Local 安装及恢复步骤。固定 SHA 由 Cursor 获取插件,无需先下载源码。macOS/Linux 的已登记托管 Local 支持 `/helix-update`;原生市场安装通过 Cursor 管理更新,手工复制副本没有托管登记。 + +Keep a single intended Helix source active in Cursor. A Skill from an imported copy can conflict with a Hook from another installation. Resolve `plugin_source_mismatch` by checking the actual Skill and plugin root. Matching names or versions alone do not identify the selected source. Imported Claude hooks may also duplicate checks. Preserve other hosts' installations and user settings while resolving these conflicts. + +Cursor 中应选择明确的 Helix 来源。导入副本的 Skill 与另一安装的 Hook 可能冲突,遇到 `plugin_source_mismatch` 时核对实际 Skill 与插件根路径。同名或同版本不能证明来源一致;导入 Claude hooks 也可能重复检查。处理冲突时保留其他宿主安装及用户设置。 + +Statistics require explicit consent and current-session identity. Missing identity skips statistics while workflows continue. Token attribution can be partial or unavailable. Consent revocation cleans the current repository; window-close and later-startup cleanup are best effort. CLI, Cloud and full D2C are outside this release's complete acceptance scope. See [support and verification boundaries](cursor-testing.md). + +统计需要明确授权和本次会话身份,缺身份时跳过统计并继续业务,Token 归属可为 partial/unavailable。关闭授权清理当前仓库,关窗及后续启动清理尽力执行。CLI、Cloud、完整 D2C 不在本期完整验收范围,详见[支持与验证边界](cursor-testing.md)。 + ## Updates -Run `/helix:update` in the host conversation. The plugin checks the configured marketplace, shows an available update and uses the host adapter after authorization. +On Claude Code and Codex, run `/helix:update` in the host conversation. The plugin checks the configured marketplace, shows an available update and uses the host adapter after authorization. Cursor uses `/helix-update` for registered Helix-managed local installations on macOS/Linux, following the same check, confirmation and one-time authorization protocol. Manual copies and Cursor marketplace installations use their original update mechanism. - **Git source:** the host refreshes the configured repository; use the same marketplace for later versions. - **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. @@ -73,8 +97,8 @@ Use the host's plugin management to uninstall `helix@helixharness-marketplace`. ## 中文说明 -需要 Python 3.10+、Git,以及支持插件市场的 Codex 或 Claude Code。先确保宿主已完成登录或模型配置,能够正常使用。平台不是安装插件的前置条件。 +需要 Python 3.9+、Git,以及支持插件的 Codex、Claude Code 或 Cursor。Cursor 使用上面的 [Cursor 独立安装流程](#cursor-preview)。先确保宿主已完成登录或模型配置,能够正常使用。平台不是安装插件的前置条件。 -正式发布后使用上面的 GitHub 安装命令,无需先手动克隆源码。发布前测试或修改插件时,使用[开发者安装(本地源码)](#developer-installation):先下载或克隆源码,再从**包含两个子项目的根目录**添加本地市场。根市场指向 `./helixharness`,不会安装平台。独立插件副本仍可添加插件目录本身;同名市场只保留一个来源。 +正式发布后,Codex 与 Claude Code 使用上面的 GitHub 安装命令,Cursor 使用市场界面流程;这些市场安装方式无需先手动克隆源码。发布前测试或修改插件时,使用[开发者安装(本地源码)](#developer-installation):先下载或克隆源码,再从**包含两个子项目的根目录**添加本地市场。根市场指向 `./helixharness`,不会安装平台。独立插件副本仍可添加插件目录本身;同名市场只保留一个来源。 -安装后新开会话,确认九个命令可见、插件 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`(Cursor 为 `/helix-init`)并检查项目 hooks。单仓 Init 还需检查非空的 `docs/harness/index.md`、`docs/knowledge/index.md`、`docs/knowledge/project-context.md` 及对应项目类型要求的其他产物,不能只看“已完成”回复。若出现 `plugin_source_mismatch`,先核对市场来源与当前安装插件,选定正确来源并新开会话,避免混用其他 checkout 或缓存版本。Claude Code/Codex 更新使用 `/helix:update`;本地来源需先自行更新源码,不能把版本识别成功当作已完成跨版本升级。Cursor 在 macOS/Linux 上使用 `/helix-update` 升级已登记的 Helix 托管本地安装,复用检查、确认与一次性授权协议;手工副本和原生市场安装仍通过原安装方式更新。 diff --git a/docs/user-guide.md b/docs/user-guide.md index cd65ead..d544bbd 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 Cursor, 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 / Cursor · 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.9+, Git, and a plugin-capable Codex, Claude Code or Cursor installation that is signed in or has its model configuration set up and works normally | | 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 | @@ -58,7 +58,7 @@ The terminal examples below use Bash / Zsh. GitHub plugin installation does not ### 1. Install the Plugin -After the repository is public, run the commands for your coding agent in a terminal. For testing before publication or modifying the plugin, use [developer installation from local source](installation.md#developer-installation). +After the repository is public, use the terminal commands below for Codex/Claude Code or the marketplace UI for Cursor. For testing before publication or modifying the plugin, use [developer installation from local source](installation.md#developer-installation). **Codex** @@ -76,9 +76,13 @@ 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. +**Cursor** + +Install `helix` through **Customize → helix → Install** after the release repository is available in your Cursor marketplace. Use the [marketplace setup and optional installation paths](installation.md#cursor-preview) for administrator setup, fixed-source configuration or managed Local installation. Reload the window and open a new Agent. Cursor's nine `/helix-{command}` Skills use the same arguments and business gates as the `/helix:*` examples below. Statistics require consent and current-session identity and may be partial. Native marketplace updates are managed by Cursor; `/helix-update` supports registered managed-local installations. See [support and verification boundaries](cursor-testing.md). + ### 2. Build Your First Feature -Enter the following `/helix:*` commands **in your coding agent's conversation**, not in a terminal shell. +Enter commands **in your coding agent's conversation**, not in a terminal shell. The examples below use the Codex / Claude Code prefix `/helix:`. In Cursor, replace that prefix with `/helix-`, keeping the command name and arguments unchanged; for example, `/helix:init` becomes `/helix-init`, and `/helix:bug-fix` becomes `/helix-bug-fix`. Initialize your application repository: @@ -149,7 +153,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 / Cursor 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 @@ -178,7 +182,7 @@ Keep three directories distinct: **HelixHarness plugin source**, **application r ## Commands -There are nine public commands. `--loop` is an option on `propose`. +There are nine public commands. `--loop` is an option on `propose`. The examples use `/helix:` for Codex / Claude Code; in Cursor, use the `/helix-` prefix with the same arguments. | Command | Purpose | Example | | --- | --- | --- | @@ -219,6 +223,8 @@ There are nine public commands. `--loop` is an option on `propose`. Execute one change at a time. Telemetry changes require `--scope project|user`; user-level disabling overrides project-level enabling, within the current host. Addresses are local user settings, separate from consent. Changing an address neither enables telemetry nor sends a request. Reset restores the published default, which may still name a recipient; explicitly disable consent to stop telemetry. The data notice is shown before enabling; an explicit change request does not require repeated confirmation. Corrupt configuration files are preserved and reported. +An explicit enable request is one interaction: the agent displays the full notice in a visible progress message, then continues the same request without waiting for “continue” or another consent choice. Direct CLI callers receive a read-only `request_complete=false` notice response and must display it before following `continuation` with the original authorization and scope. `request_complete=true` means the script request has finished, not that the change succeeded; inspect `change.updated`, warnings, and the effective settings. + Models, credentials, application configuration, and platform deployment are outside this entrypoint. See the full [status](../helixharness/commands/status.md) and [config](../helixharness/commands/config.md) contracts. ### Workflow Artifacts @@ -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 / Cursor. 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 / Cursor 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 and Cursor each install 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. `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. diff --git a/docs/user-guide.zh-CN.md b/docs/user-guide.zh-CN.md index 012896f..cb8da40 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 与 Cursor 的研发工作流,以及提供数据看板、版本评测与自进化的配套平台。** 从一个需求到有验证依据的代码变更:明确边界、拆分任务、实现、测试、评审,再把结果归档到项目中。HelixHarness 将这些步骤作为可复用的工作流交给编码助手,需求和执行进度保存在仓库里,便于检查和续跑。 @@ -14,7 +14,7 @@ Propose → Apply → Archive └─ 测试 + 代码评审 + 验证依据 ``` -**9 个公开命令 · 3 个核心阶段 · Codex / Claude Code · 单仓 / 多仓 Workspace · Apache-2.0** +**9 个公开命令 · 3 个核心阶段 · Codex / Claude Code / Cursor · 单仓 / 多仓 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.9+、Git,以及支持插件的 Codex、Claude Code 或 Cursor;宿主已完成登录或模型配置,能够正常使用 | | 运行平台 Demo / 使用看板 | Python 3.10+、Git;安装平台 `server` 依赖 | | 真实版本评测 | 平台依赖、可用的 Codex 执行环境、模型凭据、可访问的 Git 仓库,以及 Case 所需的构建与测试工具 | | 前端预览与视觉验证 | 项目自身的 Node.js、包管理器及浏览器工具;设计服务按实际使用情况配置 | @@ -59,7 +59,7 @@ Propose → Apply → Archive ### 1. 安装 HelixHarness 插件 -仓库公开后,在终端选择使用的宿主,只执行对应的一组命令。发布前测试或修改插件时,使用[开发者安装(本地源码)](installation.md#developer-installation)。 +仓库公开后,Codex 和 Claude Code 使用下方对应终端命令,Cursor 使用市场界面安装。发布前测试或修改插件时,使用[开发者安装(本地源码)](installation.md#developer-installation)。 **Codex** @@ -77,9 +77,13 @@ claude plugin install helix@helixharness-marketplace 安装后,在你要开发的业务仓库中新开宿主会话,确认能找到 `helixharness` 的九个公开命令。宿主适配说明见 [Codex 安装指南](../helixharness/hosts/codex/installer.md) 和 [Claude Code 安装指南](../helixharness/hosts/claude-code/installer.md)。 +**Cursor** + +发行仓库已加入可访问的 Cursor 市场后,通过 **Customize → helix → Install** 安装。管理员配置、高级固定来源配置及托管 Local 安装见[市场安装与可选路径](installation.md#cursor-preview)。安装后重载窗口并新建 Agent。Cursor 的九个 `/helix-{command}` Skill 与下文 `/helix:*` 示例使用相同参数和业务门禁。统计需授权及本次会话身份,数据可能为 partial。原生市场更新由 Cursor 管理,`/helix-update` 支持已登记的托管 Local。详见[支持与验证边界](cursor-testing.md)。 + ### 2. 完成第一个需求 -以下 `/helix:*` 是**输入到编码助手会话中的命令**,不是终端 Shell 命令。 +命令应**输入到编码助手会话中**,不是终端 Shell 命令。以下示例使用 Codex / Claude Code 的 `/helix:` 前缀;在 Cursor 中将该前缀替换为 `/helix-`,命令名和参数保持不变。例如 `/helix:init` 对应 `/helix-init`,`/helix:bug-fix` 对应 `/helix-bug-fix`。 先在业务仓库初始化项目: @@ -150,7 +154,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 / Cursor 会话及业务仓库 | | [`helixharness-platform/`](../helixharness-platform/README.md) | 观测和改进 HelixHarness 框架的维护者 | 数据看板、版本评测、自进化 | 独立 Python Web 服务与评测 Worker | ```mermaid @@ -179,7 +183,7 @@ flowchart LR ## 命令参考 -公开命令共九个,`--loop` 是 `propose` 的参数。 +公开命令共九个,`--loop` 是 `propose` 的参数。表中示例使用 Codex / Claude Code 的 `/helix:`;在 Cursor 中使用 `/helix-` 前缀,参数相同。 | 命令 | 用途 | 示例 | | --- | --- | --- | @@ -220,6 +224,8 @@ flowchart LR 每次执行一项修改。统计开关必须同时指定 `--scope project|user`;用户级关闭优先于项目级开启,用户级设置属于当前宿主。地址是本机用户配置,独立于统计授权;修改地址不会开启统计,也不会发送请求。恢复默认地址可能仍有接收方,需要停止统计时明确关闭授权。开启前展示数据说明;明确的修改请求不需要重复确认。损坏配置保留原文件并报错。 +明确开启请求在同一次交互内完成:Agent 先通过用户可见的进度消息展示完整说明,再沿用原请求继续执行,不等待再次回复“继续”或重新选择授权。直接调用 CLI 时,首次只返回只读的 `request_complete=false` 说明回执;调用方必须先展示说明,再按 `continuation` 沿用原授权与范围续执行。`request_complete=true` 只表示本次脚本请求已处理结束,不代表修改成功;仍须检查 `change.updated`、warning 和实际有效配置。 + 模型、密钥、业务配置和平台部署不在此入口范围内。完整合同见 [status](../helixharness/commands/status.md) 和 [config](../helixharness/commands/config.md)。 ### 工作流产物 @@ -399,7 +405,7 @@ DEFAULT_FEEDBACK_ENDPOINT = "" ### 模型配置 -日常使用插件时,模型由 Codex / Claude Code 宿主配置。平台自身的模型配置用于平台发起的评测、分析等任务。 +日常使用插件时,模型由 Codex / Claude Code / Cursor 宿主配置。平台自身的模型配置用于平台发起的评测、分析等任务。 配置模板见 [`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 / Cursor 适配 │ ├── 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 与 Cursor 安装目录各包含九个公开入口 Skill 和上述八个方法 Skill;Claude Code 直接发现根 `skills/`。四个生命周期命令继续使用工作流路由;`status`、`config` 与辅助 Skill 不增加研发阶段。正式 Spec/Tasks、执行进度和完成验证仍由对应研发阶段负责。 `git-diff-impact` 无需 Init、活跃 feature 或平台服务。示例:“使用 HelixHarness git-diff-impact,分析当前未提交改动,--no-save”;也可明确提供两个提交或分支,以及 `--req` / `--design` 文档。默认保存 Markdown 到 `diff-impact-reports/`,`--out` 可指定位置。它不自动修复代码,也不改变评审结论。 diff --git a/docs/workflow-architecture.md b/docs/workflow-architecture.md index a340e01..eccc602 100644 --- a/docs/workflow-architecture.md +++ b/docs/workflow-architecture.md @@ -22,11 +22,11 @@ Workspace 子任务从公共入口进入 Single 正文,根目录不写子仓 ## 宿主边界 [`Host API`](../helixharness/reference/host-api.md) 定义 manifest 和适配器合同。 -Claude Code 使用原生命令,Codex 使用 Skill 投影;宿主机制由 `hosts/{host-id}/` 提供。 -两个原生插件清单显式选择各自的 hook 配置。宿主入口负责固定身份和事件转换, +Claude Code 使用原生命令,Codex 与 Cursor 使用各自的 Skill 投影;宿主机制由 `hosts/{host-id}/` 提供。 +三个原生插件清单显式选择各自的 hook 配置。宿主入口负责固定身份和事件转换, 共享生命周期逻辑不得根据平台名称、环境变量或缓存目录猜测宿主。 -Codex Init 入口加载 `project_config`、`project_hooks`;UT 入口加载 `ut`。 +宿主 Init 入口加载 `project_config`、`project_hooks`;UT 入口加载 `ut`。 单仓 Init 必须实际生成并校验当前 Host Kit 的项目 hooks,重复初始化保留用户配置并去重。 业务阶段显式记录 start/finish;会话 Stop 不是业务完成证据。 @@ -40,6 +40,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 与 Cursor 投影校验。 +Cursor 采用 Host API 1.2 的扁平项目 hooks 策略;1.1 的嵌套策略保持兼容。Cursor 桌面宿主按已声明的能力边界正式支持,发布范围和验证边界详见 [Cursor 验证说明](cursor-testing.md)。 原生客户端验收分别核查插件装载、启动身份、真实子任务、测试和覆盖率、 完整工件、归档状态与清理;单测通过、命令退出成功或模型回复完成均不能单独证明闭环通过。 diff --git a/helixharness-platform/README.md b/helixharness-platform/README.md index 8a2d529..c0b55e2 100644 --- a/helixharness-platform/README.md +++ b/helixharness-platform/README.md @@ -4,6 +4,16 @@ FastAPI + Jinja2 + HTMX 单服务,包含使用数据看板、可信评测与证据驱动的自进化。`web_ui` 组合独立的 `eval`、`bench`、`evolution` 模块;各模块不互相导入、不跨模块查库。 +## 宿主兼容范围 / Host compatibility + +平台可接收带 `claude-code`、`codex`、`cursor` 身份的合规健康事件,并在使用看板与反馈详情中展示宿主名称。Cursor Host Kit 当前为 preview,已支持授权后统计和托管本地安装的受控更新。平台保留用量的采集状态、父代理范围和缺失原因;部分采集显示小计,缺失用量保持“未采集”,缓存命中不重复计入总 Token。 + +Bench 执行器仍只有 `CODEX` 与 `MOCK`,Candidate 生成仍使用 Codex。插件接入 Cursor 不包含 Cursor benchmark 执行器,也不自动开启统计、模型调用或评测。 + +The platform accepts valid health events identified as `claude-code`, `codex`, or `cursor`, and displays host names in usage dashboards and feedback details. The Cursor Host Kit remains a preview with opt-in telemetry and confirmed updates for managed local installations. The platform retains collection status, parent-only scope and missing-data reasons; partial usage is shown as a subtotal, missing usage stays unavailable, and cached tokens are not added twice. + +Bench execution remains limited to `CODEX` and `MOCK`, and Candidate generation still uses Codex. Cursor plugin support does not include a Cursor benchmark executor or automatically enable telemetry, model calls, or evaluation. + ## 安装和 Demo 以下命令在 `helixharness-platform/` 目录执行。 diff --git a/helixharness-platform/eval/runtime_health.py b/helixharness-platform/eval/runtime_health.py index 7d69db7..69906f3 100644 --- a/helixharness-platform/eval/runtime_health.py +++ b/helixharness-platform/eval/runtime_health.py @@ -41,7 +41,7 @@ def validate_v2(payload: dict[str, Any]) -> dict[str, Any]: raise ValueError("runtime scope_id must be runtime") if payload["scope_kind"] == "collection" and not {"repo_name", "platform"} <= payload.keys(): raise ValueError("collection scope requires repo_name and platform") - if "platform" in payload and payload["platform"] not in {"codex", "claude-code"}: + if "platform" in payload and payload["platform"] not in {"codex", "claude-code", "cursor"}: raise ValueError("unsupported platform") if payload["event"] not in {"circuit_open", "circuit_closed", "heartbeat"}: raise ValueError("invalid health event") diff --git a/helixharness-platform/eval/stage_supplements.py b/helixharness-platform/eval/stage_supplements.py index effc623..c3786f0 100644 --- a/helixharness-platform/eval/stage_supplements.py +++ b/helixharness-platform/eval/stage_supplements.py @@ -29,6 +29,26 @@ RUNTIME_HEALTH_SCHEMAS = {RUNTIME_HEALTH_SCHEMA} LINKED_RAW_RETENTION_DAYS = 7 UNLINKED_RETENTION_DAYS = 30 +USAGE_TEXT_FIELDS = ( + "collection_status", "status", "unavailable_reason", "reason", "scope", "usage_scope", + "attribution", "source", "confidence", "contamination_risk", +) + + +def usage_metadata(usage: dict[str, Any]) -> dict[str, Any]: + """Keep bounded collection facts without retaining arbitrary provider payloads.""" + metadata = { + key: usage[key][:128] + for key in USAGE_TEXT_FIELDS + if isinstance(usage.get(key), str) and usage[key] + } + if isinstance(usage.get("input_tokens_include_cache"), bool): + metadata["input_tokens_include_cache"] = usage["input_tokens_include_cache"] + generations = usage.get("generations") + if isinstance(generations, int) and not isinstance(generations, bool) and generations >= 0: + metadata["generations"] = generations + return metadata + _REQUIRED_TEXT_FIELDS = ( "supplement_id", @@ -110,6 +130,7 @@ def _snapshot_payload(item: dict[str, Any]) -> dict[str, Any]: ) if key in usage } + snapshot["usage"].update(usage_metadata(usage)) models = usage.get("models") if isinstance(usage.get("models"), list) else [] if models: snapshot["usage"]["models"] = [ @@ -140,6 +161,9 @@ def _snapshot_payload(item: dict[str, Any]) -> dict[str, Any]: "persistence_latency_ms", "record_write_count", "collection_status", + "unavailable_reason", + "scope", + "attribution", ) if key in execution } diff --git a/helixharness-platform/eval/telemetry_materialization.py b/helixharness-platform/eval/telemetry_materialization.py index 94bbb13..9dd2be2 100644 --- a/helixharness-platform/eval/telemetry_materialization.py +++ b/helixharness-platform/eval/telemetry_materialization.py @@ -13,7 +13,7 @@ from copy import deepcopy from typing import Any -from eval.stage_supplements import LEDGER_SCHEMA, LinkedStageSupplement +from eval.stage_supplements import LEDGER_SCHEMA, LinkedStageSupplement, usage_metadata def index_linked_supplements( @@ -33,7 +33,7 @@ def materialized_hash(raw: bytes, records: Mapping[str, LinkedStageSupplement]) """Identify the combined fixed-ledger and active-Supplement projection.""" identity = { - "materializer": "helixharness-eval-materialized/2.0", + "materializer": "helixharness-eval-materialized/2.1", "supplements": { entry_id: { "payload_hash": record.payload_hash, @@ -203,22 +203,49 @@ def _materialize_quality(value: object, linked: bool, trace: dict[str, Any]) -> def _materialize_usage(usage: dict[str, Any]) -> dict[str, Any]: + def token_count(value: object) -> bool: + return isinstance(value, int) and not isinstance(value, bool) and value >= 0 + numeric: dict[str, int] = {} for field in ("input_tokens", "output_tokens", "cache_write_tokens"): value = usage.get(field) - if isinstance(value, int) and not isinstance(value, bool): + if token_count(value): numeric[field] = value cache_read = usage.get("cache_read_tokens", usage.get("cached_input_tokens")) - if isinstance(cache_read, int) and not isinstance(cache_read, bool): + if token_count(cache_read): numeric["cache_read_tokens"] = cache_read - collected = bool(numeric) total = usage.get("total_tokens") - if not isinstance(total, int) or isinstance(total, bool): - primary = [numeric[field] for field in ("input_tokens", "output_tokens") if field in numeric] - total = sum(primary) if primary else (sum(numeric.values()) if collected else None) + if not token_count(total): + total = ( + numeric["input_tokens"] + numeric["output_tokens"] + if {"input_tokens", "output_tokens"} <= numeric.keys() else None + ) + metadata = usage_metadata(usage) + explicit_status = metadata.get("collection_status") or metadata.get("status") + status = {"available": "collected"}.get(explicit_status, explicit_status) + reason = metadata.get("unavailable_reason") + if status is None: + status = "collected" if total is not None else "unavailable" + elif status not in {"collected", "partial", "pending", "unavailable"}: + reason = reason or "unsupported_usage_collection_status" + status = "unavailable" + if total is None and status in {"collected", "partial"}: + status = "unavailable" + if status in {"partial", "pending", "unavailable"}: + reported_reason = metadata.get("reason") + if reported_reason == "native_generation_snapshots": + reported_reason = None + reason = reason or reported_reason or ( + "partial_usage_coverage" if total is not None else + "incomplete_token_fields" if numeric else "async_usage_unavailable" + ) + collected = status in {"collected", "partial"} and total is not None + legacy_exact = collected and not metadata + scope = metadata.get("usage_scope") or metadata.get("scope") or ("stage_session" if legacy_exact else "unknown") raw_models = usage.get("models") if isinstance(usage.get("models"), list) else [] models = [item if isinstance(item, dict) else {"model": str(item)} for item in raw_models] return { + **metadata, **{ field: numeric.get(field) for field in ("input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens") @@ -226,13 +253,13 @@ def _materialize_usage(usage: dict[str, Any]) -> dict[str, Any]: "total_tokens": total, "model": usage.get("model") or "unknown", "models": models, - "collection_status": "collected" if collected else "unavailable", - "unavailable_reason": None if collected else "async_usage_unavailable", - "source": "async_stage_supplement" if collected else "unknown", - "attribution": "exact_session_window" if collected else "unknown", - "usage_scope": "stage_session" if collected else "unknown", - "contamination_risk": "low" if collected else "unknown", - "confidence": "high" if collected else "unknown", + "collection_status": status, + "unavailable_reason": reason, + "source": metadata.get("source") or ("async_stage_supplement" if collected else "unknown"), + "attribution": metadata.get("attribution") or ("exact_session_window" if legacy_exact else "unknown"), + "usage_scope": scope, + "contamination_risk": metadata.get("contamination_risk") or ("low" if legacy_exact else "unknown"), + "confidence": metadata.get("confidence") or ("high" if legacy_exact else "unknown"), } @@ -300,7 +327,10 @@ def _evolution_evidence( "coverage": dict(evidence.get("coverage") or {}), "execution": { key: execution.get(key) - for key in ("tool_call_count", "subagent_spawn_count", "context_reads") + for key in ( + "tool_call_count", "subagent_spawn_count", "context_reads", "child_agent_scope", + "collection_status", "unavailable_reason", "scope", "attribution", + ) if execution.get(key) is not None }, "workflow_trace": { @@ -321,10 +351,12 @@ def _bounded_evolution_usage(usage: dict[str, Any]) -> dict[str, Any]: "cached_input_tokens", "cache_read_tokens", "cache_write_tokens", + "total_tokens", "model", ) if usage.get(key) is not None } + result.update(usage_metadata(usage)) models = usage.get("models") if isinstance(usage.get("models"), list) else [] if models: result["models"] = [ diff --git a/helixharness-platform/eval/tests/test_runtime_health.py b/helixharness-platform/eval/tests/test_runtime_health.py index 295d700..38c6147 100644 --- a/helixharness-platform/eval/tests/test_runtime_health.py +++ b/helixharness-platform/eval/tests/test_runtime_health.py @@ -34,7 +34,8 @@ def health_event(**changes) -> dict: } -def test_health_v2_preserves_open_recovery_and_heartbeat(tmp_path): +@pytest.mark.parametrize("platform", ["claude-code", "codex", "cursor"]) +def test_health_v2_preserves_open_recovery_and_heartbeat(tmp_path, platform): path = tmp_path / "inbox.db" store = StageSupplementStore(path) events = [ @@ -44,6 +45,8 @@ def test_health_v2_preserves_open_recovery_and_heartbeat(tmp_path): health_event(event_id="health_heartbeat", event="heartbeat", circuit_open=False, consecutive_failures=0, observed_at="2026-09-09T03:10:00Z"), ] + for event in events: + event.update(platform=platform, scope_id=f"repo_a_{platform}") # Delayed arrival must not overwrite any other event or scope. for event in reversed(events): assert store.ingest_runtime_health(event)["status"] == "accepted" @@ -54,21 +57,25 @@ def test_health_v2_preserves_open_recovery_and_heartbeat(tmp_path): assert all(row["received_at"] for row in rows) assert {json.loads(row["payload_json"])["event_id"] for row in rows} == {e["event_id"] for e in events} assert all(json.loads(row["payload_json"])["user_name"] == "test-user" for row in rows) + assert all(json.loads(row["payload_json"])["platform"] == platform for row in rows) -def test_v2_conflicting_retry_does_not_overwrite_original(tmp_path): +@pytest.mark.parametrize("platform", ["claude-code", "codex", "cursor"]) +def test_v2_conflicting_retry_does_not_overwrite_original(tmp_path, platform): store = StageSupplementStore(tmp_path / "inbox.db") - store.ingest_runtime_health(health_event()) + store.ingest_runtime_health(health_event(platform=platform)) with pytest.raises(StageSupplementError, match="different content") as error: - store.ingest_runtime_health(health_event(feature="different-feature")) + store.ingest_runtime_health(health_event(platform=platform, feature="different-feature")) assert error.value.code == "identity_conflict" with store._connect() as connection: row = connection.execute("SELECT payload_json FROM runtime_health_events").fetchone() assert json.loads(row[0])["feature"] == "test-feature" + assert json.loads(row[0])["platform"] == platform @pytest.mark.parametrize("change", [ {"scope_kind": "all_projects"}, {"platform": "invalid"}, {"circuit_open": "true"}, + {"platform": "Cursor"}, {"platform": "cursor\n"}, {"platform": "../cursor"}, {"consecutive_failures": True}, {"consecutive_failures": -1}, {"consecutive_failures": 0}, {"event": "circuit_closed"}, {"observed_at": "2026-09-09T03:00:00"}, {"circuit_resume_at": "2026-09-08T03:00:00Z"}, {"reason_code": ""}, diff --git a/helixharness-platform/eval/tests/test_usage_loader.py b/helixharness-platform/eval/tests/test_usage_loader.py index 54b8d16..8dacf2c 100644 --- a/helixharness-platform/eval/tests/test_usage_loader.py +++ b/helixharness-platform/eval/tests/test_usage_loader.py @@ -528,19 +528,56 @@ def test_workflow_detail_uses_three_business_stages_for_duration_and_process(tmp assert "未采集本次代码文件清单" in timeline_html -def test_workflow_detail_displays_helixharness_version_and_execution_platform(tmp_path: Path) -> None: +@pytest.mark.parametrize("platform,label", [("claude-code", "Claude Code"), ("codex", "Codex"), ("cursor", "Cursor")]) +def test_workflow_detail_displays_helixharness_version_and_execution_platform( + tmp_path: Path, platform: str, label: str, +) -> None: feature_dir = tmp_path / "docs" / "eval" / "workflow-runtime" feature_dir.mkdir(parents=True) + log = _workflow_log() + log["entries"][0]["platform"] = platform (feature_dir / "eval-log.json").write_text( - json.dumps(_workflow_log(), ensure_ascii=False), + json.dumps(log, ensure_ascii=False), encoding="utf-8", ) html = render_usage_overview_html([str(tmp_path)], "按需求维度") - timeline_html = render_feature_timeline_html(_workflow_log()) + timeline_html = render_feature_timeline_html(log) + + assert f'HelixHarness 2.2.0 · 平台 {label}' in html + assert f"HelixHarness 2.2.0 · {label}" in timeline_html - assert 'HelixHarness 2.2.0 · 平台 Codex' in html - assert "HelixHarness 2.2.0 · Codex" in timeline_html + +def test_cursor_identity_does_not_create_usage_measurements(tmp_path: Path) -> None: + log = _workflow_log() + log["entries"][0]["platform"] = "cursor" + feature_dir = tmp_path / "docs" / "eval" / "example-feature" + feature_dir.mkdir(parents=True) + (feature_dir / "eval-log.json").write_text(json.dumps(log), encoding="utf-8") + loaded = discover_projects([str(tmp_path)])[0]["features"][0] + entry = loaded["entries"][0] + + usage = _resource_usage(entry) + assert usage["total_tokens"] is None + assert usage["collection_status"] == "unavailable" + assert entry["telemetry_status"] == "pending" + timeline = render_feature_timeline_html(loaded) + assert "HelixHarness 2.2.0 · Cursor" in timeline + assert "当前不按 0 统计" in timeline + assert "工具调用 0 次" not in timeline + assert "用户交互轮次 0 轮" not in timeline + + +def test_runtime_distribution_keeps_cursor_separate_from_existing_hosts() -> None: + entries = [ + _runtime_entry("Alice", platform="codex"), + _runtime_entry("Bob", platform="claude-code"), + _runtime_entry("Carol", platform="cursor"), + ] + chart = _runtime_distribution_html([{"entries": entries}], "platform") + for label in ("Codex", "Claude Code", "Cursor"): + assert f'data-label="{label}" data-count="1"' in chart + assert "共 3 人" in chart def _runtime_entry(user: str, time: str = "2026-09-08T00:00:00Z", **values) -> dict: diff --git a/helixharness-platform/eval/tests/test_usage_materialization.py b/helixharness-platform/eval/tests/test_usage_materialization.py new file mode 100644 index 0000000..bf7faa8 --- /dev/null +++ b/helixharness-platform/eval/tests/test_usage_materialization.py @@ -0,0 +1,88 @@ +"""Collection completeness is independent from observed numeric usage.""" +from __future__ import annotations + +import pytest + +from eval.telemetry_materialization import _materialize_usage +from eval.tests.test_usage_loader import _repeated_apply_log +from eval.usage_loader import _aggregate_resource_usages, _resource_usage, render_feature_timeline_html + + +@pytest.mark.parametrize("usage,total", [ + ({"input_tokens": 0, "output_tokens": 0}, 0), + ({"input_tokens": 150, "output_tokens": 10, "cache_read_tokens": 30, "cache_write_tokens": 20}, 160), + ({"total_tokens": 0}, 0), + ({"total_tokens": 160, "cache_read_tokens": 30}, 160), + ({"input_tokens": 10}, None), + ({"cache_read_tokens": 10, "cache_write_tokens": 5}, None), + ({"input_tokens": True, "output_tokens": 10}, None), + ({"input_tokens": -1, "output_tokens": 10}, None), + ({"input_tokens": "10", "output_tokens": 10}, None), + ({"input_tokens": 1.5, "output_tokens": 10}, None), +]) +def test_materializer_requires_a_real_total_or_both_primary_counts(usage: dict, total: int | None) -> None: + result = _materialize_usage(usage) + assert result["total_tokens"] == total + assert result["collection_status"] == ("collected" if total is not None else "unavailable") + + +def test_explicit_unavailable_usage_is_not_counted_despite_stale_numbers() -> None: + usage = _resource_usage({"resource_usage": _materialize_usage({ + "input_tokens": 100, "output_tokens": 10, + "collection_status": "unavailable", "unavailable_reason": "no_complete_generation_in_stage_window", + "scope": "parent_only", "attribution": "complete_generations_within_stage", + })}) + assert usage["total_tokens"] is None + assert usage["unavailable_reason"] == "no_complete_generation_in_stage_window" + assert usage["attribution"] == "complete_generations_within_stage" + + +@pytest.mark.parametrize("status", ["collected", "partial"]) +def test_nested_rollups_keep_parent_only_usage_partial(status: str) -> None: + entry = {"resource_usage": _materialize_usage({ + "input_tokens": 0, "output_tokens": 0, "collection_status": status, + "scope": "parent_only", "attribution": "complete_generations_within_stage", + })} + first = _aggregate_resource_usages([_resource_usage(entry)]) + second = _aggregate_resource_usages([first], "global") + for result in (first, second): + assert result["total_tokens"] == 0 + assert result["collection_status"] == "partial" + assert result["collected_entries"] == 1 + assert result["partial_entries"] == 1 + assert result["exact"] is False + assert result["exact_total_tokens"] is None + assert result["limited_scopes"] == ["parent_only"] + + +def test_legacy_complete_usage_keeps_existing_attribution() -> None: + result = _materialize_usage({"input_tokens": 20, "output_tokens": 10, "cached_input_tokens": 4}) + assert result["total_tokens"] == 30 + assert result["cache_read_tokens"] == 4 + assert result["attribution"] == "exact_session_window" + assert result["usage_scope"] == "stage_session" + assert result["confidence"] == "high" + + +def test_incomplete_collected_snapshot_does_not_use_success_reason_as_missing_reason() -> None: + result = _materialize_usage({ + "input_tokens": 10, "collection_status": "collected", "reason": "native_generation_snapshots", + }) + assert result["total_tokens"] is None + assert result["collection_status"] == "unavailable" + assert result["unavailable_reason"] == "incomplete_token_fields" + + +@pytest.mark.parametrize("execution,tools,expected", [ + ({}, {}, "未采集"), + ({"tool_error_count": 0}, {}, "0 次"), + ({}, {"failed": 0}, "0 次"), +]) +def test_missing_execution_count_is_distinct_from_explicit_zero(execution: dict, tools: dict, expected: str) -> None: + log = _repeated_apply_log() + for entry in log["entries"]: + entry.update(execution_stats=execution, async_evidence={"tools": tools}) + timeline = render_feature_timeline_html(log) + assert f"调用未成功 {expected}" in timeline + if expected == "未采集": + assert "调用未成功 0 次" not in timeline diff --git a/helixharness-platform/eval/usage_loader.py b/helixharness-platform/eval/usage_loader.py index 2c3645d..06348dd 100644 --- a/helixharness-platform/eval/usage_loader.py +++ b/helixharness-platform/eval/usage_loader.py @@ -53,6 +53,7 @@ "claude": "Claude Code", "claude-code": "Claude Code", "codex": "Codex", + "cursor": "Cursor", } REVISION_REASON_LABELS = { "clarification": "澄清修正", @@ -407,10 +408,20 @@ def _artifacts(entry: dict) -> dict: def _execution_stats(entry: dict) -> dict: stats = entry.get("execution_stats") if isinstance(entry.get("execution_stats"), dict) else {} reads = stats.get("context_reads") if isinstance(stats.get("context_reads"), dict) else {} + evidence = entry.get("async_evidence") if isinstance(entry.get("async_evidence"), dict) else {} + tools = evidence.get("tools") if isinstance(evidence.get("tools"), dict) else {} + status = stats.get("collection_status") + available = status not in {"unavailable", "pending"} + tool_errors = None + if available: + failures = [item for item in evidence.get("failed_tools", []) if isinstance(item, dict)] + tool_errors = len(failures) or _to_int_or_none(stats.get("tool_error_count")) + if tool_errors is None: + tool_errors = _to_int_or_none(tools.get("failed")) return { - "tool_call_count": int(stats.get("tool_call_count", 0) or 0), - "tool_error_count": int(stats.get("tool_error_count", 0) or 0), - "subagent_spawn_count": int(stats.get("subagent_spawn_count", 0) or 0), + "tool_call_count": _to_int_or_none(stats.get("tool_call_count")) if available else None, + "tool_error_count": tool_errors, + "subagent_spawn_count": _to_int_or_none(stats.get("subagent_spawn_count")) if available else None, "child_agent_scope": stats.get("child_agent_scope") or "unavailable", "context_reads": { key: int(reads.get(key, 0) or 0) @@ -418,7 +429,8 @@ def _execution_stats(entry: dict) -> dict: }, "persistence_latency_ms": stats.get("persistence_latency_ms"), "record_write_count": int(stats.get("record_write_count", 0) or 0), - "collection_status": stats.get("collection_status") or "unavailable", + "collection_status": status, + "unavailable_reason": stats.get("unavailable_reason"), } @@ -535,20 +547,20 @@ def _resource_usage(entry: dict) -> dict: if not collection_status: collection_status = "unavailable" unavailable_reason = unavailable_reason or "missing_collection_status" - elif collection_status not in {"pending", "collected", "unavailable"}: + elif collection_status not in {"pending", "collected", "partial", "unavailable"}: unavailable_reason = unavailable_reason or f"unsupported_collection_status:{collection_status}" collection_status = "unavailable" - if collection_status == "collected" and result["total_tokens"] is None: + if collection_status in {"collected", "partial"} and result["total_tokens"] is None: collection_status = "unavailable" unavailable_reason = unavailable_reason or "missing_total_tokens" - if collection_status != "collected": + if collection_status not in {"collected", "partial"}: result = {key: None for key in RESOURCE_KEYS} model = ru.get("model") or "unknown" models = [item for item in ru.get("models", []) if isinstance(item, dict)] return { **result, - "scope": ru.get("usage_scope") or "unknown", - "usage_scope": ru.get("usage_scope") or "unknown", + "scope": ru.get("usage_scope") or ru.get("scope") or "unknown", + "usage_scope": ru.get("usage_scope") or ru.get("scope") or "unknown", "model": model, "models": models, "collection_status": collection_status, @@ -557,6 +569,8 @@ def _resource_usage(entry: dict) -> dict: "attribution": ru.get("attribution") or "unknown", "contamination_risk": ru.get("contamination_risk") or "unknown", "confidence": ru.get("confidence") or "unknown", + "input_tokens_include_cache": ru.get("input_tokens_include_cache"), + "generations": ru.get("generations"), } @@ -633,11 +647,17 @@ def _resource_unavailable_reason(usage: dict) -> str: return reason if usage.get("collection_status") == "pending": return "resource_usage_pending" + if usage.get("usage_scope") == "parent_only": + return "parent_only" if _to_int_or_none(usage.get("total_tokens")) is None: return "missing_total_tokens" return "resource_usage_unavailable" +def _limited_resource_usage(usage: dict) -> bool: + return usage.get("collection_status") == "partial" or usage.get("usage_scope") == "parent_only" + + def _lowest_confidence(usages: list[dict]) -> str: values = {str(usage.get("confidence") or "unknown") for usage in usages} if "low" in values: @@ -672,7 +692,10 @@ def _aggregate_resource_usages(usages: list[dict], scope: str = "aggregate") -> ) for key in RESOURCE_KEYS } - exact = bool(eligible_count) and collected_count == eligible_count + partial_count = sum(int(usage.get("partial_entries", 0) or 0) for usage in usages) + exact = bool(eligible_count) and collected_count == eligible_count and all( + usage.get("exact") for usage in usages if usage.get("eligible_entries") + ) exact_totals = {key: observed[key] if exact else None for key in RESOURCE_KEYS} reasons = sorted({ str(reason) @@ -688,6 +711,8 @@ def _aggregate_resource_usages(usages: list[dict], scope: str = "aggregate") -> "eligible_entries": eligible_count, "collected_entries": collected_count, "missing_entries": max(eligible_count - collected_count, 0), + "partial_entries": partial_count, + "limited_scopes": sorted({scope for usage in usages for scope in usage.get("limited_scopes", [])}), "missing_reasons": reasons, "exact": exact, "scope": scope, @@ -709,12 +734,12 @@ def _aggregate_resource_usages(usages: list[dict], scope: str = "aggregate") -> eligible = [ usage for usage in usages - if usage.get("collection_status") in {"pending", "collected", "unavailable"} + if usage.get("collection_status") in {"pending", "collected", "partial", "unavailable"} ] collected = [ usage for usage in eligible - if usage.get("collection_status") == "collected" + if usage.get("collection_status") in {"collected", "partial"} and _to_int_or_none(usage.get("total_tokens")) is not None ] observed = { @@ -725,12 +750,13 @@ def _aggregate_resource_usages(usages: list[dict], scope: str = "aggregate") -> ) for key in RESOURCE_KEYS } - exact = bool(eligible) and len(collected) == len(eligible) + limited = [usage for usage in collected if _limited_resource_usage(usage)] + exact = bool(eligible) and len(collected) == len(eligible) and not limited exact_totals = { key: observed[key] if exact and all(_to_int_or_none(usage.get(key)) is not None for usage in collected) else None for key in RESOURCE_KEYS } - incomplete = [usage for usage in eligible if usage not in collected] + incomplete = [usage for usage in eligible if usage not in collected or _limited_resource_usage(usage)] reasons = sorted({_resource_unavailable_reason(usage) for usage in incomplete}) unavailable_reason = reasons[0] if len(reasons) == 1 else ("multiple_resource_usage_failures" if reasons else None) if exact: @@ -748,6 +774,8 @@ def _aggregate_resource_usages(usages: list[dict], scope: str = "aggregate") -> "eligible_entries": len(eligible), "collected_entries": len(collected), "missing_entries": max(len(eligible) - len(collected), 0), + "partial_entries": len(limited), + "limited_scopes": sorted({u["usage_scope"] for u in eligible if u.get("usage_scope") == "parent_only"}), "missing_reasons": reasons, "exact": exact, "scope": scope if eligible else "unknown", @@ -936,10 +964,29 @@ def _resource_summary_line(usage: dict) -> str: observed = _to_int_or_none(usage.get("total_tokens")) eligible = int(usage.get("eligible_entries", 0) or 0) collected = int(usage.get("collected_entries", 0) or 0) + note = _resource_scope_note(usage) if observed is None: - return "Token 未采集" - exact = "完整准确" if usage.get("exact") else f"准确覆盖 {collected}/{eligible}" - return f'已采集 {_fmt_tokens(observed)} · {exact}' + return "Token 未采集" + (f" · {note}" if note else "") + exact = "完整准确" if usage.get("exact") else f"记录覆盖 {collected}/{eligible}" + return f'已采集 {_fmt_tokens(observed)} · {exact}' + (f" · {note}" if note else "") + + +def _resource_scope_note(usage: dict) -> str: + notes = [] + if usage.get("usage_scope") == "parent_only" or "parent_only" in usage.get("limited_scopes", []): + notes.append("仅父代理,不含子代理用量") + reasons = set(usage.get("missing_reasons") or []) + if usage.get("unavailable_reason"): + reasons.add(str(usage["unavailable_reason"])) + labels = { + "some_generations_unattributable": "部分轮次跨越阶段边界,仅统计可归属轮次", + "no_complete_generation_in_stage_window": "阶段窗口内没有可完整归属的轮次", + "ambiguous_workspace": "多个仓库同时处于活跃阶段,无法确定用量归属", + "incomplete_token_fields": "Token 字段不完整,无法计算总量", + "async_usage_unavailable": "宿主未提供可用 Token 数据", + } + notes.extend(labels[reason] for reason in sorted(reasons) if reason in labels) + return ";".join(notes) def _code_summary_line(delta: dict) -> str: @@ -2644,15 +2691,14 @@ def _stage_execution_summary_html( execution_lines = [] for field, title in (("tool_call_count", "工具调用"), ("tool_error_count", "调用未成功"), ("subagent_spawn_count", "子 Agent 创建")): values = [] + partial = False for entry, ready in zip(entries, available): - raw = entry.get("execution_stats") if isinstance(entry.get("execution_stats"), dict) else {} - value = _to_int_or_none(raw.get(field)) if ready else None - if field == "tool_error_count" and ready: - evidence = entry.get("async_evidence") or {} - failures = [item for item in evidence.get("failed_tools", []) if isinstance(item, dict)] - if failures: - value = len(failures) + stats = _execution_stats(entry) + value = stats.get(field) if ready else None + partial = partial or (value is not None and stats.get("collection_status") == "partial") values.append(value) + if partial: + title += "(已记录小计)" execution_lines.append(_stage_total_html(title, values)) user_messages = [_entry_user_turns(entry) for entry in entries] assistant_messages = [] @@ -2666,6 +2712,8 @@ def _stage_execution_summary_html( )) people = "、".join(dict.fromkeys(_actor(entry)["user_name"] for entry in entries)) segments = f" · 共 {len(entries)} 段记录" if len(entries) > len(runs) else "" + resource_note = _resource_scope_note(usage) + resource_note_html = f'
{_esc(resource_note)}' if resource_note else "" return ( '
' f'
{index}{_esc(label)}' @@ -2678,7 +2726,8 @@ def _stage_execution_summary_html( '
' f'{artifact_block}' f'

{token_label}

{_fmt_tokens(usage.get("total_tokens"))}' - f'
输入 {_fmt_tokens(usage.get("input_tokens"))} · 输出 {_fmt_tokens(usage.get("output_tokens"))}
' + f'
输入 {_fmt_tokens(usage.get("input_tokens"))} · 输出 {_fmt_tokens(usage.get("output_tokens"))}' + f'{resource_note_html}
' f'

执行情况

{"
".join(execution_lines)}
' f'

对话记录

{interaction_html}
' f'{_archive_knowledge_html(archive_changes) if latest.get("stage_kind") == "archive" or latest.get("command") == "archive" else ""}' @@ -2745,11 +2794,14 @@ def render_feature_timeline_html(eval_log: dict, *, archive_changes: dict | None f'{_fmt_tokens(usage.get("total_tokens"))}', f'输入 {_fmt_tokens(usage.get("input_tokens"))} · 输出 {_fmt_tokens(usage.get("output_tokens"))}', ] - tool_failure_count = len(failed_tools) or execution["tool_error_count"] + resource_note = _resource_scope_note(usage) + if resource_note: + resource_bits.append(f'{_esc(resource_note)}') + execution_suffix = "(已记录小计)" if execution["collection_status"] == "partial" else "" execution_bits = [ - _stage_total_html("工具调用", [execution["tool_call_count"]]), - _stage_total_html("调用未成功", [tool_failure_count]), - _stage_total_html("子 Agent 创建", [execution["subagent_spawn_count"]]), + _stage_total_html("工具调用" + execution_suffix, [execution["tool_call_count"]]), + _stage_total_html("调用未成功" + execution_suffix, [execution["tool_error_count"]]), + _stage_total_html("子 Agent 创建" + execution_suffix, [execution["subagent_spawn_count"]]), ] interaction_bits = [ _stage_total_html("用户交互轮次", [_entry_user_turns(e)], "轮"), @@ -3335,7 +3387,7 @@ def _metric_guide_html() -> str: "接受 HelixHarness Ledger 1.0 与已关联异步 Supplement 的物化数据;缺少必填字段的日志拒绝进入聚合。", ), ("用户交互轮次", "按阶段记录累计已采集的用户消息轮次,包含“继续/OK”等确认;不等同于有效介入、澄清或返工。部分采集显示小计与覆盖数,未采集不计为 0。"), - ("Token 消耗", "统计模型输入、输出、缓存读写 Token 的总消耗,只看资源用量,不计算金额。"), + ("Token 消耗", "使用宿主报告的总量,或完整的输入加输出 Token;缓存读写作为明细,不重复加总。仅父代理或部分轮次的统计会标注覆盖范围,不计算金额。"), ("归因和污染风险", "Token 优先来自平台结构化 usage 或精确 session 窗口;代码变更来自需求 Git 区间并优先限制 produced_files。范围不足时会降低 confidence 或明确 unavailable。"), ("验收事实", "分别展示验收通过数、验收依据完整数和审查问题数;每项都能回到 eval-log 的结构化字段,不合成质量分。"), ("跨阶段修正", "HelixHarness 不回写旧阶段;后续阶段修改上一更新内容时,记录在当前阶段的 workflow.revises_previous_stage,并标明 revised_stage_kind 与 revision_reason。语义性修正同时计入返工。"), diff --git a/helixharness-platform/web_ui/templates/eval/feedback_detail.html b/helixharness-platform/web_ui/templates/eval/feedback_detail.html index 0073b6a..f273078 100644 --- a/helixharness-platform/web_ui/templates/eval/feedback_detail.html +++ b/helixharness-platform/web_ui/templates/eval/feedback_detail.html @@ -85,7 +85,7 @@

提交信息

提交人
{{ row.user_name or '—' }}
分类
{{ category }}
插件版本
{{ row.plugin_version or '—' }}
-
使用平台
{{ {'claude-code': 'Claude Code', 'codex': 'Codex', 'unknown': '未采集'}.get(row.host, row.host or '—') }}
+
使用平台
{{ {'claude-code': 'Claude Code', 'codex': 'Codex', 'cursor': 'Cursor', 'unknown': '未采集'}.get(row.host, row.host or '—') }}
需求
{{ row.feature or '未关联需求' }}
项目标识
{{ row.project or '—' }}
diff --git a/helixharness-platform/web_ui/tests/test_claude_usage_precision_pipeline.py b/helixharness-platform/web_ui/tests/test_claude_usage_precision_pipeline.py new file mode 100644 index 0000000..b4a933b --- /dev/null +++ b/helixharness-platform/web_ui/tests/test_claude_usage_precision_pipeline.py @@ -0,0 +1,141 @@ +"""Synthetic Claude source usage survives the real plugin-to-dashboard boundary.""" +from __future__ import annotations + +import json +import os +import subprocess +import sys +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient + +from eval.telemetry_materialization import materialize_eval_log +from eval.tests.test_usage_loader import _workflow_log, _workflow_supplement +from eval.usage_loader import _resource_usage, aggregate_feature, render_feature_timeline_html +from web_ui import create_app + + +def _parse_supplement(source: Path, ledger: dict) -> dict: + """Use separate interpreters so plugin modules never leak into platform imports.""" + scripts = Path(__file__).resolve().parents[3] / "helixharness/scripts" + if not scripts.is_dir(): + pytest.skip("cross-package acceptance requires the sibling plugin checkout") + code = """ +import json +import sys +from pathlib import Path +from telemetry_hosts.supplement_parsers import collect_claude_window +from telemetry_protocol import build_evolution_evidence, build_stage_supplement + +source, ledger = json.load(sys.stdin) +entry = ledger["entries"][0] +window = collect_claude_window( + Path(source), started_at=entry["started_at"], ended_at=entry["ended_at"], + max_bytes=Path(source).stat().st_size, +) +fixed = {**entry, "requirement_id": ledger["requirement"]["id"], + "requirement_name": ledger["requirement"]["name"], "feature": ledger["feature"]} +payload = build_stage_supplement( + fixed, session_hash=entry["session_hash"], usage=window.usage, execution={}, + evidence=build_evolution_evidence( + window.events, started_at=entry["started_at"], ended_at=entry["ended_at"], + ), +) +print(json.dumps(payload)) +""" + env = {**os.environ, "PYTHONPATH": str(scripts), "PYTHONNOUSERSITE": "1", + "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "core.hooksPath", "GIT_CONFIG_VALUE_0": os.devnull, + "CLAUDE_CONFIG_DIR": str(source.parent / "synthetic-claude"), + "HELIXHARNESS_TELEMETRY_HOME": str(source.parent / "synthetic-telemetry"), + "HELIXHARNESS_TELEMETRY_DISABLE_SCHEDULER": "1"} + result = subprocess.run( + [sys.executable, "-c", code], input=json.dumps([str(source), ledger]), + cwd=scripts, env=env, check=True, capture_output=True, text=True, timeout=30, + ) + return json.loads(result.stdout) + + +def _assert_report_usage( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ledger: dict, payload: dict, total: int | None, +) -> None: + from eval import usage_sync + + root = tmp_path / "repo" + path = root / "docs/eval/example-feature/eval-log.json" + path.parent.mkdir(parents=True) + path.write_text(json.dumps(ledger), encoding="utf-8") + monkeypatch.setenv("HELIXHARNESS_PLATFORM_HELIXHARNESS_ROOTS", str(root)) + monkeypatch.setattr(usage_sync, "schedule_usage_ai_regeneration", lambda roots: None) + with TestClient(create_app()) as client: + receipt = client.post("/report", json={"items": [payload]}) + assert receipt.json()["items"][0]["status"] == "accepted" + store = client.app.state.stage_supplement_store + assert store.refresh_links([root]) == 1 + records = store.active_linked_records() + assert len(records) == 1 + assert records[0].payload["usage"] == payload["usage"] + materialized = materialize_eval_log(ledger, {payload["entry_id"]: records[0]}) + usage = _resource_usage(materialized["entries"][0]) + assert usage["total_tokens"] == total + assert usage["collection_status"] == ("collected" if total is not None else "unavailable") + summary = aggregate_feature(materialized)["resource_usage"] + assert summary["total_tokens"] == total + assert summary["exact"] is (total is not None) + assert summary["exact_total_tokens"] == total + dashboard = client.get("/") + assert dashboard.status_code == 200 + for html in (render_feature_timeline_html(materialized), dashboard.text): + assert "Claude Code" in html + if total is None: + assert "Token 数据完整" not in html + assert "Token 不可用" in html + else: + assert "Token 数据完整 1/1 条记录" in html + assert f"输入 {payload['usage']['input_tokens']}" in html + assert f"输出 {payload['usage']['output_tokens']}" in html + + +@pytest.mark.parametrize("raw_usages,expected,total", [ + ([{"input_tokens": 0, "output_tokens": 10}], {"input_tokens": 0, "output_tokens": 10}, 10), + ([{"input_tokens": 10, "output_tokens": 0}], {"input_tokens": 10, "output_tokens": 0}, 10), + ([{"input_tokens": 0, "output_tokens": 0, "cache_read_tokens": 0, "cache_write_tokens": 0}], + {"input_tokens": 0, "output_tokens": 0, "cache_read_tokens": 0, "cache_write_tokens": 0}, 0), + ([{"input_tokens": 0, "output_tokens": 10}, {"input_tokens": 0, "output_tokens": 5}], + {"input_tokens": 0, "output_tokens": 15}, 15), + ([{"input_tokens": 10}], {"input_tokens": 10}, None), + ([{"output_tokens": 10}], {"output_tokens": 10}, None), + ([{"input_tokens": 10}, {"output_tokens": 20}], {}, None), + ([{"input_tokens": 10, "output_tokens": 20}, None], {}, None), + ([{"input_tokens": True, "output_tokens": 10}], {"output_tokens": 10}, None), + ([{"input_tokens": -1, "output_tokens": 10}], {"output_tokens": 10}, None), + ([None], {}, None), +]) +def test_claude_source_parser_to_supplement_to_dashboard( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, raw_usages: list, expected: dict, total: int | None, +) -> None: + ledger = _workflow_log() + ledger["entries"][0]["platform"] = "claude-code" + source = tmp_path / "synthetic-session.jsonl" + records = [{"type": "assistant", "timestamp": "2026-08-01T00:01:00Z", + "message": {"content": "Synthetic answer", "usage": usage}} for usage in raw_usages] + # Missing outside-window records neither supply nor invalidate stage counts. + records.extend({"type": "assistant", "timestamp": timestamp, "message": {"content": "Outside"}} + for timestamp in ("2026-07-31T23:59:59Z", "2026-08-01T00:10:01Z")) + source.write_text("\n".join(json.dumps(record) for record in records) + "\n", encoding="utf-8") + payload = _parse_supplement(source, ledger) + assert payload["usage"] == expected + _assert_report_usage(tmp_path, monkeypatch, ledger, payload, total) + + +@pytest.mark.parametrize("legacy_usage", [{"input_tokens": 10}, {"output_tokens": 10}, {}]) +def test_legacy_supplement_omitted_zero_cannot_be_distinguished_from_missing_usage( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, legacy_usage: dict, +) -> None: + """An old lossy payload cannot justify imputing an unreported primary count.""" + ledger = _workflow_log() + ledger["entries"][0]["platform"] = "claude-code" + payload = _workflow_supplement() + payload.update(platform="claude-code", usage=legacy_usage) + _assert_report_usage(tmp_path, monkeypatch, ledger, payload, None) diff --git a/helixharness-platform/web_ui/tests/test_cursor_native_usage_pipeline.py b/helixharness-platform/web_ui/tests/test_cursor_native_usage_pipeline.py new file mode 100644 index 0000000..1a57656 --- /dev/null +++ b/helixharness-platform/web_ui/tests/test_cursor_native_usage_pipeline.py @@ -0,0 +1,155 @@ +"""Synthetic native Cursor hooks reach the real plugin outbox and platform UI.""" +from __future__ import annotations + +import json +import os +import subprocess +import sys +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient + +from eval.telemetry_materialization import materialize_eval_log +from eval.usage_loader import _resource_usage, aggregate_feature, render_feature_timeline_html +from web_ui import create_app + + +def _native_stage(root: Path, native_usage: dict | None) -> tuple[Path, dict, dict]: + """Keep plugin imports separate and obtain unmodified CLI-produced artifacts.""" + plugin = Path(__file__).resolve().parents[3] / "helixharness" + if not (plugin / "scripts/metrics.py").is_file(): + pytest.skip("cross-package acceptance requires the sibling plugin checkout") + root.mkdir() + code = r''' +import gzip, json, subprocess, sys +from pathlib import Path + +plugin, root, native_usage = json.load(sys.stdin) +plugin, root = Path(plugin), Path(root) +repo = root / "synthetic Cursor project" +repo.mkdir() +telemetry = root / "telemetry" +telemetry.mkdir() +(telemetry / "config.json").write_text('{"endpoint":""}') +def run(arguments, *, payload=None, env=None): + result = subprocess.run(list(map(str, arguments)), cwd=repo, env=env, + input=json.dumps(payload) if payload is not None else None, + capture_output=True, text=True, check=False, timeout=30) + assert result.returncode == 0, result.stdout + result.stderr + return json.loads(result.stdout) if result.stdout.strip() else None +def cli(script, *args, env=None): + return run([sys.executable, plugin / "scripts" / script, *args], env=env) +hooks = json.loads((plugin / "hosts/cursor/hooks.json").read_text())["hooks"] +identity = {"conversation_id":"synthetic-native-pipeline", "workspace_roots":[str(repo)], "cwd":str(repo)} +def hook(event, **fields): + return run(["sh", "-c", hooks[event][0]["command"]], + payload={**identity, "hook_event_name":event, **fields}) +run(["git", "init", "-q", repo]) +started = hook("sessionStart") +import os +bound = {**os.environ, **started["env"]} +notice = cli("user_config.py", "--repo-root", repo, "--platform", "cursor", + "--telemetry", "enabled", "--scope", "project", "--user-confirmed") +assert notice["read_only"] and notice["notice_required"] and not notice["change"]["updated"] +assert notice["telemetry"]["effective_mode"] == "disabled" +# Synthetic protocol acknowledgment; native UI display is a separate acceptance. +configured = cli("user_config.py", "--repo-root", repo, "--platform", "cursor", + "--telemetry", "enabled", "--scope", "project", "--user-confirmed", + "--telemetry-notice-shown", notice["notice"]["sha256"]) +assert configured["change"]["updated"] +cli("user_config.py", "--repo-root", repo, "--platform", "cursor", + "--report-endpoint", "https://telemetry.example.test/report", "--user-confirmed") +entry = cli("metrics.py", "--repo-root", repo, "--platform", "cursor", "start", + "--feature", "native-cursor", "--stage", "apply", "--trigger", "user_command", env=bound) +hook("beforeSubmitPrompt", generation_id="synthetic-generation", prompt="Synthetic request") +fields = {} if native_usage is None else native_usage +hook("afterAgentResponse", generation_id="synthetic-generation", text="Synthetic answer", **fields) +hook("stop", generation_id="synthetic-generation", **fields) +finished = cli("metrics.py", "--repo-root", repo, "--platform", "cursor", "finish", + "--feature", "native-cursor", "--stage", "apply", "--status", "completed", env=bound) +assert finished["entry_id"] == entry["entry_id"] +collection = cli("telemetry_collector.py", "--repo-root", repo) +assert collection["collected"] == 1, collection +files = list((telemetry / "outbox").glob("*.json.gz")) +assert len(files) == 1 +envelope = json.loads(gzip.decompress(files[0].read_bytes())) +assert envelope["attempt_count"] == 0 +assert not (telemetry / "scheduler").exists() +assert cli("telemetry_collector.py", "--repo-root", repo)["collected"] == 0 +ledger = json.loads((repo / "docs/eval/native-cursor/eval-log.json").read_text()) +print(json.dumps({"repo":str(repo), "ledger":ledger, "supplement":envelope["supplement"]})) +''' + environment = { + "PATH": str(Path(sys.executable).parent) + os.pathsep + os.defpath, + "PYTHONDONTWRITEBYTECODE": "1", "PYTHONIOENCODING": "utf-8", + "TMPDIR": str(root), "CURSOR_PLUGIN_ROOT": str(plugin), + "CODEX_HOME": str(root / "codex"), "CLAUDE_CONFIG_DIR": str(root / "claude"), + "HELIXHARNESS_CURSOR_HOME": str(root / "cursor"), + "HELIXHARNESS_TELEMETRY_HOME": str(root / "telemetry"), + "HELIXHARNESS_FEEDBACK_HOME": str(root / "feedback"), + "HELIXHARNESS_TELEMETRY_DISABLE_SCHEDULER": "1", + "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_SYSTEM": os.devnull, + "GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "core.hooksPath", "GIT_CONFIG_VALUE_0": os.devnull, + } + result = subprocess.run( + [sys.executable, "-I", "-c", code], cwd=root, env=environment, + input=json.dumps([str(plugin), str(root), native_usage]), + capture_output=True, text=True, check=False, timeout=60, + ) + assert result.returncode == 0, result.stdout + result.stderr + artifacts = json.loads(result.stdout) + return Path(artifacts["repo"]), artifacts["ledger"], artifacts["supplement"] + + +@pytest.mark.parametrize("native_usage,total,status", [ + ({"input_tokens": 150, "output_tokens": 10, "cache_read_tokens": 30, "cache_write_tokens": 20}, 160, "collected"), + ({"input_tokens": 0, "output_tokens": 0, "cache_read_tokens": 0, "cache_write_tokens": 0}, 0, "collected"), + (None, None, "unavailable"), +], ids=["complete-native-tokens", "real-native-zero", "native-usage-absent"]) +def test_native_cursor_hook_to_local_outbox_to_platform_dashboard( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, native_usage: dict | None, total: int | None, status: str, +) -> None: + from eval import usage_sync + + repo, ledger, payload = _native_stage(tmp_path / "plugin-cli", native_usage) + assert payload["platform"] == "cursor" + assert payload["usage"]["collection_status"] == status + assert payload["usage"]["scope"] == "parent_only" + assert payload["usage"].get("total_tokens") == total + assert "synthetic-native-pipeline" not in json.dumps(ledger) + monkeypatch.setenv("HELIXHARNESS_PLATFORM_HELIXHARNESS_ROOTS", str(repo)) + monkeypatch.setattr(usage_sync, "schedule_usage_ai_regeneration", lambda roots: None) + with TestClient(create_app()) as client: + receipt = client.post("/report", json={"items": [payload]}) + assert receipt.status_code == 200 + assert receipt.json()["items"][0]["status"] == "accepted" + assert receipt.json()["items"][0]["linked"] is False + retry = client.post("/report", json={"items": [payload]}) + assert retry.json()["items"][0]["status"] == "duplicate" + store = client.app.state.stage_supplement_store + assert store.refresh_links([repo]) == 1 + records = store.active_linked_records() + assert len(records) == 1 + assert records[0].payload["usage"] == payload["usage"] + materialized = materialize_eval_log(ledger, {payload["entry_id"]: records[0]}) + usage = _resource_usage(materialized["entries"][0]) + assert usage["collection_status"] == status + assert usage["total_tokens"] == total + assert usage["usage_scope"] == "parent_only" + summary = aggregate_feature(materialized)["resource_usage"] + assert summary["total_tokens"] == total + assert summary["exact"] is False + assert summary["exact_total_tokens"] is None + dashboard = client.get("/") + assert dashboard.status_code == 200 + for html in (render_feature_timeline_html(materialized), dashboard.text): + assert "Cursor" in html + assert "仅父代理,不含子代理用量" in html + assert "Token 数据完整" not in html + if total is None: + assert "Token 不可用" in html + assert "阶段窗口内没有可完整归属的轮次" in html + else: + assert f"输入 {native_usage['input_tokens']}" in html + assert f"输出 {native_usage['output_tokens']}" in html diff --git a/helixharness-platform/web_ui/tests/test_feedback_report.py b/helixharness-platform/web_ui/tests/test_feedback_report.py index c14d850..7956d57 100644 --- a/helixharness-platform/web_ui/tests/test_feedback_report.py +++ b/helixharness-platform/web_ui/tests/test_feedback_report.py @@ -6,6 +6,7 @@ from pathlib import Path from unittest import mock +import pytest from fastapi.testclient import TestClient from web_ui.main import create_app @@ -97,3 +98,19 @@ def test_report_accepts_future_host_identity_and_rejects_invalid_ids(): item["document"]["host"] = invalid receipt = client.post("/feedback/report", json={"items": [item]}) assert receipt.json()["items"][0]["error"]["code"] == "schema_violation" + + +@pytest.mark.parametrize("host,label", [ + ("claude-code", "Claude Code"), ("codex", "Codex"), ("cursor", "Cursor"), ("future-host", "future-host"), +]) +def test_feedback_detail_preserves_host_identity_and_displays_label(host: str, label: str) -> None: + with TestClient(create_app()) as client: + item = _item() + item["document"]["host"] = host + receipt = client.post("/feedback/report", json={"items": [item]}) + assert receipt.json()["items"][0]["status"] == "accepted" + assert client.app.state.feedback_store.get(item["feedback_id"])["document"]["host"] == host + detail = client.get(f"/feedback/detail/{item['feedback_id']}") + assert detail.status_code == 200 + assert f"
使用平台
{label}
" in detail.text + assert "<script>" in detail.text diff --git a/helixharness-platform/web_ui/tests/test_telemetry_report.py b/helixharness-platform/web_ui/tests/test_telemetry_report.py index 1a03ea3..7900341 100644 --- a/helixharness-platform/web_ui/tests/test_telemetry_report.py +++ b/helixharness-platform/web_ui/tests/test_telemetry_report.py @@ -66,6 +66,28 @@ def test_report_accepts_mixed_health_versions_and_supplements(client: TestClient assert connection.execute("SELECT COUNT(*) FROM runtime_health_events").fetchone()[0] == 2 +def test_report_accepts_cursor_identity_without_synthesizing_usage(client: TestClient) -> None: + from eval.tests.test_runtime_health import health_event + + cursor_health = health_event(platform="cursor", scope_id="repo_a_cursor") + supplement = _supplement_payload() + supplement.update(platform="cursor", usage={}, execution={}) + supplement["session"]["platform"] = "cursor" + invalid_health = health_event(event_id="health_invalid_host", platform="unregistered-host") + response = client.post("/report", json={"items": [cursor_health, supplement, invalid_health]}) + assert response.status_code == 200 + assert [item["status"] for item in response.json()["items"]] == ["accepted", "accepted", "rejected"] + replay = client.post("/report", json={"items": [cursor_health, supplement]}) + assert [item["status"] for item in replay.json()["items"]] == ["duplicate", "duplicate"] + with client.app.state.stage_supplement_store._connect() as connection: + health = json.loads(connection.execute("SELECT payload_json FROM runtime_health_events").fetchone()[0]) + stored = json.loads(connection.execute("SELECT payload_json FROM stage_supplements").fetchone()[0]) + assert health["platform"] == "cursor" + assert stored["platform"] == stored["session"]["platform"] == "cursor" + assert stored["usage"] == {} + assert stored["execution"] == {} + + def test_report_rejects_bad_health_item_without_blocking_recovery(client: TestClient) -> None: from eval.tests.test_runtime_health import health_event diff --git a/helixharness-platform/web_ui/tests/test_usage_precision_pipeline.py b/helixharness-platform/web_ui/tests/test_usage_precision_pipeline.py new file mode 100644 index 0000000..6a858c8 --- /dev/null +++ b/helixharness-platform/web_ui/tests/test_usage_precision_pipeline.py @@ -0,0 +1,188 @@ +"""Exercise real report receipts, frozen snapshots, materialization and dashboard HTML.""" +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient + +from eval.telemetry_materialization import materialize_eval_log +from eval.tests.test_usage_loader import _workflow_log, _workflow_supplement +from eval.usage_loader import _resource_usage, aggregate_feature, render_feature_timeline_html +from web_ui import create_app + + +def _cursor_usage(**changes: object) -> dict: + return { + "collection_status": "collected", "reason": "native_generation_snapshots", + "scope": "parent_only", "attribution": "complete_generations_within_stage", + "input_tokens_include_cache": True, "generations": 1, + "input_tokens": 150, "output_tokens": 10, "cache_read_tokens": 30, "cache_write_tokens": 20, + **changes, + } + + +@pytest.mark.parametrize("usage,total,status,note", [ + (_cursor_usage(), 160, "collected", "仅父代理,不含子代理用量"), + (_cursor_usage(input_tokens=0, output_tokens=0, cache_read_tokens=0, cache_write_tokens=0), + 0, "collected", "仅父代理,不含子代理用量"), + (_cursor_usage(collection_status="partial", unavailable_reason="some_generations_unattributable"), + 160, "partial", "部分轮次跨越阶段边界"), + (_cursor_usage(collection_status="partial", unavailable_reason="ambiguous_workspace"), + 160, "partial", "多个仓库同时处于活跃阶段,无法确定用量归属"), + ({"scope": "parent_only", "collection_status": "unavailable", "unavailable_reason": "ambiguous_workspace"}, + None, "unavailable", "多个仓库同时处于活跃阶段,无法确定用量归属"), + ({"scope": "parent_only", "attribution": "complete_generations_within_stage", "generations": 0, + "collection_status": "unavailable", "unavailable_reason": "no_complete_generation_in_stage_window"}, + None, "unavailable", "阶段窗口内没有可完整归属的轮次"), + ({"scope": "parent_only", "input_tokens": 10}, None, "unavailable", "Token 字段不完整"), + ({"scope": "parent_only", "cache_read_tokens": 30}, None, "unavailable", "Token 字段不完整"), +]) +def test_cursor_report_preserves_usage_precision_through_dashboard( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, usage: dict, total: int | None, status: str, note: str, +) -> None: + from eval import usage_sync + + root = tmp_path / "repo" + path = root / "docs/eval/example-feature/eval-log.json" + path.parent.mkdir(parents=True) + ledger = _workflow_log() + ledger["entries"][0]["platform"] = "cursor" + path.write_text(json.dumps(ledger), encoding="utf-8") + monkeypatch.setenv("HELIXHARNESS_PLATFORM_HELIXHARNESS_ROOTS", str(root)) + monkeypatch.setattr(usage_sync, "schedule_usage_ai_regeneration", lambda roots: None) + payload = _workflow_supplement() + payload.update(platform="cursor", usage=usage, execution={ + "collection_status": "collected", "child_agent_scope": "parent_only", + "tool_call_count": 0, "tool_error_count": 0, "subagent_spawn_count": 0, + }) + with TestClient(create_app()) as client: + # Receipt before Git discovery remains inactive; retry does not create another record. + first = client.post("/report", json={"items": [payload]}) + assert first.json()["items"][0]["status"] == "accepted" + assert first.json()["items"][0]["linked"] is False + assert client.post("/report", json={"items": [payload]}).json()["items"][0]["status"] == "duplicate" + store = client.app.state.stage_supplement_store + assert store.refresh_links([root]) == 1 + records = store.active_linked_records() + assert len(records) == 1 + for key, value in usage.items(): + assert records[0].payload["usage"][key] == value + assert records[0].payload["execution"]["child_agent_scope"] == "parent_only" + materialized = materialize_eval_log(ledger, {payload["entry_id"]: records[0]}) + entry = materialized["entries"][0] + resource = _resource_usage(entry) + assert resource["collection_status"] == status + assert resource["total_tokens"] == total + assert resource["usage_scope"] == "parent_only" + assert entry["async_evidence"]["resource_usage"]["scope"] == "parent_only" + summary = aggregate_feature(materialized)["resource_usage"] + assert summary["exact"] is False + assert summary["total_tokens"] == total + assert summary["exact_total_tokens"] is None + timeline = render_feature_timeline_html(materialized) + assert note in timeline + assert "工具调用 0 次" in timeline + assert "Token 数据完整" not in timeline + dashboard = client.get("/") + assert dashboard.status_code == 200 + assert note in dashboard.text + assert "Cursor" in dashboard.text + + +def test_three_host_report_rollup_keeps_legacy_totals_and_cursor_scope( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + from eval import usage_sync + + root = tmp_path / "repo" + path = root / "docs/eval/example-feature/eval-log.json" + path.parent.mkdir(parents=True) + ledger = _workflow_log() + template = ledger["entries"][0] + ledger["entries"] = [] + payloads = [] + for index, host in enumerate(("claude-code", "codex", "cursor")): + entry_id = f"entry-{index:016x}" + ledger["entries"].append({**template, "entry_id": entry_id, "platform": host, "attempt": index + 1}) + payload = _workflow_supplement() + payload.update(entry_id=entry_id, supplement_id=f"supp_{index:016x}", platform=host) + payload["usage"] = _cursor_usage() if host == "cursor" else { + "input_tokens": 20, "output_tokens": 10, "cached_input_tokens": 4, + } + payloads.append(payload) + path.write_text(json.dumps(ledger), encoding="utf-8") + monkeypatch.setenv("HELIXHARNESS_PLATFORM_HELIXHARNESS_ROOTS", str(root)) + monkeypatch.setattr(usage_sync, "schedule_usage_ai_regeneration", lambda roots: None) + with TestClient(create_app()) as client: + receipt = client.post("/report", json={"items": payloads}) + assert [item["status"] for item in receipt.json()["items"]] == ["accepted"] * 3 + store = client.app.state.stage_supplement_store + assert store.refresh_links([root]) == 3 + records = {record.payload["entry_id"]: record for record in store.active_linked_records()} + materialized = materialize_eval_log(ledger, records) + for entry in materialized["entries"][:2]: + assert entry["resource_usage"]["attribution"] == "exact_session_window" + assert entry["resource_usage"]["total_tokens"] == 30 + summary = aggregate_feature(materialized)["resource_usage"] + assert summary["total_tokens"] == 220 + assert summary["cache_read_tokens"] == 38 + assert summary["collection_status"] == "partial" + assert summary["collected_entries"] == 3 + assert summary["partial_entries"] == 1 + assert summary["exact_total_tokens"] is None + dashboard = client.get("/") + assert dashboard.status_code == 200 + assert "仅父代理,不含子代理用量" in dashboard.text + for label in ("Claude Code", "Codex", "Cursor"): + assert label in dashboard.text + + +@pytest.mark.parametrize("status", ["unavailable", "pending", "partial"]) +def test_execution_collection_gap_does_not_render_placeholder_zero_as_complete( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, status: str, +) -> None: + from eval import usage_sync + + root = tmp_path / "repo" + path = root / "docs/eval/example-feature/eval-log.json" + path.parent.mkdir(parents=True) + ledger = _workflow_log() + template = ledger["entries"][0] + ledger["entries"] = [] + payloads = [] + for index in range(2): + entry_id = f"entry-{index:016x}" + ledger["entries"].append({**template, "entry_id": entry_id, "platform": "cursor", "attempt": index + 1}) + payload = _workflow_supplement() + payload.update(entry_id=entry_id, supplement_id=f"supp_{index:016x}", platform="cursor") + payload["usage"] = { + "scope": "parent_only", "collection_status": "unavailable", "unavailable_reason": "ambiguous_workspace", + } + payload["execution"] = { + "tool_call_count": 0, "tool_error_count": 0, "subagent_spawn_count": 0, + "collection_status": status, "unavailable_reason": "ambiguous_workspace", + } + payloads.append(payload) + path.write_text(json.dumps(ledger), encoding="utf-8") + monkeypatch.setenv("HELIXHARNESS_PLATFORM_HELIXHARNESS_ROOTS", str(root)) + monkeypatch.setattr(usage_sync, "schedule_usage_ai_regeneration", lambda roots: None) + with TestClient(create_app()) as client: + receipt = client.post("/report", json={"items": payloads}) + assert [item["status"] for item in receipt.json()["items"]] == ["accepted"] * 2 + store = client.app.state.stage_supplement_store + assert store.refresh_links([root]) == 2 + records = {record.payload["entry_id"]: record for record in store.active_linked_records()} + materialized = materialize_eval_log(ledger, records) + assert all(entry["execution_stats"]["collection_status"] == status for entry in materialized["entries"]) + timeline = render_feature_timeline_html(materialized) + dashboard = client.get("/") + assert dashboard.status_code == 200 + for html in (timeline, dashboard.text): + for title in ("工具调用", "调用未成功", "子 Agent 创建"): + if status == "partial": + assert html.count(f"{title}(已记录小计) 0 次") >= 3 + else: + assert html.count(f"{title} 未采集") >= 3 + assert f"{title} 0 次" not in html diff --git a/helixharness/.cursor-plugin/marketplace.json b/helixharness/.cursor-plugin/marketplace.json new file mode 100644 index 0000000..f96ee7b --- /dev/null +++ b/helixharness/.cursor-plugin/marketplace.json @@ -0,0 +1,14 @@ +{ + "name": "helixharness-marketplace", + "owner": {"name": "HelixHarness contributors"}, + "metadata": {"description": "Standalone HelixHarness Cursor marketplace"}, + "plugins": [ + { + "name": "helix", + "description": "HelixHarness workflow skills for Cursor", + "source": ".", + "version": "1.0.0", + "license": "Apache-2.0" + } + ] +} diff --git a/helixharness/.cursor-plugin/plugin.json b/helixharness/.cursor-plugin/plugin.json new file mode 100644 index 0000000..33891da --- /dev/null +++ b/helixharness/.cursor-plugin/plugin.json @@ -0,0 +1,12 @@ +{ + "name": "helix", + "version": "1.0.0", + "description": "HelixHarness workflow skills for Cursor", + "author": {"name": "HelixHarness contributors"}, + "license": "Apache-2.0", + "skills": "./hosts/cursor/skills/", + "commands": [], + "agents": [], + "rules": [], + "hooks": "./hosts/cursor/hooks.json" +} diff --git a/helixharness/PLUGIN_USAGE.md b/helixharness/PLUGIN_USAGE.md index ac7f204..2db95f6 100644 --- a/helixharness/PLUGIN_USAGE.md +++ b/helixharness/PLUGIN_USAGE.md @@ -1,9 +1,11 @@ # HelixHarness -面向 Codex 与 Claude Code 的 HelixHarness 研发工作流。通过项目约束、知识库、Spec、任务和验证证据完成研发。 +面向 Codex、Claude Code 与 Cursor 的 HelixHarness 研发工作流。通过项目约束、知识库、Spec、任务和验证证据完成研发。 ## 命令 +以下 `/helix:*` 为公共逻辑命令名,也是 Codex / Claude Code 的输入形式。Cursor 使用 `/helix-{command}`,从 `/helix-` 补全选择入口,参数和业务门禁相同。Cursor 默认通过市场安装,固定来源配置和托管 Local 作为可选方式;统计及更新的能力边界见 [Cursor 安装说明](hosts/cursor/installer.md)。 + - `/helix:init`:初始化当前项目;`--workspace` 初始化多仓目录。 - `/helix:propose `:收敛需求并生成 Spec/Tasks。 - `/helix:propose --loop`:自动串联 Propose → Apply → Archive;同名 `propose --loop` 续跑。 @@ -12,10 +14,12 @@ - `/helix:bug-fix `:修订尚未归档的单仓需求。 - `/helix:ut`:扫描后选择包与并发,生成和维护单测;也支持显式参数。 - `/helix:update`:检查并更新当前宿主已配置的插件源。 +- `/helix:status [name]`:只读查看需求进度、阻塞原因与建议命令;`--completed` 查已归档需求。 +- `/helix:config`:查看配置;通过参数修改统计开关、范围、统计与反馈地址。 ## 安装 -需要 Python 3.10+、Git,以及 Codex 或 Claude Code。将本目录作为本地 marketplace 添加。宿主具体命令见 `hosts/codex/installer.md` 或 `hosts/claude-code/installer.md`。 +需要 Python 3.9+、Git,以及 Codex、Claude Code 或 Cursor。Codex、Claude Code 可将本目录作为本地 marketplace 添加;Cursor 通过市场界面安装。宿主步骤见 [Codex](hosts/codex/installer.md)、[Claude Code](hosts/claude-code/installer.md) 和 [Cursor](hosts/cursor/installer.md) 安装说明。 ## 项目结构 @@ -23,7 +27,7 @@ ## 可选配置 -统计默认关闭,授权询问独立于异步地址。report 与 feedback 都由发布方在 `scripts/reporting_config.py` 设置默认地址,当前默认留空;用户可分别在 `~/.helixharness/telemetry/config.json` 与 `~/.helixharness/feedback/config.json` 中设置 `endpoint` 覆盖。用户文件优先,缺少或为空时使用发布默认值;无效配置不回退。地址环境变量不再生效。配置示例见 [README](README.md#可选配置)。未配置异步地址时静默跳过,授权后的同步账本仍正常记录;未授权时不新增同步账本,也不异步采集或投递。 +支持统计的宿主上,统计默认关闭,授权询问独立于异步地址。report 与 feedback 都由发布方在 `scripts/reporting_config.py` 设置默认地址,当前默认留空;用户可分别在 `~/.helixharness/telemetry/config.json` 与 `~/.helixharness/feedback/config.json` 中设置 `endpoint` 覆盖。用户文件优先,缺少或为空时使用发布默认值;无效配置不回退。地址环境变量不再生效。配置示例见 [README](README.md#可选配置)。未配置异步地址时静默跳过,授权后的同步账本仍正常记录;未授权时不新增同步账本,也不异步采集或投递。 前端保留设计解析、还原、预览和视觉验收能力。可用用户提供的设计素材;设计服务认证由用户配置。 diff --git a/helixharness/README.md b/helixharness/README.md index 4176733..93a1b5a 100644 --- a/helixharness/README.md +++ b/helixharness/README.md @@ -2,10 +2,12 @@ 当前版本:**1.0.0**。 -面向 Codex 与 Claude Code 的 HelixHarness 研发工作流。通过项目约束、知识库、Spec、任务和验证证据完成研发。 +面向 Codex、Claude Code 与 Cursor 的 HelixHarness 研发工作流。通过项目约束、知识库、Spec、任务和验证证据完成研发。 ## 命令 +以下 `/helix:*` 为公共逻辑命令名,也是 Codex / Claude Code 的输入形式。Cursor 使用 `/helix-{command}`,从 `/helix-` 补全选择入口,参数和业务门禁相同。Cursor 默认通过市场安装,固定来源配置和托管 Local 作为可选方式;统计及更新的能力边界见 [Cursor 安装说明](hosts/cursor/installer.md)。 + - `/helix:init`:初始化当前项目;`--workspace` 初始化多仓目录。 - `/helix:propose `:收敛需求并生成 Spec/Tasks。 - `/helix:propose --loop`:自动串联 Propose → Apply → Archive;同名 `propose --loop` 续跑。 @@ -19,7 +21,7 @@ ## 安装 -需要 Python 3.10+、Git,以及 Codex 或 Claude Code。将本目录作为本地 marketplace 添加。宿主具体命令见 `hosts/codex/installer.md` 或 `hosts/claude-code/installer.md`。 +需要 Python 3.9+、Git,以及 Codex、Claude Code 或 Cursor。Codex、Claude Code 可将本目录作为本地 marketplace 添加;Cursor 通过市场界面安装。宿主步骤见 [Codex](hosts/codex/installer.md)、[Claude Code](hosts/claude-code/installer.md) 和 [Cursor](hosts/cursor/installer.md) 安装说明。 ## 独立方案探索与调试 @@ -44,7 +46,7 @@ 随时使用 `/helix:config` 查看生效值。显式设置示例:`/helix:config --telemetry disabled --scope project`、`/helix:config --report-endpoint http://127.0.0.1:7860/report`。反馈地址用 `--feedback-endpoint`;`--reset-report-endpoint` / `--reset-feedback-endpoint` 恢复对应发布默认地址,不等于关闭统计。详见[配置命令](commands/config.md)。 -统计默认关闭,但**无论是否配置异步地址,Init / 规定的 Propose 入口都按授权缓存和提醒周期正常询问**。选择开启后,同步写入 `docs/eval//eval-log.json`,平台可本地读取或经 Git 同步获取;没有有效异步地址时仅跳过后台采集和投递。未授权或关闭时,同步账本不新增记录,异步也不采集或投递;历史记录不会自动删除。账本 `completed` 只表示阶段完成,不能声称平台已收到异步明细。 +支持统计的宿主上,统计默认关闭,但**无论是否配置异步地址,Init / 规定的 Propose 入口都按授权缓存和提醒周期正常询问**。选择开启后,同步写入 `docs/eval//eval-log.json`,平台可本地读取或经 Git 同步获取;没有有效异步地址时仅跳过后台采集和投递。未授权或关闭时,同步账本不新增记录,异步也不采集或投递;历史记录不会自动删除。账本 `completed` 只表示阶段完成,不能声称平台已收到异步明细。 未配置异步统计地址时,正常流程静默跳过,不额外显示地址缺失、未异步上报或配置提醒;仅在用户主动查询或排障时解释。 diff --git a/helixharness/agents/init-frontend-bootstrap.md b/helixharness/agents/init-frontend-bootstrap.md index b597f3f..2280f1d 100644 --- a/helixharness/agents/init-frontend-bootstrap.md +++ b/helixharness/agents/init-frontend-bootstrap.md @@ -1,10 +1,10 @@ --- -description: "前端项目初始化收尾 agent。消费扫描产物,生成 harness、knowledge、hooks、linters,更新宿主入口文件与状态文件,汇总扫描耗时并输出初始化报告。" +description: "前端项目初始化生成 agent。消费扫描产物,生成 harness、knowledge、hooks、linters,更新宿主入口文件,汇总扫描耗时并返回父流程验收。" --- ## 任务:前端项目初始化收尾 -前提:init 命令已完成 6 路并行扫描(scan-frontend-meta / api / routes / state / components / tracking),产物在 `docs/knowledge/` 下。你负责收尾,包括 harness 约束与 linters、knowledge 索引与占位、hooks 与 runtime 配置、平台入口更新、state file 更新与初始化报告。 +前提:init 命令已完成 6 路并行扫描(scan-frontend-meta / api / routes / state / components / tracking),产物在 `docs/knowledge/` 下。你负责生成 harness 约束与 linters、knowledge 索引与占位、hooks 与 runtime 配置、平台入口,并把实际产物和阶段结果返回父流程;状态提交和整体完成报告由父流程负责。 输入必须包含当前平台(`$PLATFORM`)和顶层 init 已解析的 `$EFFECTIVE_TELEMETRY_MODE`(只能是 `enabled|disabled`);不得在本 agent 内重新默认或再次询问 consent。 @@ -317,7 +317,7 @@ fi - `owner=parent`:不得写 settings;在 final 返回结构化 `PROJECT_HOOKS_MERGE_REQUEST`,由父流程校验后串行合并。 - 资源与 `resources.project_config.settings_file` 不一致时 `BLOCKED: project_hooks_contract_invalid`。 -### Phase 5:更新宿主入口文件并输出初始化报告 +### Phase 5:更新宿主入口文件并返回生成结果 #### 5.1 更新平台入口文件 @@ -325,41 +325,43 @@ fi - 若不存在 → 基于 Host Kit 的 `entry_template` 生成 `entry_file`; - 不探测或生成其他宿主的入口文件。 -**追加规则**(读取 `entry_template`,提取四个区块并以 `## HelixHarness 导航` 为标题追加): +**追加规则**(读取 `entry_template`,以 `## HelixHarness 导航` 为标题合并以下内容;常用命令 +只能由下方管理区工具处理,不能先手工追加或改写): 1. **目录导航**(用实际 frontend 目录结构替换) 2. **关键约束速览**(3-5 条,来自 `docs/harness/index.md` 全局约束摘要) -3. **常用命令**(`/helix:propose`、`/helix:apply` 等) +3. **常用命令**(保留模板中带宿主标签的九个公共命令管理区) 4. **Agent 工作规则**(含 harness/knowledge 按需加载协议) 追前检查文件末尾是否已含 `## HelixHarness 导航` 或 `## Agent 工作规则` → 已存在则不重复,仅确认是否需要更新。 -#### 5.2 最终提交 state file +完整读取 `entry_template` 中 `` 至 `` +的唯一管理区,同时保留 Cursor `/helix-xxx` 与 Claude Code/Codex `/helix:xxx` 标签及九个公共命令。 +先生成/合并入口其他内容,再执行 +`python3 {plugin_root}/scripts/init_guidance.py --repo-root {repo_root} --platform {canonical_host_id} --mode {init_mode} merge`, +其中纯前端 `init_mode=frontend`,完整全栈为 `fullstack`;沿用父流程已验证的运行时与 Host Context。 +既有常用命令区不得先由模型改写;仅工具更新合法管理区或精确识别的旧默认区,保留用户正文。 +自定义冲突、损坏/重复边界或失败必须返回父流程,不得全局替换命令前缀后宣称通过。 -只有 Phase 4 hooks 与 Phase 5.1 Host Kit 入口全部生成并通过逐项验证后,才使用公共 -`Read/Edit/Write` 工具语义原子更新 `docs/.helixharness-init-state.json`;其他宿主只按 -`resources.runtime` 映射,不依赖外部 JSON CLI: +#### 5.2 返回生成结果,等待父流程验收 -1. state 文件缺失、为空或不是 JSON 对象时立即 `BLOCKED:init_state_missing`,不得跳过后继续完成。 -2. `scanPlan` 为空时补 - `["scan-frontend-meta","scan-frontend-api","scan-frontend-routes","scan-frontend-state","scan-frontend-components","scan-frontend-tracking"]`; - 已有非空计划保持不变。设置 - `scanStatus=completed`、`bootstrapStatus=completed` 与 `completedAt`。 -3. `bootstrap_mode=fullstack-merge` 时额外写 `frontendCompletedAt`,且必须保留前序 - `backendCompletedAt`;缺少后端完成事实时 `BLOCKED:backend_bootstrap_incomplete`。所有 `*At` - 字段固定为当前 UTC Unix epoch 秒的 JSON number,与既有状态产物类型一致,不得写 ISO - 字符串或宿主本地时间文本。 -4. 从实际文件列表构造排序、去重后的 knowledge、harness、hooks 三组 deliverables;每个 `count` - 必须等于对应 `files` 数组长度。 -5. 只修改上述字段,保留其他键。写入后重新 `Read`,确认 JSON 可解析、字段类型正确、入口、hooks - 及所有 deliverable 文件均存在;任一步失败报告 `BLOCKED:init_state_update_failed`。 +本 bootstrap 不得写入或删除 `docs/.helixharness-init-state.json`,不得调用状态提交器, +不得写最终完成字段或宣称整个 Init 已完成。只返回实际 knowledge、harness、hooks 三组相对 +文件清单、入口路径、逐项检查结果和适用时的 Hooks 合并请求。清单必须指向本仓实际非空文件, +全栈模式同时保留后端与前端工件,不覆盖后端内容。 -> 不要删除 `docs/.helixharness-init-state.json`(供后续命令使用)。 +`bootstrap_mode=fullstack-merge` 只消费父流程确认的后端检查点,缺少该完成事实时 +`BLOCKED:backend_bootstrap_incomplete`。前端生成结束不代表全栈通过;父流程在两侧产物、 +入口、实际 Hooks 和统计门禁全部通过之后才提交整体完成状态,并保留后端阶段时间。 -#### 5.3 输出初始化报告 +#### 5.3 向父流程输出生成结果 + +以下是返回父流程的阶段报告,不是最终完成报告。最终报告、错误重试与下一步建议按当前 +Host Context 显示公共命令入口:Cursor `/helix-xxx`,Claude Code/Codex `/helix:xxx`;参数、 +路径、引号、`--loop`、`--workspace` 和 `bug-fix` 保持原义。 ```text -## HelixHarness 前端初始化完成 +## HelixHarness 前端生成阶段结果(等待父流程验收) ### 项目信息 - 项目模式: {greenfield|brownfield} @@ -391,15 +393,15 @@ fi - [x] docs/hooks/index.md — Hook 机制总览 - [x] docs/hooks/post-action.md — 写后自动检查 - [x] docs/hooks/cr-checklist.md — CR 检查清单 -- [x] Host Kit `settings_file` 已按 `resources.project_hooks` 合并,或明确为跳过/parent-owned +- Host Kit `settings_file`:如实报告已合并、契约明确跳过,或待父流程合并;待合并不计为最终通过 - [x] docs/eval/.gitkeep — 仅遥测开启时生成 -- [x] docs/.helixharness-init-state.json — 已更新 +- docs/.helixharness-init-state.json — 由父流程在最终验收后提交,本子任务未写入 -### 下一步 +### 父流程最终验收通过后才可展示的下一步 1. 审核 docs/harness/ 下的约束文件,补充项目特有规则 2. 审核 docs/knowledge/ 知识库,确认准确性 3. 手动填写 docs/knowledge/domain-mapping.md(产品别名→业务域) -4. 执行 /helix:propose 开始第一个需求开发 +4. 执行 {当前宿主的 propose 命令入口} 开始第一个需求开发 ``` ## 注意事项 diff --git a/helixharness/agents/init-service-bootstrap.md b/helixharness/agents/init-service-bootstrap.md index f92a933..1981c41 100644 --- a/helixharness/agents/init-service-bootstrap.md +++ b/helixharness/agents/init-service-bootstrap.md @@ -308,44 +308,50 @@ status_entities: [] - 若不存在 → 基于 Host Kit 的 `entry_template` 生成 `entry_file`; - 不探测其他宿主的入口文件,也不同时生成多个入口文件。 -**追加规则**:读取 `entry_template`,提取其中的“目录导航”“关键约束速览”“常用命令” -“Agent 工作规则”四个区块,以 `## HelixHarness 导航` 为标题追加到 `entry_file` 末尾。关键约束 -速览中的占位符用实际生成的 harness invariants 填充。 +**追加规则**:读取 `entry_template`,提取其中的“目录导航”“关键约束速览”“Agent 工作规则” +区块,以 `## HelixHarness 导航` 为标题追加到 `entry_file` 末尾。关键约束速览中的占位符用 +实际生成的 harness invariants 填充。“常用命令”必须由下方管理区工具合并,不先手工追加或改写。 追加前检查文件末尾是否已包含 `## HelixHarness 导航` 或 `## Agent 工作规则` 区块: - 若已存在 → **不重复追加**,仅确认内容是否需要更新 - 若不存在 → 追加完整区块 +**常用命令管理区**:完整读取 `entry_template` 中 +`` 至 `` 的唯一管理区;其中同时保留 +Cursor `/helix-xxx` 与 Claude Code/Codex `/helix:xxx` 的明确宿主标签和九个公共命令。 +先生成或合并入口的其他内容,再执行 +`python3 {plugin_root}/scripts/init_guidance.py --repo-root {repo_root} --platform {canonical_host_id} --mode {init_mode} merge`, +其中 `init_mode=service`,完整全栈为 `fullstack`。使用父流程已验证的 Python、插件根与 Host Context。 +已有入口的常用命令不得先由模型改写;工具只更新合法管理区或精确识别的旧默认区,保留用户正文。 +自定义冲突、损坏/重复边界或工具失败均返回父流程 BLOCKED,不得全局替换前缀后宣称通过。 + **无论新增还是追加**,入口文件最终必须包含以下核心内容: - 项目概述(技术栈、架构风格、业务领域) - 目录导航地图(指向 harness/、knowledge/、specs/、hooks/) - 关键约束速览(最重要的 3-5 条 invariants) -- 常用命令速查(/helix:propose、/helix:apply 等) +- 带宿主标签的常用命令管理区(九个公共命令,两种入口写法共同保留) - Agent 工作规则(含 harness 和 knowledge 的按需加载协议引用) -### Phase 5.5: 最终提交 state file +### Phase 5.5: 返回生成结果,等待父流程验收 -只有 Phase 4 hooks 与 Phase 5 Host Kit 入口全部生成并通过逐项验证后,才使用公共 -`Read/Edit/Write` 工具语义原子更新 `docs/.helixharness-init-state.json`;其他宿主只按 -`resources.runtime` 映射,不依赖外部 JSON CLI: +本 bootstrap 不得写入或删除 `docs/.helixharness-init-state.json`,不得调用状态提交器, +不得写最终完成字段或把自身生成结束表述为整体 Init 完成。父流程是检测后状态的唯一写入者。 +返回实际生成的 knowledge、harness、hooks 三组仓库相对文件清单、入口路径、逐项检查结果, +以及适用时的 `PROJECT_HOOKS_MERGE_REQUEST`。清单只包含实际已生成、非空且属于本仓的文件, +保留异常和待确认项,不用 `parent-owned` 代替实际 Hooks 通过事实。 -1. state 文件缺失、为空或不是 JSON 对象时立即 `BLOCKED:init_state_missing`,不得跳过后继续完成。 -2. `scanPlan` 为空时补后端六路数组;已有非空计划保持不变。设置 `scanStatus=completed`。 -3. `bootstrap_mode=fullstack-base` 时设置 `bootstrapStatus=backend_completed`、写 - `backendCompletedAt` 并移除过早的 `completedAt`;service 模式设置 - `bootstrapStatus=completed` 与 `completedAt`。所有 `*At` 字段固定为当前 UTC Unix epoch - 秒的 JSON number,与既有状态产物类型一致,不得写 ISO 字符串或宿主本地时间文本。 -4. 从实际文件列表构造排序、去重后的 `deliverables.knowledge.files` 和 - `deliverables.harness.files`,`count` 必须等于对应数组长度。 -5. 只修改上述字段,保留其他键。写入后重新 `Read`,确认 JSON 可解析、字段类型正确、入口、hooks - 及所有 deliverable 文件均存在;任一步失败报告 `BLOCKED:init_state_update_failed`。 +`bootstrap_mode=fullstack-base` 时只报告后端生成阶段已结束;父流程先核验后端产物, +再提交 backend_completed/backendCompletedAt 检查点并进入前端 bootstrap。整个 Init 的最终 +状态必须等父流程完成所有产物、实际 Hooks 和统计门禁之后才提交。 -> 不要删除 `docs/.helixharness-init-state.json`(供后续命令使用)。 +### Phase 6: 向父流程输出生成结果 -### Phase 6: 输出初始化报告 +以下是返回父流程的阶段报告,不是面向用户的最终完成报告。最终报告、错误重试和下一步建议中的 +公共命令入口必须按当前 Host Context 展示:Cursor 使用 `/helix-xxx`,Claude Code/Codex 使用 +`/helix:xxx`,参数、路径、引号、`--loop`、`--workspace` 和 `bug-fix` 保持原义。 ```text -## HelixHarness 初始化完成 +## HelixHarness 后端生成阶段结果(等待父流程验收) ### 项目信息 - 项目模式: {project-mode} @@ -357,7 +363,7 @@ status_entities: [] ### 生成的文件 - [x] Host Kit `entry_file` -- [x] Host Kit `settings_file` 已按 `resources.project_hooks` 合并,或明确为跳过/parent-owned +- Host Kit `settings_file`:如实报告已合并、契约明确跳过,或待父流程合并;待合并不计为最终通过 - [x] docs/harness/index.md - [x] docs/harness/invariants/index.md + 相关叶子规则 — {N} 条规则 - [x] docs/harness/architecture/index.md @@ -385,10 +391,10 @@ status_entities: [] - [x] docs/eval/.gitkeep(仅数据统计开启时) - [x] .gitignore 中包含 `docs/eval/**` 提交例外(仅数据统计开启时) -### 下一步 +### 父流程最终验收通过后才可展示的下一步 1. 审核 docs/harness/ 下的约束文件,补充项目特有规则 2. 审核 docs/knowledge/ 知识库,确认准确性 -3. 执行 /helix:propose 开始第一个需求开发 +3. 执行 {当前宿主的 propose 命令入口} 开始第一个需求开发 ``` ## 注意事项 diff --git a/helixharness/agents/init-workspace-bootstrap.md b/helixharness/agents/init-workspace-bootstrap.md index 33265de..2b65189 100644 --- a/helixharness/agents/init-workspace-bootstrap.md +++ b/helixharness/agents/init-workspace-bootstrap.md @@ -11,6 +11,11 @@ description: "多仓 workspace 初始化 agent。生成 helixharness.workspace.y `entry_template` 仅供单仓 init 使用,`settings_file` 在 workspace 模式不写。宿主工具语义读取 `resources.runtime`,禁止按平台名硬编码入口文件。 +向用户展示完成报告、错误重试、下一步建议或子仓初始化命令时,按当前 Host Context +映射公共命令入口:Cursor 使用 `/helix-xxx`,Claude Code / Codex 使用 `/helix:xxx`。 +本文中的 `/helix:xxx` 是公共逻辑标识,不能直接复制成 Cursor 的用户输入示例。 +只改变入口标识;参数、路径、引号、`--workspace`、`--loop` 与 `bug-fix` 名称保持原义。 + ## 输入 - workspace 根目录 @@ -104,6 +109,21 @@ Host Kit 的 `workspace_entry_template` - 只在文件末尾追加或更新 `HelixHarness Workspace` 导航区块 - 不写入 repo-local harness 规则 +常用命令区必须由模板中的 `` 与 +`` 包围,同时保留 Cursor 和 Claude Code / Codex 的入口标签。 +不要用全局前缀替换修改用户正文,也不要先手工改写已有常用命令区来掩盖冲突。 +生成其他导航内容后,用已验证的 Python、插件根和当前 Host Context 执行机械合并: + +```text + /scripts/init_guidance.py --repo-root --platform --mode workspace merge +``` + +参数必须使用宿主工具提供的独立 argv 或正确引用,保留路径中的空格。该工具只管理命令块, +不替代 Workspace 产物验收;不存在管理区且没有常用命令冲突时追加,合法管理区仅更新此区, +可精确识别的旧默认区才允许迁移。自定义冲突、重复/损坏边界或未知宿主返回 blocked, +保留用户内容,不得继续报告初始化完成。Cursor 与 Codex 共用 `AGENTS.md` 时仍保留两组入口, +不能随本次宿主覆盖另一组;本次合并也不得进入子仓。 + workspace 入口文件必须明确: - 当前目录是 HelixHarness workspace root @@ -203,6 +223,17 @@ test -d ./docs/specs/active test -d ./docs/specs/completed ``` +还必须读取根入口的实际命令区,并执行同一机械工具的只读检查: + +```text + /scripts/init_guidance.py --repo-root --platform --mode workspace check +``` + +确认 Cursor 行为 `/helix-xxx`、Claude Code / Codex 行为 `/helix:xxx`,保留 +`--workspace`、`--loop` 和需求参数。Workspace 根不支持 BugFix,不得把子仓 BugFix 指引写成根命令。 +该检查同样用于 refresh 后产物;失败不得报告完成。`validate_init_outputs.py` 仍只用于开发期/CI, +不得作为本流程运行期的语义验收替代品。 + 若任一检查失败,不得输出“完成”,改为输出: ```text diff --git a/helixharness/agents/scan-db.md b/helixharness/agents/scan-db.md index 7c09074..fb7ea6e 100644 --- a/helixharness/agents/scan-db.md +++ b/helixharness/agents/scan-db.md @@ -136,7 +136,7 @@ description: "数据库深度扫描 agent。分析代码库中所有数据库表 - 无数据源配置(`spring.datasource` / JDBC URL / HikariCP / Druid / `@DS`) - 无有效 JDBC / MyBatis / JPA 依赖 -> 结论:本服务不直接持有数据表。代码中出现的表名仅为文本引用,权威 schema 需查阅下游数据服务。 +> 结论:本服务不直接持有数据表。 ## 表清单总览 @@ -145,16 +145,22 @@ description: "数据库深度扫描 agent。分析代码库中所有数据库表 ## 表字段详情 (无) +``` -## 附录:跨服务数据线索(非本服务表) +无表结论仅陈述已验证的持久化事实,不自动断言存在文本表名、下游服务或需要查阅下游 schema。 +没有表名引用时到此结束,不添加附录。只有确实发现代码、测试、注释或字符串中的表名引用时, +才在上面的基础文档之后追加以下附录,且必须给出实际文件与行号;引用仍不得作为本服务表或 ER 实体。 -> 仅当代码(测试类/注释/字符串)中确实出现表名引用时填写本节;否则整节省略。 +```markdown +## 附录:跨服务数据线索(非本服务表) -| 引用表名 | 来源文件:行号 | 引用上下文 | 推测归属服务 | +| 引用表名 | 来源文件:行号 | 引用上下文 | 有证据的归属服务或待确认 | | :--- | :--- | :--- | :--- | | xxx | src/test/.../FooTest.java:42 | 测试 SQL 中出现 | 待确认 | ``` +仅当仓库证据能绑定具体下游数据服务时才说明其归属/查询位置,否则写“待确认”,不能凭表名猜下游。 + ### er.md 格式 er.md 是独立的 ER 关系图文档,按业务模块分区,每个模块用独立 mermaid 代码块展示,并附带文字说明提升可读性。 diff --git a/helixharness/commands/config.md b/helixharness/commands/config.md index 87264d9..deaf7d9 100644 --- a/helixharness/commands/config.md +++ b/helixharness/commands/config.md @@ -38,10 +38,15 @@ python3 "{plugin_root}/scripts/user_config.py" --repo-root "{repo_root}" --platf ## 修改 1. 用户已给出明确修改命令或明确自然语言目标、值和范围时,这就是该项修改的授权,不再重复要求确认。参数不完整时,先查看当前值,只询问缺失的必要信息。默认查看、推荐项和未提交的选择不构成授权。 -2. 开启统计之前逐字展示 `reference/eval-protocol.md` 中 `helixharness-eval-data-notice-v1` 的数据说明。用户已明确要求开启时展示说明后执行;仅表达查看/配置意图时展示说明并由用户选择,不能自动开启。 -3. 使用同一个 `user_config.py`,追加一项实际修改参数及内部 `--user-confirmed` 标记。该标记仅在已有明确请求或选择后由 Agent 传入。授权缓存始终通过捆绑 `telemetry_consent.py` 的 API 写入,不手改 JSON。项目开启被用户级关闭覆盖时展示 warning 和实际有效范围,不自动扩大授权。 +2. 开启统计必须顺序执行以下两阶段,不能把固定说明放到修改成功后的总结中: + - 已有明确开启请求或用户选择后,先调用同一个 `user_config.py`,带原请求的 `--telemetry enabled --scope {scope} --user-confirmed`,不带 `--telemetry-notice-shown`。此调用只准备说明,不开启统计;返回 `read_only=true`、`change.updated=false`、`request_complete=false`、`notice_required=true`、`next_action=display_notice_before_enable`、`notice` 和 `continuation`。这是**未完成的中间态**,不是只读查看请求的终态。 + - 读取成功后,在**单独一条用户可见的进度消息(非最终回复)**中逐字展示 `notice.text`(即 `reference/eval-protocol.md` 中 `helixharness-eval-data-notice-v1` 的固定说明),然后才进行下一次工具调用。不能只把说明留在工具输出中,也不能在同一 shell、并行调用或同一工具批次里连续准备和开启。展示说明不是 `AskUserQuestion` 决策门禁,不得展示后结束当前轮次或等待用户再说“继续”。 + - 说明已经实际展示,且用户未撤销原开启请求时,按 `continuation` **在同一轮立即继续**:复用相同的脚本、仓库、宿主、作用范围和原开启参数,追加内部 `--telemetry-notice-shown "{notice.sha256}"`;仍必须带 `--user-confirmed`。原明确开启请求的授权持续有效,不需要第二次授权,也不能将续执行扩大到其他范围。仅表达查看/配置意图时,先取得缺失的明确选择,不能把准备说明或默认选项当作授权。 + - 准备回执的 `telemetry` 是修改前的配置诊断;其中的 `prompt_due`、`allowed_actions` 不撤销本次明确授权,也不要求再打开授权选择。当前请求的后续动作以 `continuation` 为准。 + - `notice.sha256` 仅校验当前说明版本,不证明用户已看见消息,也不代替开启授权。不得编造该值、从旧调用复用或在展示前传入。说明不可读取、digest 过期或准备返回异常时停止开启;修复原因后重新准备并展示,不绕过为直接 `telemetry_consent.py set/choose`。 +3. 关闭统计及地址修改仍使用同一个 `user_config.py`,追加一项实际修改参数及内部 `--user-confirmed` 标记,不传说明 digest;该标记仅在已有明确请求或选择后由 Agent 传入。授权缓存始终通过捆绑 `telemetry_consent.py` 的 API 写入,不手改 JSON。项目开启被用户级关闭覆盖时展示 warning 和实际有效范围,不自动扩大授权。 4. 地址配置按当前 `HELIXHARNESS_TELEMETRY_HOME` / `HELIXHARNESS_FEEDBACK_HOME` 或默认本机目录定位,脚本只合并目标 `endpoint` 字段并原子写入,保留其他字段。非法地址或损坏 JSON 拒绝写入并保留原文件;不自行删除重建。URL 不允许凭据、查询参数和 fragment。 -5. 根据返回的 `change.updated`、warning 和重新读取的有效值报告。`updated=false` 不能称修改成功。操作后显示实际作用范围和配置来源。 +5. `request_complete=false` 时仍须消费中间态的后续动作;`request_complete=true` 仅说明本次脚本请求已经处理结束,不等于修改成功。最终根据 `change.updated`、warning 和重新读取的有效值报告。`updated=false` 不能称修改成功。操作后显示实际作用范围和配置来源。用户取消、真实工具错误或宿主确实无法先发可见进度再调用工具时如实报告本次请求未完成及当前实际有效状态,不隐藏说明、不伪造授权、不绕过保护。 地址设置不代表统计授权;恢复默认地址不是关闭统计,发布默认值可能仍有接收方。停止统计必须显式关闭授权。开启本人范围仅影响当前 Host Kit 的授权缓存,不擅自改另一宿主。关闭后不删除历史账本或平台数据;未发送私有证据由既有授权协议清理。 diff --git a/helixharness/commands/init.md b/helixharness/commands/init.md index 7f096a6..d9252b4 100644 --- a/helixharness/commands/init.md +++ b/helixharness/commands/init.md @@ -6,6 +6,15 @@ description: "HelixHarness 初始化入口。默认初始化单服务仓库; > Init Agent DAG 不变量:本文件中的 Agent tool 拼写按 `reference/tool-semantics.md` 执行。后端 A 组三路并行,B 组保持 `scan-service → scan-boundary → scan-service-meta` 依赖顺序;前端保持六路并行。当前 Host Kit 只能映射派发、等待和物理写入者,不得改变 Agent 数量、依赖、产物或 BLOCKED 传播。 +> Init 完成状态不变量:检测后 init state 的唯一写入者是父流程。所有扫描和 bootstrap 子任务 +> 只返回事实与产物,不得写最终完成字段、调用状态提交器或把子阶段结果称为整体 Init 完成。 +> 父流程必须在实际产物、命令指引、Hooks 和统计门禁全部通过后,最后提交 completed/completedAt。 + +> 面向用户的命令指引:公共正文的 `/helix:xxx` 是逻辑标识;完成报告、错误重试、下一步建议及 +> 子仓初始化指引必须按当前 Host Context 映射入口:Cursor `/helix-xxx`,Claude Code/Codex +> `/helix:xxx`。只映射公共命令入口,保持参数、路径、引号、`--loop`、`--workspace` 和 `bug-fix` +> 名称原义。生成入口的受管常用命令块则同时保留两类宿主标签,不能由最后一次 Init 覆盖另一类写法。 + > Telemetry Host Kit 门禁:读取 `reference/telemetry-command-protocol.md` 和 `resources.telemetry_protocol`,只按 capability、生命周期模式和逻辑动作执行;不得根据宿主名称选择宿主私有缓存、stage 或 finish 流程。 @@ -80,7 +89,7 @@ result_reencode_budget: 1 | job_id | prompt_source | depends_on | write_scope | forbidden_scope | expected_artifacts / validation | |---|---|---|---|---|---| | `init_workspace_bootstrap` | `agents/init-workspace-bootstrap.md` | W0 repo registry 已确定 | workspace 根入口文件(由 `resources.project_config.workspace_entry_template` 生成)、`helixharness.workspace.yaml`、workspace `docs/knowledge/**`、`docs/specs/active/`、`docs/specs/completed/` | 所有 repo-local 路径 | W1.5 的 8 项 workspace 产物全部存在并通过结构校验 | -| `init_scan_tech` | `agents/scan-tech.md` | 项目类型为 backend/unknown,或全栈 scan plan 含后端扫描,且未传 `--knowledge` | `docs/knowledge/architecture.md` | `docs/knowledge/index.md`、init state、timings | 文件存在且非空 | +| `init_scan_tech` | `agents/scan-tech.md` | backend/unknown 且未传 `--knowledge`;或完整全栈 scan plan 含后端扫描(仍按已确认计划执行,不因 `--knowledge` 跳过) | `docs/knowledge/architecture.md` | `docs/knowledge/index.md`、init state、timings | 文件存在且非空 | | `init_scan_db` | `agents/scan-db.md` | 同上 | `docs/knowledge/database/**` | `docs/knowledge/index.md`、init state、timings | `database/index.md`、`database/er.md` 存在且非空 | | `init_scan_api` | `agents/scan-api.md` | 同上 | `docs/knowledge/api/**` | `docs/knowledge/index.md`、init state、timings | `api/index.md` 存在且非空 | | `init_scan_service` | `agents/scan-service.md` | A 组三项全部通过 | `docs/knowledge/domain-model.md` | 其他扫描产物、共享索引、init state、timings | 文件存在且非空 | @@ -113,7 +122,10 @@ A 组三个 final 的 evidence index 业务事实每个 job 最多 30 项;`sup ### Step 0: 项目类型快速检测 -读取此 plugin 捆绑的 reference 文档:`reference/project-type-detection.md`,执行其中的检测脚本,生成 `docs/.helixharness-init-state.json` 状态文件,供 Step 1 按项目类型分支编排。 +先按下方参数规则区分单仓与 `--workspace`。仅单仓读取此 plugin 捆绑的 +`reference/project-type-detection.md` 并执行检测脚本,生成本轮 pending 状态的 +`docs/.helixharness-init-state.json`,供 Step 1 按项目类型分支编排。每次重新检测均按既有规则 +替换上轮 state,不沿用旧 completed/completedAt;Workspace 跳过单仓检测和状态提交器。 --- @@ -280,6 +292,12 @@ BLOCKED: workspace_init_outputs_missing 并列出缺失路径。不得把子 repo 下的 `.helixharness/`、`docs/` 或 telemetry 文件视为 workspace root 产物。 +父流程还须实际读取根入口的唯一 `` 至 +`` 管理区,核对 Cursor 与 Claude Code/Codex 两类标签及 workspace +命令适用范围;执行 +`python3 {plugin_root}/scripts/init_guidance.py --repo-root {repo_root} --platform {canonical_host_id} --mode workspace check`。 +缺项、错误前缀、自定义冲突或坏/重复边界均不得算作完成;不因此新增 workspace 根级 BugFix 支持。 + `/helix:init --workspace` 的成功判定只看 workspace root 上述产物;每个服务 repo 下的 `.helixharness/telemetry.json`、`.helixharness/upload-state.json` 不属于 workspace 初始化目标。 ### Step W2:服务关系基线 @@ -410,6 +428,14 @@ fi 完成 knowledge 导入或扫描后,按项目类型选择 bootstrap agent: +父流程将 `backend|unknown` 映射为 `init_mode=service`,`frontend` 映射为 `frontend`, +完整全栈/monorepo 映射为 `fullstack`。扫描 job 全部真实完成并通过逐项校验后,父流程调用 +`python3 {plugin_root}/scripts/init_state.py --repo-root {repo_root} --mode {init_mode} scan-complete`。 +空 scanPlan 由提交器补充对应计划,非空计划和 timings 保留;失败立即 BLOCKED,不进入 bootstrap。 +仅 service 分支因 `--knowledge` 跳过扫描、导入实际发生在 bootstrap 内时,暂不提交此检查点, +待 Step 3 独立核验导入产物后再调用;已经完成扫描的 frontend/fullstack 仍立即提交扫描检查点。 +调用使用 runtime preflight 已验证的 Python 和当前已验证 plugin root,不额外寻找解释器或工具。 + **纯前端项目(`$PROJECT_TYPE` = `frontend`)**: - 读取 agent prompt:`agents/init-frontend-bootstrap.md` - 调用 `init_scan_frontend_meta` 时传入 `architecture_mode=frontend-create`;无既有 `architecture.md` 时必须创建纯前端架构文档。 @@ -425,7 +451,13 @@ fi **完整全栈 bootstrap(`$PROJECT_TYPE` = `fullstack-node` / `fullstack-separated` / `monorepo`,且用户选择完整全栈扫描)**: 1. 先执行 `agents/init-service-bootstrap.md`,传入 `bootstrap_mode=fullstack-base`,消费后端扫描 DAG,生成公共目录、后端 knowledge/harness、Host Kit 入口和可选设置。 -2. `init_scan_frontend_meta` 传入 `architecture_mode=fullstack-merge`;它必须等待 `init_scan_tech` 并只更新前端架构区块。后端 bootstrap 真实完成并通过产物校验后,再执行 `agents/init-frontend-bootstrap.md`,传入 `bootstrap_mode=fullstack-merge`,消费六路前端扫描结果;只增量补充前端 knowledge/harness/linters 和同一个 Host Kit 入口区块,不覆盖 service bootstrap 已生成内容,也不因公共目录已存在再次询问是否更新。 +2. `init_scan_frontend_meta` 传入 `architecture_mode=fullstack-merge`;它必须等待 `init_scan_tech` 并只更新前端架构区块。后端 bootstrap 真实完成后,由父流程校验后端实际生成物,并用下文 deliverables JSON 格式调用 + `python3 {plugin_root}/scripts/init_state.py --repo-root {repo_root} --mode fullstack backend-complete --artifacts-verified --deliverables-json '{backend_deliverables_json}'`。 + 这里只记录 backend_completed/backendCompletedAt 检查点;`owner=parent` 的待合并 settings 仍留给 + 最终 Hooks 门禁,不视为整体成功。然后执行 `agents/init-frontend-bootstrap.md`,传入 + `bootstrap_mode=fullstack-merge` 及已核验的后端检查点,消费六路前端扫描结果;只增量补充前端 + knowledge/harness/linters 和同一个 Host Kit 入口区块,不覆盖 service bootstrap 已生成内容, + 也不因公共目录已存在再次询问是否更新。前端失败或取消保留后端检查点,不提交整体完成。 3. 两个 bootstrap 绝对串行;最终同时校验后端必需产物、前端必需产物、唯一根索引、Host Kit 的 `entry_file` 和可选 settings 去重结果。任一侧失败都不能把全栈 init 声称为完成。 初始化目标产物: @@ -453,6 +485,14 @@ bootstrap 达到真实终态后,父流程必须逐项检查上述初始化目 目录和可选 settings 合并结果符合当前模式。任一必需产物缺失或为空时沿用既有产物门禁收口;不得以 额外 Python validator 替代逐项检查。 +父流程实际读取 Host Kit `entry_file` 的 +`` 至 `` 唯一管理区,核对 Cursor +`/helix-xxx`、Claude Code/Codex `/helix:xxx` 标签及九个公共命令完整。再执行 +`python3 {plugin_root}/scripts/init_guidance.py --repo-root {repo_root} --platform {canonical_host_id} --mode {init_mode} check`。 +该工具只检查命令管理区,不替代入口和产物的语义验收;冲突、坏边界、缺项或错误前缀均必须停止, +不得提交完成。bootstrap 合并只允许修改合法管理区或精确旧默认区,用户正文不做全局替换。 +service 的 `--knowledge` 导入分支在此验证导入产物后,才补做 Step 2 的 scan-complete 检查点。 + 项目 hooks 是完成门禁的一部分,不能以 bootstrap 的 `parent-owned` 或合并请求代替实际文件: - `resources.project_hooks.owner=parent` 时,父流程在 bootstrap 返回后执行 @@ -475,6 +515,36 @@ Consent、repo 命名和扫描模式选择只服务初始化,不属于任何 f - 若统计保持开启,`/helix:init` 结束前必须确认 `.gitignore` 允许提交 `docs/eval/**`;若仍被忽略,输出 `WARN:usage_telemetry_gitignored` - 若用户关闭统计,不创建新的 eval-log,不追加 eval `.gitignore` 例外块;已存在的历史 `docs/eval/**` 不删除 +#### Step 4:父流程提交最终状态 + +本步骤仅适用于 service/frontend/fullstack。Workspace 继续使用 W1.5 完成验收和既有 refresh +规则,不得调用单仓状态提交器,不新增根级统计、Hooks 或子仓初始化。 + +只有所有 bootstrap 已达到真实终态、父流程逐项产物及命令指引检查通过、实际 Hooks check +通过(或 Host Kit 明确 skipped),并完成上方统计门禁后,才允许执行最终提交。统计 +`.gitignore` 的既有 WARN 仍保持告警,不升级为额外阻断。缺产物、Hooks 合并/check 失败、 +状态损坏、子任务失败/取消或中断时停止并保留工件与未完成状态,不写 completedAt。 + +从实际已核验的本仓文件构造 deliverables JSON: +`{"knowledge":["docs/knowledge/index.md", "..."],"harness":["docs/harness/index.md", "..."],"hooks":["docs/hooks/index.md", "..."]}`。 +这里只列真实的完整相对文件路径,`...` 是说明占位符,不能传入。全栈必须合并两侧实际清单, +不得用仅前端列表覆盖后端。以正确 shell quoting 或工具的结构化参数传递 JSON,不能拼入未经转义的路径。 +hooks 清单指 `docs/hooks/` 中的生成文档,不是 Host Kit settings;实际 settings 的合并与检查 +使用上方独立 Hooks 门禁,后端阶段检查点不会要求提前合并 parent-owned settings。 + +父流程调用: +`python3 {plugin_root}/scripts/init_state.py --repo-root {repo_root} --mode {init_mode} complete --artifacts-verified --hooks-verified --telemetry-verified --deliverables-json '{deliverables_json}'`。 + +三个 verified 参数是父流程在本轮已完成对应检查的声明,不是工具独立证明语义正确;不得提前传入, +不得用提交器替代逐项检查或把开发期/CI validator 接到业务命令。提交器只校验状态对象、有限转换、 +清单路径/文件存在及原子写入;它不合并 Hooks、不判定知识内容,也不扫描业务代码。 + +提交器保留检测字段、timings 和扩展键,清单排序去重且 count 对齐;所有时间为 UTC Unix epoch +数值。fullstack 必须已有本轮后端检查点,最终写 frontendCompletedAt 并保留 backendCompletedAt。 +重复成功提交相同清单不重写完成时间。任何非零退出或非 updated/unchanged 回执都报告 BLOCKED; +状态缺失、损坏或非对象时不得伪造新成功状态。写入后父流程重新读取,确认最终字段、类型和清单与 +本轮实际验收事实一致;只有此时输出整体 Init 完成报告和当前宿主写法的下一步命令。 + ## 约束 - **命令文件只负责编排** — 详细生成流程统一下沉到 bootstrap agents diff --git a/helixharness/commands/propose.md b/helixharness/commands/propose.md index b0b4da6..742219e 100644 --- a/helixharness/commands/propose.md +++ b/helixharness/commands/propose.md @@ -16,7 +16,8 @@ $ARGUMENTS ## 1. 只执行一次确定性路由 -把 `$ARGUMENTS` 原样按当前 shell 的单参数规则安全引用,然后执行: +首次路由前绑定完整 `$ARGUMENTS`:包含本次用户消息中命令名之后的首行参数及全部换行需求正文。 +不要先用 ` --loop` 试探,再补正文调用第二次。将该完整文本原样按当前 shell 的单参数规则安全引用,然后执行: ```bash python3 "{plugin_root}/scripts/workflow_router.py" --repo-root "{repo_root}" route --command propose --arguments={SHELL_QUOTED_ARGUMENTS} --arguments-mode auto @@ -28,6 +29,9 @@ python3 "{plugin_root}/scripts/workflow_router.py" --repo-root "{repo_root}" rou 业务正文只接收 Router 返回的 shell-safe `workflow_arguments`,不重新解析原始 `$ARGUMENTS`。`--` 后全部视为字面需求;`--loop`、`--revise` 由 Router 消费并剥离。旧版本迁移及需求地址参数不属于当前合同。 +“只执行一次”指同一阶段的初次入口不得试探或改参重路由;只有下节明确要求的用户选择/补名, +以及 `--loop` 中实际阶段成功后的续跑,才允许按对应规则再次路由。它们不是补救首次截断输入的捷径。 + ## 2. 只按 `action` 消费 JSON 退出码 0 或 2 且 stdout 是有效 JSON 时都按 `action` 处理;只有进程异常、无有效 JSON 或未知 action 才输出 `BLOCKED:workflow_router_failed`,不得退回模型推断。 diff --git a/helixharness/commands/update.md b/helixharness/commands/update.md index f28ed8c..7b1e653 100644 --- a/helixharness/commands/update.md +++ b/helixharness/commands/update.md @@ -40,6 +40,7 @@ python3 {plugin_root}/scripts/version_update.py \ `canonical_host_id` 必须取自预绑定 Host Context,禁止传 `darwin/linux/windows` 等操作系统名。 - 脚本必须从 Host Registry 解析当前宿主,动态加载清单声明的适配器。 +- 如果返回 `pending_installation`,表示此前已确认、尚未收口且可验证恢复的安装事务。优先按 Step 3 的恢复分支处理;不能被 `latest` 或新版本检查失败的 warning/`--strict` 分支提前截断。 - `unsupported_host + continue_silently` 时静默结束,不创建缓存、授权或提示。 - `next_action=continue_with_warning` 时原样输出脚本 `warning`;`--strict` 额外将该状态作为阻断。 - 不得绕过结构化结果,手工补造当前版本、最新版本、安装范围或升级路径。 @@ -54,7 +55,7 @@ python3 {plugin_root}/scripts/version_update.py \ - 当前版本到目标版本之间的完整 release notes; - 跨版本路径是否包含 `update_type=required`。 -如果已是最新版本,输出: +如果没有 `pending_installation` 且已是最新版本,输出: ```text HelixHarness 已是最新版本,无需升级。 @@ -62,6 +63,12 @@ HelixHarness 已是最新版本,无需升级。 ### Step 3:执行统一授权状态机 +如果 `check` 返回 `pending_installation`:展示其中的 `target_version` 和已有事务尚未收口的事实。 +传入 `--check` 时到此仅展示,不执行任何安装;否则使用回执中的原 `challenge_id` 调用 `install`, +恢复同一份仍有效的用户授权,不重新 `prepare/decide`,也不选择刚检查到的其他版本。 +脚本会复验授权有效期、独立事务凭据、安装来源和批准的目标;失败就停止本次恢复,不能绕过验证。 +成功后进入 Step 4。本次恢复不同时安装新发现的更高版本;更高版本须另走新的确认流程。 + 如果传入 `--check`: - 只展示版本状态和更新内容; @@ -128,3 +135,8 @@ HelixHarness 已更新。请重启当前编程平台或新开会话,让新的 ``` 宿主资源声明:`resources.runtime`、`resources.subagent_protocol`、`resources.telemetry_protocol`。 + + +## Cursor native update boundary + +仅 Cursor 原生安装:`check` 返回 `reason=installation_update_not_supported`、`next_action=continue_with_warning` 时,展示当前安装及手动更新步骤后结束更新流程;业务继续。不得进入 prepare/decide/install,不得改用旧 Local 缓存或授权,不把 unknown 当作已是最新。显式后续更新操作退出码为 2。此限制不改变 managed-local、Claude Code 或 Codex 的原协议。 diff --git a/helixharness/hosts/cursor/cleanup_worker.py b/helixharness/hosts/cursor/cleanup_worker.py new file mode 100644 index 0000000..35f9d16 --- /dev/null +++ b/helixharness/hosts/cursor/cleanup_worker.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +"""One-shot Cursor shutdown cleanup; never a collector, sender or scheduler.""" +from __future__ import annotations + +import os +import sys +import time +from contextlib import contextmanager +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "scripts")) + +import telemetry_consent_state as consent # noqa: E402 +import telemetry_ledger # noqa: E402 + + +@contextmanager +def cleanup_lease(repo: Path): + """Deduplicate only Cursor cleanup, with crash-safe OS lock release.""" + path = telemetry_ledger._managed(repo, Path(".helixharness/telemetry-v2/cursor-cleanup.lock")) + fd = os.open(path, os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0), 0o600) + with os.fdopen(fd, "a+b") as stream: + if os.name == "nt": + import msvcrt + if stream.seek(0, os.SEEK_END) == 0: + stream.write(b"\0") + stream.flush() + stream.seek(0) + else: + import fcntl + try: + if os.name == "nt": + msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1) + else: + fcntl.flock(stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + yield False + return + try: + yield True + finally: + if os.name == "nt": + stream.seek(0) + msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1) + else: + fcntl.flock(stream.fileno(), fcntl.LOCK_UN) + + +def cleanup_repository(repo: Path) -> bool: + """Hold current disabled consent throughout deletion; re-enabling waits.""" + private = telemetry_ledger._managed(repo, Path(".helixharness/telemetry-v2")) + if not private.is_dir(): + return False + with cleanup_lease(repo) as acquired: + if not acquired: + return False + with consent.consent_snapshot(repo, "cursor", deadline=time.monotonic() + 1.5) as state: + if state.get("effective_mode") != "disabled": + return False + import metrics + metrics.purge_private_states(repo, "cursor", strict_scope=True) + return True + + +def main(workspaces: list[str] | None = None) -> int: + deadline = time.monotonic() + 15.0 + seen: set[Path] = set() + for workspace in workspaces if workspaces is not None else sys.argv[1:]: + if time.monotonic() >= deadline: + break + try: + if not Path(workspace).is_absolute(): + continue + repo = consent._repo_root(workspace, deadline=deadline) + if repo in seen: + continue + seen.add(repo) + cleanup_repository(repo) + except (OSError, ValueError): + # No persistent job and no authorization guess on a failed attempt. + continue + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/helixharness/hosts/cursor/command-projection.json b/helixharness/hosts/cursor/command-projection.json new file mode 100644 index 0000000..d18ca88 --- /dev/null +++ b/helixharness/hosts/cursor/command-projection.json @@ -0,0 +1,15 @@ +{ + "projection_version": "1.0", + "surface": "skill", + "entrypoints": { + "apply": ["hosts/cursor/skills/helix-apply/SKILL.md", "commands/apply.md"], + "archive": ["hosts/cursor/skills/helix-archive/SKILL.md", "commands/archive.md"], + "bug-fix": ["hosts/cursor/skills/helix-bug-fix/SKILL.md", "commands/bug-fix.md"], + "config": ["hosts/cursor/skills/helix-config/SKILL.md", "commands/config.md"], + "init": ["hosts/cursor/skills/helix-init/SKILL.md", "commands/init.md"], + "propose": ["hosts/cursor/skills/helix-propose/SKILL.md", "commands/propose.md"], + "status": ["hosts/cursor/skills/helix-status/SKILL.md", "commands/status.md"], + "update": ["hosts/cursor/skills/helix-update/SKILL.md", "commands/update.md"], + "ut": ["hosts/cursor/skills/helix-ut/SKILL.md", "commands/ut.md"] + } +} diff --git a/helixharness/hosts/cursor/d2c_gate.cjs b/helixharness/hosts/cursor/d2c_gate.cjs new file mode 100644 index 0000000..593bb99 --- /dev/null +++ b/helixharness/hosts/cursor/d2c_gate.cjs @@ -0,0 +1,163 @@ +#!/usr/bin/env node +'use strict' + +// Explicit Cursor gate: check this invocation's checkpoint, never read transcripts. +const fs = require('fs') +const path = require('path') +const { decideStop, isHeadlessEnv } = require('../../skills/d-d2c/scripts/lib/d2c-workflow-guard-core.cjs') + +function within(root, candidate) { + const relative = path.relative(root, candidate) + return relative !== '' && relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative) +} + +function readInside(root, candidate, optional = false) { + if (optional && !fs.existsSync(candidate)) return null + const real = fs.realpathSync(candidate) + if (!within(root, real)) throw new Error('checkpoint path escapes its state directory') + const value = JSON.parse(fs.readFileSync(real, 'utf8')) + if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('checkpoint must be an object') + return value +} + +function parseArgs(argv) { + const args = { headless: false } + const values = new Set(['--repo-root', '--page-dir', '--started-at', '--action', '--session-id']) + for (let index = 0; index < argv.length; index += 1) { + const key = argv[index] + if (key === '--headless' && !args.headless) { + args.headless = true + } else if (values.has(key) && !Object.prototype.hasOwnProperty.call(args, key) && argv[index + 1] && !argv[index + 1].startsWith('--')) { + args[key] = argv[++index] + } else { + throw new Error(`invalid or duplicate argument: ${key}`) + } + } + for (const key of ['--repo-root', '--page-dir', '--started-at', '--action']) { + if (!args[key]) throw new Error(`required argument: ${key}`) + } + if (!['stop', 'ask'].includes(args['--action'])) throw new Error('action must be stop or ask') + if (!Number.isFinite(Date.parse(args['--started-at']))) throw new Error('started-at must be a timestamp') + return args +} + +function timestamp(value) { + return typeof value === 'string' ? Date.parse(value) : NaN +} + +function currentInvocationState(state, startedAt) { + const phases = {} + for (const phase of [0, 1, 2, 3, 4, 6]) { + const entry = state.phases[phase] + if (!entry || !Number.isFinite(timestamp(entry.enteredAt)) || timestamp(entry.enteredAt) < startedAt) continue + if (entry.status === 'completed' && (!Number.isFinite(timestamp(entry.completedAt)) || timestamp(entry.completedAt) < timestamp(entry.enteredAt))) continue + // The canonical checkpoint CLI retains previous phases on --enter 0. + // A retained phase 6 must never outrank the new current phase. + if (phase === 6 && Number(state.currentPhase) !== 6) continue + phases[phase] = entry + } + return { ...state, phases } +} + +function currentInvocationHandoff(handoff, startedAt) { + if (!handoff || !Number.isFinite(timestamp(handoff.updatedAt)) || timestamp(handoff.updatedAt) < startedAt) return null + if (handoff.status === 'awaiting-user' && (!Number.isFinite(timestamp(handoff.browserReadyAt)) || timestamp(handoff.browserReadyAt) < startedAt)) return null + // The canonical guard prioritizes handoff over workflowPause. Old handoff + // state must neither authorize this invocation nor hide its explicit pause. + return handoff +} + +function requireFresh(value, startedAt, label) { + const time = timestamp(value) + if (!Number.isFinite(time) || time < startedAt) throw new Error(`${label} is missing or belongs to an earlier invocation`) + return time +} + +function validateCompletedPhases(state, phases, startedAt) { + let previousEnd = startedAt + for (const phase of phases) { + const entry = state.phases[phase] + if (!entry || entry.status !== 'completed') throw new Error(`phase ${phase} has no completed evidence for this invocation`) + const entered = requireFresh(entry.enteredAt, previousEnd, `phase ${phase} entry`) + previousEnd = requireFresh(entry.completedAt, entered, `phase ${phase} completion`) + } + return previousEnd +} + +function validateAllowedDecision(decision, state, handoff, startedAt) { + if (!decision.allow) return + const kind = decision.action && decision.action.kind + if (state.workflowPause) { + const pause = state.workflowPause + requireFresh(pause.createdAt, startedAt, 'workflow pause') + if (!['external-input', 'user-cancelled'].includes(pause.kind) || !pause.reason) throw new Error('invalid workflow pause') + if (pause.kind === 'external-input' && !pause.detail && !pause.evidence) throw new Error('external-input pause needs evidence or detail') + const pauseKind = pause.kind === 'external-input' ? 'wait-external-input' : 'aborted' + if (kind === pauseKind && decision.reason === pause.reason) return + } + if (kind === 'done') { + if (Number(state.currentPhase) !== 6) throw new Error('only the current phase 6 can complete this invocation') + validateCompletedPhases(state, [0, 1, 2, 3, 4, 6], startedAt) + if (state.phases[4].decision !== 'cancel') throw new Error('phase 4 must authorize finalization') + } else if (kind === 'wait-user-decision') { + const previousEnd = validateCompletedPhases(state, [0, 1, 2, 3], startedAt) + const phase = state.phases[4] + if (Number(state.currentPhase) !== 4 || !phase || phase.status !== 'in_progress') throw new Error('no current phase 4 decision') + requireFresh(phase.enteredAt, previousEnd, 'phase 4 entry') + } else if (handoff && ['wait-browser', 'wait-outer-runner', 'wait-external-input', 'aborted'].includes(kind)) { + requireFresh(handoff.updatedAt, startedAt, 'browser handoff') + if (kind === 'wait-browser') requireFresh(handoff.browserReadyAt, startedAt, 'browser readiness') + } else { + throw new Error('no current invocation evidence authorizes this decision') + } +} + +function check(args) { + const root = fs.realpathSync(args['--repo-root']) + const stateDir = fs.realpathSync(path.join(root, 'd-d2c/temp')) + if (!within(root, stateDir)) throw new Error('state directory escapes repository') + const marker = readInside(stateDir, path.join(stateDir, '.active-workflow.json')) + if (marker.pageDir !== args['--page-dir'] || marker.workflowStartedAt !== args['--started-at']) { + throw new Error('checkpoint does not belong to this invocation') + } + if (marker.ownerSessionId && marker.ownerSessionId !== args['--session-id']) { + throw new Error('checkpoint belongs to another or unidentified session') + } + const pageDir = path.resolve(stateDir, marker.pageDir) + if (!within(stateDir, pageDir)) throw new Error('invalid checkpoint page directory') + const stateFile = fs.realpathSync(marker.stateFile || path.join(pageDir, 'workflow-state.json')) + if (stateFile !== fs.realpathSync(path.join(pageDir, 'workflow-state.json'))) { + throw new Error('checkpoint state does not match page directory') + } + const storedState = readInside(stateDir, stateFile) + if (!storedState.phases || !storedState.phases[0] || storedState.phases[0].enteredAt !== args['--started-at']) { + throw new Error('phase 0 does not match this invocation') + } + const startedAt = timestamp(args['--started-at']) + const state = currentInvocationState(storedState, startedAt) + const handoff = currentInvocationHandoff(readInside(stateDir, path.join(pageDir, 'browser-handoff.json'), true), startedAt) + const decision = decideStop({ root, stateDir, marker, state, handoff }, { + sessionId: args['--session-id'], + headless: args.headless || isHeadlessEnv(process.env), + scoreThreshold: process.env.D2C_SCORE_THRESHOLD, + }) + validateAllowedDecision(decision, state, handoff, startedAt) + if (args['--action'] === 'ask' && !(decision.allow && decision.action && decision.action.askUser)) { + return { ...decision, allow: false, reason: 'user interaction is not permitted at this checkpoint' } + } + return decision +} + +function main(argv = process.argv.slice(2)) { + let result + try { + result = check(parseArgs(argv)) + } catch (error) { + result = { allow: false, reason: 'cursor_d2c_gate_failed', detail: error.message } + } + process.stdout.write(`${JSON.stringify(result)}\n`) + return result.allow ? 0 : 2 +} + +if (require.main === module) process.exitCode = main() +module.exports = { check, main, parseArgs } diff --git a/helixharness/hosts/cursor/hook_bootstrap.sh b/helixharness/hosts/cursor/hook_bootstrap.sh new file mode 100644 index 0000000..1fb9f8f --- /dev/null +++ b/helixharness/hosts/cursor/hook_bootstrap.sh @@ -0,0 +1,45 @@ +#!/bin/sh +# Cursor startup hooks use native response fields and never grant permissions. +set -u + +event_name=${1:-} +case "$event_name" in + sessionStart|sessionEnd|beforeSubmitPrompt|afterAgentResponse|postToolUse|postToolUseFailure|subagentStart|subagentStop|stop) ;; + *) exit 0 ;; +esac + +# Missing runtime must preserve the native permission-hook response shape. +# Other hook sources and Cursor's own approval policy remain authoritative. +neutral_response() { + case "$event_name" in + beforeSubmitPrompt) printf '%s\n' '{"continue":true}' ;; + subagentStart) printf '%s\n' '{"permission":"allow"}' ;; + esac +} + +script_dir=${0%/*} +if [ "$script_dir" = "$0" ]; then + script_dir=. +fi +script_dir=$(CDPATH= cd -P "$script_dir" && pwd) || exit 0 +target="$script_dir/hook_entry.py" + +# Keep the lightweight hook gate aligned with scripts/runtime_preflight.sh. +# Do not run the full command preflight on every latency-sensitive hook. +if command -v python3 >/dev/null 2>&1 \ + && python3 -c 'import sys; raise SystemExit(0 if sys.version_info >= (3, 9) else 1)' >/dev/null 2>&1; then + if [ -f "$target" ]; then + exec python3 "$target" + fi + if [ "$event_name" = sessionStart ]; then + printf '%s\n' '{"additional_context":"HelixHarness Cursor hook unavailable: runtime_target_missing. Verify the current plugin installation before running a HelixHarness command."}' + fi + neutral_response + exit 0 +fi + +if [ "$event_name" = sessionStart ]; then + printf '%s\n' '{"additional_context":"HelixHarness requires Python 3.9+ with python3 on PATH. Its command runtime preflight must succeed before workflow execution."}' +fi +neutral_response +exit 0 diff --git a/helixharness/hosts/cursor/hook_entry.py b/helixharness/hosts/cursor/hook_entry.py new file mode 100644 index 0000000..afd09f7 --- /dev/null +++ b/helixharness/hosts/cursor/hook_entry.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +"""Cursor-native lifecycle boundary, bound only to this installed Host Kit.""" + +import json +import shlex +import sys +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "scripts")) + +from telemetry_hosts.cursor import HOOK_EVENTS, HOOK_BUDGET_SECONDS, native_identity, native_identity_fields, record_hook # noqa: E402 + +EVENTS = {"sessionStart": "SessionStart", "sessionEnd": "SessionEnd"} + + +def prompt_response(payload: dict, *, deadline: float) -> dict: + """Best-effort current-prompt binding; no discovery, consent or filesystem reads.""" + response = {"continue": True} + try: + roots = payload.get("workspace_roots") + if time.monotonic() >= deadline or not isinstance(roots, list) or len(roots) > 64: + return response + identity = native_identity_fields(payload, deadline=deadline) + if identity is None: + return response + environment = { + "HELIXHARNESS_BOUND_PLUGIN_ROOT": str(ROOT), + "HELIXHARNESS_CURSOR_CONVERSATION_ID": identity[0], + "HELIXHARNESS_CURSOR_WORKSPACE_ROOTS": json.dumps(identity[1], ensure_ascii=True), + } + prefix = " ".join(key + "=" + shlex.quote(value) for key, value in environment.items()) + context = ( + "Cursor current prompt identity: use this native binding for this prompt, not an earlier session binding. " + "Every HelixHarness Python invocation must explicitly prefix that Python command with these environment " + "assignments (hook env is not guaranteed in Shell). Keep the runtime require before any Python script. " + "Repository ownership is still checked by the command consumer:\n" + prefix + ) + if len(context.encode("utf-8")) <= 8192 and time.monotonic() < deadline: + response["additional_context"] = context + except (OSError, ValueError): + pass + return response + + +def _spawn_cleanup(workspaces: list[str]) -> None: + """One-shot, local cleanup only; no payload, queue or shared scheduler work.""" + import os + import subprocess + options = {"creationflags": subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP} if os.name == "nt" else {"start_new_session": True} + subprocess.Popen( + [sys.executable, str(Path(__file__).with_name("cleanup_worker.py")), *workspaces], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + close_fds=True, **options, + ) + + +def main() -> int: + deadline = time.monotonic() + HOOK_BUDGET_SECONDS + try: + raw = sys.stdin.read(4 * 1024 * 1024 + 1) + if len(raw.encode("utf-8")) > 4 * 1024 * 1024: + return 0 + payload = json.loads(raw) + if not isinstance(payload, dict): + return 0 + native_event = payload.get("hook_event_name") + if not isinstance(native_event, str) or native_event not in EVENTS.keys() | HOOK_EVENTS: + return 0 + if native_event in HOOK_EVENTS: + # Frequent native events need neither startup context nor a scan of + # every Host Kit. Keep their permission response before telemetry. + if native_event == "beforeSubmitPrompt": + print(json.dumps(prompt_response(payload, deadline=deadline)), flush=True) + elif native_event == "subagentStart": + print('{"permission":"allow"}', flush=True) + record_hook(payload, deadline=deadline) + return 0 + identity = native_identity(payload, deadline=deadline) + if native_event == "sessionEnd": + if identity is not None: + _spawn_cleanup(identity[1]) + return 0 + from host_runtime import HostRegistry + from lifecycle_service import handle_event, startup_context_text + + manifest = HostRegistry.discover(ROOT / "hosts").require("cursor") + if native_event == "sessionStart": + environment = {"HELIXHARNESS_BOUND_PLUGIN_ROOT": str(ROOT)} + context = startup_context_text(manifest) + if identity is not None: + environment.update(HELIXHARNESS_CURSOR_CONVERSATION_ID=identity[0], + HELIXHARNESS_CURSOR_WORKSPACE_ROOTS=json.dumps(identity[1], ensure_ascii=False)) + prefix = " ".join(key + "=" + shlex.quote(value) for key, value in environment.items()) + context += ("\nCursor session identity: every HelixHarness Python invocation must explicitly prefix " + "that Python command with these environment assignments (hook env is not guaranteed in Shell). " + "In a shell chain, prefix each Python command, not only the first sh command; " + "keep the runtime require before any Python script:\n" + prefix) + print(json.dumps({ + "additional_context": context, + "env": environment, + }, ensure_ascii=False), flush=True) + if identity is not None: + # sessionEnd can be lost by the host. A later startup retries + # only the same repository-scoped, currently-disabled cleanup. + # Dispatch after flushing context; never wait for the worker. + try: + _spawn_cleanup(identity[1]) + except OSError: + pass + if identity is not None: + import telemetry_consent_state + for workspace in identity[1]: + if time.monotonic() >= deadline: + break + try: + repo = telemetry_consent_state._repo_root(workspace, deadline=deadline) + except (OSError, ValueError): + continue + handle_event(manifest, {"hook_event_name": EVENTS[native_event], "cwd": str(repo)}, emit_startup_context=False) + except (OSError, ValueError): + # Session creation is fire-and-forget. The command entrypoint performs + # strict source/manifest verification before any workflow work. + return 0 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/helixharness/hosts/cursor/hooks.json b/helixharness/hosts/cursor/hooks.json new file mode 100644 index 0000000..418a3bd --- /dev/null +++ b/helixharness/hosts/cursor/hooks.json @@ -0,0 +1,24 @@ +{ + "version": 1, + "hooks": { + "sessionStart": [ + { + "command": "sh \"${CURSOR_PLUGIN_ROOT}/hosts/cursor/hook_bootstrap.sh\" sessionStart", + "timeout": 3 + } + ], + "beforeSubmitPrompt": [{"command": "sh \"${CURSOR_PLUGIN_ROOT}/hosts/cursor/hook_bootstrap.sh\" beforeSubmitPrompt", "timeout": 3}], + "afterAgentResponse": [{"command": "sh \"${CURSOR_PLUGIN_ROOT}/hosts/cursor/hook_bootstrap.sh\" afterAgentResponse", "timeout": 3}], + "postToolUse": [{"command": "sh \"${CURSOR_PLUGIN_ROOT}/hosts/cursor/hook_bootstrap.sh\" postToolUse", "timeout": 3}], + "postToolUseFailure": [{"command": "sh \"${CURSOR_PLUGIN_ROOT}/hosts/cursor/hook_bootstrap.sh\" postToolUseFailure", "timeout": 3}], + "subagentStart": [{"command": "sh \"${CURSOR_PLUGIN_ROOT}/hosts/cursor/hook_bootstrap.sh\" subagentStart", "timeout": 3}], + "subagentStop": [{"command": "sh \"${CURSOR_PLUGIN_ROOT}/hosts/cursor/hook_bootstrap.sh\" subagentStop", "timeout": 3}], + "stop": [{"command": "sh \"${CURSOR_PLUGIN_ROOT}/hosts/cursor/hook_bootstrap.sh\" stop", "timeout": 3}], + "sessionEnd": [ + { + "command": "sh \"${CURSOR_PLUGIN_ROOT}/hosts/cursor/hook_bootstrap.sh\" sessionEnd", + "timeout": 3 + } + ] + } +} diff --git a/helixharness/hosts/cursor/host.json b/helixharness/hosts/cursor/host.json new file mode 100644 index 0000000..3fd68e6 --- /dev/null +++ b/helixharness/hosts/cursor/host.json @@ -0,0 +1,53 @@ +{ + "host_id": "cursor", + "host_api_version": "1.2", + "aliases": [], + "support": { + "level": "stable", + "display_name": "Cursor", + "evidence": null, + "limitations": [ + "Desktop IDE support validated on macOS Cursor 3.30.14; local CLI requires separate native acceptance. Cloud Agents are outside this support scope.", + "Public Cursor commands use /helix-. Native /helix: aliases and colon-prefix completion are outside this release scope; arguments are bound by the Skill entry protocol.", + "Telemetry requires explicit consent and a real current-session identity visible to the model. If host context injection is unavailable, statistics skip without blocking workflows. Missing or cross-stage tokens remain unavailable.", + "Automatic plugin updates require a Helix-managed local installation on macOS/Linux. Marketplace-managed or unregistered copies are not modified.", + "D2C uses an explicit checkpoint gate; no native skill-scoped Stop or user-question hook is claimed. An owner-bound completion requires the real current session identity; missing identity cannot be bypassed.", + "sessionEnd delivery/execution is best effort. Explicit consent revocation cleans this repository; a later sessionStart retries scoped cleanup while consent remains disabled. Closing a window does not guarantee cleanup.", + "Pinned native project installation is supported on the tested desktop build. Native automatic updates are unsupported; check provides current-installation facts and manual steps without consuming managed-local authorization. Statistics may remain partial." + ] + }, + "capabilities": { + "command_surface": "emulated", + "skill_discovery": "native", + "session_start": "native", + "session_end": "native", + "stop_hook": "unsupported", + "failure_hook": "unsupported", + "command_lifecycle": "emulated", + "workflow_transition": "emulated", + "subagents": "native", + "unit_test_workflow": "emulated", + "task_tracking": "emulated", + "project_hooks": "native", + "session_events": "native", + "telemetry": "emulated", + "plugin_install": "native", + "plugin_update": "emulated" + }, + "adapters": { + "distribution": "resource:.cursor-plugin/plugin.json", + "installer": "resource:hosts/cursor/installer.md", + "command_projection": "resource:hosts/cursor/command-projection.json", + "runtime": "resource:hosts/cursor/runtime.md", + "subagent_protocol": "resource:hosts/cursor/subagent.md", + "workflow_transition": "resource:hosts/cursor/workflow-transition.md", + "project_config": "resource:hosts/cursor/project.json", + "project_hooks": "resource:hosts/cursor/project-hooks.json", + "ut": "resource:hosts/cursor/ut.md", + "lifecycle": "resource:hosts/cursor/lifecycle.md", + "telemetry_protocol": "resource:hosts/shared/telemetry.md", + "telemetry": "python:telemetry_hosts.cursor:CursorAdapter", + "version": "python:update_hosts.cursor:plugin_version", + "update": "python:update_hosts.cursor:CursorUpdateAdapter" + } +} diff --git a/helixharness/hosts/cursor/installer.md b/helixharness/hosts/cursor/installer.md new file mode 100644 index 0000000..536fd32 --- /dev/null +++ b/helixharness/hosts/cursor/installer.md @@ -0,0 +1,154 @@ +# Cursor installation / Cursor 安装 + +Cursor desktop support is stable within the documented capability limits. Use a Cursor marketplace as the normal distribution channel. A published, accessible repository is required. Helix includes the marketplace and plugin manifests, while public Cursor Marketplace listing requires a separate submission and review. + +Cursor 桌面接入按已声明的能力边界正式支持,常规分发采用 Cursor 插件市场。安装来源需是已发布且可访问的仓库。Helix 已包含市场和插件清单,Cursor 公共市场上架还需单独提交和审核。 + +## Marketplace installation / 市场安装 + +For a team marketplace, an administrator imports the release repository under **Dashboard → Plugins & MCPs → Add Marketplace → Import from Repo**, then reviews and makes `helix` available. Users open **Customize**, select `helix`, choose **Install** and a project or user scope. Repository-provider access and account permissions follow Cursor's prompts. After installation, reload the window, open a new Agent and select `/helix-status` from `/helix-` completion. + +团队市场由管理员在 **Dashboard → Plugins & MCPs → Add Marketplace → Import from Repo** 导入发行仓库,审核并提供 `helix`。用户进入 **Customize**,选择 `helix`,点击 **Install** 并选择项目或用户范围。按 Cursor 提示完成仓库访问与账号权限配置。安装后重载窗口,新建 Agent,从 `/helix-` 补全选择 `/helix-status`。 + +The combined repository's `.cursor-plugin/marketplace.json` points to `./helixharness`. The standalone plugin's manifest points to `.`. Marketplace availability and updates are managed by Cursor. This release's native smoke used the fixed-source configuration below; the general marketplace UI flow has not been fully accepted for this candidate. That verification gap is accepted within the current release scope. See [Cursor's marketplace documentation](https://cursor.com/docs/plugins). + +组合仓库的 `.cursor-plugin/marketplace.json` 指向 `./helixharness`,独立插件仓指向 `.`。市场可见性和更新由 Cursor 管理。本次原生实机样例使用下方固定来源配置;当前候选的普通市场 UI 完整流程保留为已接受的验证缺口。参考 [Cursor 市场说明](https://cursor.com/docs/plugins)。 + +## Advanced pinned project source / 高级固定来源配置 + +For reproducible project installation, pin a remote repository and full commit in the project's `.cursor/settings.json`. Keep the plugin key `helixharness-marketplace/helix` and `/helix-xxx` commands. This was tested in Cursor 3.30.14 Agents Window on macOS; it is not an official marketplace listing or acceptance of every Cursor version. + +需要固定版本的项目可在 `.cursor/settings.json` 固定远程仓库与完整提交,保留 `helixharness-marketplace/helix` 和 `/helix-xxx`。已实测 macOS Cursor 3.30.14 Agents Window;不代表官方市场上架或所有版本均已验收。 + +Merge only the Helix entry into existing settings (do not replace other settings). Replace URL and SHA with a reviewed, reachable release; use `.` for a standalone plugin repository and `./helixharness` for the combined repository: + +仅合并 Helix 配置,保留其他设置。地址和 SHA 必须换成已审核且可取得的发行提交;独立插件仓用 `.`,组合仓用 `./helixharness`: + +```json +{ + "plugins": { + "helixharness-marketplace/helix": { + "enabled": true, + "gitUrl": "https://example.invalid/owner/helixharness.git", + "gitRef": "REPLACE_WITH_FULL_40_CHARACTER_COMMIT_SHA", + "gitPath": "./helixharness" + } + } +} +``` + +No source download is required for this manual configuration route: Cursor obtains the pinned package. If a reviewed plugin copy is already available, the optional maintenance tool provides `plan`, `configure`, `check`, and `restore`: + +人工配置方式不要求先下载源码,Cursor 会获取固定的插件包。已有审核过的插件副本时,可使用维护工具: + +```text +python3 {plugin_root}/scripts/cursor_native_install.py plan --project-root {project} --source {Git_URL} --commit {SHA} +python3 {plugin_root}/scripts/cursor_native_install.py configure --project-root {project} --source {Git_URL} --commit {SHA} --user-confirmed +python3 {plugin_root}/scripts/cursor_native_install.py check --project-root {project} --source {Git_URL} --commit {SHA} --plugin-root {actual_Cursor_cache_root} +python3 {plugin_root}/scripts/cursor_native_install.py restore --project-root {project} --user-confirmed +``` + +Quote actual paths/arguments in your shell. `configure` reports configuration only; after Developer: Reload Window, start a new Agent, select `/helix-status`, and verify the actual Skill/root and Hook binding. A matching cache alone cannot prove current-session selection. The tool accepts strict JSON; it refuses JSONC/duplicate keys without replacing them. Replacement needs `--replace`; restore a previous tool-owned transaction before choosing a new pin. Restore preserves unrelated settings and refuses an externally changed Helix entry. + +实际执行需引用路径和参数。配置成功不等于宿主加载成功:重载窗口、新建 Agent、从补全选 `/helix-status`,核验实际 Skill/root 与 Hook 绑定。工具仅接受严格 JSON,JSONC/重复键受控拒绝。不同绑定需 `--replace`;已有本工具事务先 restore 再换 pin。恢复保留其他设置,Helix 键被外部改动时停止。 + +Before switching, move only an explicitly owned Cursor Local Helix copy to a backup outside `plugins/local`, and disable a conflicting account-native Helix through Cursor UI. Keep Claude/Codex installations and the third-party import switch unchanged. The tool diagnoses Local conflicts but never deletes caches, moves other installations, or edits private Cursor databases. If loading fails, Imported/old cache may remain usable; that is not proof the new candidate loaded. + +切换前仅将已确认归属的 Cursor Local Helix 可恢复备份到扫描目录外,通过 Cursor UI 停用冲突的账号原生 Helix。不改 Claude/Codex 或全局导入开关。工具只诊断冲突,不自动清缓存或操作其他安装。失败回退到 Imported/旧缓存不能算新版本安装成功。 + +Native automatic upgrade through `/helix-update` is unsupported in this release. `--check` shows current installation and a nonblocking warning; it does not assert the latest release. Replace the reviewed project pin explicitly (or use the owning marketplace's supported controls), reload and reverify. A pinned SHA does not follow branch updates. Existing registered managed-local installations retain their separate automatic-update/recovery contract. + +本期原生渠道不支持 `/helix-update` 自动升级。`--check` 只显示当前安装和非阻塞提示,不宣称已是最新。升级需明确更换已审核 pin(或使用所属市场的管理入口),重载并复验;固定 SHA 不自动跟随分支。已有 managed-local 的升级/恢复能力保留。 + +Statistics retain `partial`/`unavailable` when attribution is incomplete. The native test covered isolated real Hook events, a loopback ACK and repeat-collection deduplication, not full token precision, default-background delivery or production-server ingestion. `sessionEnd` remains best effort; revoke consent for explicit scoped cleanup. CLI/Cloud and full D2C acceptance are outside this native installation smoke test. + +统计保留 `partial/unavailable`;当前原生验证是隔离环境真实 Hook、本机接收和重复采集去重,不代表全量 token、默认后台投递或生产入库验收。`sessionEnd` 仍尽力执行,关闭授权触发明确清理;CLI/Cloud、完整 D2C 不由本次安装 smoke 替代。 + +## Optional Local installation / 可选本地安装 + +Cursor 插件清单为 `.cursor-plugin/plugin.json`,只装载当前宿主的薄 Skills 与 hooks。 +根 marketplace 指向 `./helixharness`;独立插件副本的 marketplace 指向 `.`。 + +### Helix 管理的本地安装 + +`plugin_update=emulated` 使用 Helix 自己管理的 local 安装,不是 Cursor 原生 marketplace 更新 API。 +初装前展示 Git 来源、所跟随的 branch/tag/commit 和目标 `~/.cursor/plugins/local/helix`,取得一次真实用户确认, +执行 runtime preflight 后运行安装器(此维护 CLI 不增加公开业务命令): + +```text +python3 "{plugin_root}/scripts/cursor_managed_install.py" install --source "{已确认的Git来源}" --ref "{已确认的ref}" --user-confirmed +``` + +来源只接受无内嵌凭据的 HTTPS/SSH Git URL 或用户明确选定的绝对本地 Git 路径。拒绝 URL password、 +query 和 fragment;本地来源仅发布所选 Git commit,未提交文件不会安装。安装器从 Git archive 选择分发目录, +排除 `.git`、`.env*`、用户配置、运行输出和缓存,拒绝链接与越界路径;不递归复制工作目录。 + +目标必须不存在。安装器不接管已有手工副本、Cursor marketplace cache 或其它宿主管理的安装。 +已有安装需用户先通过所属管理方式移除,再明确选择初装;不能为通过登记检查而手写收据。 +初装生成独立登记 `~/.cursor/helixharness/managed-install.json`,以及安装内的 `.helixharness-managed.json` 收据。 +登记固定安装 ID、Git 来源/ref、插件子路径和安装根;收据记录版本、commit、分发树摘要与登记摘要。 +初装在移动目录前,将已核验候选持久保存到 `~/.cursor/helixharness/initial-{install-id}/plugin`, +并写入 `managed-install.pending.json`。权限失败、进程中断或登记发布后的同步失败会保留可恢复状态。 +修复环境问题并取得用户确认后,运行 `cursor_managed_install.py recover-initial --user-confirmed`, +或以相同来源和 ref 重试初装。两者都续办原日志冻结的 commit,不重新获取 branch 上的新版本。 +恢复只接受原日志绑定的安装 ID、来源、收据和文件树;未知目录、被替换的登记或越界暂存路径均拒绝。 +目录和登记均以独占重命名发布,不覆盖并发出现的陌生内容;不能手工补造登记或覆盖现有插件。 +成功后清理本次暂存目录和 pending 日志。日志发布前的普通失败会清理暂存目录;在该窗口强制终止 +进程可能留下未被日志引用的暂存目录,安装器不会猜测其归属并自动删除。 + +当前受管理更新支持 macOS/Linux 的原子目录交换。安装与更新均使用真实目录,不使用 symlink; +不支持原子交换的环境受控失败,不退化为原地逐文件覆盖。测试可用 `HELIXHARNESS_CURSOR_HOME` 指向 +隔离目录;这不改变真实 Cursor 的插件发现设置,不能仅凭测试目录存在宣称 IDE 已加载。 + +### 本地 IDE 验收与手工副本 + +将**完整插件目录**复制到 `~/.cursor/plugins/local/helix`,其中必须包含 `.cursor-plugin/plugin.json`、 +`hosts/`、`commands/`、`workflows/`、`skills/` 和 `scripts/`。然后重载窗口,在 Customize 检查组件。 +不只复制薄 Skill;它们依赖同一安装内的 canonical 文件。 +此手工复制方式可用于本地安装及验收,但没有 Helix 管理登记,因此版本更新入口会明确报告来源不可识别; +需要自动升级时使用上一节的受管理初装。 + +本地导入受 Cursor 管理策略约束;企业管理员可以禁用。已安装同名 marketplace 插件优先于本地副本。 +Cursor 不加载指向该 local 目录外部的 symlink,不把创建外部软链当作安装成功。 +本说明不代表插件已经提交或获准在官方 marketplace 发布。 + +确认九个入口:`helix-init`、`helix-propose`、`helix-apply`、`helix-archive`、`helix-bug-fix`、 +`helix-ut`、`helix-update`、`helix-status`、`helix-config`。通过 `/` 搜索相应 Skill; +canonical `/helix:*` 由 runtime 映射,参数按 Skill 入口合同绑定;本期不提供 `/helix:xxx` 冒号别名。 + +新开会话确认 Hook 注入 `host_id=cursor` 与当前安装路径;仅菜单可见不能证明 hooks 已执行。 +用合成仓库验证 Init、参数保真、Router、独立子 agent、工作流门禁与重复 Init 的幂等性。 + +## 本地 CLI 与能力边界 + +官方 CLI 可用 `agent --plugin-dir "{绝对插件目录}"` 临时装载,多个目录可重复该参数。 +这只用于独立验收,不等同于 IDE 安装或稳定支持。测试需隔离用户配置、Git hooks、凭据与真实对话, +不得为了 headless 测试自动设置 `--force`、`--yolo` 或扩大审批策略。 + +`agent update` 和 Cursor `/update` 更新 Agent 本体,不能用来升级 HelixHarness。 +Cursor 官方 marketplace/dashboard 的 Refresh 与 Auto Refresh 由其管理,不属于本适配器。 +卸载通过 Cursor 的插件管理,只移除选定安装;不删除业务仓库工件。 + +## 受管理更新与恢复 + +`helix-update` 复用公共 `check → prepare → decide → install`:scope 为 `local`。检查在临时目录读取 Git +快照和版本策略,不改变安装;授权前再次校验独立登记与当前安装树。确认框明确展示来源、安装位置、commit +与摘要。一次性授权绑定这些事实,安装时不接受相同版本号下的不同文件树,也不接受被替换的登记或来源。 +branch 在确认后推进时仍只安装已批准的精确 commit;该 commit 不可获取则失败,不能偷换成最新 branch。 + +确认后先准备、核验完整候选目录,再原子交换;安装后重新核验版本、commit、目录摘要、Host Kit 与九个入口。 +验证失败交换恢复旧目录。交换后进程中断可用同一未过期授权重试,已完成的精确目标不重复部署。 +后续检查即使刷新当前版本、发现更高版本或因离线失败,仍可依据独立事务凭据恢复原批准目标。 +`helix-update --check` 只展示待恢复事务;正常更新入口优先完成该事务,更高版本需另行确认。 +托管目录内仅允许已登记分发文件及 Python 生成的 `__pycache__/*.pyc`。发现额外用户文件、配置、 +运行输出或其它未托管路径时拒绝升级,不读取这些文件内容,也不将它们悄悄从当前安装移入备份; +由用户将需保留的内容移到插件安装外后,再重新检查和授权。 +成功后一次性授权被消耗,旧目录保留在 `~/.cursor/helixharness/rollback/{challenge-id}`;不自动删除备份。 +任何阶段失败都保留真实错误,不能声称更新成功。重试仍须使用公共安装状态机,不直接调用内部部署函数。 + +完成后执行 Developer: Reload Window 或重启 Cursor,并新开 Agent 会话;再次确认加载路径、版本与组件。 +有同名 marketplace 安装时它优先于 local 副本,因此磁盘部署成功不等同于当前会话已切换。 + +参考文档:[插件安装](https://cursor.com/docs/plugins)、 +[插件格式](https://cursor.com/docs/reference/plugins)、 +[CLI 参数](https://cursor.com/docs/cli/reference/parameters)。桌面 IDE 按上述范围支持;本地 CLI 待独立验收,Cloud Agents 不在本期范围。 diff --git a/helixharness/hosts/cursor/lifecycle.md b/helixharness/hosts/cursor/lifecycle.md new file mode 100644 index 0000000..a733357 --- /dev/null +++ b/helixharness/hosts/cursor/lifecycle.md @@ -0,0 +1,67 @@ +# Cursor 生命周期适配 + +分发清单显式引用 `hosts/cursor/hooks.json`,宿主入口为 `hosts/cursor/hook_entry.py`。 +它只接收本宿主原生事件,绑定当前 `cursor` Host Kit,不借用另一宿主配置或转录格式。 + +- `sessionStart` 注入当前安装 Host Context,输出使用 Cursor 的 `additional_context`。 + Hook 启动不构成业务授权;薄 Skill 仍显式执行当前安装的 runtime preflight 与 Host Context 解析。 +- `beforeSubmitPrompt` 在单个 `continue=true` 响应中尽力附加本次原生身份。该兼容字段需按客户端 + 版本和界面原生验证,不能仅凭 stdout 宣称模型可见。身份只做纯字段校验,不访问文件系统、 + Git、授权或 HostRegistry;最多 64 个 roots、上下文最多 8 KiB,超限或预算耗尽只放行。 + 统计消费端仍规范化路径并验证真实仓库归属;采集在响应 flush 后继续使用同一截止时间。 +- `sessionStart` 在启动上下文完整 flush 后,尽力派发一次现有本地清理任务;不等待完成。 + 派发失败不抑制原有 lifecycle repair。它只使用本次原生 workspace roots,worker 解析到的 Git + 仓库才参与;不递归发现非 Git workspace 下的子仓,不访问未打开的其他仓库。 +- `sessionEnd` 可能缺失或在退出时无法启动命令,不能承诺关窗、关聊天或归档必然清理。 + 主动关闭授权仍立即清理当前仓库;遗漏的数据可由下次同仓 sessionStart 补扫。若仓库不再打开, + 不保证补扫发生;未知/损坏且无法证明归属的数据会保留。两次补扫均需重新确认授权仍为关闭。 +- `sessionEnd` 不是阶段完成。不注册业务 `stop`/failure 自动续跑,不读取会话文本或伪造 token。 + 它只启动一次性本地清理任务,按仓库去重并重新持锁确认当前 Cursor 授权为关闭;清理期间 + 保持授权锁,重新开启后不会被旧任务误删。会话退出不等待清理完成;锁不可用或任务失败时 + 本次清理可跳过,不创建持久重试队列。只删除明确归属本仓 Cursor 的数据,保留归属不明的 + 异常文件;不拆除其他宿主可能仍使用的全局统计调度器,也不启动采集或发送。 +- `telemetry=emulated`:统一授权开启后记录阶段账本;有有效上报地址时,原生 + `beforeSubmitPrompt`、`afterAgentResponse`、`postToolUse`、`postToolUseFailure`、 + `subagentStart`、`subagentStop` 与观察型 `stop` + 为当前活跃阶段提供私有事件 journal。它经过同一精确窗口、DLP、Archive 封口与 Outbox 投递。 + 不读取 `transcript_path`、Cursor 私有数据库、Thinking、工具原始输入输出或附件。 + 子代理仅保留原生 ID、类型、终态和时长,不保留 task/summary;按 subagent_id 去重, + 不用其 generation_id 冒充父 turn,也不把 Task 完成回调再算作一次派发。 +- `stop` 只提供实际存在的 turn usage 快照,不返回 `followup_message`、不重试、不调用业务 + finish,因此 `stop_hook=unsupported` 仍表示没有业务停止门禁。 +- 项目 hooks 由 `project-hooks.json` 定义,必须保留用户已有 hook 并幂等合并。 +- 官方 Cloud Agents 缺少桌面 session 生命周期,Cloud Agents 不在当前支持范围;CLI 需独立验收。 + +SessionStart 输出真实 `conversation_id` 和原生 `workspace_roots`,分别绑定 +`HELIXHARNESS_CURSOR_CONVERSATION_ID`、`HELIXHARNESS_CURSOR_WORKSPACE_ROOTS`(JSON 数组)。 +官方仅保证 hook 的 env 对后续 hooks 可用,因此每次 HelixHarness Shell 调用都须显式传入这两项; +身份或项目归属缺失时统计受控跳过,不借用其他宿主环境或同仓库最近会话。 + +宿主 Hook 超时保持 3 秒。同步采集使用整次调用共享的 1.5 秒预算,授权锁、Git 查询、 +journal 锁与多仓遍历消费同一截止时间。允许响应及启动上下文立即刷新到输出流;预算耗尽 +时跳过本次可选采集,不无锁读授权、不沿用旧 epoch。竞争可能导致事件缺失,统计只表示实际 +观察范围;该预算约束已知等待路径,不承诺任意文件系统或系统级卡死都能被强制中断。 + +授权缓存位于 `${HELIXHARNESS_CURSOR_HOME:-~/.cursor}/helixharness/telemetry-consent-cache.json`, +隔离覆写为 HelixHarness 自有变量。journal 位于当前仓库 `.helixharness/telemetry-v2/cursor-events/`, +按会话与授权 epoch 隔离、权限为私有;未授权或地址不可用时不采集事件正文。关闭授权清理私有 +源,最终投递后无 Entry 再引用的自有 journal 会删除,其他宿主的日志和已提交账本不删除。 + +Cursor 3.15.6 的 `afterAgentResponse` 与 `stop` 可带同一 generation 的 token 总量快照。 +按真实 conversation/generation 去重,`input_tokens` 已包含 cache,total 仅为 input + output。 +只计入起止完整落在一个阶段窗口内的 generation,范围明确为 `parent_only`;跨阶段、缺字段、 +客户端不提供或无法归属时保持 `partial/unavailable`,不填零或估算。初始 prompt 早于 start、 +最终 response 晚于 finish 的常见顺序会使该 turn token 不可归属,基础阶段与工具事件仍可上报。 +工具与交互统计表示实际观察到的 hook 事件,不宣称完整客户端会话覆盖。单 hook 输入上限 4 MiB、 +单私有 journal 上限 128 MiB;超限事件不落盘,不用零值补齐。缺失 hook、生命周期竞态和多仓 +未登记的子仓也可能减少可观察事件;多仓无 cwd 的回调仅访问原生 workspace 内已登记且具有 +同一活跃 conversation 的子仓。有 cwd 时只记录该仓;没有 cwd 且多个子仓同时活跃时不复制 +正文或数值,只记录 `ambiguous_workspace` 缺口,补充统计标为 partial/unavailable。 +不扫描其他仓库或猜测最近会话。 + +Cursor 可导入 `.claude/settings.local.json`、`.claude/settings.json`、`~/.claude/settings.json` +中的 hooks,前提是第三方导入启用。所有匹配 hook 来源可能同时运行,应检测重复安装来源;同一仓库 +存在 `.claude-plugin` 文件本身不等于已经双重安装。不得为消除重复而修改用户的全局第三方导入偏好。 + +参考:[Cursor Hooks](https://cursor.com/docs/hooks)、 +[第三方 Hooks](https://cursor.com/docs/reference/third-party-hooks)。 diff --git a/helixharness/hosts/cursor/project-hooks.json b/helixharness/hosts/cursor/project-hooks.json new file mode 100644 index 0000000..0024176 --- /dev/null +++ b/helixharness/hosts/cursor/project-hooks.json @@ -0,0 +1,16 @@ +{ + "project_hooks_version": "1.1", + "owner": "parent", + "settings_file": ".cursor/hooks.json", + "merge_strategy": "json_flat_append_dedup", + "dedupe_key": "hooks.*[].command+matcher", + "payload": { + "version": 1, + "hooks": { + "afterFileEdit": [ + {"command": "bash docs/harness/linters/invariant-check.sh 2>&1 | head -50"}, + {"command": "bash docs/harness/linters/spec-sync-check.sh 2>&1 | head -50"} + ] + } + } +} diff --git a/helixharness/hosts/cursor/project.json b/helixharness/hosts/cursor/project.json new file mode 100644 index 0000000..1aad9c3 --- /dev/null +++ b/helixharness/hosts/cursor/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": ".cursor/hooks.json" +} diff --git a/helixharness/hosts/cursor/runtime.md b/helixharness/hosts/cursor/runtime.md new file mode 100644 index 0000000..6f93dd0 --- /dev/null +++ b/helixharness/hosts/cursor/runtime.md @@ -0,0 +1,120 @@ +# Cursor 宿主运行时 + +当前 Host Context 必须显式绑定 `cursor` 和本次插件安装。首期支持桌面 IDE;本地 CLI +需单独原生验收,Cloud Agents 不在此支持范围。工具与能力以本轮 Cursor 实际提供的 schema 为准。 + +| 逻辑动作 | Cursor 映射 | +|---|---| +| `read_file` | 当前宿主的原生读取工具,完整读取指定文件 | +| `edit_file` | 当前宿主原生编辑工具,保留 sandbox、写域和单写者约束 | +| `run_command` | 原生 Shell/终端工具,保留 cwd、退出状态和实际输出 | +| `invoke_skill` | 当前安装的 Cursor Skill;内部方法完整读取唯一 canonical 正文 | +| `spawn_job` / `wait_job` | `resources.subagent_protocol` 的原生 Task 与对应完成结果 | +| `ask_user` | 本轮实际可用的交互工具;不可用时普通文本提问并等待真实回答 | +| `update_plan` | 本轮原生待办能力;不可用时维护当前 Feature `tasks.md` | +| `stage_finish` | 公共命令直接验证阶段工件;会话结束不等于阶段完成 | +| `project_entry` | 依 `resources.project_config` 合并 `AGENTS.md` | +| `project_hooks` | 父流程依 `resources.project_hooks` 幂等合并 `.cursor/hooks.json` | + +不把公共拼写当作 Cursor 工具名。尤其不调用其他宿主的私有工具、loader、环境配置或运行日志。 +额外权限必须使用 Cursor 的真实审批;不得为工作流修改全局审批模式或自动批准所有工具。 + +## canonical 方法的资源路径 + +canonical 方法正文中的 `HELIXHARNESS_PLUGIN` 只指本次已验证的 `plugin_root`。不信任继承的同名环境变量, +不搜索全局 Skill、其他版本缓存或其他宿主安装。每次 Shell 调用都须用该根路径重新绑定变量,并在同一次 +调用中执行相关命令;不依赖跨调用环境保持,也不依赖 session hook 向终端传播环境。 +对变量赋值使用 Shell 安全引用,对 `$HELIXHARNESS_PLUGIN/...` 展开后的完整路径安全引用;也可将其替换为 +本次根内的绝对路径再完整引用。赋值必须先于使用该变量的命令,不能把未绑定变量的展开留在临时环境赋值的同一命令中。 +方法正文的 `Read`、`Write`、`AskUserQuestion`、`Skill` 等公共拼写按 `reference/tool-semantics.md` +和上表映射;MCP 操作只使用当前宿主真实提供的工具 schema,不照搬其他宿主的工具前缀。 + +## 命令表面 + +本次 Cursor 公开入口使用 `/helix-{command}`。在输入框输入 `/helix-` 后选择对应 Skill; +不提供 `/helix:{command}` 原生别名或冒号前缀补全。以下左列仅为公共合同的逻辑名称。 + +| canonical 逻辑名称 | 当前 Cursor Skill | +|---|---| +| `/helix:init` | `/helix-init` | +| `/helix:propose` | `/helix-propose` | +| `/helix:apply` | `/helix-apply` | +| `/helix:archive` | `/helix-archive` | +| `/helix:bug-fix` | `/helix-bug-fix` | +| `/helix:ut` | `/helix-ut` | +| `/helix:update` | `/helix-update` | +| `/helix:status` | `/helix-status` | +| `/helix:config` | `/helix-config` | + +展示建议命令时使用此映射;`--loop` 内部继续执行 Router 返回的 canonical workflow,不依赖菜单 +名称、重新输入 slash 命令或再次调用入口 Skill。命令参数由 `skill-entry.md` 明确绑定。 +方法 Skill 是可复用方法,不增加研发阶段或新的公开工作流命令。 + +## 生命周期、统计与交互 + +统计和更新通过本 Host Kit 的 `emulated` 适配器执行同一套公共授权与业务协议。 +统计只在用户已明确开启后记录阶段、事件和可归属的用量;不读取 Cursor 私有数据库或 transcript。 +Token 仅使用原生 hook 实际提供的数字,重复 generation 快照只计一次;缺字段、跨阶段或缺少 +完整轮次边界时标记 unavailable/partial,不估算、不填 0,不把父代理用量宣称为全部子代理用量。 +`stop` 只观察事件,不触发阶段完成、自动续跑或替代 D2C 门禁。 + +每次执行 HelixHarness Python 命令时,优先使用本次 `beforeSubmitPrompt` 注入的真实绑定; +没有本次绑定时只可使用仍属于当前会话的 `sessionStart` 绑定,不能借用此前会话。 +beforeSubmitPrompt 的 additional_context 是经过受测客户端探针验证的兼容路径, +不是所有 Cursor 版本均保证的接口;实际不可见时仍按缺身份降级。 +通过工具的环境参数或 Shell 安全引用显式传入 `HELIXHARNESS_CURSOR_CONVERSATION_ID` 与 +`HELIXHARNESS_CURSOR_WORKSPACE_ROOTS`(原生 `workspace_roots` 的 JSON 数组)。这些变量只作用于 +当前命令;不得从旧进程、最近会话文件或用户输入中猜测身份。Cursor 对 hook 的环境传播不保证 +Shell 继承,必须每次绑定。缺少身份或当前仓库不在这些 roots 内时,统计受控跳过并保留原因, +业务继续,不把其他会话的 ID 借来使用。父流程传递明确的绑定与仓库范围,子任务不得扩大归属。 +授权 enabled 不代表本次采集可用。开启或首次尝试统计时,如当前模型上下文缺少真实绑定,说明 +`cursor_session_context_unavailable` 和本次统计跳过;不改授权设置,不反复打断后续业务。 +受测 Agents Window 的 sessionStart 上下文曾未进入模型,不能仅凭 Hook 输出有效就宣布统计可用。 + +主动关闭授权立即清理当前仓库的 Cursor 私有状态;sessionEnd 与下一次 sessionStart 只作尽力补扫。 +不承诺关窗即时删除,不在 stop 删除仍可能使用的 journal;保留其他宿主、公开账本及归属不明数据。 + +更新使用 `resources.installer` 登记的 Helix-managed local 安装。检查版本不改变安装;实际升级 +必须走公共 `prepare → decide → install` 的真实用户确认和一次性授权,只部署批准的来源与版本。 +未登记的副本、Cursor Marketplace 缓存不被接管。升级完成后按 installer 重载,再重新绑定宿主。 +公共业务门禁、TDD、双轴 Review、归档证据仍完整执行;统计关闭不能用作跳过门禁的理由。 + +用户决策须取得真实回答;取消、空结果、超时或默认高亮不构成授权。没有合适交互工具时用文本 +展示完整选项,并在必要决策处等待;可以先推进不依赖回答的工作。既有明确授权按命令合同复用。 +提问不构成决策完成,不能用完成摘要替代待回答问题;`--loop` 不能授权提交、推送或发布。 + +## D2C 的显式完成门禁 + +完整执行 `skills/d-d2c/SKILL.md` 正文及所选 mode 的 rules:phase 0 初始化、实际构建和 SPA +runtime 健康、设计 DSL、截图、geometry/vertical/render/overlay 联合检查、fidelity 评测与 phase 6 +清理均不可省略。`d2c-fidelity-evaluator` 仍须产出真实报告,不以投影说明代替。 + +canonical frontmatter 中的 Claude skill hooks 不在 Cursor 注册。当前适配使用可执行的显式门禁: + +1. 新 D2C 工作流先按 canonical 初始化新的 phase 0,从其 checkpoint 回执记录本次 + `pageDir`、phase 0 的 `enteredAt`。明确 `--resume` 时使用已选择恢复的同一工作流 checkpoint, + 核对这两个锚点;不得借用无关或先前已完成工作流的锚点。 +2. 任何结束当前 turn 或询问用户前,用当前真实项目根和上述锚点运行: + + ```text + node "{plugin_root}/hosts/cursor/d2c_gate.cjs" --repo-root "{repo_root}" --page-dir "{pageDir}" --started-at "{enteredAt}" --action stop + ``` + + 询问用户用 `--action ask`;headless 验收额外传 `--headless`。 + checkpoint 已绑定 owner 时还须传本次真实会话的 `--session-id`,不能从其他会话借用身份。 + 当前上下文缺少真实身份时,该 owner 完成结论不可用;不得删掉、复制或改写 owner 绕过门禁。 +3. 只接受退出码 0 且 JSON `allow=true`。`allow=false` 或脚本失败时按 `action` 继续修复/推进; + 缺 checkpoint、旧 invocation 或路径非法须恢复正确状态,不能声称完成。合法等待仍不代表完成, + 只有 `action.kind=done` 才能声明 D2C 完成。合法用户取消、外部输入或 browser handoff 保留原语义。 + 完成还必须满足当前阶段为 6,阶段 0/1/2/3/4/6 的 enteredAt/completedAt 属于本次 invocation + 且按依赖有序,阶段 4 已选择 cancel。新 phase 0 残留的旧 phase 6 不能成为完成证据; + pause 与 browser handoff 也必须有本次 invocation 内的新鲜时间证据。旧 browser handoff 在决策前忽略, + 既不能放行本轮,也不能覆盖本轮合法的 pause 或取消。 + +该 CLI 只检查本次业务 checkpoint,不读取 transcript,不声称具有原生 Stop/提问拦截能力。 +原生工具不可用或门禁不能运行时应报告阻塞;不能把检查缺失改成成功。 + + +## Cursor native update boundary + +仅 Cursor 原生安装:`check` 返回 `reason=installation_update_not_supported`、`next_action=continue_with_warning` 时,展示当前安装及手动更新步骤后结束更新流程;业务继续。不得进入 prepare/decide/install,不得改用旧 Local 缓存或授权,不把 unknown 当作已是最新。显式后续更新操作退出码为 2。此限制不改变 managed-local、Claude Code 或 Codex 的原协议。 diff --git a/helixharness/hosts/cursor/skill-entry.md b/helixharness/hosts/cursor/skill-entry.md new file mode 100644 index 0000000..e63e076 --- /dev/null +++ b/helixharness/hosts/cursor/skill-entry.md @@ -0,0 +1,56 @@ +# Cursor Skill Entry Protocol + +当前 Skill 的实际文件位于 `hosts/cursor/skills/{name}/SKILL.md`。以该文件向上四级为唯一 +`plugin_root`,所有资源都固定在这一安装内,不搜索全局同名 Skill 或其他版本缓存。 + +## 公共绑定(command 与 method 都执行) + +1. 完整读取 `reference/runtime-preflight.md` 并执行其中的 shell preflight;SessionStart 给出的 + `require && ... resolve ...` 已先执行同一检查,只有 `ok=true` 才会继续来源解析。Python 不可用时 + 遵循该协议恢复;不绕过 preflight 直接执行 Python,不以 `check` 的退出码 0 代替 JSON 就绪判定。 +2. 执行 `python3 "{plugin_root}/scripts/host_runtime_cli.py" resolve --platform cursor --expected-plugin-root "{plugin_root}"`。 + 仅接受 `status=resolved`、`host_id=cursor` 与当前安装一致的回执。资源缺失或来源不符时停止, + 不回退到另一宿主。不依赖 session hook 环境变量传播到终端。 +3. 完整读取 `reference/host-runtime-protocol.md`、`reference/tool-semantics.md` 与 `resources.runtime`。 + 后续每次 HelixHarness Python 调用按 runtime 显式绑定当前原生会话的 + `HELIXHARNESS_CURSOR_CONVERSATION_ID` 和 `HELIXHARNESS_CURSOR_WORKSPACE_ROOTS`; + 不假设 hook 环境会自动传到 Shell,不使用其他会话身份补缺。 +4. 只读解析本次实际 Skill 路径: + + ```text + python3 "{plugin_root}/scripts/cursor_skill_projection.py" --root "{plugin_root}" --resolve-entry "{当前SKILL.md绝对路径}" + ``` + + 回执 `entry_kind` 必须与薄入口声明的类型一致,`entry`、`canonical` 必须绑定当前安装。 + `command` 仅进入下方“命令入口”;`method` 仅进入“方法入口”。未知类型、失败或路径不符时停止。 + +## 命令入口(仅 entry_kind=command) + +1. 完整读取 `reference/workflow-projection-protocol.md`。入口解析器已核验 + `resources.command_projection` 的对应 command 条目;只使用回执中的唯一 `commands/{command}.md`。 +2. 将用户本次调用附带的参数文本作为公共命令的 `$ARGUMENTS`,保留原始标点、引号、换行和 + `--` 后字面参数;这是一项逻辑参数绑定,不假定 Cursor 会展开 `$ARGUMENTS`。 + 同一条用户消息中 Skill 名后的所有文本都是本次输入,包括首行参数后的换行需求正文; + 不能只取 `/helix-propose name --loop` 首行而丢弃后续描述。第一次调用 Router 前先绑定完整输入, + 不先用名称/开关试探路由,再补正文重跑;未能取得完整输入时先澄清,不猜测或截断。 + 按公共命令要求安全传参,禁止 `eval` 或拼接未经引用的用户文本。确实未提供参数时才使用空串。 +3. 完整读取回执中的 canonical 命令并执行;按需读取它声明的宿主资源。 + Router 返回唯一 workflow 后只执行该正文,不在投影层重复路由、拆解需求或补写业务步骤。 + +本次 Cursor 的公开入口统一使用 `/helix-init`、`/helix-propose` 等 `/helix-{command}` Skill 名。 +`/helix:*` 是 canonical 文档的逻辑名称,由 `runtime.md` 映射为 Cursor 的连字符入口; +用户可见的命令指引与下一步建议使用映射后的写法。本次不提供原生冒号别名或冒号前缀补全。 +参数按上述协议显式绑定,不依赖宿主自动展开。 + +## 方法入口(仅 entry_kind=method) + +1. 方法解析独立于九个 command:不查询 `command_projection` 条目,不要求 + `commands/{method}.md` 存在,也不调用 Router 或命令入口分支。 +2. 完整读取回执中的唯一 `skills/{method}/SKILL.md`,只执行其正文,忽略 Claude 专属 frontmatter。 + 原样保留方法本次输入;正文中的相对资源以该 canonical 方法目录为基准。 + 正文中的 `HELIXHARNESS_PLUGIN` 必须绑定本次已验证的 `plugin_root`,每次 Shell 调用遵循 + `resources.runtime` 的独立绑定与完整路径安全引用规则,不继承旧变量或搜索其他安装。 +3. 按方法需要读取公共子代理协议、`resources.subagent_protocol` 及其它已声明资源,保留实际 + 步骤和门禁。D2C 的显式 checkpoint 门禁按 `resources.runtime` 执行。 + +参考:[Cursor Skills](https://cursor.com/docs/skills)。 diff --git a/helixharness/hosts/cursor/skills/helix-apply/SKILL.md b/helixharness/hosts/cursor/skills/helix-apply/SKILL.md new file mode 100644 index 0000000..42cd98d --- /dev/null +++ b/helixharness/hosts/cursor/skills/helix-apply/SKILL.md @@ -0,0 +1,11 @@ +--- +name: helix-apply +description: "执行任务、验证并完成双轴代码评审。" +disable-model-invocation: true +--- + +# Cursor command projection: apply + +入口类型:`command`。插件根固定为当前文件的 `../../../..`。完整读取 `hosts/cursor/skill-entry.md`,执行“公共绑定”后仅执行“命令入口”分支;完成 runtime preflight,以 `--platform cursor` 显式解析同一安装的 Host Context。 + +当前逻辑命令为 `apply`,原生 Skill 名为 `helix-apply`。按入口协议绑定本次用户参数为 `$ARGUMENTS`,然后完整读取并执行唯一公共契约 `commands/apply.md`;不复制业务步骤,不重新发现插件,不把建议命令当成自动授权。 diff --git a/helixharness/hosts/cursor/skills/helix-archive/SKILL.md b/helixharness/hosts/cursor/skills/helix-archive/SKILL.md new file mode 100644 index 0000000..62a33e7 --- /dev/null +++ b/helixharness/hosts/cursor/skills/helix-archive/SKILL.md @@ -0,0 +1,11 @@ +--- +name: helix-archive +description: "校验完成证据,更新知识并归档需求。" +disable-model-invocation: true +--- + +# Cursor command projection: archive + +入口类型:`command`。插件根固定为当前文件的 `../../../..`。完整读取 `hosts/cursor/skill-entry.md`,执行“公共绑定”后仅执行“命令入口”分支;完成 runtime preflight,以 `--platform cursor` 显式解析同一安装的 Host Context。 + +当前逻辑命令为 `archive`,原生 Skill 名为 `helix-archive`。按入口协议绑定本次用户参数为 `$ARGUMENTS`,然后完整读取并执行唯一公共契约 `commands/archive.md`;不复制业务步骤,不重新发现插件,不把建议命令当成自动授权。 diff --git a/helixharness/hosts/cursor/skills/helix-brainstorming/SKILL.md b/helixharness/hosts/cursor/skills/helix-brainstorming/SKILL.md new file mode 100644 index 0000000..5610034 --- /dev/null +++ b/helixharness/hosts/cursor/skills/helix-brainstorming/SKILL.md @@ -0,0 +1,11 @@ +--- +name: helix-brainstorming +description: "用户独立调用的方案探索工具。澄清问题与约束,比较可行方案并给出推荐方向,不由研发命令自动触发。" +disable-model-invocation: true +--- + +# Cursor method projection: brainstorming + +入口类型:`method`。插件根固定为当前文件的 `../../../..`。完整读取 `hosts/cursor/skill-entry.md`,执行“公共绑定”后仅执行“方法入口”分支;不查询命令投影、不加载 commands 文件、不调用 Router。执行 runtime preflight 并以 `--platform cursor` 解析同一安装的 Host Context。完整读取 `reference/host-runtime-protocol.md`、`reference/tool-semantics.md` 和 `resources.runtime`;需要子 agent 时再读取公共子代理协议及 `resources.subagent_protocol`。 + +完整读取并执行唯一 canonical 方法 `skills/brainstorming/SKILL.md` 的正文。canonical frontmatter 不属于 Cursor 元数据,不装载其中的 Claude hooks、工具声明或调用标记。正文相对资源从 `skills/brainstorming/` 解析;不得改以投影目录为基准。保留实际步骤、输出工件与全部门禁,不复制或改写业务语义,不扫描全局同名 Skill。 diff --git a/helixharness/hosts/cursor/skills/helix-bug-fix/SKILL.md b/helixharness/hosts/cursor/skills/helix-bug-fix/SKILL.md new file mode 100644 index 0000000..37c6da7 --- /dev/null +++ b/helixharness/hosts/cursor/skills/helix-bug-fix/SKILL.md @@ -0,0 +1,11 @@ +--- +name: helix-bug-fix +description: "修订未归档需求并复用原 Apply 基线。" +disable-model-invocation: true +--- + +# Cursor command projection: bug-fix + +入口类型:`command`。插件根固定为当前文件的 `../../../..`。完整读取 `hosts/cursor/skill-entry.md`,执行“公共绑定”后仅执行“命令入口”分支;完成 runtime preflight,以 `--platform cursor` 显式解析同一安装的 Host Context。 + +当前逻辑命令为 `bug-fix`,原生 Skill 名为 `helix-bug-fix`。按入口协议绑定本次用户参数为 `$ARGUMENTS`,然后完整读取并执行唯一公共契约 `commands/bug-fix.md`;不复制业务步骤,不重新发现插件,不把建议命令当成自动授权。 diff --git a/helixharness/hosts/cursor/skills/helix-code-review/SKILL.md b/helixharness/hosts/cursor/skills/helix-code-review/SKILL.md new file mode 100644 index 0000000..ebe2bd9 --- /dev/null +++ b/helixharness/hosts/cursor/skills/helix-code-review/SKILL.md @@ -0,0 +1,11 @@ +--- +name: helix-code-review +description: "为 HelixHarness Apply 评审固定比较点之后的代码变化;并行执行 Standards 与 Spec 两个独立评审轴,分轴报告结果,并按 HelixHarness 合同完成修复和复审。" +disable-model-invocation: false +--- + +# Cursor method projection: code-review + +入口类型:`method`。插件根固定为当前文件的 `../../../..`。完整读取 `hosts/cursor/skill-entry.md`,执行“公共绑定”后仅执行“方法入口”分支;不查询命令投影、不加载 commands 文件、不调用 Router。执行 runtime preflight 并以 `--platform cursor` 解析同一安装的 Host Context。完整读取 `reference/host-runtime-protocol.md`、`reference/tool-semantics.md` 和 `resources.runtime`;需要子 agent 时再读取公共子代理协议及 `resources.subagent_protocol`。 + +完整读取并执行唯一 canonical 方法 `skills/code-review/SKILL.md` 的正文。canonical frontmatter 不属于 Cursor 元数据,不装载其中的 Claude hooks、工具声明或调用标记。正文相对资源从 `skills/code-review/` 解析;不得改以投影目录为基准。保留实际步骤、输出工件与全部门禁,不复制或改写业务语义,不扫描全局同名 Skill。 diff --git a/helixharness/hosts/cursor/skills/helix-config/SKILL.md b/helixharness/hosts/cursor/skills/helix-config/SKILL.md new file mode 100644 index 0000000..50cff48 --- /dev/null +++ b/helixharness/hosts/cursor/skills/helix-config/SKILL.md @@ -0,0 +1,11 @@ +--- +name: helix-config +description: "查看或修改 HelixHarness 用户配置:统计授权、作用范围、统计与反馈上报地址。" +disable-model-invocation: true +--- + +# Cursor command projection: config + +入口类型:`command`。插件根固定为当前文件的 `../../../..`。完整读取 `hosts/cursor/skill-entry.md`,执行“公共绑定”后仅执行“命令入口”分支;完成 runtime preflight,以 `--platform cursor` 显式解析同一安装的 Host Context。 + +当前逻辑命令为 `config`,原生 Skill 名为 `helix-config`。按入口协议绑定本次用户参数为 `$ARGUMENTS`,然后完整读取并执行唯一公共契约 `commands/config.md`;不复制业务步骤,不重新发现插件,不把建议命令当成自动授权。 diff --git a/helixharness/hosts/cursor/skills/helix-d-d2c/SKILL.md b/helixharness/hosts/cursor/skills/helix-d-d2c/SKILL.md new file mode 100644 index 0000000..1706318 --- /dev/null +++ b/helixharness/hosts/cursor/skills/helix-d-d2c/SKILL.md @@ -0,0 +1,13 @@ +--- +name: helix-d-d2c +description: "用户提到 d-d2c、设计稿还原、MasterGo、贴图比对、design-to-code、页面开发,或使用 d-d2c --create-page / --update-page / --component 时,按这个 skill 要求执行;支持新建整页、更新已有页、组件/弹层/卡片三种流程入口,后两者分别读取 rules/d-d2c-update-page.md / rules/d-d2c-component.md 作为流程覆盖层" +disable-model-invocation: false +--- + +# Cursor method projection: d-d2c + +入口类型:`method`。插件根固定为当前文件的 `../../../..`。完整读取 `hosts/cursor/skill-entry.md`,执行“公共绑定”后仅执行“方法入口”分支;不查询命令投影、不加载 commands 文件、不调用 Router。执行 runtime preflight 并以 `--platform cursor` 解析同一安装的 Host Context。完整读取 `reference/host-runtime-protocol.md`、`reference/tool-semantics.md` 和 `resources.runtime`;需要子 agent 时再读取公共子代理协议及 `resources.subagent_protocol`。 + +完整读取并执行唯一 canonical 方法 `skills/d-d2c/SKILL.md` 的正文。canonical frontmatter 不属于 Cursor 元数据,不装载其中的 Claude hooks、工具声明或调用标记。正文相对资源从 `skills/d-d2c/` 解析;不得改以投影目录为基准。保留实际步骤、输出工件与全部门禁,不复制或改写业务语义,不扫描全局同名 Skill。 + +D2C 必须执行 mode 对应的完整 canonical workflow、实际 runtime 健康与截图联合检查、fidelity 评测和 phase 6。新 phase 0 后记录本次 `pageDir` 与 `enteredAt`;在任何用户询问或结束前执行 `resources.runtime` 规定的 `hosts/cursor/d2c_gate.cjs`,分别使用 `--action ask` 或 `--action stop`。只有退出码 0 且 `allow=true` 可询问/结束;只有 `action.kind=done` 可宣称完成。不把缺少原生 skill hook 当作省略门禁的理由。 diff --git a/helixharness/hosts/cursor/skills/helix-d2c-fidelity-evaluator/SKILL.md b/helixharness/hosts/cursor/skills/helix-d2c-fidelity-evaluator/SKILL.md new file mode 100644 index 0000000..e2fb648 --- /dev/null +++ b/helixharness/hosts/cursor/skills/helix-d2c-fidelity-evaluator/SKILL.md @@ -0,0 +1,11 @@ +--- +name: helix-d2c-fidelity-evaluator +description: "Evaluate design-to-code fidelity for a generated page by comparing design inputs and implementation outputs. Use when the user provides or references a design screenshot, design DSL, source code, rendered page screenshot, and optionally a transparent design-over-render overlay image, and wants a restoration/fidelity percentage plus an actionable report that can drive the next D2C optimization pass." +disable-model-invocation: false +--- + +# Cursor method projection: d2c-fidelity-evaluator + +入口类型:`method`。插件根固定为当前文件的 `../../../..`。完整读取 `hosts/cursor/skill-entry.md`,执行“公共绑定”后仅执行“方法入口”分支;不查询命令投影、不加载 commands 文件、不调用 Router。执行 runtime preflight 并以 `--platform cursor` 解析同一安装的 Host Context。完整读取 `reference/host-runtime-protocol.md`、`reference/tool-semantics.md` 和 `resources.runtime`;需要子 agent 时再读取公共子代理协议及 `resources.subagent_protocol`。 + +完整读取并执行唯一 canonical 方法 `skills/d2c-fidelity-evaluator/SKILL.md` 的正文。canonical frontmatter 不属于 Cursor 元数据,不装载其中的 Claude hooks、工具声明或调用标记。正文相对资源从 `skills/d2c-fidelity-evaluator/` 解析;不得改以投影目录为基准。保留实际步骤、输出工件与全部门禁,不复制或改写业务语义,不扫描全局同名 Skill。 diff --git a/helixharness/hosts/cursor/skills/helix-feedback/SKILL.md b/helixharness/hosts/cursor/skills/helix-feedback/SKILL.md new file mode 100644 index 0000000..16ba2b8 --- /dev/null +++ b/helixharness/hosts/cursor/skills/helix-feedback/SKILL.md @@ -0,0 +1,11 @@ +--- +name: helix-feedback +description: "HelixHarness 使用问题反馈通道。当用户在 /helix:* 命令与工作流中遇到问题并表现出困扰时主动使用:命令反复失败或报错无法推进、生成的文档/字段/结构与用户预期不符、流程在某一步卡住不动、用户对 HelixHarness 表达不满困惑或抱怨、放弃工作流改用手工方式,或明确要求提交反馈。此时向用户建议提交反馈,发送前必须经用户确认。不触发:用户业务代码的问题、与 HelixHarness 无关的报错、一般使用咨询、模型已自行修复的故障。" +disable-model-invocation: false +--- + +# Cursor method projection: feedback + +入口类型:`method`。插件根固定为当前文件的 `../../../..`。完整读取 `hosts/cursor/skill-entry.md`,执行“公共绑定”后仅执行“方法入口”分支;不查询命令投影、不加载 commands 文件、不调用 Router。执行 runtime preflight 并以 `--platform cursor` 解析同一安装的 Host Context。完整读取 `reference/host-runtime-protocol.md`、`reference/tool-semantics.md` 和 `resources.runtime`;需要子 agent 时再读取公共子代理协议及 `resources.subagent_protocol`。 + +完整读取并执行唯一 canonical 方法 `skills/feedback/SKILL.md` 的正文。canonical frontmatter 不属于 Cursor 元数据,不装载其中的 Claude hooks、工具声明或调用标记。正文相对资源从 `skills/feedback/` 解析;不得改以投影目录为基准。保留实际步骤、输出工件与全部门禁,不复制或改写业务语义,不扫描全局同名 Skill。 diff --git a/helixharness/hosts/cursor/skills/helix-git-diff-impact/SKILL.md b/helixharness/hosts/cursor/skills/helix-git-diff-impact/SKILL.md new file mode 100644 index 0000000..e2d646f --- /dev/null +++ b/helixharness/hosts/cursor/skills/helix-git-diff-impact/SKILL.md @@ -0,0 +1,11 @@ +--- +name: helix-git-diff-impact +description: "分析指定 Git 改动的调用链、业务影响和兼容性风险,生成影响报告。用户主动要求影响分析时单独使用,无需 HelixHarness feature。" +disable-model-invocation: true +--- + +# Cursor method projection: git-diff-impact + +入口类型:`method`。插件根固定为当前文件的 `../../../..`。完整读取 `hosts/cursor/skill-entry.md`,执行“公共绑定”后仅执行“方法入口”分支;不查询命令投影、不加载 commands 文件、不调用 Router。执行 runtime preflight 并以 `--platform cursor` 解析同一安装的 Host Context。完整读取 `reference/host-runtime-protocol.md`、`reference/tool-semantics.md` 和 `resources.runtime`;需要子 agent 时再读取公共子代理协议及 `resources.subagent_protocol`。 + +完整读取并执行唯一 canonical 方法 `skills/git-diff-impact/SKILL.md` 的正文。canonical frontmatter 不属于 Cursor 元数据,不装载其中的 Claude hooks、工具声明或调用标记。正文相对资源从 `skills/git-diff-impact/` 解析;不得改以投影目录为基准。保留实际步骤、输出工件与全部门禁,不复制或改写业务语义,不扫描全局同名 Skill。 diff --git a/helixharness/hosts/cursor/skills/helix-init/SKILL.md b/helixharness/hosts/cursor/skills/helix-init/SKILL.md new file mode 100644 index 0000000..7d307ad --- /dev/null +++ b/helixharness/hosts/cursor/skills/helix-init/SKILL.md @@ -0,0 +1,11 @@ +--- +name: helix-init +description: "HelixHarness 初始化入口。默认初始化单服务仓库;传入 --workspace 时初始化多仓 workspace,并生成 workspace registry 与服务关系基线。" +disable-model-invocation: true +--- + +# Cursor command projection: init + +入口类型:`command`。插件根固定为当前文件的 `../../../..`。完整读取 `hosts/cursor/skill-entry.md`,执行“公共绑定”后仅执行“命令入口”分支;完成 runtime preflight,以 `--platform cursor` 显式解析同一安装的 Host Context。 + +当前逻辑命令为 `init`,原生 Skill 名为 `helix-init`。按入口协议绑定本次用户参数为 `$ARGUMENTS`,然后完整读取并执行唯一公共契约 `commands/init.md`;不复制业务步骤,不重新发现插件,不把建议命令当成自动授权。 diff --git a/helixharness/hosts/cursor/skills/helix-propose/SKILL.md b/helixharness/hosts/cursor/skills/helix-propose/SKILL.md new file mode 100644 index 0000000..43ee898 --- /dev/null +++ b/helixharness/hosts/cursor/skills/helix-propose/SKILL.md @@ -0,0 +1,11 @@ +--- +name: helix-propose +description: "收敛需求并生成 Spec/Tasks;--loop 自动串联至 Archive。" +disable-model-invocation: true +--- + +# Cursor command projection: propose + +入口类型:`command`。插件根固定为当前文件的 `../../../..`。完整读取 `hosts/cursor/skill-entry.md`,执行“公共绑定”后仅执行“命令入口”分支;完成 runtime preflight,以 `--platform cursor` 显式解析同一安装的 Host Context。 + +当前逻辑命令为 `propose`,原生 Skill 名为 `helix-propose`。按入口协议绑定本次用户参数为 `$ARGUMENTS`,然后完整读取并执行唯一公共契约 `commands/propose.md`;不复制业务步骤,不重新发现插件,不把建议命令当成自动授权。 diff --git a/helixharness/hosts/cursor/skills/helix-status/SKILL.md b/helixharness/hosts/cursor/skills/helix-status/SKILL.md new file mode 100644 index 0000000..4c4dc25 --- /dev/null +++ b/helixharness/hosts/cursor/skills/helix-status/SKILL.md @@ -0,0 +1,11 @@ +--- +name: helix-status +description: "只读查看需求阶段、任务进度、阻塞原因和下一步命令。" +disable-model-invocation: true +--- + +# Cursor command projection: status + +入口类型:`command`。插件根固定为当前文件的 `../../../..`。完整读取 `hosts/cursor/skill-entry.md`,执行“公共绑定”后仅执行“命令入口”分支;完成 runtime preflight,以 `--platform cursor` 显式解析同一安装的 Host Context。 + +当前逻辑命令为 `status`,原生 Skill 名为 `helix-status`。按入口协议绑定本次用户参数为 `$ARGUMENTS`,然后完整读取并执行唯一公共契约 `commands/status.md`;不复制业务步骤,不重新发现插件,不把建议命令当成自动授权。 diff --git a/helixharness/hosts/cursor/skills/helix-systematic-debugging/SKILL.md b/helixharness/hosts/cursor/skills/helix-systematic-debugging/SKILL.md new file mode 100644 index 0000000..c874edf --- /dev/null +++ b/helixharness/hosts/cursor/skills/helix-systematic-debugging/SKILL.md @@ -0,0 +1,11 @@ +--- +name: helix-systematic-debugging +description: "用户独立调用的调试工具。复现异常、缩小范围、验证假设并定位根因,按用户授权修复和验证,不由研发命令自动触发。" +disable-model-invocation: true +--- + +# Cursor method projection: systematic-debugging + +入口类型:`method`。插件根固定为当前文件的 `../../../..`。完整读取 `hosts/cursor/skill-entry.md`,执行“公共绑定”后仅执行“方法入口”分支;不查询命令投影、不加载 commands 文件、不调用 Router。执行 runtime preflight 并以 `--platform cursor` 解析同一安装的 Host Context。完整读取 `reference/host-runtime-protocol.md`、`reference/tool-semantics.md` 和 `resources.runtime`;需要子 agent 时再读取公共子代理协议及 `resources.subagent_protocol`。 + +完整读取并执行唯一 canonical 方法 `skills/systematic-debugging/SKILL.md` 的正文。canonical frontmatter 不属于 Cursor 元数据,不装载其中的 Claude hooks、工具声明或调用标记。正文相对资源从 `skills/systematic-debugging/` 解析;不得改以投影目录为基准。保留实际步骤、输出工件与全部门禁,不复制或改写业务语义,不扫描全局同名 Skill。 diff --git a/helixharness/hosts/cursor/skills/helix-tdd/SKILL.md b/helixharness/hosts/cursor/skills/helix-tdd/SKILL.md new file mode 100644 index 0000000..b2440fc --- /dev/null +++ b/helixharness/hosts/cursor/skills/helix-tdd/SKILL.md @@ -0,0 +1,11 @@ +--- +name: helix-tdd +description: "为 HelixHarness feature 或 Bug Fix 的可观察行为改动执行测试驱动开发;在 Spec 已确认的公共测试 seam 上按红灯 → 绿灯的垂直切片实现,并生成可长期保留、对重构稳定的测试。" +disable-model-invocation: false +--- + +# Cursor method projection: tdd + +入口类型:`method`。插件根固定为当前文件的 `../../../..`。完整读取 `hosts/cursor/skill-entry.md`,执行“公共绑定”后仅执行“方法入口”分支;不查询命令投影、不加载 commands 文件、不调用 Router。执行 runtime preflight 并以 `--platform cursor` 解析同一安装的 Host Context。完整读取 `reference/host-runtime-protocol.md`、`reference/tool-semantics.md` 和 `resources.runtime`;需要子 agent 时再读取公共子代理协议及 `resources.subagent_protocol`。 + +完整读取并执行唯一 canonical 方法 `skills/tdd/SKILL.md` 的正文。canonical frontmatter 不属于 Cursor 元数据,不装载其中的 Claude hooks、工具声明或调用标记。正文相对资源从 `skills/tdd/` 解析;不得改以投影目录为基准。保留实际步骤、输出工件与全部门禁,不复制或改写业务语义,不扫描全局同名 Skill。 diff --git a/helixharness/hosts/cursor/skills/helix-update/SKILL.md b/helixharness/hosts/cursor/skills/helix-update/SKILL.md new file mode 100644 index 0000000..4277f16 --- /dev/null +++ b/helixharness/hosts/cursor/skills/helix-update/SKILL.md @@ -0,0 +1,11 @@ +--- +name: helix-update +description: "检查并升级 HelixHarness plugin。通过 Host Kit 识别安装版本、展示更新内容,并在用户授权后执行当前宿主的更新适配器。" +disable-model-invocation: true +--- + +# Cursor command projection: update + +入口类型:`command`。插件根固定为当前文件的 `../../../..`。完整读取 `hosts/cursor/skill-entry.md`,执行“公共绑定”后仅执行“命令入口”分支;完成 runtime preflight,以 `--platform cursor` 显式解析同一安装的 Host Context。 + +当前逻辑命令为 `update`,原生 Skill 名为 `helix-update`。按入口协议绑定本次用户参数为 `$ARGUMENTS`,然后完整读取并执行唯一公共契约 `commands/update.md`;不复制业务步骤,不重新发现插件,不把建议命令当成自动授权。 diff --git a/helixharness/hosts/cursor/skills/helix-ut/SKILL.md b/helixharness/hosts/cursor/skills/helix-ut/SKILL.md new file mode 100644 index 0000000..a3f8940 --- /dev/null +++ b/helixharness/hosts/cursor/skills/helix-ut/SKILL.md @@ -0,0 +1,11 @@ +--- +name: helix-ut +description: "单元测试生成与维护命令。基于知识库和活跃需求,逐层扫描代码并生成/维护单测,运行验证并检查逻辑缺陷,确保覆盖率达标。" +disable-model-invocation: true +--- + +# Cursor command projection: ut + +入口类型:`command`。插件根固定为当前文件的 `../../../..`。完整读取 `hosts/cursor/skill-entry.md`,执行“公共绑定”后仅执行“命令入口”分支;完成 runtime preflight,以 `--platform cursor` 显式解析同一安装的 Host Context。 + +当前逻辑命令为 `ut`,原生 Skill 名为 `helix-ut`。按入口协议绑定本次用户参数为 `$ARGUMENTS`,然后完整读取并执行唯一公共契约 `commands/ut.md`;不复制业务步骤,不重新发现插件,不把建议命令当成自动授权。 diff --git a/helixharness/hosts/cursor/subagent.md b/helixharness/hosts/cursor/subagent.md new file mode 100644 index 0000000..f4147e9 --- /dev/null +++ b/helixharness/hosts/cursor/subagent.md @@ -0,0 +1,40 @@ +# Cursor 子代理适配 + +遵守 `reference/subagent-runtime-protocol.md` 与当前命令 Dispatch Contract。Cursor 使用本轮实际 +暴露的 Task/子 agent 工具,不复制其他宿主的参数。角色 prompt 来自当前插件的 `prompt_source`, +不依赖自动导入的同名全局角色。官方支持独立上下文和前台/后台任务,不构成当前安装的验收证据。 + +```text +apply_shared_write_mode: parent_finalize +ut_experience_write_mode: parent_finalize +result_encoding: native_agent_result +``` + +- 显式传递 `job_id`、prompt、依赖、`ownership_root`、read/write/forbidden scope、预期产物与验证。 + 子 agent 默认不继承会话;必须提供完整必要上下文,不能让它搜索父会话或猜测资源来源。 +- 每次派发保留当前命令 Dispatch Contract 解析后的 `delegation_policy`;未声明时使用 + `delegation_policy=leaf`,此时子 agent 不得继续递归。命令明确声明 + `delegation_policy=may_delegate` 时保留该授权,例如 Workspace Apply 的每仓 job 必须执行 + 本仓 Single Apply 并派发两个独立 Review 轴,不能被宿主适配器一律降为 leaf。 + 交互映射为 `interaction_mode=afk`,待决策事实回传父流程,子 agent 不直接提问或扩大权限。 + 共享文件由父流程验证后串行写入。 +- `may_delegate` 只允许当前命令明确要求的子任务,不是任意递归授权。子任务的 `read_scope` + 必须是该 job 已解析范围的子集;reviewer 的 `write_scope=none`,reviewer 自身使用 + `delegation_policy=leaf`。依赖仓库的只读权限不能转成写入权限,也不能读取未授权的兄弟仓库。 + 父流程发现越界读取时拒绝成功结果并返回 `BLOCKED: agent_read_scope_violation`;越界写入同样 + 拒绝结果并按当前命令的 blocked 语义收口。 +- 通用角色按当前 Cursor schema 选择 general-purpose 等价能力;不硬编码 Claude 类型名。 + 原生只读开关可用时为 reviewer 开启,并始终声明 `write_scope=none`。 +- 保留 command-local job 数量和两个独立 Review 轴。只有读任务或互斥写域可以并行;没有安全的 + 并行能力时遵守命令的 fallback,不把多角色合并成一份自评。 +- 前台任务返回后立即验证真实终态和 result;后台任务使用实际提供的完成事件/结果读取工具。 + 不用文件出现、静默时长或普通文字替代终态,不重复派发仍运行的 job。 +- 父流程从原生 result 映射业务身份、状态、written paths、validation 与错误,并复核 diff 和产物。 + 文本自报不能覆盖失败/取消;未知终态保持未完成。运行 handle 仅保存在 invocation 内存。 +- 原生失败或取消停止新的任务准入并按 `BLOCKED: agent_failed` 安全收口。容量暂满不触发内联重试; + 只有明确能力不可用且 command-local contract 允许时,才按同一 prompt 内联并执行相同验证。 + `may_delegate` 也不证明当前 Cursor 模式实际提供嵌套 Task 能力。必要 reviewer 无法派发且没有 + 命令允许的等价降级时返回 `BLOCKED: cursor_subagent_unavailable`;不能把两个独立 Review 轴合并 + 为子流程自评、伪造完成结果,或仅凭已有报告跳过真实终态和验证。 + +参考:[Cursor Subagents](https://cursor.com/docs/subagents)。 diff --git a/helixharness/hosts/cursor/ut.md b/helixharness/hosts/cursor/ut.md new file mode 100644 index 0000000..2544979 --- /dev/null +++ b/helixharness/hosts/cursor/ut.md @@ -0,0 +1,26 @@ +# Cursor UT 运行适配 + +本资源只映射 [公共 UT 命令](../../commands/ut.md) 的宿主动作。扫描、6 Loop、重试、覆盖率、 +缺陷分级和报告均完整执行 canonical;通用派发和终态消费服从 `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 +``` + +权限准备只验证当前 workspace、worker 临时目录和必要构建工具;需要授权时调用 Cursor 真实审批。 +不修改 `.claude/settings.local.json`、其他宿主配置或 Cursor 全局自动批准设置。没有本次权限改动, +清理为 `not_required`,不删除用户设置。 + +每个 worker 映射为 `ut_worker_` 逻辑 job,并完整读取当前安装的 +`agents/unit-test-worker.md`。只授权 worker 自己的临时目录、result/defects、唯一目标测试文件; +业务源码、构建配置、共享 queue/session/summary/experience 与其他 worker 路径禁止写入。 +冲突目标测试或 fixture 必须串行,任务数和验证要求不变。 + +原生 Task 终态后父流程校验 result、defects、目标测试、6 Loop、覆盖率和写域,再更新队列。 +队列的 Agent ID 写 `-`,运行 handle 不持久化。经验摘要由 worker 返回,父流程验证后串行原子合并。 +失败、取消或越界不当成成功;恢复时不能验证的旧 `in_progress` 重新归为 `pending`。 +只有确认子代理能力不可用且公共命令允许时才内联一次,记录 `WARN:cursor_subagent_unavailable`。 diff --git a/helixharness/hosts/cursor/workflow-transition.md b/helixharness/hosts/cursor/workflow-transition.md new file mode 100644 index 0000000..c62a2fd --- /dev/null +++ b/helixharness/hosts/cursor/workflow-transition.md @@ -0,0 +1,10 @@ +# Cursor 工作流跳转适配 + +模式:`inline`。Propose `--loop` 在当前主 agent 内按 Router 返回值依次执行唯一 +`workflows/single/*.md` 或 `workflows/workspace/*.md`。保留 feature、execution_scope、trigger +和 workflow_arguments;不依赖原生 slash namespace,不嵌套调用另一入口 Skill。 + +Apply 的双轴评审完整执行 `skills/code-review/SKILL.md`,按当前子代理协议派发 Standards 与 Spec +两个独立只读角色。Review 属于 Apply,不创建另一个阶段。TDD、修复、复审与归档证据保持完整。 +统计关闭、缺少会话身份或采集失败仅影响可选统计;阶段工件、依赖和实际测试仍决定完成与续跑。 +blocked/失败按公共合同停止,不把 `stop` 或 `sessionEnd` 当作业务完成,也不自动重试失败 job。 diff --git a/helixharness/hosts/host-manifest-v1.schema.json b/helixharness/hosts/host-manifest-v1.schema.json index fc3d1b6..33ce68d 100644 --- a/helixharness/hosts/host-manifest-v1.schema.json +++ b/helixharness/hosts/host-manifest-v1.schema.json @@ -17,7 +17,7 @@ "pattern": "^[a-z0-9][a-z0-9._-]{0,63}$" }, "host_api_version": { - "enum": ["1.1"] + "enum": ["1.1", "1.2"] }, "aliases": { "type": "array", @@ -81,7 +81,7 @@ { "if": { "properties": { - "host_api_version": {"const": "1.1"} + "host_api_version": {"enum": ["1.1", "1.2"]} } }, "then": { diff --git a/helixharness/reference/eval-protocol.md b/helixharness/reference/eval-protocol.md index c85bc8f..00fb7a3 100644 --- a/helixharness/reference/eval-protocol.md +++ b/helixharness/reference/eval-protocol.md @@ -23,17 +23,20 @@ Usage telemetry 只有 `enabled` 和 `disabled` 两档,默认 `disabled`。 ```text Claude Code: ${CLAUDE_CONFIG_DIR:-$HOME/.claude}/helixharness/telemetry-consent-cache.json Codex: ${CODEX_HOME:-$HOME/.codex}/helixharness/telemetry-consent-cache.json +Cursor: ${HELIXHARNESS_CURSOR_HOME:-$HOME/.cursor}/helixharness/telemetry-consent-cache.json ``` 用户主动查询和修改配置使用 `/helix:config`,通过 `scripts/user_config.py` 复用本协议 API;默认查看不触发 CLI resolve 的清理副作用,显式修改仍由既有授权 API 管理 scope、epoch 和清理。 +Config 开启统计使用两阶段 CLI:首次明确开启请求返回只读 `notice_required` 和本文件固定说明,不改授权;Agent 先在单独用户可见消息中逐字展示 `notice.text`,下一次调用才附加内部 `--telemetry-notice-shown {notice.sha256}` 与 `--user-confirmed` 执行。说明 digest 只核对内容版本,不能证明 UI 已展示,也不代替用户授权;旧 digest 不允许开启。不得并行或合并准备与修改调用,不通过直接 set/choose 绕过 Config 入口。关闭、地址设置与普通查询不需要此内部标记;Init/Propose 保持各自既有授权交互合同。 + 缓存必须由 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..38859da 100644 --- a/helixharness/reference/eval-supplement-protocol.md +++ b/helixharness/reference/eval-supplement-protocol.md @@ -29,7 +29,9 @@ 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 与 Cursor 均注册 Adapter。CLI 输入仅做大小写规范化,并接受已安装 manifest 明确声明的 aliases;不能根据模型名、包装标签或包含 `claude` / `codex` 的子串猜测宿主。公开 Ledger 与 Supplement 始终只落 canonical ID。Cursor 通过授权后的原生 hooks 维护自有事件源,不读取私有数据库或 transcript。会话身份和 workspace roots 必须来自当前 sessionStart,显式绑定每次命令;缺失时按 `cursor_session_context_unavailable` 跳过本次统计,业务继续。新增统计能力在 `scripts/telemetry_hosts/` 实现 `HostAdapter`(含统一 Supplement 窗口),由 Host Kit manifest 绑定;不得修改业务正文,也不得在 Ledger、Collector 或 Schema 中增加平台分支。 + +Cursor 的输入/输出 Token 只使用原生 hook 中实际存在的非负整数,同一 conversation/generation 的 afterAgentResponse 与 stop 快照去重。只有完整落在阶段内的轮次才数值归属;正常单轮命令的 prompt 可能早于 start、终值晚于 finish,不能伪造阶段差值。用量保留 `collection_status=collected|partial|unavailable`、`unavailable_reason`、`scope=parent_only`、`attribution=complete_generations_within_stage`、`input_tokens_include_cache=true` 与 `generations`。缓存是 input 的明细,total=input+output;不把缺失计数填成 0,也不把父代理数值称为子代理总量。基础阶段/工具统计仍可用,平台部分采集显示小计并保留范围与原因。 同一 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..86f0c3e 100644 --- a/helixharness/reference/host-api.md +++ b/helixharness/reference/host-api.md @@ -1,6 +1,6 @@ -# HelixHarness Host API 1.1 +# HelixHarness Host API 1.1 / 1.2 -HelixHarness 当前只发布 Claude Code 与 Codex 两个 Host Kit。公共业务契约与宿主运行机制保持解耦: +HelixHarness 提供 Claude Code、Codex 和 Cursor Host Kit。公共业务契约与宿主运行机制保持解耦: `commands/`、`workflows/`、共享 `skills/`、`agents/` 和 `templates/` 定义业务结果,`hosts/{host-id}/` 只定义如何在某个宿主中安装、发现和执行。 @@ -14,9 +14,11 @@ HelixHarness 当前只发布 Claude Code 与 Codex 两个 Host Kit。公共业 - `claude-code`:原生命令、Hook 生命周期、原生 Agent、Claude marketplace; - `codex`:Skill 命令投影、独立启动/结束 Hook 与命令驱动阶段生命周期、Codex subagent、Codex marketplace。 +- `cursor`:独立 Skill 投影、Cursor 原生 hooks、Task 子代理与 Cursor plugin 分发;Stable(桌面范围)。 -两者使用 Host API 1.1,支持等级均为 Stable。仓库不提供其他平台的 manifest、安装器、分发清单、 -运行时适配器或入口文件。未知宿主必须关闭失败,不能回退到 Claude Code 或借用 Codex 资源。 +Claude Code 与 Codex 保持 Host API 1.1 / Stable;Cursor 使用向后兼容的 1.2 / Stable。 +Cursor 的会话统计和插件更新为 `emulated`:原生 hook 提供有边界的事件/用量证据,登记的托管本地安装通过批准后的原子交换升级。本次正式支持范围为桌面研发工作流;原生自动升级等限制与已接受的验证缺口见 Cursor 安装说明。 +未知宿主必须关闭失败,不能回退到 Claude Code 或借用 Codex 资源。 ## 共享核心与 Host Kit @@ -37,14 +39,14 @@ Host Kit 负责: - 子代理派发、等待、结果编码和资源回收; - workflow transition、autopilot、UT、delivery 与 lifecycle; - 项目入口、settings/hook 合并; -- 会话数据采集、consent 路径和原生更新命令。 +- 会话数据采集、consent 路径和受控更新执行。 ## Manifest 契约 `hosts/{host-id}/host.json` 只允许以下顶层字段: - `host_id`:规范宿主 ID,必须与目录名一致; -- `host_api_version`:当前正式 Host Kit 使用 `1.1`; +- `host_api_version`:接受 `1.1` 与 `1.2`;旧 Host Kit 不需迁移; - `aliases`:可选输入别名,必须全局唯一; - `capabilities`:能力等级; - `adapters`:`resource:` 或 `python:` 引用; @@ -58,7 +60,7 @@ Skill 已声明的调用意图确定性投影为自己的原生 metadata,但 ## 标准资源适配器 -Host API 1.1 的业务 Host Kit 必须提供: +Host API 1.1 / 1.2 的业务 Host Kit 必须提供: - `distribution`:该宿主的原生 marketplace/plugin 清单; - `installer`:安装、升级、卸载与重载 smoke 手册; @@ -83,6 +85,26 @@ Host API 1.1 的业务 Host Kit 必须提供: - `plugin_update=native|emulated`:必须提供 `update` 与 `version`; - `detector`:仅供开发诊断和 Host Context CLI 自动识别使用。 +### 1.2 的项目 hooks 扩展 + +1.1 保留 `project_hooks_version=1.0` 的 `json_append_dedup` 嵌套事件结构。 +1.2 兼容旧资源,并允许 `project_hooks_version=1.1` 的 `json_flat_append_dedup`: +目标文件使用 `{version: 1, hooks: {event: [{command, matcher?}]}}`。 +按处理器身份去重,保留用户选项和其他事件;非法配置不覆盖,重复 Init 不重复追加。 +共享合并器按版本和策略选择行为,不按宿主名称分支。事件转换与响应编码由 Host Kit 负责。 + +### 可选统计源与更新扩展 + +Host API 1.2 允许统计 Adapter 自愿声明 `strict_private_cleanup = True`。共享清理在任何删除前取得 +Adapter;仅该属性严格为布尔 True 或调用方显式指定 `strict_scope=True` 时,规范化本仓路径并保留 +归属不明、损坏或其他宿主的数据。Adapter 装载失败时不开始删除。未声明、False 及非布尔值均保留 +既有默认语义;显式 strict_scope 不能被 Adapter 关闭。此属性不是 HostAdapter Protocol 的必需字段, +不改变 manifest、Registry 或后台快照格式。Cursor 选择严格策略,Claude Code、Codex 保持原默认。 + +统计 Adapter 可以提供 `prepare_session_source`、`release_session_source` 和 `purge_private_sources`,用于创建、最终投递后释放和撤销授权后清理自有私有事件源。调用方持有有效 consent lease;旧 Adapter 不实现时保持既有原生日志行为,不删除宿主日志。缺少可靠会话身份可抛出 `SessionContextUnavailable`,只跳过该次统计,业务继续。后台 Runtime 必须携带安装时从 Registry 验证得到的 Adapter 快照,不能依赖源码 checkout 或其他版本缓存。 + +Update Adapter 可以提供 `update_binding`、`validate_update_binding`、`prepare_update_binding`、`cache_binding_matches_installation`、`execute_install_step` 和 `verify_installation`。默认实现保持既有原生 CLI 行为;有绑定的实现必须把同一 `update_binding` 贯穿版本缓存、用户确认、一次性授权和安装验证,不能批准后重选来源。可选 `validate_install_resume` 默认返回 false;只有能以独立事务凭据验证原授权及不可变目标的适配器,才允许 `installing` 状态使用授权内冻结的 `approved_releases` 恢复,不依赖后续刷新的检查缓存。尚未开始的授权、无恢复凭据的历史授权与原生更新适配器继续严格校验缓存。共享核心不按宿主名称分支。详见 [版本更新协议](version-update-protocol.md)。 + ## 能力等级 - `native`:宿主直接提供该行为; @@ -106,7 +128,7 @@ Context,不在每条命令中启动 Python 重新识别。 架构保留清单驱动扩展点,但新增宿主必须作为一次独立架构变更重新引入,不得只复制旧平台文件。 最小步骤是: -1. 评估新宿主能否满足 Host API 1.1;不能满足时先设计新的通用 API 版本; +1. 评估新宿主能否满足已支持的 Host API;不能满足时先设计新的通用 API 版本; 2. 新增 `hosts/{host-id}/host.json` 和全部必需资源; 3. 新增宿主原生分发入口、安装/重载流程和 Host Context 绑定; 4. 为 telemetry/update 提供独立 adapter,或真实声明 `unsupported`; @@ -119,7 +141,7 @@ Context,不在每条命令中启动 Python 重新识别。 ## 插件 Hook 分发 -两个宿主的原生 plugin manifest 都必须显式声明 `hosts/{host-id}/hooks.json`。 +所有宿主的原生 plugin manifest 都必须显式声明 `hosts/{host-id}/hooks.json`。 不得发布根目录默认 `hooks/hooks.json`,以免客户端自动装载另一个宿主的入口。 Hook 入口位于对应 Host Kit,绑定自身安装目录的规范 manifest,转换宿主事件与环境持久化。 共享 `scripts/lifecycle_service.py` 只消费显式 HostManifest 和规范事件,不猜平台。 diff --git a/helixharness/reference/host-runtime-protocol.md b/helixharness/reference/host-runtime-protocol.md index 5d2128a..63b8eb4 100644 --- a/helixharness/reference/host-runtime-protocol.md +++ b/helixharness/reference/host-runtime-protocol.md @@ -6,11 +6,12 @@ ## 1. Host Context 绑定 -Host Context 在 command/Skill 进入业务工作流前由安装分发或宿主启动适配器绑定,不在每条命令中 -启动 Python 进程重新识别: +Host Context 在 command/Skill 进入业务工作流前由安装分发或宿主启动适配器绑定,不通过 Python +进程、环境或 CLI 探测重新识别: 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. Cursor 的 `hosts/cursor/skills/{entry}/SKILL.md` plugin Skill 表面绑定 `hosts/cursor/host.json`。 “分发表面绑定”是一种确定性入口绑定,不要求宿主额外设置环境变量或在目标项目 生成 settings:当前产品加载 `resources.command_projection` 已声明的原生命令或宿主 Skill @@ -25,16 +26,18 @@ Host Kit,不得假定所有入口都位于根 `skills/{entry}/`。这一确定 环境变量或 plugin cache。 绑定后读取精确路径 `hosts/{current_host_id}/host.json`,确认 `host_id` 与目录名一致、 -`host_api_version` 为当前支持的 1.1,且引用的资源位于插件根内,再读取 +`host_api_version` 为当前支持的 1.1 或 1.2,且引用的资源位于插件根内,再读取 `resources.runtime`,并绑定不可变规范身份 `canonical_host_id = host.json.host_id`。`current_host_id` 只用于选择 manifest 路径;后续版本检查、遥测 `--platform` 和宿主回执统一使用 `canonical_host_id`,不得从操作系统、CLI 名称、环境变量或自然语言别名重新猜测。 恢复同一命令时使用 当前分发表面重新绑定,不复用其他会话或宿主的 Host Context。 -`scripts/host_runtime_cli.py resolve` 保留为安装器、开发诊断和契约测试工具;正常业务命令不得为了 -识别宿主调用它。这样 Python 不可用且 telemetry 关闭时,原本不依赖 Python 的 Claude Code/Codex -业务动作不会因 Host Registry 新增阻断或工具调用。 +`scripts/host_runtime_cli.py resolve` 可用于安装器、开发诊断和契约测试;正常业务命令不得为了 +猜测或识别宿主调用它。Host Kit 或 `runtime-preflight.md` 已要求的来源校验可以在确定性绑定后 +显式传入 `--platform {canonical_host_id} --expected-plugin-root {plugin_root}`,检查当前执行副本 +与绑定来源一致。这是验证既定身份,不是重新发现宿主;校验失败不得搜索其他安装来补齐。 +本协议不额外要求原本不依赖 Python 的动作启动进程,宿主入口已有的 runtime preflight 仍须执行。 当前产品与插件分发表面无法共同确定唯一宿主、规范 ID 含路径分隔符或 `..`、清单不匹配、版本 不支持、资源越过插件根目录时,立即返回 `BLOCKED: helixharness_host_unavailable`。不得从 PATH 中 @@ -47,7 +50,7 @@ Host Kit,不得假定所有入口都位于根 `skills/{entry}/`。这一确定 ## 2. 逻辑动作 公共 command 的工具拼写和不可降低语义先读取 -`reference/tool-semantics.md`。Claude Code 对这些拼写使用原生工具语义;Codex 按 Host Kit 映射。 +`reference/tool-semantics.md`。Claude Code 对这些拼写使用原生工具语义;其他宿主按各自 Host Kit 映射。 共享工作流使用下列逻辑动作,实际工具名以 `resources.runtime` 为准: @@ -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 映射为上述逻辑动作。 +其他宿主不得虚构同名工具,必须按 Host Kit 映射为上述逻辑动作。 ## 3. 能力选择规则 @@ -99,7 +102,7 @@ Codex 不得虚构同名工具,必须按 Host Kit 映射为上述逻辑动作 ## 5. 未来宿主扩展契约 -当前仓库不发布其他 Host Kit。未来重新接入新宿主时,正常改动范围应限制为: +当前仓库提供 Claude Code、Codex、Cursor。未来接入新宿主时,正常改动范围应限制为: - `hosts/{host-id}/host.json`; - 该 Host Kit 引用的分发、安装、入口投影、启动、工具映射、生命周期、项目配置、遥测或更新适配器; diff --git a/helixharness/reference/project-type-detection.md b/helixharness/reference/project-type-detection.md index 90a377f..73a4188 100644 --- a/helixharness/reference/project-type-detection.md +++ b/helixharness/reference/project-type-detection.md @@ -1,11 +1,17 @@ # 项目类型检测协议 -init 命令的 Step 0 执行此脚本,使用 bash 检测项目类型(<100ms),写入状态文件供 Step 1 分支编排。 +单仓 init 命令的 Step 0 执行此脚本,使用 bash 检测项目类型(<100ms),写入状态文件供 Step 1 分支编排。 +Workspace 只执行自己的 W0/W1/W2,不运行本检测或单仓状态提交器。 ## 状态文件 `docs/.helixharness-init-state.json` +本检测每次开始新一轮单仓 Init,按既有规则替换上一轮检测状态;初始状态明确为 pending, +不得沿用上一轮的 completed/completedAt。后续 checkpoint 和最终完成状态只有父流程可通过 +`scripts/init_state.py` 提交;扫描和 bootstrap 子任务不得写入该状态文件。缺失、损坏或非对象 +状态必须停止,不得跳过后声称完成;重新执行完整检测才可开始新一轮。 + ## 检测脚本 ```bash @@ -125,7 +131,9 @@ cat > "$STATE_FILE" << JSONEOF "hasFrontend": $HAS_FRONTEND }, "scanPlan": $SCAN_PLAN, - "userConfirmed": $USER_CONFIRMED + "userConfirmed": $USER_CONFIRMED, + "scanStatus": "pending", + "bootstrapStatus": "pending" } JSONEOF diff --git a/helixharness/reference/runtime-preflight.md b/helixharness/reference/runtime-preflight.md index 2644683..4595264 100644 --- a/helixharness/reference/runtime-preflight.md +++ b/helixharness/reference/runtime-preflight.md @@ -21,6 +21,12 @@ Python。任何命令在第一次调用 `python3` 前都必须执行本协议, sh {plugin_root}/scripts/runtime_preflight.sh check ``` +`require` 执行同一检查并输出同一 JSON,但在 `ok=false` 时退出 2。SessionStart 的 +来源绑定使用 `sh "{plugin_root}/scripts/runtime_preflight.sh" require && python3 ... resolve ...`, +由 shell 确保依赖未就绪时不执行 resolver;这已经执行了本次来源绑定的 preflight。 +不得把 `&&` 改为命令分隔符或在失败后单独重跑 Python。原 `check` 保留只读诊断的退出码 0, +不能单凭 `check` 的退出码判断就绪;两种调用都按下列 JSON 字段及恢复规则处理。 + 只使用脚本返回的结构化字段: - `ok=true`:Python 3.9+ 与 Git 均可用,继续版本检查和后续流程。 diff --git a/helixharness/reference/ut-business-protocol.md b/helixharness/reference/ut-business-protocol.md index c94d935..74fca96 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..076ee8c 100644 --- a/helixharness/reference/version-update-protocol.md +++ b/helixharness/reference/version-update-protocol.md @@ -10,19 +10,20 @@ - 刷新 marketplace 后识别可更新版本。 - 展示当前版本到目标版本之间的更新内容。 - 按版本策略决定是否允许继续使用旧版本。 -- 使用当前平台的 plugin 原生命令完成升级,不手工复制 plugin 文件。 +- 由当前 Host Kit 执行经过验证的安装步骤:原生 plugin 命令,或已登记托管安装的原子替换;Agent 不手工覆盖插件。 - 所有实际升级必须经过用户交互确认和一次性授权;强制升级只决定是否允许继续旧版本,不能代替用户授权安装。 ## 宿主支持边界 update 与 eval 分别使用动态 Host Registry,并保持独立 capability、cache 和生命周期。update 是否 可用只看当前 Host Kit 的 `plugin_update=native|emulated|unsupported`;公共协议不维护宿主白名单。 -当前内置 Claude Code/Codex adapter 都提供正式更新能力。任何未注册宿主执行 update `check` 时固定返回 +Claude Code/Codex adapter 提供原生更新能力。Cursor 的 `plugin_update=emulated`,仅更新通过 Helix installer 登记的 macOS/Linux 本地安装;未登记副本或原生市场缓存不被接管。 +任何未注册宿主或未启用更新能力的宿主执行 update `check` 时固定返回 `state=unsupported, reason=unsupported_host, next_action=continue_silently`,不读取或写入 版本缓存、不提示更新、不创建 authorization,也不执行任何 plugin 命令。 公共版本策略、缓存、授权、安装 journal 和并发控制不包含宿主分支;宿主差异只存在于 -Host Kit 的 update adapter。未来新增宿主必须先实现正式安装识别、marketplace 定位、原生安装 +Host Kit 的 update adapter。未来新增宿主必须先实现正式安装识别、marketplace 定位、受控安装 步骤和验证门禁,再声明 `plugin_update=native|emulated`;不得增加共享平台分支。 ## 数据来源 @@ -38,10 +39,12 @@ python3 {plugin_root}/scripts/version_update.py \ 脚本内部匹配规则: -1. 只匹配完整 ID `helix@helixharness-marketplace` 且 enabled;`helix-local`、其他 marketplace、手工目录全部忽略。 +1. Claude Code/Codex 只匹配完整 ID `helix@helixharness-marketplace` 且 enabled;`helix-local`、其他 marketplace、手工目录全部忽略。 2. Claude Code project 安装仅在 `projectPath` 覆盖当前 repo 时生效;多个匹配时选路径最深者,否则选择唯一 user scope。Codex 只接受唯一 enabled/installed 的正式 plugin,scope 固定为 `default`。 3. Claude Code 当前执行脚本的 plugin root 必须等于 `installPath`,或等于唯一已注册 `source=directory` marketplace 的 manifest 中 `helix.source` 声明的本地路径;该相对路径不得越出 marketplace root。Codex 允许 plugin root 等于 `source.path`,或等于 `${CODEX_HOME:-$HOME/.codex}/plugins/cache/helixharness-marketplace/helix/{selected.version}` 这一精确的宿主管理版本缓存路径。两端版本都必须等于脚本所在的当前宿主 version 权威源(Claude Code 为 `.claude-plugin/marketplace.json` 的 entry version,Codex 为 `.codex-plugin/plugin.json` 的 version);否则报告 `WARN:helixharness_version_unknown`,不得猜测或跨来源比较。 +4. Cursor 只接受 `${HELIXHARNESS_CURSOR_HOME:-$HOME/.cursor}/plugins/local/helix`,执行根必须等于已登记安装根。外部 `managed-install.json` 绑定安装 ID、Git 来源/ref、布局;安装目录内 receipt 绑定该登记、版本、commit 和文件摘要。未登记、来源不符、版本或文件被修改时拒绝更新,不接管其他副本。首次安装使用 [Cursor installer](../hosts/cursor/installer.md)。 + ### 可用版本 当前宿主 adapter 刷新并列出正式 marketplace: @@ -59,7 +62,10 @@ codex plugin marketplace upgrade helixharness-marketplace --json codex plugin marketplace list --json ``` -脚本从 marketplace list 中找到唯一 `name == "helixharness-marketplace"`,Claude 读取 `installLocation`、Codex 读取 `root`,记为 `{marketplace_root}`。然后读取根 manifest: +脚本从 marketplace list 中找到唯一 `name == "helixharness-marketplace"`,Claude 读取 `installLocation`、Codex 读取 `root`,记为 `{marketplace_root}`。 +Cursor 从登记的 Git 来源/ref 获取临时、不可变的 commit 快照,只提取公开分发文件,使用 `.cursor-plugin/marketplace.json`。检查只更新版本缓存,不修改已安装副本;来源中的未提交改动不会被发布。 + +根 manifest 路径由当前 update adapter 的 `marketplace_manifest_path` 提供;路径必须留在所选来源内,禁止越界符号链接。现有两宿主仍读取: - `{marketplace_root}/.claude-plugin/marketplace.json` @@ -68,7 +74,7 @@ codex plugin marketplace list --json - `{formal_plugin_root}/reference/version-policy.json` - `{formal_plugin_root}/{当前宿主 manifest}/plugin.json` -`version-policy.json.latest_version` 是自动版本决策的唯一 latest 来源,并且必须与当前宿主的 version 权威源(Claude Code 的 marketplace entry version、Codex 的 `.codex-plugin/plugin.json` version)一致。任一文件缺失或版本不一致时,本次 policy 不可用;禁止回退到 CHANGELOG、目录名或其他安装源。 +`version-policy.json.latest_version` 是自动版本决策的唯一 latest 来源,并且必须与当前宿主的 version 权威源(Claude Code 的 marketplace entry version、Codex 的 `.codex-plugin/plugin.json` version;Cursor 的 `.cursor-plugin/plugin.json` 与 marketplace entry version)一致。任一文件缺失或版本不一致时,本次 policy 不可用;禁止回退到 CHANGELOG、目录名或其他安装源。 ### 更新内容 @@ -196,6 +202,12 @@ claude plugin update helix@helixharness-marketplace --scope project - 同时列出 user scope 仍可能影响其他项目。 - 用户传入 `--all` 时,逐个更新所有启用 scope。 +Cursor 的实际安装同样只能由 `version_update.py install` 消费有效授权后执行。缓存和授权中的 `update_binding` 固定安装 ID、登记摘要、原安装摘要、来源/ref、目标 commit、目标文件摘要和版本。准备授权时展示来源与目标;安装前重新验证登记与旧树,只提取批准的 commit,不执行候选代码。macOS/Linux 用原子目录交换部署,验证失败恢复旧目录;成功保留回滚副本,进程在交换后中断可幂等恢复。完成后须重载 Cursor 并新开会话。未登记副本、符号链接、未知文件覆盖、无原子交换能力或布局变化均受控拒绝;不虚构 Cursor plugin-update CLI。 + +新 authorization 同时冻结 `approved_releases`。进入 `installing` 前仍须与当前检查缓存完全匹配;Cursor 部署前再独立记录批准的来源绑定与授权事实摘要。恢复时只有适配器验证该独立凭据、原安装或批准目标、来源和有效授权后,才使用冻结的 release 信息继续,后续 `check` 刷新、缓存损坏或上游发布新版不改变原目标。缺少冻结信息或独立凭据时不得绕过缓存校验。旧原生 CLI 适配器默认不启用此能力,防止恢复操作安装未批准的 latest。 + +`check` 只读返回可恢复事务的 `pending_installation`(challenge、scope、target_version、expires_at),不消费授权或执行部署;无效、过期、未确认或尚未进入安装的授权不返回该字段。公共 update 在非 `--check` 模式优先恢复该事务,再走升级后重载提示;`latest` 或网络检查失败不能吞掉恢复入口,更高版本必须另行确认。 + ## 版本策略缓存 为了让主流程命令能发现“远端发布了强制升级版本”,又避免每次都被网络拖慢,HelixHarness 使用本机缓存保存最近一次远端版本策略检查结果。 @@ -205,9 +217,10 @@ claude plugin update helix@helixharness-marketplace --scope project ```text Claude Code: ${CLAUDE_CONFIG_DIR:-$HOME/.claude}/helixharness/version-check-cache.json Codex: ${CODEX_HOME:-$HOME/.codex}/helixharness/version-check-cache.json +Cursor: ${HELIXHARNESS_CURSOR_HOME:-$HOME/.cursor}/helixharness/version-check-cache.json ``` -缓存只能由 plugin 捆绑的 `scripts/version_update.py` 读写,禁止命令或 Agent 自行构造、修改 JSON。调用方式: +缓存与 authorization 保持 schema 1.0,新增 `update_binding` 为可选字段;是否必需及其内容由当前 Adapter 校验,旧宿主缓存仍兼容。Cursor 必须携带完整绑定,不能用缺失该字段的旧缓存安装。新 authorization 另含可选兼容字段 `approved_releases`;旧 authorization 缺失该字段时仍执行严格缓存校验,不能启用独立恢复。缓存只能由 plugin 捆绑的 `scripts/version_update.py` 读写,禁止命令或 Agent 自行构造、修改 JSON。调用方式: ```text python3 {plugin_root}/scripts/version_update.py --platform claude-code --repo-root {repo_root} check @@ -281,9 +294,14 @@ python3 {plugin_root}/scripts/version_update.py --platform claude-code skip --ta 真正执行升级必须按以下顺序: -1. 按正式格式调用 `python3 {plugin_root}/scripts/version_update.py --platform {当前平台} prepare --scope {Claude: user|project|all;Codex: default}`,生成 10 分钟有效的 pending `challenge_id`,并返回正式 `prompt.title/message/allowed_actions`。 +1. 按正式格式调用 `python3 {plugin_root}/scripts/version_update.py --platform {当前平台} prepare --scope {Claude: user|project|all;Codex: default;Cursor: local}`,生成 10 分钟有效的 pending `challenge_id`,并返回正式 `prompt.title/message/allowed_actions`。 2. 交互框原样使用 prompt,不得自行改写、缩减或重排按钮。 3. 用户选择后按正式格式调用 `python3 {plugin_root}/scripts/version_update.py --platform {当前平台} decide --challenge-id {id} --action {upgrade_now|skip_update} --user-confirmed`。`upgrade_now` 将 challenge 标为 authorized;`skip_update` 取消 challenge,recommended 保存 skip,required 返回阻断结果。 4. 仅 `upgrade_now` 可以继续调用 `python3 {plugin_root}/scripts/version_update.py --platform {当前平台} install --challenge-id {id}`。install 校验 platform、scope、目标版本、有效期、实时正式安装和 authorized 状态;随后写入 `installing` journal,逐步执行 adapter 命令。Claude 执行 `plugin update`;Codex 在授权后执行 `plugin marketplace upgrade`,再执行幂等 `plugin add`;每个完成步骤立即原子持久化,全部成功后才消费 authorization,中途失败保留 journal,重试只执行未完成步骤。 -禁止跳过任一步骤;禁止 Agent 直接执行平台 plugin 安装命令。pending、过期、目标版本变化、无交互环境或用户取消时均不得安装。`--check` 不得创建 authorization。所有宿主 CLI 都有有界输出和超时;普通状态锁等待上限 2 秒,marketplace 获取的每条 Git/宿主命令上限 20 秒,单个安装步骤上限 60 秒。 +禁止跳过任一步骤;禁止 Agent 直接执行平台 plugin 安装命令。pending、过期、无交互确认或用户取消时均不得安装;尚未进入安装的授权在缓存目标变化后也不得安装。已进入 `installing` 的事务只有通过上述独立恢复校验,才能在检查缓存变化后继续原批准目标,禁止改用新目标。`--check` 不得创建 authorization。所有宿主 CLI 都有有界输出和超时;普通状态锁等待上限 2 秒,marketplace 获取的每条 Git/宿主命令上限 20 秒,单个安装步骤上限 60 秒。 + + +## Cursor native update boundary + +仅 Cursor 原生安装:`check` 返回 `reason=installation_update_not_supported`、`next_action=continue_with_warning` 时,展示当前安装及手动更新步骤后结束更新流程;业务继续。不得进入 prepare/decide/install,不得改用旧 Local 缓存或授权,不把 unknown 当作已是最新。显式后续更新操作退出码为 2。此限制不改变 managed-local、Claude Code 或 Codex 的原协议。 diff --git a/helixharness/reference/workflow-projection-protocol.md b/helixharness/reference/workflow-projection-protocol.md index 7211e63..de89228 100644 --- a/helixharness/reference/workflow-projection-protocol.md +++ b/helixharness/reference/workflow-projection-protocol.md @@ -36,6 +36,10 @@ - Codex 方法薄入口必须先绑定 `hosts/codex/host.json`、公共 Host Runtime/Tool Semantics 与 `resources.runtime`,然后才执行 canonical 正文;正文首次派发 Agent/Task 时再按需读取公共协议和 `resources.subagent_protocol`。直接调用方法 Skill 与从公共 command 调用时使用同一能力映射。 +- Cursor 薄入口由 `scripts/cursor_skill_projection.py` 生成,绑定 `hosts/cursor/host.json`。 + `/helix-{command}` 是原生 Skill 表面,公共 `/helix:{command}` 是相同命令的逻辑标识;转场按当前 + `resources.workflow_transition` 内联执行唯一 contract,不依赖 UI 别名。方法入口只投影调用意图, + 不携带 Claude hooks 或 Codex metadata;D2C 的宿主门禁由 Cursor runtime 明确执行。 - Host Context、projection 和 manifest 已给出的资源路径必须直接使用;不得枚举或搜索 plugin 根目录、 安装目录或 cache 来重新发现同名资源,也不得用 `find/rg/ls/wc/stat` 试探已绑定资源的位置或长度。 - 固定且互不依赖的资源可在宿主支持时合并为一个有界读取批次;生命周期协议要求独占工具轮次的动作 diff --git a/helixharness/scripts/cursor_managed_install.py b/helixharness/scripts/cursor_managed_install.py new file mode 100644 index 0000000..7985625 --- /dev/null +++ b/helixharness/scripts/cursor_managed_install.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +"""Explicit installer for Helix-managed Cursor local distributions.""" + +from __future__ import annotations + +import argparse +import json + +from update_hosts.base import BoundedCommandRunner, UpdateHostError +from update_hosts.cursor import CursorUpdateAdapter +from version_update import _read_json, _version_text + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + install = commands.add_parser("install") + install.add_argument("--source", required=True, help="credential-free Git URL or absolute local Git path") + install.add_argument("--ref", required=True, help="explicit branch, tag or commit to follow") + install.add_argument("--user-confirmed", action="store_true") + recovery = commands.add_parser("recover-initial") + recovery.add_argument("--user-confirmed", action="store_true") + args = parser.parse_args() + try: + adapter = CursorUpdateAdapter(_version_text, _read_json) + result = adapter.recover_initial(user_confirmed=args.user_confirmed) if args.command == "recover-initial" else adapter.initialize(args.source, args.ref, BoundedCommandRunner(), user_confirmed=args.user_confirmed) + except (UpdateHostError, OSError, ValueError) as exc: + print(json.dumps({"status": "error", "error": str(exc)}, ensure_ascii=False)) + return 2 + print(json.dumps(result, ensure_ascii=False)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/helixharness/scripts/cursor_native_install.py b/helixharness/scripts/cursor_native_install.py new file mode 100644 index 0000000..d504e98 --- /dev/null +++ b/helixharness/scripts/cursor_native_install.py @@ -0,0 +1,300 @@ +#!/usr/bin/env python3 +"""Configure a pinned Cursor project plugin; never write Cursor's native cache.""" +from __future__ import annotations + +import argparse +from contextlib import contextmanager +import hashlib +import json +import os +from pathlib import Path, PurePosixPath +import re +import tempfile +from urllib.parse import urlsplit + +import eval_json +from update_hosts.base import BoundedCommandRunner + +KEY = "helixharness-marketplace/helix" +MISSING = {"absent": True} + + +def safe(path): + path = Path(path).expanduser().absolute() + if any(p.is_symlink() for p in (path, *path.parents)): + raise ValueError("symlink path is not supported") + return path.resolve() + + +def read(path): + path = safe(path) + if not path.exists(): + return {} + if not path.is_file() or path.stat().st_size > 1024 * 1024: + raise ValueError("configuration must be a bounded JSON file") + value = eval_json.loads(path.read_text()) + if not isinstance(value, dict): + raise ValueError("configuration must be a JSON object") + return value + + +def fingerprint(path): + path = safe(path) + return hashlib.sha256(path.read_bytes()).hexdigest() if path.exists() else None + + +def atomic(path, value): + path = safe(path) + path.parent.mkdir(parents=True, exist_ok=True) + fd, name = tempfile.mkstemp(prefix=".helix-native-", dir=path.parent) + try: + with os.fdopen(fd, "w") as stream: + json.dump(value, stream, ensure_ascii=False, indent=2) + stream.write("\n") + stream.flush() + os.fsync(stream.fileno()) + os.replace(name, path) + descriptor = os.open(path.parent, os.O_RDONLY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + finally: + if os.path.exists(name): + os.unlink(name) + + +def validate_source(url, commit): + if not isinstance(url, str) or any(c.isspace() for c in url) or "\x00" in url: + raise ValueError("invalid Git source") + parsed = urlsplit(url) + https = parsed.scheme == "https" and parsed.hostname and not parsed.username and not parsed.password + ssh = re.fullmatch(r"git@[A-Za-z0-9.-]+:[A-Za-z0-9._/-]+", url) + if not (https or ssh) or parsed.query or parsed.fragment: + raise ValueError("use credential-free HTTPS or git@ source; local sources are not supported") + if not re.fullmatch(r"[0-9a-f]{40}", commit): + raise ValueError("an explicit full lowercase commit SHA is required") + + +def source_snapshot(url, commit, runner=None): + """Inspect committed data, without executing candidate code or extracting it.""" + validate_source(url, commit) + runner = runner or BoundedCommandRunner() + with tempfile.TemporaryDirectory(prefix="helix-native-source-") as temporary: + def git(*args): + return runner.run(["git", "-c", "core.hooksPath=/dev/null", "-C", temporary, *args], timeout=20).stdout + git("init", "--bare", "--quiet") + git("fetch", "--quiet", "--depth=1", "--", url, commit) + if git("rev-parse", "FETCH_HEAD^{commit}").strip() != commit: + raise ValueError("source commit mismatch") + market = eval_json.loads(git("show", commit + ":.cursor-plugin/marketplace.json")) + if not isinstance(market, dict) or market.get("name") != "helixharness-marketplace": + raise ValueError("unexpected marketplace") + entries = market.get("plugins", []) + if not isinstance(entries, list): + raise ValueError("invalid marketplace plugins") + matches = [v for v in entries if isinstance(v, dict) and v.get("name") == "helix"] + if len(matches) != 1 or not isinstance(matches[0].get("source"), str): + raise ValueError("expected one relative helix plugin source") + raw = matches[0]["source"] + part = PurePosixPath(raw) + if not raw or part.is_absolute() or ".." in part.parts or "\\" in raw: + raise ValueError("invalid plugin subdirectory") + prefix = "" if str(part) == "." else str(part) + "/" + files = {} + for record in git("ls-tree", "-rz", "--full-tree", commit).split("\x00"): + if not record: + continue + header, name = record.split("\t", 1) + if not name.startswith(prefix): + continue + relative = name[len(prefix):] + if not relative or PurePosixPath(relative).is_absolute() or ".." in PurePosixPath(relative).parts or "\\" in relative: + raise ValueError("distribution path escapes plugin") + mode, kind, digest = header.split() + if kind != "blob" or mode not in {"100644", "100755"}: + raise ValueError("plugin distribution contains links or submodules") + if any(p.startswith(".env") or p in {".git", "output", "__pycache__"} for p in PurePosixPath(relative).parts): + raise ValueError("plugin distribution contains non-public runtime files") + files[relative] = digest + if not files or len(files) > 5000: + raise ValueError("invalid distribution size") + required = {".cursor-plugin/plugin.json", "hosts/cursor/hooks.json", "hosts/cursor/host.json", "scripts/host_runtime_cli.py"} + for command in ("init", "propose", "apply", "archive", "ut", "bug-fix", "update", "status", "config"): + required.update({f"hosts/cursor/skills/helix-{command}/SKILL.md", f"commands/{command}.md"}) + if not required.issubset(files): + raise ValueError("Cursor distribution is incomplete") + manifest = eval_json.loads(git("show", commit + ":" + prefix + ".cursor-plugin/plugin.json")) + if not isinstance(manifest, dict) or manifest.get("name") != "helix" or manifest.get("hooks") != "./hosts/cursor/hooks.json": + raise ValueError("invalid Cursor plugin manifest") + return {"binding": {"enabled": True, "gitUrl": url, "gitRef": commit, "gitPath": "./" + str(part) if prefix else "."}, "files": files} + + +class ProjectInstall: + def __init__(self, project, home=None): + self.project = safe(project) + if not self.project.is_dir(): + raise ValueError("project directory does not exist") + self.settings = safe(self.project / ".cursor/settings.json") + self.home = safe(home or os.environ.get("HELIXHARNESS_CURSOR_HOME") or Path.home() / ".cursor") + key = hashlib.sha256(str(self.project).encode()).hexdigest() + self.state = self.home / "helixharness/native-project-installs" / key + self.receipt = self.state / "binding.json" + + @contextmanager + def locked(self): + # Scope is the tested macOS/Linux desktop channel. + import fcntl + safe(self.state).mkdir(parents=True, exist_ok=True) + lock = safe(self.state / "lock") + with lock.open("a") as stream: + fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB) + yield + + def configuration(self): + value = read(self.settings) + if not isinstance(value.get("plugins", {}), dict): + raise ValueError("plugins must be an object") + if KEY in value.get("plugins", {}) and value["plugins"][KEY] == MISSING: + raise ValueError("invalid existing Helix binding") + return value + + def transaction(self): + record = read(self.receipt) + if record and (set(record) != {"phase", "old", "new", "settings_existed"} + or record["phase"] not in {"pending", "configured", "restored"} + or not isinstance(record["new"], dict) + or type(record["settings_existed"]) is not bool): + raise ValueError("invalid native configuration recovery record") + return record + + def conflicts(self): + local = safe(self.home / "plugins/local") + result = [] + if local.is_dir(): + for directory in local.iterdir(): + for name in (".cursor-plugin/plugin.json", ".claude-plugin/plugin.json", "plugin.json"): + path = directory / name + if path.exists() and read(path).get("name") == "helix": + result.append(str(directory)); break + return result + + def configure(self, snapshot, confirmed=False, replace=False): + if not confirmed: + raise ValueError("configuration requires user confirmation") + if self.conflicts(): + raise ValueError("Cursor Local helix conflict: move the owned copy outside plugins/local first; do not delete other hosts") + with self.locked(): + initial = fingerprint(self.settings) + config = self.configuration() + old = config.get("plugins", {}).get(KEY, MISSING) + target = snapshot["binding"] + record = self.transaction() + if record and record.get("phase") != "restored": + if record.get("new") != target: + raise ValueError("restore the prior configuration transaction before replacing its pin") + if old not in (record["old"], target): + raise ValueError("configuration changed outside this transaction") + else: + if old == target: + return {"status": "configured", "changed": False, "reload_required": True} + if old != MISSING and not replace: + raise ValueError("different binding exists; explicit --replace is required") + record = {"phase": "pending", "old": old, "new": target, "settings_existed": self.settings.exists()} + atomic(self.receipt, record) + config.setdefault("plugins", {})[KEY] = target + if fingerprint(self.settings) != initial: + raise ValueError("concurrent settings modification") + atomic(self.settings, config) + atomic(self.receipt, {**record, "phase": "configured"}) + return {"status": "configured", "reload_required": True, "session_loaded": "not_verified"} + + def restore(self, confirmed=False): + if not confirmed: + raise ValueError("restore requires user confirmation") + with self.locked(): + record = self.transaction() + if not record or record.get("phase") == "restored": + return {"status": "unchanged"} + initial = fingerprint(self.settings) + config = self.configuration() + current = config.get("plugins", {}).get(KEY, MISSING) + if current not in (record["new"], record["old"]): + raise ValueError("Helix binding changed externally; restore refused") + plugins = config.setdefault("plugins", {}) + if record["old"] == MISSING: + plugins.pop(KEY, None) + else: + plugins[KEY] = record["old"] + if not plugins: + config.pop("plugins") + if fingerprint(self.settings) != initial: + raise ValueError("concurrent settings modification") + if not config and not record["settings_existed"]: + self.settings.unlink(missing_ok=True) + if self.settings.parent.exists(): + fd = os.open(self.settings.parent, os.O_RDONLY) + try: + os.fsync(fd) + finally: + os.close(fd) + else: + atomic(self.settings, config) + atomic(self.receipt, {**record, "phase": "restored"}) + return {"status": "restored", "reload_required": True} + + def check(self, snapshot, plugin_root): + if self.configuration().get("plugins", {}).get(KEY) != snapshot["binding"]: + raise ValueError("project binding mismatch") + expected = self.home / "plugins/cache/helixharness-marketplace/helix" / snapshot["binding"]["gitRef"] + root = safe(plugin_root) + if root != expected or self.conflicts(): + raise ValueError("unexpected plugin root or Local conflict") + for name, expected_hash in snapshot["files"].items(): + path = safe(root / name) + if not path.is_file() or path.stat().st_size > 8 * 1024 * 1024: + raise ValueError("missing or oversized payload file") + data = path.read_bytes() + digest = hashlib.sha1(b"blob " + str(len(data)).encode() + b"\x00" + data).hexdigest() + if digest != expected_hash: + raise ValueError("installed payload differs from pinned source") + return {"status": "payload_verified", "files": len(snapshot["files"]), "session_loaded": "not_verified", "next_action": "reload_and_verify_status_and_hook_identity"} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=("plan", "configure", "check", "restore")) + parser.add_argument("--project-root", required=True) + parser.add_argument("--source") + parser.add_argument("--commit") + parser.add_argument("--plugin-root") + parser.add_argument("--replace", action="store_true") + parser.add_argument("--user-confirmed", action="store_true") + args = parser.parse_args() + try: + project = ProjectInstall(args.project_root) + if args.action == "restore": + result = project.restore(args.user_confirmed) + else: + if not args.source or not args.commit: + raise ValueError("--source and --commit are required") + snapshot = source_snapshot(args.source, args.commit) + if args.action == "configure": + result = project.configure(snapshot, args.user_confirmed, args.replace) + elif args.action == "check": + if not args.plugin_root: + raise ValueError("--plugin-root is required") + result = project.check(snapshot, args.plugin_root) + else: + project.configuration() + result = {"status": "planned", "binding": snapshot["binding"], "local_conflicts": project.conflicts(), "account_source": "verify_in_cursor_ui", "session_loaded": "not_verified"} + print(json.dumps(result, ensure_ascii=False)) + return 0 + except (ValueError, OSError) as exc: + # Never echo unknown configuration values, credentials or Git output. + print(json.dumps({"status": "error", "error": str(exc) if isinstance(exc, ValueError) and not isinstance(exc, json.JSONDecodeError) else "native_configuration_failed"})) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/helixharness/scripts/cursor_skill_projection.py b/helixharness/scripts/cursor_skill_projection.py new file mode 100644 index 0000000..8df980f --- /dev/null +++ b/helixharness/scripts/cursor_skill_projection.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""Generate and verify Cursor skill entries bound to canonical HelixHarness sources.""" + +from __future__ import annotations + +import argparse +import json +import re +from pathlib import Path +from typing import Sequence + + +PLUGIN_ROOT = Path(__file__).resolve().parents[1] +COMMANDS = frozenset({"init", "propose", "apply", "archive", "bug-fix", "ut", "update", "status", "config"}) +NAME_PATTERN = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*") + + +class ProjectionError(ValueError): + """A source or generated entry violates the Cursor projection contract.""" + + +def _inside(root: Path, relative: str, *, source: bool = True) -> Path: + path = root / relative + try: + path.resolve().relative_to(root) + except ValueError as exc: + raise ProjectionError(f"projection path escapes plugin root: {relative}") from exc + if source and not path.is_file(): + raise ProjectionError(f"projection source is missing: {relative}") + return path + + +def _fields(path: Path) -> dict[str, str]: + text = path.read_text(encoding="utf-8") + if not text.startswith("---\n") or "\n---\n" not in text[4:]: + raise ProjectionError(f"source frontmatter is missing: {path.name}") + lines = text[4:text.index("\n---\n", 4)].splitlines() + fields: dict[str, str] = {} + for index, line in enumerate(lines): + match = re.match(r"^(name|description|disable-model-invocation):\s*(.*)$", line) + if not match: + continue + key, raw = match.groups() + if key in fields: + raise ProjectionError(f"duplicate source frontmatter field: {key}") + if raw in {">", ">-", ">+", "|", "|-", "|+"}: + block: list[str] = [] + for continuation in lines[index + 1:]: + if continuation and not continuation.startswith((" ", "\t")): + break + block.append(continuation.strip()) + value = " ".join(block) + elif raw.startswith('"'): + try: + value = json.loads(raw) + except ValueError as exc: + raise ProjectionError(f"invalid source frontmatter quoting: {key}") from exc + elif raw.startswith("'") and raw.endswith("'"): + value = raw[1:-1].replace("''", "'") + else: + value = raw + if not isinstance(value, str) or not value.strip(): + raise ProjectionError(f"empty source frontmatter field: {key}") + fields[key] = re.sub(r"\s+", " ", value).strip() + if "description" not in fields: + raise ProjectionError("source description is missing") + if fields.get("disable-model-invocation", "false") not in {"true", "false"}: + raise ProjectionError("disable-model-invocation must be a boolean") + return fields + + +def _frontmatter(name: str, fields: dict[str, str], *, command: bool) -> str: + disabled = "true" if command else fields.get("disable-model-invocation", "false") + return ( + "---\n" + f"name: helix-{name}\n" + f"description: {json.dumps(fields['description'], ensure_ascii=False)}\n" + f"disable-model-invocation: {disabled}\n" + "---\n\n" + ) + + +def _command_projection(root: Path) -> dict: + projection_path = _inside(root, "hosts/cursor/command-projection.json") + try: + projection = json.loads(projection_path.read_text(encoding="utf-8")) + except (ValueError, OSError) as exc: + raise ProjectionError("invalid Cursor command projection") from exc + if ( + not isinstance(projection, dict) + or set(projection) != {"projection_version", "surface", "entrypoints"} + or projection.get("projection_version") != "1.0" + or projection.get("surface") != "skill" + or not isinstance(projection.get("entrypoints"), dict) + or set(projection["entrypoints"]) != COMMANDS + ): + raise ProjectionError("Cursor projection must cover exactly nine canonical commands") + return projection + + +def resolve_entry(plugin_root: Path, entry: Path) -> dict[str, str]: + """Resolve commands and methods independently without loading another entry type.""" + root = plugin_root.resolve() + candidate = entry if entry.is_absolute() else root / entry + try: + relative = candidate.resolve().relative_to(root) + except ValueError as exc: + raise ProjectionError("Cursor entry escapes plugin root") from exc + parts = relative.parts + if len(parts) != 5 or parts[:3] != ("hosts", "cursor", "skills") or parts[-1] != "SKILL.md" or not parts[3].startswith("helix-"): + raise ProjectionError("invalid Cursor entry path") + name = parts[3][len("helix-"):] + if not NAME_PATTERN.fullmatch(name): + raise ProjectionError("invalid Cursor entry name") + source = _inside(root, relative.as_posix()) + if _fields(source).get("name") != f"helix-{name}": + raise ProjectionError("Cursor entry name does not match its path") + if name in COMMANDS: + kind = "command" + canonical = f"commands/{name}.md" + pair = _command_projection(root)["entrypoints"][name] + if pair != [relative.as_posix(), canonical]: + raise ProjectionError("Cursor command projection redirects its entry or contract") + command_source = _inside(root, canonical) + if "HelixHarness 公共命令唯一契约" not in command_source.read_text(encoding="utf-8"): + raise ProjectionError("canonical command marker is missing") + else: + # Methods deliberately do not consult command-projection.json or commands/. + kind = "method" + canonical = f"skills/{name}/SKILL.md" + if _fields(_inside(root, canonical)).get("name") != name: + raise ProjectionError("canonical method name does not match its path") + return {"entry_kind": kind, "name": name, "entry": relative.as_posix(), "canonical": canonical} + + +def projected_skills(plugin_root: Path) -> dict[Path, str]: + """Build only thin entries; canonical business instructions remain single-source.""" + root = plugin_root.resolve() + projection = _command_projection(root) + result: dict[Path, str] = {} + for name in sorted(COMMANDS): + canonical = f"commands/{name}.md" + target = f"hosts/cursor/skills/helix-{name}/SKILL.md" + if projection["entrypoints"][name] != [target, canonical]: + raise ProjectionError(f"Cursor command source or entry is invalid: {name}") + source = _inside(root, canonical) + if "HelixHarness 公共命令唯一契约" not in source.read_text(encoding="utf-8"): + raise ProjectionError(f"canonical command marker is missing: {name}") + result[_inside(root, target, source=False)] = ( + _frontmatter(name, _fields(source), command=True) + + f"# Cursor command projection: {name}\n\n" + + "入口类型:`command`。插件根固定为当前文件的 `../../../..`。完整读取 " + + "`hosts/cursor/skill-entry.md`,执行“公共绑定”后仅执行“命令入口”分支;" + + "完成 runtime preflight,以 `--platform cursor` 显式解析同一安装的 Host Context。\n\n" + + f"当前逻辑命令为 `{name}`,原生 Skill 名为 `helix-{name}`。按入口协议绑定本次用户参数为 " + + f"`$ARGUMENTS`,然后完整读取并执行唯一公共契约 `{canonical}`;" + + "不复制业务步骤,不重新发现插件,不把建议命令当成自动授权。\n" + ) + + for source in sorted((root / "skills").glob("*/SKILL.md")): + name = source.parent.name + if not NAME_PATTERN.fullmatch(name) or name in COMMANDS: + raise ProjectionError(f"invalid or colliding canonical method name: {name}") + source = _inside(root, f"skills/{name}/SKILL.md") + fields = _fields(source) + if fields.get("name") != name: + raise ProjectionError(f"canonical method name differs from directory: {name}") + content = ( + _frontmatter(name, fields, command=False) + + f"# Cursor method projection: {name}\n\n" + + "入口类型:`method`。插件根固定为当前文件的 `../../../..`。完整读取 " + + "`hosts/cursor/skill-entry.md`,执行“公共绑定”后仅执行“方法入口”分支;" + + "不查询命令投影、不加载 commands 文件、不调用 Router。" + + "执行 runtime preflight 并以 `--platform cursor` 解析同一安装的 Host Context。" + + "完整读取 `reference/host-runtime-protocol.md`、`reference/tool-semantics.md` 和 " + + "`resources.runtime`;需要子 agent 时再读取公共子代理协议及 `resources.subagent_protocol`。\n\n" + + f"完整读取并执行唯一 canonical 方法 `skills/{name}/SKILL.md` 的正文。" + + "canonical frontmatter 不属于 Cursor 元数据,不装载其中的 Claude hooks、工具声明或调用标记。" + + f"正文相对资源从 `skills/{name}/` 解析;不得改以投影目录为基准。" + + "保留实际步骤、输出工件与全部门禁,不复制或改写业务语义,不扫描全局同名 Skill。\n" + ) + if name == "d-d2c": + content += ( + "\nD2C 必须执行 mode 对应的完整 canonical workflow、实际 runtime 健康与截图联合检查、" + "fidelity 评测和 phase 6。新 phase 0 后记录本次 `pageDir` 与 `enteredAt`;" + "在任何用户询问或结束前执行 `resources.runtime` 规定的 " + "`hosts/cursor/d2c_gate.cjs`,分别使用 `--action ask` 或 `--action stop`。" + "只有退出码 0 且 `allow=true` 可询问/结束;只有 `action.kind=done` 可宣称完成。" + "不把缺少原生 skill hook 当作省略门禁的理由。\n" + ) + result[_inside(root, f"hosts/cursor/skills/helix-{name}/SKILL.md", source=False)] = content + return result + + +def write(plugin_root: Path) -> None: + for target, content in projected_skills(plugin_root).items(): + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(content, encoding="utf-8") + + +def check(plugin_root: Path) -> None: + expected = projected_skills(plugin_root) + for target, content in expected.items(): + if not target.is_file() or target.read_text(encoding="utf-8") != content: + raise ProjectionError(f"Cursor projection is missing or stale: {target.parent.name}") + actual = set((plugin_root.resolve() / "hosts/cursor/skills").rglob("SKILL.md")) + if actual != set(expected): + raise ProjectionError("unexpected Cursor skill projection") + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, default=PLUGIN_ROOT) + actions = parser.add_mutually_exclusive_group(required=True) + actions.add_argument("--write", action="store_true") + actions.add_argument("--check", action="store_true") + actions.add_argument("--resolve-entry", type=Path, metavar="SKILL", help="Resolve one installed command or method entry") + arguments = parser.parse_args(argv) + try: + if arguments.resolve_entry is not None: + print(json.dumps(resolve_entry(arguments.root, arguments.resolve_entry), ensure_ascii=False, sort_keys=True)) + else: + (write if arguments.write else check)(arguments.root) + except (ProjectionError, OSError, UnicodeError) as exc: + parser.exit(2, f"Cursor projection error: {exc}\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/helixharness/scripts/host_runtime/__init__.py b/helixharness/scripts/host_runtime/__init__.py index 21850c4..25f47ad 100644 --- a/helixharness/scripts/host_runtime/__init__.py +++ b/helixharness/scripts/host_runtime/__init__.py @@ -15,8 +15,8 @@ import eval_json -HOST_API_VERSION = "1.1" -SUPPORTED_HOST_API_VERSIONS = frozenset({HOST_API_VERSION}) +HOST_API_VERSION = "1.2" +SUPPORTED_HOST_API_VERSIONS = frozenset({"1.1", HOST_API_VERSION}) HOST_ID_PATTERN = re.compile(r"^[a-z0-9][a-z0-9._-]{0,63}$") CAPABILITY_LEVELS = frozenset({"native", "emulated", "unsupported"}) SUPPORT_LEVELS = frozenset({"stable", "preview"}) diff --git a/helixharness/scripts/host_runtime/project_hooks.py b/helixharness/scripts/host_runtime/project_hooks.py index 7a77a75..ac80955 100644 --- a/helixharness/scripts/host_runtime/project_hooks.py +++ b/helixharness/scripts/host_runtime/project_hooks.py @@ -13,7 +13,32 @@ HOOK_OWNERS = frozenset({"bootstrap", "parent"}) -HOOK_MERGE_STRATEGIES = frozenset({"json_append_dedup", "unsupported"}) +HOOK_MERGE_STRATEGIES = frozenset({"json_append_dedup", "json_flat_append_dedup", "unsupported"}) +FLAT_DEDUPE_KEY = "hooks.*[].command+matcher" + + +def validate_flat_payload(payload: dict[str, Any]) -> None: + """Validate native flat hook settings without discarding user options.""" + + if type(payload.get("version")) is not int or payload["version"] != 1: + raise ValueError("flat project hooks version must be 1") + events = payload.get("hooks") + if not isinstance(events, dict): + raise ValueError("settings.hooks must be an object") + for event, handlers in events.items(): + if not isinstance(handlers, list): + raise ValueError(f"invalid flat project hook handlers: {event}") + for handler in handlers: + if not isinstance(handler, dict): + raise ValueError(f"invalid flat project hook handler: {event}") + kind = handler.get("type", "command") + if not isinstance(kind, str): + raise ValueError(f"invalid flat project hook type: {event}") + value_key = {"command": "command", "prompt": "prompt"}.get(kind) + if value_key is None or not isinstance(handler.get(value_key), str) or not handler[value_key].strip(): + raise ValueError(f"missing flat project hook {value_key or 'type'}: {event}") + if "matcher" in handler and not isinstance(handler["matcher"], str): + raise ValueError(f"invalid flat project hook matcher: {event}") def _optional_relative_path(value: Any, label: str) -> str | None: @@ -53,7 +78,8 @@ def load_project_hooks(manifest: HostManifest) -> ProjectHooks: } if not isinstance(payload, dict) or set(payload) != required_fields: raise HostContractError(f"项目 hooks 字段无效: {manifest.host_id}") - if payload.get("project_hooks_version") != "1.0": + version = payload.get("project_hooks_version") + if not isinstance(version, str) or version not in {"1.0", "1.1"} or (version == "1.1" and manifest.host_api_version != "1.2"): raise HostContractError(f"项目 hooks 版本无效: {manifest.host_id}") owner = str(payload.get("owner") or "") @@ -62,6 +88,8 @@ def load_project_hooks(manifest: HostManifest) -> ProjectHooks: raise HostContractError(f"项目 hooks owner 无效: {manifest.host_id}") if strategy not in HOOK_MERGE_STRATEGIES: raise HostContractError(f"项目 hooks merge_strategy 无效: {manifest.host_id}") + if strategy == "json_flat_append_dedup" and version != "1.1": + raise HostContractError(f"项目 flat hooks 必须使用 1.1 契约: {manifest.host_id}") settings_file = _optional_relative_path( payload.get("settings_file"), f"{manifest.host_id}.project_hooks.settings_file" ) @@ -85,6 +113,21 @@ def load_project_hooks(manifest: HostManifest) -> ProjectHooks: if dedupe_key is None or not isinstance(raw_hook_payload, dict) or not raw_hook_payload: raise HostContractError(f"项目 hooks 合并参数无效: {manifest.host_id}") hook_payload = raw_hook_payload + if strategy == "json_flat_append_dedup": + if dedupe_key != FLAT_DEDUPE_KEY: + raise HostContractError(f"项目 flat hooks dedupe_key 无效: {manifest.host_id}") + try: + validate_flat_payload(hook_payload) + except ValueError as exc: + raise HostContractError(f"项目 flat hooks payload 无效: {manifest.host_id}: {exc}") from exc + if not hook_payload["hooks"]: + raise HostContractError(f"项目 flat hooks payload 为空: {manifest.host_id}") + if any( + handler.get("type", "command") != "command" + for handlers in hook_payload["hooks"].values() + for handler in handlers + ): + raise HostContractError(f"项目 flat hooks 托管 payload 必须是 command: {manifest.host_id}") return ProjectHooks( owner=owner, @@ -97,7 +140,9 @@ def load_project_hooks(manifest: HostManifest) -> ProjectHooks: __all__ = [ "HOOK_MERGE_STRATEGIES", + "FLAT_DEDUPE_KEY", "HOOK_OWNERS", "ProjectHooks", "load_project_hooks", + "validate_flat_payload", ] diff --git a/helixharness/scripts/init_guidance.py b/helixharness/scripts/init_guidance.py new file mode 100644 index 0000000..0935470 --- /dev/null +++ b/helixharness/scripts/init_guidance.py @@ -0,0 +1,206 @@ +#!/usr/bin/env python3 +"""Render, merge or check only Init's managed command navigation block. + +This is a mechanical project-entry operation, not Init's semantic validator. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import tempfile +from pathlib import Path + +from host_runtime import HostContractError, HostRegistry +from host_runtime.project_config import load_project_config + + +PLUGIN_ROOT = Path(__file__).resolve().parent.parent +START = "" +END = "" +MODES = ("service", "frontend", "fullstack", "workspace") +LEGACY_SINGLE = ( + "## 常用命令\n\n" + "`/helix:init`、`/helix:propose`、`/helix:apply`、`/helix:archive`、\n" + "`/helix:ut`、`/helix:bug-fix`、`/helix:update`。\n" + "`propose --loop` 按顺序执行 Propose → Apply → Archive。\n" +) +LEGACY_WORKSPACE = ( + "## 常用命令\n\n" + "`/helix:init --workspace` 初始化根目录。`/helix:propose `\n" + "建立需求;`--loop` 串联 Propose → Apply → Archive。`apply` 与 `archive` 按 Router 的 Workspace\n" + "范围调度子仓;其他命令的适用范围仍以各自 Router 和完整命令为准。\n" +) + + +class GuidanceError(ValueError): + """Navigation cannot safely be generated, updated or accepted.""" + + +def _lines(text: str): + """Yield source offsets and fence context without rewriting user bytes.""" + offset = 0 + fence: tuple[str, int] | None = None + for source in text.splitlines(keepends=True): + line = source.rstrip("\r\n") + match = re.match(r"^ {0,3}(`{3,}|~{3,})(.*)$", line) + fenced = fence is not None + if match: + marks, tail = match.groups() + if fence is None: + fence = (marks[0], len(marks)) + elif marks[0] == fence[0] and len(marks) >= fence[1] and not tail.strip(): + fence = None + fenced = True + yield offset, line, fenced + offset += len(source) + + +def _managed_span(text: str) -> tuple[int, int] | None: + markers = [] + for offset, line, fenced in _lines(text): + if "" +END = "" +COMMANDS = ("init", "propose", "apply", "archive", "ut", "bug-fix", "update", "status", "config") +LEGACY_SINGLE = ( + "## 常用命令\n\n" + "`/helix:init`、`/helix:propose`、`/helix:apply`、`/helix:archive`、\n" + "`/helix:ut`、`/helix:bug-fix`、`/helix:update`。\n" + "`propose --loop` 按顺序执行 Propose → Apply → Archive。\n" +) +LEGACY_WORKSPACE = ( + "## 常用命令\n\n" + "`/helix:init --workspace` 初始化根目录。`/helix:propose `\n" + "建立需求;`--loop` 串联 Propose → Apply → Archive。`apply` 与 `archive` 按 Router 的 Workspace\n" + "范围调度子仓;其他命令的适用范围仍以各自 Router 和完整命令为准。\n" +) + + +class InitGuidanceTest(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory(prefix="helix-init-guidance-") + self.addCleanup(temp.cleanup) + self.repo = Path(temp.name) + + def cli(self, platform="cursor", mode="service", action="merge", code=0): + result = subprocess.run( + [sys.executable, "-B", str(SCRIPT), "--repo-root", str(self.repo), + "--platform", platform, "--mode", mode, action], + capture_output=True, text=True, timeout=10, + ) + self.assertEqual(result.returncode, code, result.stdout + result.stderr) + return json.loads(result.stdout) + + def template(self, mode): + name = "workspace-entry.md.tpl" if mode == "workspace" else "project-entry.md.tpl" + return (PLUGIN / "templates" / name).read_text().replace("{{PROJECT_CONTEXT}}", "Synthetic project context.") + + def test_shared_templates_label_both_entry_styles_and_preserve_parameters(self): + for mode in ("service", "workspace"): + with self.subTest(mode=mode): + source = self.template(mode) + self.assertEqual(source.count(START), 1) + self.assertEqual(source.count(END), 1) + block = source.split(START)[1].split(END)[0] + self.assertIn("Cursor", block) + self.assertIn("Claude Code / Codex", block) + commands = COMMANDS if mode == "service" else ("init", "propose", "apply", "archive") + for command in commands: + self.assertIn(f"/helix-{command}", block) + self.assertIn(f"/helix:{command}", block) + self.assertIn("--loop", block) + if mode == "workspace": + self.assertIn("--workspace", block) + self.assertIn(" ", block) + self.assertIn("Workspace 根不支持 BugFix", block) + + def test_all_hosts_and_modes_generate_check_and_repeat_without_rewriting(self): + for platform in ("cursor", "codex", "claude-code"): + for mode in ("service", "frontend", "fullstack", "workspace"): + with self.subTest(platform=platform, mode=mode): + entry = self.repo / ("CLAUDE.md" if platform == "claude-code" else "AGENTS.md") + entry.write_text(self.template(mode)) + initial = entry.read_bytes() + self.assertFalse(self.cli(platform, mode)["changed"]) + self.assertEqual(self.cli(platform, mode, "check")["status"], "pass") + self.assertEqual(entry.read_bytes(), initial) + modified = entry.stat().st_mtime_ns + self.assertFalse(self.cli(platform, mode)["changed"]) + self.assertEqual(entry.stat().st_mtime_ns, modified) + + def test_both_host_orders_preserve_custom_bytes_and_identical_guidance(self): + original = ('# 用户规则\r\n保留 `/helix:propose "需求 空格.md" --loop` 原文。\r\n' + '```text\r\n## 常用命令\r\n这是引用示例,不是导航区。\r\n```\r\n').encode() + final = [] + for order in (("cursor", "codex"), ("codex", "cursor")): + entry = self.repo / "AGENTS.md" + entry.write_bytes(original) + self.assertTrue(self.cli(order[0])["changed"]) + before = entry.read_bytes() + self.assertTrue(before.startswith(original)) + self.assertFalse(self.cli(order[1])["changed"]) + self.assertEqual(before, entry.read_bytes()) + final.append(before) + self.assertEqual(*final) + + def test_claude_entry_is_separate_and_other_hosts_are_untouched(self): + agents = self.repo / "AGENTS.md" + agents.write_bytes(b"# Existing Codex and Cursor rules\n") + self.assertTrue(self.cli("claude-code")["changed"]) + self.assertEqual(agents.read_bytes(), b"# Existing Codex and Cursor rules\n") + self.assertEqual(self.cli("claude-code", action="check")["status"], "pass") + self.assertEqual({p.name for p in self.repo.iterdir()}, {"AGENTS.md", "CLAUDE.md"}) + + def test_exact_legacy_blocks_migrate_only_the_owned_section(self): + for mode, legacy, title in (("service", LEGACY_SINGLE, "HelixHarness 导航"), + ("workspace", LEGACY_WORKSPACE, "HelixHarness Workspace")): + with self.subTest(mode=mode): + prefix = f"# 用户说明\n命令引号与路径不能变:`/helix:ut --packages 'a b'`。\n\n# {title}\n\n" + suffix = "\n## Agent 工作规则\n用户自行扩展的约束。\n" + entry = self.repo / "AGENTS.md" + entry.write_text(prefix + legacy + suffix) + self.assertTrue(self.cli(mode=mode)["changed"]) + actual = entry.read_text() + self.assertTrue(actual.startswith(prefix)) + self.assertTrue(actual.endswith(suffix)) + self.assertNotIn(legacy, actual) + self.assertEqual(self.cli(mode=mode, action="check")["status"], "pass") + + def test_custom_or_ambiguous_navigation_is_never_rewritten(self): + cases = ( + "# HelixHarness 导航\n\n## 常用命令\n`/helix:propose` 自定义调用规则。\n", + "## 常用命令(项目自定义)\n保留用户命令。\n", + "# HelixHarness 导航\n\n" + LEGACY_SINGLE + "新增用户说明,不能作为默认区迁移。\n", + LEGACY_SINGLE, # A matching section alone does not prove Helix ownership. + START + "\nmissing end\n", + END + "\nreversed\n" + START, + START + "\nold\n" + END + "\n" + START + "\nold\n" + END, + "')[1] + expected = expected.split('```text\n', 1)[1].split('\n```', 1)[0] + before = self.files() + for host in ('cursor', 'codex', 'claude-code'): + for scope in ('project', 'user'): + with self.subTest(host=host, scope=scope), mock.patch.object( + telemetry_consent, 'set_mode', side_effect=AssertionError('notice preparation must not write'), + ), mock.patch.object( + telemetry_consent, '_purge_current_repo_private_state', + side_effect=AssertionError('notice preparation must not purge'), + ): + code, result = self.enable(scope=scope, platform=host) + self.assertEqual(code, 0, result) + self.assertTrue(result['read_only']) + self.assertTrue(result['notice_required']) + self.assertEqual(result['next_action'], 'display_notice_before_enable') + self.assertEqual(result['change'], {'updated': False, 'reason': 'telemetry_notice_required'}) + self.assertEqual(result['notice']['text'], expected) + self.assertEqual(result['notice']['sha256'], hashlib.sha256(expected.encode()).hexdigest()) + self.assertEqual(result['telemetry']['effective_mode'], 'disabled') + self.assertTrue(result['telemetry']['prompt_due']) + self.assertFalse(result['request_complete']) + self.assertFalse(result['continuation']['new_user_confirmation_required']) + self.assertEqual(before, self.files()) + + def test_current_notice_acknowledgment_allows_authorized_change_for_each_host(self): + for host in ('cursor', 'codex', 'claude-code'): + with self.subTest(host=host): + code, prepared = self.enable(platform=host) + self.assertEqual(code, 0) + code, applied = self.enable(platform=host, digest=prepared['notice']['sha256']) + self.assertEqual(code, 0, applied) + self.assertFalse(applied['read_only']) + self.assertTrue(applied['change']['updated']) + self.assertEqual(applied['telemetry']['effective_mode'], 'enabled') + self.assertEqual(applied['telemetry']['effective_scope'], 'project') + self.assertFalse((self.repo / 'docs/eval').exists()) + self.assertFalse((self.home / 'telemetry').exists()) + self.assertFalse((self.home / 'feedback').exists()) + + def test_prepared_enable_exposes_a_same_request_continuation_on_every_host_and_scope(self): + for host in ('cursor', 'codex', 'claude-code'): + for scope in ('user', 'project'): + with self.subTest(host=host, scope=scope): + original = ['--telemetry', 'enabled', '--scope', scope, '--user-confirmed'] + before = self.files() + code, prepared = self.run_config(*original, platform=host) + self.assertEqual(code, 0, prepared) + self.assertFalse(prepared['request_complete']) + self.assertEqual(before, self.files()) + continuation = prepared['continuation'] + self.assertEqual(continuation['after'], 'display_notice_to_user') + self.assertEqual(continuation['action'], 'repeat_same_request') + self.assertTrue(continuation['same_turn']) + self.assertFalse(continuation['new_user_confirmation_required']) + self.assertEqual(continuation['append_arguments'], + ['--telemetry-notice-shown', prepared['notice']['sha256']]) + # Simulate a caller that has displayed the notice. The original + # explicit authorization and scope are reused, not expanded. + code, applied = self.run_config(*original, *continuation['append_arguments'], platform=host) + self.assertEqual(code, 0, applied) + self.assertTrue(applied['request_complete']) + self.assertNotIn('continuation', applied) + self.assertTrue(applied['change']['updated']) + _, readback = self.run_config(platform=host) + self.assertEqual(readback['telemetry']['effective_mode'], 'enabled') + self.assertEqual(readback['telemetry']['effective_scope'], scope) + # A new enable request still prepares its notice, even when + # the setting is already enabled; it must not change state. + before = self.files() + _, again = self.run_config(*original, platform=host) + self.assertFalse(again['request_complete']) + self.assertEqual(again['telemetry']['effective_mode'], 'enabled') + self.assertEqual(before, self.files()) + + def test_queries_disable_and_endpoint_changes_do_not_request_continuation(self): + for args in [(), ('--telemetry', 'disabled', '--scope', 'project', '--user-confirmed'), + ('--report-endpoint', 'http://127.0.0.1:12345/report', '--user-confirmed'), + ('--reset-report-endpoint', '--user-confirmed')]: + with self.subTest(args=args), mock.patch.object( + user_config, 'telemetry_enable_notice', side_effect=AssertionError('must not load notice'), + ): + code, result = self.run_config(*args) + self.assertEqual(code, 0, result) + self.assertTrue(result['request_complete']) + self.assertNotIn('continuation', result) + + def test_notice_digest_does_not_replace_explicit_authorization(self): + digest = user_config.telemetry_enable_notice()['sha256'] + before = self.files() + for supplied in (None, digest): + code, result = self.enable(confirmed=False, digest=supplied) + self.assertEqual(code, 2, result) + self.assertIn('explicit user', result['error']) + self.assertEqual(before, self.files()) + + def test_all_hosts_keep_scope_precedence_read_only_and_endpoint_reset_contracts(self): + for host in ('cursor', 'codex', 'claude-code'): + with self.subTest(host=host): + for scope in ('user', 'project'): + _, prepared = self.enable(platform=host, scope=scope) + code, changed = self.enable(platform=host, scope=scope, digest=prepared['notice']['sha256']) + self.assertEqual(code, 0, changed) + self.assertTrue(changed['change']['updated']) + self.assertEqual(changed['telemetry']['effective_mode'], 'enabled') + self.assertEqual(changed['telemetry']['effective_scope'], scope) + code, disabled = self.run_config('--telemetry', 'disabled', '--scope', 'user', + '--user-confirmed', platform=host) + self.assertEqual(code, 0, disabled) + self.assertEqual(disabled['telemetry']['effective_scope'], 'user') + self.assertEqual(disabled['telemetry']['effective_mode'], 'disabled') + _, prepared = self.enable(platform=host) + code, overridden = self.enable(platform=host, digest=prepared['notice']['sha256']) + self.assertEqual(code, 0, overridden) + self.assertTrue(overridden['request_complete']) + self.assertNotIn('continuation', overridden) + self.assertFalse(overridden['change']['updated']) + self.assertEqual(overridden['change']['warning'], 'WARN:telemetry_user_scope_disabled') + code, disabled = self.run_config('--telemetry', 'disabled', '--scope', 'project', + '--user-confirmed', platform=host) + self.assertEqual(code, 0, disabled) + self.assertTrue(disabled['change']['updated']) + before = self.files() + code, viewed = self.run_config(platform=host) + self.assertEqual(code, 0, viewed) + self.assertTrue(viewed['read_only']) + self.assertEqual(before, self.files()) + for channel in ('report', 'feedback'): + code, changed = self.run_config(f'--{channel}-endpoint', + f'http://127.0.0.1:12345/{channel}', + '--user-confirmed', platform=host) + self.assertEqual(code, 0, changed) + self.assertTrue(changed['change']['updated']) + self.assertEqual(changed[channel]['source'], 'user') + code, reset = self.run_config(f'--reset-{channel}-endpoint', '--user-confirmed', platform=host) + self.assertEqual(code, 0, reset) + self.assertTrue(reset['change']['updated']) + self.assertNotEqual(reset[channel]['source'], 'user') + + def test_incorrect_and_changed_notice_digests_do_not_enable(self): + _, prepared = self.enable() + old_digest = prepared['notice']['sha256'] + revised = self.root / 'revised-protocol.md' + revised.write_text(user_config.EVAL_PROTOCOL.read_text().replace('数据统计说明:默认关闭。', '数据统计说明:默认关闭。新增合成测试说明。')) + before = self.files() + for digest in ('', 'bad-value', '0' * 64): + code, result = self.enable(digest=digest) + self.assertEqual(code, 2, result) + self.assertEqual(before, self.files()) + with mock.patch.object(user_config, 'EVAL_PROTOCOL', revised): + code, result = self.enable(digest=old_digest) + self.assertEqual(code, 2, result) + self.assertEqual(before, self.files()) + _, current = self.enable() + self.assertNotEqual(old_digest, current['notice']['sha256']) + self.assertEqual(before, self.files()) + + def test_missing_or_malformed_canonical_notice_never_enables(self): + broken = self.root / 'broken.md' + marker = 'helixharness-eval-data-notice-v1' + values = ['', f'\nplain text\n', + f'\n```text\n\n```\n', + f'\n', + user_config.EVAL_PROTOCOL.read_text() * 2] + for text in values: + with self.subTest(format=text[:30]): + broken.write_text(text) + before = self.files() + with mock.patch.object(user_config, 'EVAL_PROTOCOL', broken): + code, result = self.enable() + self.assertEqual(code, 2, result) + self.assertEqual(before, self.files()) + with mock.patch.object(user_config, 'EVAL_PROTOCOL', self.root / 'absent.md'): + code, _ = self.enable() + self.assertEqual(code, 2) + + def test_disable_endpoint_and_read_only_do_not_depend_on_notice_loading(self): + with mock.patch.object(user_config, 'telemetry_enable_notice', side_effect=AssertionError('must not load notice')): + code, viewed = self.run_config() + self.assertEqual(code, 0, viewed) + code, disabled = self.run_config('--telemetry', 'disabled', '--scope', 'project', '--user-confirmed') + self.assertEqual(code, 0, disabled) + self.assertTrue(disabled['change']['updated']) + code, endpoint = self.run_config('--report-endpoint', 'http://127.0.0.1:12345/report', '--user-confirmed') + self.assertEqual(code, 0, endpoint) + self.assertTrue(endpoint['change']['updated']) + + def test_notice_marker_cannot_be_used_on_unrelated_actions(self): + digest = user_config.telemetry_enable_notice()['sha256'] + before = self.files() + for args in [(), ('--telemetry', 'disabled', '--scope', 'project', '--user-confirmed'), + ('--report-endpoint', 'http://127.0.0.1:12345/report', '--user-confirmed')]: + code, result = self.run_config(*args, '--telemetry-notice-shown', digest) + self.assertEqual(code, 2, result) + self.assertEqual(before, self.files()) + + def test_unsupported_host_does_not_prepare_notice_or_write(self): + before = self.files() + code, result = self.enable(platform='synthetic-unknown-host') + self.assertEqual(code, 2, result) + self.assertNotIn('notice', result) + self.assertEqual(before, self.files()) + + +if __name__ == '__main__': + unittest.main() diff --git a/helixharness/scripts/tests/test_workspace_init_registry.py b/helixharness/scripts/tests/test_workspace_init_registry.py index 2c4450c..23f9380 100644 --- a/helixharness/scripts/tests/test_workspace_init_registry.py +++ b/helixharness/scripts/tests/test_workspace_init_registry.py @@ -21,6 +21,8 @@ def setUp(self) -> None: target = self.root / path target.parent.mkdir(parents=True, exist_ok=True) target.write_text('Initialized workspace\n', encoding='utf-8') + template = Path(__file__).resolve().parents[2] / 'templates/workspace-entry.md.tpl' + (self.root / 'AGENTS.md').write_text(template.read_text(encoding='utf-8'), encoding='utf-8') self.registry = self.root / 'helixharness.workspace.yaml' self.registry.write_text('''version: 1 repos: diff --git a/helixharness/scripts/update_hosts/base.py b/helixharness/scripts/update_hosts/base.py index 7eeb122..de52886 100644 --- a/helixharness/scripts/update_hosts/base.py +++ b/helixharness/scripts/update_hosts/base.py @@ -14,7 +14,6 @@ import eval_json - MARKETPLACE = "helixharness-marketplace" PLUGIN_ID = "helix@helixharness-marketplace" PLUGIN_NAME = "helix" @@ -91,18 +90,21 @@ def run(self, command: Sequence[str], *, timeout: float) -> CommandResult: terminate_lock = threading.Lock() def drain(stream: Any, target: bytearray, limit: int, label: str) -> None: - while True: - chunk = stream.read(65536) - if not chunk: - return - remaining = limit - len(target) - if remaining > 0: - target.extend(chunk[:remaining]) - if len(chunk) > remaining: - overflow.append(label) - with terminate_lock: - self._terminate(process) - return + try: + while True: + chunk = stream.read(65536) + if not chunk: + return + remaining = limit - len(target) + if remaining > 0: + target.extend(chunk[:remaining]) + if len(chunk) > remaining: + overflow.append(label) + with terminate_lock: + self._terminate(process) + return + finally: + stream.close() threads = [ threading.Thread( @@ -179,6 +181,11 @@ class UpdateHostAdapter(ABC): supported_scopes: frozenset[str] aggregate_scope_members: Mapping[str, frozenset[str]] = {} manifest_directory: str + marketplace_manifest_directory: str + + def entry_policy(self, plugin_root: Path) -> dict[str, Any] | None: + """Optional execution-channel restriction; existing hosts remain unchanged.""" + return None def validate_scope(self, scope: str) -> None: if scope not in self.supported_scopes: @@ -244,6 +251,18 @@ def install_steps( def manifest_path(self, plugin_root: Path) -> Path: return plugin_root / self.manifest_directory / "plugin.json" + def marketplace_manifest_path(self, marketplace_root: Path) -> Path: + """Locate the host's marketplace metadata inside the selected source.""" + + root = marketplace_root.resolve() + directory = Path(self.marketplace_manifest_directory) + if directory.is_absolute() or ".." in directory.parts: + raise UpdateHostError("marketplace manifest directory escapes its root") + path = (root / directory / "marketplace.json").resolve() + if not path.is_relative_to(root): + raise UpdateHostError("marketplace manifest path escapes its root") + return path + def declared_version(self, plugin_root: Path) -> Any: """The version the executing plugin declares for itself. @@ -265,3 +284,40 @@ def volatile_check_cache_paths( del plugin_root return None, None + + def update_binding(self, snapshot_root: Path | None, installation: Mapping[str, Any], runner: BoundedCommandRunner) -> dict[str, Any] | None: + """Optionally bind an immutable deployment source to the checked policy.""" + del snapshot_root, installation, runner + return None + + def validate_update_binding(self, binding: Any) -> None: + if binding is not None: + raise UpdateHostError(f"{self.host_id} does not support an update binding") + + def prepare_update_binding(self, binding: Any) -> str: + """Read-only pre-consent validation; return additional prompt context.""" + self.validate_update_binding(binding) + return "" + + def cache_binding_matches_installation(self, binding: Any, installation: Mapping[str, Any]) -> bool: + del binding, installation + return True + + def validate_install_resume(self, authorization: Mapping[str, Any], *, plugin_root: Path) -> bool: + """Opt into cache-independent resume only with independent transaction evidence. + + Native commands that may select the latest release keep strict cache + validation. An adapter must prove it can resume the approved target. + """ + del authorization, plugin_root + return False + + def execute_install_step(self, step: InstallStep, runner: BoundedCommandRunner, *, authorization: Mapping[str, Any], plugin_root: Path) -> None: + """Execute an authorized step. Legacy adapters keep their native command.""" + del authorization, plugin_root + runner.run(step.command, timeout=INSTALL_TIMEOUT_SECONDS) + + def verify_installation(self, authorization: Mapping[str, Any], runner: BoundedCommandRunner, *, plugin_root: Path) -> dict[str, Any]: + """Optional host verification before consuming the one-time authorization.""" + del authorization, runner, plugin_root + return {} diff --git a/helixharness/scripts/update_hosts/claude_code.py b/helixharness/scripts/update_hosts/claude_code.py index 8df0c14..5256c08 100644 --- a/helixharness/scripts/update_hosts/claude_code.py +++ b/helixharness/scripts/update_hosts/claude_code.py @@ -65,6 +65,7 @@ class ClaudeCodeUpdateAdapter(UpdateHostAdapter): supported_scopes = frozenset({"user", "project", "all"}) aggregate_scope_members = {"all": frozenset({"user", "project"})} manifest_directory = ".claude-plugin" + marketplace_manifest_directory = ".claude-plugin" def __init__(self, normalize_version: Callable[[Any], str], read_json: Callable[[Path], dict[str, Any]]): self._normalize_version = normalize_version diff --git a/helixharness/scripts/update_hosts/codex.py b/helixharness/scripts/update_hosts/codex.py index 7445c40..e870f9f 100644 --- a/helixharness/scripts/update_hosts/codex.py +++ b/helixharness/scripts/update_hosts/codex.py @@ -53,6 +53,7 @@ class CodexUpdateAdapter(UpdateHostAdapter): host_id = "codex" supported_scopes = frozenset({"default"}) manifest_directory = ".codex-plugin" + marketplace_manifest_directory = ".claude-plugin" def __init__( self, diff --git a/helixharness/scripts/update_hosts/cursor.py b/helixharness/scripts/update_hosts/cursor.py new file mode 100644 index 0000000..002e962 --- /dev/null +++ b/helixharness/scripts/update_hosts/cursor.py @@ -0,0 +1,665 @@ +"""Cursor managed-local distribution; never impersonates a native marketplace API.""" + +from __future__ import annotations + +import ctypes +import hashlib +import json +import os +import re +import shutil +import sys +import tarfile +import tempfile +import uuid +from contextlib import contextmanager +from pathlib import Path, PurePosixPath +from typing import Any, Callable, Iterator, Mapping +from urllib.parse import urlparse + +from .base import ( + MARKETPLACE, + MARKETPLACE_TIMEOUT_SECONDS, + PLUGIN_ID, + PLUGIN_NAME, + BoundedCommandRunner, + InstallStep, + UpdateHostAdapter, + UpdateHostError, +) + +RECEIPT = ".helixharness-managed.json" +REGISTRATION_KEYS = {"schema_version", "kind", "install_id", "install_root", "source", "ref", "plugin_source"} +BINDING_KEYS = {"schema_version", "kind", "install_id", "registration_sha256", "install_root", "source", "ref", "plugin_source", "current_tree", "target_commit", "target_tree", "target_version"} +RECEIPT_KEYS = {"schema_version", "install_id", "registration_sha256", "version", "commit", "tree_sha256"} +DISTRIBUTION_DIRS = {".claude-plugin", ".codex-plugin", ".cursor-plugin", "agents", "commands", "hosts", "reference", "scripts", "skills", "templates", "workflows"} +DISTRIBUTION_FILES = {"AGENTS.md", "CLAUDE.md", "LICENSE", "NOTICE", "PLUGIN_USAGE.md", "README.md", "README.zh-CN.md", "SKILL.md", "THIRD_PARTY_NOTICES.md", ".gitignore"} +EXCLUDED_PARTS = {".git", ".env", ".cursor", ".claude", ".codex", ".agents", ".aws", "output", "temp", "node_modules", "__pycache__", ".pytest_cache", ".venv", "venv"} +MAX_ARCHIVE_BYTES = 256 * 1024 * 1024 +MAX_FILE_BYTES = 32 * 1024 * 1024 + + +def _json(path: Path) -> dict[str, Any]: + try: + if path.is_symlink() or path.stat().st_size > 1024 * 1024: + raise ValueError("invalid metadata file") + data = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(data, dict): + raise ValueError("metadata must be an object") + return data + except (OSError, ValueError) as exc: + raise UpdateHostError("Cursor managed-local metadata is unavailable or invalid") from exc + + +def _digest(data: Mapping[str, Any]) -> str: + return hashlib.sha256(json.dumps(data, sort_keys=True, separators=(",", ":")).encode()).hexdigest() + + +def _write_json(path: Path, data: Mapping[str, Any]) -> None: + temporary = path.with_name(path.name + ".tmp-" + uuid.uuid4().hex) + try: + with temporary.open("x", encoding="utf-8") as stream: + json.dump(data, stream, sort_keys=True) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, path) + descriptor = os.open(path.parent, os.O_RDONLY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + finally: + temporary.unlink(missing_ok=True) + + +def _distributed(relative: PurePosixPath) -> bool: + parts = relative.parts + if not parts or any(part in EXCLUDED_PARTS or part.startswith(".env") for part in parts): + return False + if relative.name in {"credentials.json", ".npmrc", RECEIPT} or relative.suffix in {".pyc", ".log"}: + return False + return (len(parts) == 1 and parts[0] in DISTRIBUTION_FILES) or (len(parts) > 1 and parts[0] in DISTRIBUTION_DIRS) + + +def _tree_digest(root: Path) -> str: + digest = hashlib.sha256() + for directory, dirs, files in os.walk(root, followlinks=False): + base = Path(directory) + dirs[:] = sorted(dirs) + for name in dirs: + path = base / name + relative = PurePosixPath(path.relative_to(root).as_posix()) + if path.is_symlink(): + raise UpdateHostError("managed distribution contains a symlink") + if name != "__pycache__" and (name in EXCLUDED_PARTS or name.startswith(".env") or relative.parts[0] not in DISTRIBUTION_DIRS): + raise UpdateHostError("managed installation contains unmanaged paths; preserve them outside the installation before updating") + for name in sorted(files): + path = base / name + relative = PurePosixPath(path.relative_to(root).as_posix()) + if relative.as_posix() == RECEIPT or ("__pycache__" in relative.parts and relative.suffix == ".pyc"): + continue + if not _distributed(relative): + raise UpdateHostError("managed installation contains unmanaged files; preserve them outside the installation before updating") + if path.is_symlink() or not path.is_file() or path.stat().st_size > MAX_FILE_BYTES: + raise UpdateHostError("managed distribution contains an invalid file") + digest.update(relative.as_posix().encode() + b"\0") + digest.update(str(path.stat().st_mode & 0o111).encode() + b"\0") + digest.update(hashlib.sha256(path.read_bytes()).digest()) + return digest.hexdigest() + + +def _exchange(left: Path, right: Path) -> None: + """Atomic directory exchange; no delete/copy fallback is safe here.""" + library = ctypes.CDLL(None, use_errno=True) + if sys.platform == "darwin" and hasattr(library, "renamex_np"): + call = library.renamex_np + call.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_uint] + result = call(os.fsencode(left), os.fsencode(right), 2) # RENAME_SWAP + elif sys.platform.startswith("linux") and hasattr(library, "renameat2"): + call = library.renameat2 + call.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint] + result = call(-100, os.fsencode(left), -100, os.fsencode(right), 2) # RENAME_EXCHANGE + else: + raise UpdateHostError("atomic managed-local update requires macOS or Linux directory exchange") + if result != 0: + raise UpdateHostError(f"atomic managed-local exchange failed (errno {ctypes.get_errno()})") + + +def plugin_version(plugin_root: Path) -> str: + data = _json(plugin_root / ".cursor-plugin/plugin.json") + value = data.get("version") + if data.get("name") != PLUGIN_NAME or not isinstance(value, str) or not re.fullmatch(r"v?\d+\.\d+(?:\.\d+)?", value): + raise UpdateHostError("Cursor plugin version manifest is invalid") + return value + + +def _validate_bundle(root: Path) -> None: + """Validate packaged references as data; never execute candidate plugin code.""" + def resource(value: Any) -> Path: + if not isinstance(value, str) or not value or Path(value).is_absolute() or ".." in PurePosixPath(value).parts: + raise UpdateHostError("Cursor distribution has an invalid resource path") + path = root / value + if path.is_symlink() or not path.exists() or not path.resolve().is_relative_to(root.resolve()): + raise UpdateHostError("Cursor distribution is missing a required packaged resource") + return path + manifest = _json(root / ".cursor-plugin/plugin.json") + for key in ("skills", "hooks", "commands", "agents", "rules"): + declared = manifest.get(key) + for item in declared if isinstance(declared, list) else ([declared] if isinstance(declared, str) else []): + resource(item) + host = _json(resource("hosts/cursor/host.json")) + if host.get("host_id") != "cursor" or host.get("host_api_version") not in {"1.1", "1.2"}: + raise UpdateHostError("Cursor distribution has an invalid Host Kit") + adapters = host.get("adapters") + if not isinstance(adapters, dict): + raise UpdateHostError("Cursor distribution has no Host Kit adapters") + for reference in adapters.values(): + if not isinstance(reference, str): + raise UpdateHostError("Cursor distribution has an invalid Host Kit adapter") + if reference.startswith("resource:"): + resource(reference.removeprefix("resource:")) + elif reference.startswith("python:"): + module = reference.removeprefix("python:").split(":", 1)[0] + if not re.fullmatch(r"[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*", module): + raise UpdateHostError("Cursor distribution has an invalid adapter module") + resource("scripts/" + module.replace(".", "/") + ".py") + projection = _json(resource("hosts/cursor/command-projection.json")) + expected = {"init", "propose", "apply", "archive", "ut", "bug-fix", "update", "status", "config"} + entries = projection.get("entrypoints") + if not isinstance(entries, dict) or set(entries) != expected: + raise UpdateHostError("Cursor distribution must include all nine command entries") + for name, pair in entries.items(): + expected_pair = [f"hosts/cursor/skills/helix-{name}/SKILL.md", f"commands/{name}.md"] + if pair != expected_pair: + raise UpdateHostError("Cursor distribution redirects a canonical command") + for value in pair: + resource(value) + + +class CursorUpdateAdapter(UpdateHostAdapter): + host_id = "cursor" + supported_scopes = frozenset({"local"}) + manifest_directory = ".cursor-plugin" + marketplace_manifest_directory = ".cursor-plugin" + + def __init__(self, normalize_version: Callable[[Any], str], read_json: Callable[[Path], dict[str, Any]], *, home: Path | None = None): + self._normalize_version = normalize_version + self._read_json = read_json + self._home = (home or Path(os.environ.get("HELIXHARNESS_CURSOR_HOME") or Path.home() / ".cursor")).expanduser().resolve() + self._snapshots: dict[str, dict[str, Any]] = {} + + def entry_policy(self, plugin_root: Path) -> dict[str, Any] | None: + root = plugin_root.expanduser().absolute() + cache = self._home / "plugins/cache/helixharness-marketplace/helix" + native_namespace = self._home / "plugins/cache" + if root.parent != cache or not re.fullmatch(r"[0-9a-f]{40}", root.name): + if root == native_namespace or native_namespace in root.parents: + raise UpdateHostError("unrecognized Cursor native cache root") + return None + if any(p.is_symlink() for p in (root, *root.parents)): + raise UpdateHostError("Cursor native installation must not use symlinks") + manifest = self._read_json(root / ".cursor-plugin/plugin.json") + if manifest.get("name") != "helix": + raise UpdateHostError("Cursor native manifest does not identify helix") + version = self._normalize_version(manifest.get("version")) + return {"state": "unavailable", "update_status": "unknown", + "reason": "installation_update_not_supported", + "warning": "WARN:cursor_native_automatic_update_unsupported", + "next_action": "continue_with_warning", "platform": "cursor", + "installation_kind": "cursor-native", "current_version": version, + "cache_revision": root.name, "plugin_root": str(root), + "automatic_update_supported": False, + "manual_steps": ["Review a new Git commit and explicitly replace the project binding, or update through the owning Cursor marketplace.", + "Reload Window, start a new Agent, and verify the actual Skill and Hook roots."]} + + def state_home(self) -> Path: + return self._home + + @property + def registration_path(self) -> Path: + return self._home / "helixharness/managed-install.json" + + @property + def install_root(self) -> Path: + return self._home / "plugins/local/helix" + + def _safe_paths(self) -> None: + for relative in ("plugins", "plugins/local", "plugins/local/helix", "helixharness", "helixharness/rollback", "helixharness/transactions", "helixharness/managed-install.json", "helixharness/managed-install.pending.json"): + if (self._home / relative).is_symlink(): + raise UpdateHostError("Cursor managed-local paths must not be symlinks") + + @staticmethod + def _source(source: Any, ref: Any) -> None: + if not isinstance(source, str) or not source or any(char in source for char in "\r\n\0") or source.startswith("-"): + raise UpdateHostError("invalid managed-local Git source") + try: + parsed = urlparse(source) + allowed = Path(source).is_absolute() or (parsed.scheme in {"https", "ssh"} and bool(parsed.hostname)) or bool(re.fullmatch(r"[\w.-]+@[\w.-]+:[^\s]+", source)) + except ValueError as exc: + raise UpdateHostError("invalid managed-local Git URL") from exc + if not allowed or parsed.password is not None or parsed.query or parsed.fragment or (parsed.scheme == "https" and parsed.username is not None): + raise UpdateHostError("managed-local source must be a credential-free Git URL or absolute local Git path") + if not isinstance(ref, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._/-]*", ref) or ".." in ref: + raise UpdateHostError("invalid managed-local Git ref") + + def _registration(self) -> dict[str, Any]: + self._safe_paths() + data = _json(self.registration_path) + return self._validate_registration(data) + + def _validate_registration(self, data: dict[str, Any]) -> dict[str, Any]: + if set(data) != REGISTRATION_KEYS or data.get("schema_version") != "1.0" or data.get("kind") != "helix-managed-local": + raise UpdateHostError("Cursor installation is not registered as Helix managed-local") + if data["install_root"] != str(self.install_root) or not re.fullmatch(r"[0-9a-f]{32}", str(data.get("install_id"))): + raise UpdateHostError("managed-local registration identity does not match the designated installation") + self._source(data["source"], data["ref"]) + source = PurePosixPath(str(data["plugin_source"])) + if source.is_absolute() or ".." in source.parts or str(source) != data["plugin_source"]: + raise UpdateHostError("managed-local plugin source escapes its Git tree") + return data + + def _receipt(self, registration: Mapping[str, Any], root: Path | None = None) -> dict[str, Any]: + root = root or self.install_root + receipt = _json(root / RECEIPT) + if set(receipt) != RECEIPT_KEYS or receipt.get("schema_version") != "1.0" or receipt.get("install_id") != registration["install_id"] or receipt.get("registration_sha256") != _digest(registration): + raise UpdateHostError("managed-local installation receipt does not match its registration") + if not re.fullmatch(r"[0-9a-f]{40,64}", str(receipt.get("commit"))) or receipt.get("tree_sha256") != _tree_digest(root): + raise UpdateHostError("managed-local installed files differ from the recorded Git distribution") + if self._normalize_version(plugin_version(root)) != receipt.get("version"): + raise UpdateHostError("managed-local installed version differs from its receipt") + return receipt + + def inspect_installation(self, repo_root: Path, plugin_root: Path, runner: BoundedCommandRunner, plugin_list_data: Any = None) -> dict[str, Any]: + del repo_root, runner + if plugin_list_data is not None: + raise UpdateHostError("Cursor managed-local does not accept a fabricated native plugin catalog") + registration = self._registration() + if plugin_root.resolve() != self.install_root or plugin_root.is_symlink(): + raise UpdateHostError("executing Cursor plugin is not the registered managed-local installation; marketplace caches are never adopted") + receipt = self._receipt(registration) + return {"platform": self.host_id, "plugin_id": PLUGIN_ID, "current_version": receipt["version"], "current_scope": "local", "current_source": MARKETPLACE, "available_scopes": ["local"], "installation_kind": "helix-managed-local", "plugin_root": str(self.install_root), "install_id": registration["install_id"], "registration_sha256": _digest(registration), "tree_sha256": receipt["tree_sha256"]} + + def marketplace_root(self, runner: BoundedCommandRunner, marketplace_list_data: Any = None) -> Path: + del runner, marketplace_list_data + raise UpdateHostError("Cursor managed-local policy requires an isolated Git snapshot") + + @contextmanager + def _snapshot(self, source: str, ref: str, runner: BoundedCommandRunner) -> Iterator[tuple[Path, dict[str, str]]]: + self._source(source, ref) + with tempfile.TemporaryDirectory(prefix="helix-cursor-source-") as temporary: + base = Path(temporary).resolve() + git = base / "git" + git_args = ["git", "-c", "core.hooksPath=/dev/null", "-c", "init.templateDir=", "-c", "protocol.ext.allow=never"] + runner.run([*git_args, "init", "--quiet", str(git)], timeout=MARKETPLACE_TIMEOUT_SECONDS) + runner.run([*git_args, "-C", str(git), "fetch", "--depth=1", "--", source, ref], timeout=MARKETPLACE_TIMEOUT_SECONDS) + commit = runner.run([*git_args, "-C", str(git), "rev-parse", "FETCH_HEAD^{commit}"], timeout=MARKETPLACE_TIMEOUT_SECONDS).stdout.strip() + if not re.fullmatch(r"[0-9a-f]{40,64}", commit): + raise UpdateHostError("Git snapshot did not identify an immutable commit") + archive = base / "source.tar" + runner.run([*git_args, "-C", str(git), "archive", "--format=tar", f"--output={archive}", commit], timeout=MARKETPLACE_TIMEOUT_SECONDS) + if archive.stat().st_size > MAX_ARCHIVE_BYTES: + raise UpdateHostError("managed-local distribution exceeds its size bound") + root = base / "snapshot" + root.mkdir() + with tarfile.open(archive) as tar: + members = tar.getmembers() + metadata = next((item for item in members if item.name == ".cursor-plugin/marketplace.json"), None) + if metadata is None or not metadata.isfile() or metadata.size > 1024 * 1024: + raise UpdateHostError("Git source lacks a Cursor marketplace manifest") + stream = tar.extractfile(metadata) + try: + marketplace = json.loads(stream.read()) if stream else None + except (ValueError, UnicodeError) as exc: + raise UpdateHostError("invalid Cursor marketplace JSON in Git source") from exc + plugins = marketplace.get("plugins") if isinstance(marketplace, dict) else None + matches = [item for item in plugins if isinstance(item, dict) and item.get("name") == PLUGIN_NAME] if isinstance(plugins, list) else [] + if not isinstance(marketplace, dict) or marketplace.get("name") != MARKETPLACE or len(matches) != 1: + raise UpdateHostError("Git source is not the HelixHarness marketplace") + plugin_source = PurePosixPath(str(matches[0].get("source", ""))) + if plugin_source.is_absolute() or ".." in plugin_source.parts or not matches[0].get("source"): + raise UpdateHostError("Git plugin source escapes the marketplace") + plugin_root = root / str(plugin_source) + plugin_root.mkdir(parents=True, exist_ok=True) + seen: set[str] = set() + for member in members: + path = PurePosixPath(member.name) + if path.is_absolute() or ".." in path.parts: + raise UpdateHostError("Git archive contains an escaping path") + try: + relative = path.relative_to(plugin_source) + except ValueError: + continue + if not _distributed(relative) or member.isdir(): + continue + if not member.isfile() or member.size > MAX_FILE_BYTES or relative.as_posix() in seen: + raise UpdateHostError("Git distribution contains an unsupported link, duplicate or oversized file") + seen.add(relative.as_posix()) + target = plugin_root / relative.as_posix() + target.parent.mkdir(parents=True, exist_ok=True) + content = tar.extractfile(member) + if content is None: + raise UpdateHostError("Git distribution file is unreadable") + target.write_bytes(content.read()) + target.chmod(0o755 if member.mode & 0o111 else 0o644) + marketplace_target = root / ".cursor-plugin/marketplace.json" + marketplace_target.parent.mkdir(parents=True, exist_ok=True) + marketplace_target.write_text(json.dumps(marketplace), encoding="utf-8") + version = self._normalize_version(plugin_version(plugin_root)) + from version_update import _load_policy + try: + policy = _load_policy(plugin_root / "reference/version-policy.json") + except ValueError as exc: + raise UpdateHostError("Cursor source version policy is invalid") from exc + if version != self._normalize_version(matches[0].get("version")) or version != self._normalize_version(policy.get("latest_version")): + raise UpdateHostError("Cursor source manifest and version policy disagree") + _validate_bundle(plugin_root) + yield root, {"commit": commit, "plugin_source": str(plugin_source), "version": version, "tree_sha256": _tree_digest(plugin_root)} + + @contextmanager + def refresh_marketplace(self, runner: BoundedCommandRunner) -> Iterator[Path]: + registration = self._registration() + with self._snapshot(registration["source"], registration["ref"], runner) as (root, snapshot): + if snapshot["plugin_source"] != registration["plugin_source"]: + raise UpdateHostError("managed-local source layout changed; explicit reinstallation is required") + self._snapshots[str(root)] = snapshot + try: + yield root + finally: + self._snapshots.pop(str(root), None) + + def update_binding(self, snapshot_root: Path | None, installation: Mapping[str, Any], runner: BoundedCommandRunner) -> dict[str, Any]: + del runner + registration = self._registration() + snapshot = self._snapshots.get(str(snapshot_root)) + if snapshot is None or installation["registration_sha256"] != _digest(registration): + raise UpdateHostError("managed-local source changed during version checking") + return {"schema_version": "1.0", "kind": "helix-managed-local", "install_id": registration["install_id"], "registration_sha256": _digest(registration), "install_root": registration["install_root"], "source": registration["source"], "ref": registration["ref"], "plugin_source": registration["plugin_source"], "current_tree": installation["tree_sha256"], "target_commit": snapshot["commit"], "target_tree": snapshot["tree_sha256"], "target_version": snapshot["version"]} + + def validate_update_binding(self, binding: Any) -> None: + if not isinstance(binding, dict) or set(binding) != BINDING_KEYS or binding.get("schema_version") != "1.0" or binding.get("kind") != "helix-managed-local": + raise UpdateHostError("Cursor managed-local update requires a checked immutable source binding") + for key in ("registration_sha256", "current_tree", "target_tree"): + if not re.fullmatch(r"[0-9a-f]{64}", str(binding[key])): + raise UpdateHostError("invalid managed-local source digest") + if not re.fullmatch(r"[0-9a-f]{40,64}", str(binding["target_commit"])): + raise UpdateHostError("invalid managed-local source commit") + self._normalize_version(binding["target_version"]) + + def _live_binding(self, binding: Any, *, allow_target: bool = False) -> tuple[dict[str, Any], dict[str, Any]]: + self.validate_update_binding(binding) + registration = self._registration() + if _digest(registration) != binding["registration_sha256"] or any(registration[key] != binding[key] for key in ("install_id", "install_root", "source", "ref", "plugin_source")): + raise UpdateHostError("managed-local registration or source changed after version checking") + receipt = self._receipt(registration) + current = receipt["tree_sha256"] == binding["current_tree"] + target = receipt["tree_sha256"] == binding["target_tree"] and receipt["commit"] == binding["target_commit"] and receipt["version"] == binding["target_version"] + if not current and not (allow_target and target): + raise UpdateHostError("managed-local installed tree changed after authorization") + return registration, receipt + + def prepare_update_binding(self, binding: Any) -> str: + self._live_binding(binding) + return f"安装方式:Helix 管理的 Cursor local 安装(非原生市场更新)\n安装位置:{binding['install_root']}\n来源:{binding['source']}\n已核验 commit:{binding['target_commit']}\n文件摘要:{binding['target_tree']}\n更新后须 Developer: Reload Window 或重启 Cursor。" + + def cache_binding_matches_installation(self, binding: Any, installation: Mapping[str, Any]) -> bool: + return isinstance(binding, dict) and binding.get("install_id") == installation.get("install_id") and binding.get("registration_sha256") == installation.get("registration_sha256") and binding.get("current_tree") == installation.get("tree_sha256") + + def install_steps(self, scope: str, runner: BoundedCommandRunner) -> tuple[InstallStep, ...]: + del runner + self.validate_scope(scope) + return (InstallStep("managed-local-atomic-exchange", ()),) + + def _update_transaction(self, authorization: Mapping[str, Any]) -> tuple[Path, Path, dict[str, str]]: + challenge = str(authorization.get("challenge_id", "")) + if not re.fullmatch(r"upd_[0-9a-f]{24}", challenge): + raise UpdateHostError("invalid managed-local update transaction") + backup = self._home / "helixharness/rollback" / challenge + transaction = self._home / "helixharness/transactions" / (challenge + ".json") + # This independent receipt is written before deployment. A later check + # may refresh its cache, but cannot change what this transaction approved. + approved = {key: authorization.get(key) for key in ( + "challenge_id", "platform", "scope", "current_version", "target_version", + "update_status", "created_at", "expires_at", "confirmation_source", + "authorized_at", "update_binding", "approved_releases", + )} + return backup, transaction, { + "binding_sha256": _digest(authorization["update_binding"]), + "authorization_sha256": _digest(approved), "backup": str(backup), + } + + def validate_install_resume(self, authorization: Mapping[str, Any], *, plugin_root: Path) -> bool: + if (authorization.get("state") != "installing" + or authorization.get("confirmation_source") != "interactive-user" + or "approved_releases" not in authorization): + return False + self.validate_scope(str(authorization.get("scope"))) + if plugin_root.is_symlink() or plugin_root.resolve() != self.install_root: + raise UpdateHostError("managed-local resume source differs from the registered installation") + binding = authorization.get("update_binding") + self._live_binding(binding, allow_target=True) + if binding["target_version"] != authorization.get("target_version"): + raise UpdateHostError("managed-local resume target differs from authorization") + _, transaction, expected = self._update_transaction(authorization) + if not transaction.exists(): + return False + if _json(transaction) != expected: + raise UpdateHostError("managed-local transaction no longer matches the approved update") + return True + + def _verify_target(self, registration: Mapping[str, Any], binding: Mapping[str, Any]) -> None: + if self._registration() != registration: + raise UpdateHostError("managed-local registration changed during deployment") + receipt = self._receipt(registration) + _validate_bundle(self.install_root) + if any(receipt[key] != binding[target] for key, target in (("version", "target_version"), ("commit", "target_commit"), ("tree_sha256", "target_tree"))): + raise UpdateHostError("managed-local post-install verification failed") + + def execute_install_step(self, step: InstallStep, runner: BoundedCommandRunner, *, authorization: Mapping[str, Any], plugin_root: Path) -> None: + from version_update import _lock + with _lock(self.registration_path.with_name("managed-install.guard")): + self._execute_install_step(step, runner, authorization=authorization, plugin_root=plugin_root) + + def _execute_install_step(self, step: InstallStep, runner: BoundedCommandRunner, *, authorization: Mapping[str, Any], plugin_root: Path) -> None: + if authorization.get("state") != "installing" or authorization.get("confirmation_source") != "interactive-user": + raise UpdateHostError("managed-local deployment requires the confirmed update state machine") + if step.step_id != "managed-local-atomic-exchange" or plugin_root.resolve() != self.install_root: + raise UpdateHostError("managed-local install step or executing source is invalid") + binding = authorization.get("update_binding") + registration, receipt = self._live_binding(binding, allow_target=True) + if binding["target_version"] != authorization.get("target_version"): + raise UpdateHostError("managed-local target version differs from authorization") + backup, transaction, transaction_data = self._update_transaction(authorization) + if transaction.exists() and _json(transaction) != transaction_data: + raise UpdateHostError("managed-local transaction no longer matches the approved update") + if receipt["tree_sha256"] == binding["target_tree"] and receipt["commit"] == binding["target_commit"]: + if not transaction.exists(): + raise UpdateHostError("managed-local deployment has no independent transaction receipt") + self._verify_target(registration, binding) + return # Recovery after a process stopped following the atomic exchange. + self._safe_paths() + backup.parent.mkdir(parents=True, exist_ok=True) + transaction.parent.mkdir(parents=True, exist_ok=True) + if backup.is_symlink(): + raise UpdateHostError("managed-local rollback directory must not be a symlink") + if backup.exists(): + if _json(transaction) != transaction_data: + raise UpdateHostError("managed-local transaction already has an unrecognized rollback directory") + shutil.rmtree(backup) # Retry staging after interruption; live old tree was verified above. + _write_json(transaction, transaction_data) + swapped = False + try: + with self._snapshot(registration["source"], binding["target_commit"], runner) as (root, snapshot): + if any(snapshot[key] != binding[target] for key, target in (("commit", "target_commit"), ("version", "target_version"), ("tree_sha256", "target_tree"), ("plugin_source", "plugin_source"))): + raise UpdateHostError("approved managed-local Git snapshot no longer matches its binding") + shutil.copytree(root / snapshot["plugin_source"], backup) + new_receipt = {"schema_version": "1.0", "install_id": registration["install_id"], "registration_sha256": _digest(registration), "version": binding["target_version"], "commit": binding["target_commit"], "tree_sha256": binding["target_tree"]} + _write_json(backup / RECEIPT, new_receipt) + self._live_binding(binding) + self._receipt(registration, backup) + _exchange(self.install_root, backup) + swapped = True + self._verify_target(registration, binding) + except BaseException: + if swapped: + _exchange(self.install_root, backup) + if backup.exists(): + shutil.rmtree(backup) + raise + + def verify_installation(self, authorization: Mapping[str, Any], runner: BoundedCommandRunner, *, plugin_root: Path) -> dict[str, Any]: + del runner + if plugin_root.resolve() != self.install_root: + raise UpdateHostError("Cursor source binding changed during installation") + binding = authorization.get("update_binding") + registration, _ = self._live_binding(binding, allow_target=True) + _, transaction, expected = self._update_transaction(authorization) + if _json(transaction) != expected: + raise UpdateHostError("managed-local transaction no longer matches the approved update") + self._verify_target(registration, binding) + return {"installation_kind": "helix-managed-local", "verified_version": binding["target_version"], "verified_commit": binding["target_commit"], "restart_required": True, "reload_instruction": "Developer: Reload Window or restart Cursor; start a new Agent session."} + + @staticmethod + def _initial_sync_directory(path: Path) -> None: + descriptor = os.open(path, os.O_RDONLY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + + @staticmethod + def _initial_rename_exclusive(source: Path, destination: Path) -> None: + """Publish without replacing even an empty directory or unrelated metadata.""" + library = ctypes.CDLL(None, use_errno=True) + if sys.platform == "darwin" and hasattr(library, "renamex_np"): + call = library.renamex_np + call.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_uint] + result = call(os.fsencode(source), os.fsencode(destination), 4) # RENAME_EXCL + elif sys.platform.startswith("linux") and hasattr(library, "renameat2"): + call = library.renameat2 + call.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint] + result = call(-100, os.fsencode(source), -100, os.fsencode(destination), 1) # RENAME_NOREPLACE + else: + raise UpdateHostError("initial managed-local installation requires an exclusive atomic rename") + if result != 0: + error = ctypes.get_errno() + raise OSError(error, os.strerror(error), str(destination)) + + def _move_initial_candidate(self, staged: Path) -> None: + self._initial_rename_exclusive(staged, self.install_root) + self._initial_sync_directory(self.install_root.parent) + self._initial_sync_directory(staged.parent) + + def _publish_initial_registration(self, registration: Mapping[str, Any], staged: Path) -> None: + self._safe_paths() + metadata = staged.parent / "registration.json" + if (metadata.exists() or metadata.is_symlink()) and _json(metadata) != registration: + raise UpdateHostError("initial recovery registration candidate changed") + if self.registration_path.exists(): + if self._registration() != registration: + raise UpdateHostError("initial recovery cannot replace another registration") + metadata.unlink(missing_ok=True) + else: + if _json(metadata) != registration: + raise UpdateHostError("initial recovery registration candidate changed") + self._initial_rename_exclusive(metadata, self.registration_path) + self._initial_sync_directory(self.registration_path.parent) + + def _initial_journal(self, pending: Path) -> tuple[dict[str, Any], Path, dict[str, Any]]: + journal = _json(pending) + if set(journal) != {"schema_version", "registration", "staged_root", "receipt"} or journal["schema_version"] != "1.0" or not isinstance(journal["registration"], dict) or not isinstance(journal["receipt"], dict): + raise UpdateHostError("invalid managed-local initial recovery journal") + registration = self._validate_registration(journal["registration"]) + staged = self.registration_path.parent / ("initial-" + registration["install_id"]) / "plugin" + if journal["staged_root"] != str(staged) or staged.parent.is_symlink() or staged.is_symlink(): + raise UpdateHostError("initial recovery staging path escapes managed storage") + receipt = journal["receipt"] + if set(receipt) != RECEIPT_KEYS or receipt.get("schema_version") != "1.0" or receipt.get("install_id") != registration["install_id"] or receipt.get("registration_sha256") != _digest(registration): + raise UpdateHostError("initial recovery receipt does not match its registration") + return registration, staged, receipt + + def _recover_initial_locked(self, pending: Path) -> dict[str, Any]: + self._safe_paths() + registration, staged, expected_receipt = self._initial_journal(pending) + if self.registration_path.exists() and self._registration() != registration: + raise UpdateHostError("initial recovery cannot replace another registration") + metadata = staged.parent / "registration.json" + if (not self.registration_path.exists() or metadata.exists() or metadata.is_symlink()) and _json(metadata) != registration: + raise UpdateHostError("initial recovery registration candidate changed") + if self.install_root.exists() and staged.exists(): + raise UpdateHostError("initial recovery found an occupied installation and a staged candidate") + candidate = self.install_root if self.install_root.exists() else staged + receipt = self._receipt(registration, candidate) + if receipt != expected_receipt: + raise UpdateHostError("initial recovery candidate differs from the authorized Git snapshot") + _validate_bundle(candidate) + if candidate == staged: + self._move_initial_candidate(staged) + # Repeat validation immediately before publication, including after a recovered rename. + self._safe_paths() + if self._receipt(registration) != expected_receipt: + raise UpdateHostError("initial recovery candidate changed during publication") + self._initial_sync_directory(self.install_root.parent) + self._publish_initial_registration(registration, staged) + if staged.parent.exists(): + staged.parent.rmdir() # Never remove unexpected files beside the candidate. + pending.unlink() + try: + self._initial_sync_directory(pending.parent) + except OSError: + # Registration and installation are already durable. A stale journal after a + # crash is safe to recover; a cleanup fsync failure does not undo the commit. + pass + return {"installed": True, "recovered": True, "installation_kind": "helix-managed-local", "plugin_root": str(self.install_root), "version": receipt["version"], "commit": receipt["commit"], "restart_required": True} + + def initialize(self, source: str, ref: str, runner: BoundedCommandRunner, *, user_confirmed: bool) -> dict[str, Any]: + if not user_confirmed: + raise UpdateHostError("managed-local installation requires explicit user confirmation") + library = ctypes.CDLL(None) + if not ((sys.platform == "darwin" and hasattr(library, "renamex_np")) or (sys.platform.startswith("linux") and hasattr(library, "renameat2"))): + raise UpdateHostError("managed-local installation requires macOS or Linux atomic directory exchange") + self._safe_paths() + pending = self.registration_path.with_name("managed-install.pending.json") + from version_update import _lock + with _lock(self.registration_path.with_name("managed-install.guard")): + self._safe_paths() + if pending.exists(): + registration, _, _ = self._initial_journal(pending) + if registration["source"] != source or registration["ref"] != ref: + raise UpdateHostError("initial retry source or ref differs from the confirmed installation") + return self._recover_initial_locked(pending) + if self.install_root.exists() or self.registration_path.exists(): + raise UpdateHostError("managed-local initial install never adopts or overwrites an existing installation") + with self._snapshot(source, ref, runner) as (root, snapshot): + registration = {"schema_version": "1.0", "kind": "helix-managed-local", "install_id": uuid.uuid4().hex, "install_root": str(self.install_root), "source": source, "ref": ref, "plugin_source": snapshot["plugin_source"]} + receipt = {"schema_version": "1.0", "install_id": registration["install_id"], "registration_sha256": _digest(registration), "version": snapshot["version"], "commit": snapshot["commit"], "tree_sha256": snapshot["tree_sha256"]} + self.install_root.parent.mkdir(parents=True, exist_ok=True) + staging_directory = self.registration_path.parent / ("initial-" + registration["install_id"]) + staging_directory.mkdir() + staged = staging_directory / "plugin" + try: + shutil.copytree(root / snapshot["plugin_source"], staged) + _write_json(staged / RECEIPT, receipt) + self._receipt(registration, staged) + _write_json(staging_directory / "registration.json", registration) + self._safe_paths() + if self.install_root.exists() or self.registration_path.exists() or pending.exists(): + raise UpdateHostError("managed-local installation appeared while preparing initial install") + _write_json(pending, {"schema_version": "1.0", "registration": registration, "staged_root": str(staged), "receipt": receipt}) + result = self._recover_initial_locked(pending) + except BaseException: + # A failed directory fsync may still have published the journal. Once it + # is visible, retain its candidate through ordinary errors and exits. + if not pending.exists() and staging_directory.exists(): + shutil.rmtree(staging_directory) + raise + result.pop("recovered", None) + return result + + def recover_initial(self, *, user_confirmed: bool) -> dict[str, Any]: + if not user_confirmed: + raise UpdateHostError("initial installation recovery requires explicit user confirmation") + from version_update import _lock + self._safe_paths() + pending = self.registration_path.with_name("managed-install.pending.json") + with _lock(self.registration_path.with_name("managed-install.guard")): + return self._recover_initial_locked(pending) diff --git a/helixharness/scripts/user_config.py b/helixharness/scripts/user_config.py index 8f21d60..213e459 100644 --- a/helixharness/scripts/user_config.py +++ b/helixharness/scripts/user_config.py @@ -3,6 +3,7 @@ from __future__ import annotations import argparse +import hashlib import json import os from pathlib import Path @@ -18,6 +19,31 @@ class ConfigError(ValueError): """A setting cannot be safely read or updated.""" +TELEMETRY_NOTICE_ID = 'helixharness-eval-data-notice-v1' +EVAL_PROTOCOL = Path(__file__).resolve().parents[1] / 'reference' / 'eval-protocol.md' + + +def telemetry_enable_notice() -> dict[str, str]: + """Read the canonical notice; its digest is a version check, not UI attestation.""" + source = EVAL_PROTOCOL.read_text(encoding='utf-8') + start = f'' + end = f'' + if source.count(start) != 1 or source.count(end) != 1: + raise ConfigError('canonical telemetry data notice is missing or ambiguous') + before, _, remaining = source.partition(start) + section, _, _ = remaining.partition(end) + if end in before: + raise ConfigError('canonical telemetry data notice markers are out of order') + lines = section.strip().splitlines() + if len(lines) < 3 or lines[0] != '```text' or lines[-1] != '```': + raise ConfigError('canonical telemetry data notice has an invalid format') + text = '\n'.join(lines[1:-1]) + if not text.strip(): + raise ConfigError('canonical telemetry data notice is empty') + return {'id': TELEMETRY_NOTICE_ID, 'text': text, + 'sha256': hashlib.sha256(text.encode('utf-8')).hexdigest()} + + def channel_home(channel: str) -> Path: if channel not in {'telemetry', 'feedback'}: raise ConfigError('unsupported configuration channel') @@ -114,6 +140,8 @@ def main(argv: list[str] | None = None) -> int: parser.add_argument('--platform', required=True) parser.add_argument('--scope', choices=('project', 'user')) parser.add_argument('--user-confirmed', action='store_true') + parser.add_argument('--telemetry-notice-shown', metavar='SHA256', + help='internal: current notice digest, only after displaying its text to the user') action = parser.add_mutually_exclusive_group() action.add_argument('--telemetry', choices=('enabled', 'disabled')) action.add_argument('--report-endpoint') @@ -127,10 +155,24 @@ def main(argv: list[str] | None = None) -> int: raise ConfigError('repo root is not a directory') if bool(args.scope) != bool(args.telemetry): raise ConfigError('--telemetry and --scope must be specified together') + if args.telemetry_notice_shown is not None and args.telemetry != 'enabled': + raise ConfigError('--telemetry-notice-shown is only valid when enabling telemetry') mutation = None + notice_required = None if args.telemetry: - mutation = set_consent(repo, args.platform, args.scope, args.telemetry, - user_confirmed=args.user_confirmed) + if not args.user_confirmed: + raise ConfigError('configuration change requires an explicit user request or selection') + if args.telemetry == 'enabled': + if get_host_adapter(normalize_host_id(args.platform)) is None: + raise ConfigError('telemetry host is not supported') + notice = telemetry_enable_notice() + if args.telemetry_notice_shown is None: + notice_required = notice + elif args.telemetry_notice_shown != notice['sha256']: + raise ConfigError('telemetry data notice acknowledgment is invalid or stale; display the current notice first') + if notice_required is None: + mutation = set_consent(repo, args.platform, args.scope, args.telemetry, + user_confirmed=args.user_confirmed) for channel, value, reset in ( ('telemetry', args.report_endpoint, args.reset_report_endpoint), ('feedback', args.feedback_endpoint, args.reset_feedback_endpoint), @@ -138,7 +180,20 @@ def main(argv: list[str] | None = None) -> int: if value is not None or reset: mutation = set_endpoint(channel, None if reset else value, user_confirmed=args.user_confirmed) - result: dict[str, Any] = {'read_only': mutation is None} + # Completion describes this CLI request, not whether a setting changed. + result: dict[str, Any] = {'read_only': mutation is None, 'request_complete': notice_required is None} + if notice_required is not None: + result.update({'change': {'updated': False, 'reason': 'telemetry_notice_required'}, + 'notice_required': True, + 'next_action': 'display_notice_before_enable', + 'notice': notice_required, + 'continuation': { + 'after': 'display_notice_to_user', + 'action': 'repeat_same_request', + 'same_turn': True, + 'new_user_confirmation_required': False, + 'append_arguments': ['--telemetry-notice-shown', notice_required['sha256']], + }}) if mutation is not None: result['change'] = mutation # Report channels independently: a corrupt consent cache must not hide diff --git a/helixharness/scripts/validate_init_outputs.py b/helixharness/scripts/validate_init_outputs.py index e9de8bb..71d77af 100644 --- a/helixharness/scripts/validate_init_outputs.py +++ b/helixharness/scripts/validate_init_outputs.py @@ -10,6 +10,7 @@ from host_runtime import HostContractError, HostRegistry from host_runtime.project_config import load_project_config +from init_guidance import project_guidance from project_hooks_cli import project_hooks from workflow import WorkflowError from workspace import WorkspaceError, load_registry @@ -142,6 +143,11 @@ def validate( checks.append(_result("repo_root", str(root), "fail", "仓库根路径不是目录")) else: checks.append(_check_file(root, project_config.entry_file)) + try: + project_guidance(root, manifest.host_id, mode, "check") + checks.append(_result("init_guidance", project_config.entry_file, "pass", "宿主命令管理区完整且与模板一致")) + except (OSError, UnicodeError, ValueError, HostContractError) as exc: + checks.append(_result("init_guidance", project_config.entry_file, "fail", str(exc))) if mode == "workspace": checks.extend(_check_dir(root, path) for path in WORKSPACE_DIRS) diff --git a/helixharness/scripts/version_update.py b/helixharness/scripts/version_update.py index 553f213..d1c355b 100644 --- a/helixharness/scripts/version_update.py +++ b/helixharness/scripts/version_update.py @@ -13,12 +13,11 @@ from contextlib import contextmanager, nullcontext from datetime import date, datetime, timedelta, timezone from pathlib import Path -from source_binding import guard_source from typing import Any, Iterator import eval_json +from source_binding import guard_source from update_hosts import ( - INSTALL_TIMEOUT_SECONDS, MARKETPLACE, PLUGIN_ID, PLUGIN_NAME, @@ -30,7 +29,6 @@ supported_update_host_ids, ) - CACHE_SCHEMA_VERSION = "1.0" AUTH_SCHEMA_VERSION = "1.0" POLICY_SCHEMA_VERSION = "1.0" @@ -349,7 +347,11 @@ def locate_formal_policy( ) except UpdateHostError as exc: raise UpdateError(str(exc)) from exc - marketplace = _read_json(root / ".claude-plugin" / "marketplace.json") + try: + marketplace_path = adapter.marketplace_manifest_path(root) + except UpdateHostError as exc: + raise UpdateError(str(exc)) from exc + marketplace = _read_json(marketplace_path) plugins = marketplace.get("plugins") if isinstance(marketplace.get("plugins"), list) else [] matches = [item for item in plugins if isinstance(item, dict) and item.get("name") == PLUGIN_NAME] if marketplace.get("name") != MARKETPLACE or len(matches) != 1: @@ -457,7 +459,7 @@ def _validate_cached_releases( def _load_cache(path: Path) -> dict[str, Any]: data = _read_json(path) _expect_exact_keys( - data, CACHE_KEYS, optional={"skip"}, label="version cache" + data, CACHE_KEYS, optional={"skip", "update_binding"}, label="version cache" ) if data["schema_version"] != CACHE_SCHEMA_VERSION: raise UpdateError(f"unsupported version cache schema: {data['schema_version']}") @@ -510,6 +512,12 @@ def _load_cache(path: Path) -> dict[str, Any]: "required_reason": required_reason, "releases": releases, } + try: + adapter.validate_update_binding(data.get("update_binding")) + except UpdateHostError as exc: + raise UpdateError(str(exc)) from exc + if "update_binding" in data: + normalized["update_binding"] = data["update_binding"] skip = data.get("skip") if skip is not None: if not isinstance(skip, dict): @@ -571,10 +579,12 @@ def refresh( *, platform: str, now: datetime | None = None, + update_binding: dict[str, Any] | None = None, ) -> dict[str, Any]: current = now or _now() adapter = _adapter(platform) adapter.validate_scope(current_scope) + adapter.validate_update_binding(update_binding) if current_scope == "all": raise UpdateError("formal installation scope cannot be all") policy = _load_policy(policy_path) @@ -621,6 +631,8 @@ def refresh( "required_reason": required_reason, "releases": path_releases, } + if update_binding is not None: + data["update_binding"] = update_binding with _lock(cache_path): if cache_path.exists(): try: @@ -737,10 +749,10 @@ def _cache_matches_installation( for key in ("platform", "plugin_id", "current_version", "current_scope", "current_source") ): return False - return True + return _adapter(str(installation["platform"])).cache_binding_matches_installation(cached.get("update_binding"), installation) -def check_for_update( +def _check_for_update( platform: str, repo_root: Path, cache_path: Path, @@ -832,6 +844,7 @@ def refresh_into(target: Path) -> dict[str, Any]: target, platform=platform, now=current, + update_binding=adapter.update_binding(snapshot_root, installation, command_runner), ) except UpdateHostError as exc: raise UpdateError(str(exc)) from exc @@ -852,7 +865,7 @@ def refresh_into(target: Path) -> dict[str, Any]: error: Exception = fallback_error else: error = primary_error - except (UpdateError, OSError) as exc: + except (UpdateError, UpdateHostError, OSError) as exc: error = exc try: @@ -895,6 +908,63 @@ def refresh_into(target: Path) -> dict[str, Any]: ) +def check_for_update( + platform: str, + repo_root: Path, + cache_path: Path, + *, + plugin_root: Path = PLUGIN_ROOT, + plugin_list_data: Any = None, + marketplace_list_data: Any = None, + force_refresh: bool = False, + now: datetime | None = None, + runner: BoundedCommandRunner | None = None, + volatile_cache_path: Path | None = None, + negative_cache_path: Path | None = None, + authorization_path: Path | None = None, +) -> dict[str, Any]: + if platform in SUPPORTED_PLATFORMS: + policy = _adapter(platform).entry_policy(plugin_root) + if policy is not None: + return policy + current = now or _now() + result = _check_for_update( + platform, repo_root, cache_path, plugin_root=plugin_root, + plugin_list_data=plugin_list_data, marketplace_list_data=marketplace_list_data, + force_refresh=force_refresh, now=current, runner=runner, + volatile_cache_path=volatile_cache_path, negative_cache_path=negative_cache_path, + ) + if authorization_path is not None and platform in SUPPORTED_PLATFORMS: + pending = _pending_installation(platform, authorization_path, plugin_root, current, runner) + if pending is not None: + result["pending_installation"] = pending + return result + + +def _pending_installation( + platform: str, path: Path, plugin_root: Path, now: datetime, + runner: BoundedCommandRunner | None, +) -> dict[str, Any] | None: + """Read an already-confirmed transaction; a check never advances it.""" + if not path.is_file(): + return None + try: + raw = _read_json(path) + authorization = _load_authorization(path, str(raw.get("challenge_id") or ""), now) + if (authorization["platform"] != platform or authorization["state"] != "installing" + or "approved_releases" not in authorization): + return None + adapter = _adapter(platform) + if not adapter.validate_install_resume(authorization, plugin_root=plugin_root): + return None + steps = adapter.install_steps(str(authorization["scope"]), runner or BoundedCommandRunner()) + if not set(authorization["completed_steps"]) <= {step.step_id for step in steps}: + return None + return {key: authorization[key] for key in ("challenge_id", "scope", "target_version", "expires_at")} + except (UpdateError, UpdateHostError, OSError): + return None + + def record_skip( cache_path: Path, target_version: str, @@ -1045,7 +1115,16 @@ def prepare_authorization( "expires_at": _timestamp(current + timedelta(minutes=AUTH_TTL_MINUTES)), "prompt": _prompt_for(cache), "completed_steps": [], + "approved_releases": cache["releases"], } + try: + binding_context = adapter.prepare_update_binding(cache.get("update_binding")) + except UpdateHostError as exc: + raise UpdateError(str(exc)) from exc + if "update_binding" in cache: + data["update_binding"] = cache["update_binding"] + if binding_context: + data["prompt"]["message"] += "\n\n" + binding_context with _lock(authorization_path): if authorization_path.exists(): try: @@ -1077,7 +1156,7 @@ def _load_authorization(path: Path, challenge_id: str, now: datetime) -> dict[st } if state not in optional_by_state: raise UpdateError("invalid update authorization state") - optional = optional_by_state[state] + optional = optional_by_state[state] | {"update_binding", "approved_releases"} required = AUTH_KEYS | ( {"confirmation_source", "authorized_at"} if state in {"authorized", "installing"} @@ -1090,12 +1169,22 @@ def _load_authorization(path: Path, challenge_id: str, now: datetime) -> dict[st raise UpdateError("invalid update authorization challenge") platform = str(data["platform"]) adapter = _adapter(platform) + try: + adapter.validate_update_binding(data.get("update_binding")) + except UpdateHostError as exc: + raise UpdateError(str(exc)) from exc try: adapter.validate_scope(str(data["scope"])) except UpdateHostError as exc: raise UpdateError(str(exc)) from exc _version_text(data["current_version"]) _version_text(data["target_version"]) + if "approved_releases" in data: + releases = _validate_cached_releases( + data["approved_releases"], data["current_version"], data["target_version"], + ) + if not any(item["version"] == data["target_version"] for item in releases): + raise UpdateError("target release is missing from update authorization") if data["update_status"] not in {"recommended", "required"}: raise UpdateError("invalid update authorization policy") created_at = _parse_timestamp(data["created_at"]) @@ -1209,6 +1298,10 @@ def _validate_install_against_cache( for authorization_key, cache_key in comparisons.items(): if authorization[authorization_key] != cache[cache_key]: raise UpdateError(f"update authorization {authorization_key} no longer matches cache") + if authorization.get("update_binding") != cache.get("update_binding"): + raise UpdateError("update authorization source binding no longer matches cache") + if "approved_releases" in authorization and authorization["approved_releases"] != cache["releases"]: + raise UpdateError("update authorization release information no longer matches cache") def install( @@ -1225,6 +1318,8 @@ def install( ) -> dict[str, Any]: current = now or _now() adapter = _adapter(platform) + if adapter.entry_policy(plugin_root) is not None: + raise UpdateError("installation_update_not_supported: Cursor native cache is not managed-local") command_runner = runner or BoundedCommandRunner() install_guard = authorization_path.with_name(f"{authorization_path.name}.install") executed: list[list[str]] = [] @@ -1235,12 +1330,24 @@ def install( raise UpdateError("update authorization has not been confirmed by the user") if authorization["platform"] != platform: raise UpdateError("update authorization platform mismatch") - cache = _load_cache(cache_path) - _validate_install_against_cache(authorization, cache) + try: + independent_resume = ( + authorization["state"] == "installing" + and "approved_releases" in authorization + and adapter.validate_install_resume(authorization, plugin_root=plugin_root) + ) + except UpdateHostError as exc: + raise UpdateError(str(exc)) from exc + if independent_resume: + releases = authorization["approved_releases"] + else: + cache = _load_cache(cache_path) + _validate_install_against_cache(authorization, cache) + releases = cache["releases"] target_release = next( ( item - for item in cache["releases"] + for item in releases if item["version"] == authorization["target_version"] ), None, @@ -1248,7 +1355,7 @@ def install( if target_release is None: raise UpdateError("target release is missing from version cache") restart_required = any( - item["restart_required"] for item in cache["releases"] + item["restart_required"] for item in releases ) try: steps = adapter.install_steps(str(authorization["scope"]), command_runner) @@ -1295,7 +1402,7 @@ def install( if step.step_id in authorization["completed_steps"]: continue try: - command_runner.run(step.command, timeout=INSTALL_TIMEOUT_SECONDS) + adapter.execute_install_step(step, command_runner, authorization=authorization, plugin_root=plugin_root) except UpdateHostError as exc: with _lock(authorization_path): failed = _load_authorization(authorization_path, challenge_id, current) @@ -1305,7 +1412,8 @@ def install( raise UpdateError( f"plugin update step failed: {step.step_id}; completed steps: {completed}" ) from exc - executed.append(list(step.command)) + if step.command: + executed.append(list(step.command)) with _lock(authorization_path): authorization = _load_authorization(authorization_path, challenge_id, current) if step.step_id not in authorization["completed_steps"]: @@ -1313,6 +1421,10 @@ def install( authorization.pop("last_error", None) _atomic_write(authorization_path, authorization) + try: + verification = adapter.verify_installation(authorization, command_runner, plugin_root=plugin_root) + except UpdateHostError as exc: + raise UpdateError(f"updated plugin verification failed: {exc}") from exc with _lock(authorization_path): authorization = _load_authorization(authorization_path, challenge_id, current) if set(authorization["completed_steps"]) != {step.step_id for step in steps}: @@ -1327,6 +1439,7 @@ def install( "resumed": resumed, "authorization_consumed": True, "restart_required": restart_required, + **verification, } @@ -1370,6 +1483,12 @@ def main() -> int: print(json.dumps(_unsupported_result(platform), ensure_ascii=False, sort_keys=True)) return 0 repo_root = Path(args.repo_root).expanduser().resolve() + policy = _adapter(platform).entry_policy(PLUGIN_ROOT) + if policy is not None: + if args.command != "check": + policy = {**policy, "status": "unsupported", "next_action": "manual_update"} + print(json.dumps(policy, ensure_ascii=False, sort_keys=True)) + return 0 if args.command == "check" else 2 cache_path = _cache_path(platform, args.cache_path) authorization_path = _authorization_path(platform, args.authorization_path) if args.command == "check": @@ -1385,6 +1504,7 @@ def main() -> int: force_refresh=args.force_refresh, volatile_cache_path=volatile_cache_path, negative_cache_path=negative_cache_path, + authorization_path=authorization_path, ) elif args.command == "resolve": result = resolve(cache_path) @@ -1428,7 +1548,7 @@ def main() -> int: args.challenge_id, repo_root=repo_root, ) - except (UpdateError, OSError) as exc: + except (UpdateError, UpdateHostError, OSError) as exc: print(json.dumps({"status": "error", "error": str(exc)}, ensure_ascii=False)) return 2 print(json.dumps(result, ensure_ascii=False, sort_keys=True)) diff --git a/helixharness/skills/d-d2c/rules/d-d2c-generate.md b/helixharness/skills/d-d2c/rules/d-d2c-generate.md index e1d6830..5c37005 100644 --- a/helixharness/skills/d-d2c/rules/d-d2c-generate.md +++ b/helixharness/skills/d-d2c/rules/d-d2c-generate.md @@ -71,12 +71,13 @@ MasterGo 设计页链接 -> 拉取 dsl_full.json -> filter-dsl.cjs -> Layer.md + ## 文本空白与水平锁宽(强制) -> 背景:HTML 会把连续空格折叠为单空格(`white-space: normal/nowrap/pre-line` 均折叠)。DSL 文案含连续/前后/全角空格时,折叠会让文本渲染宽度小于 DSL bbox,**右端逐字累积横向漂移**(叠图表现为同一文本拖尾/双轮廓)。 +> 背景:Vue 模板编译可能先合并静态文本中的空白;浏览器还会按 CSS 折叠连续普通空格(`white-space: normal/nowrap/pre-line`)。这两层都要保真,否则固定宽度的文本框仍可能掩盖文案丢失。NBSP/全角空格本身不会被 CSS 折叠。 写 `.vue` 前读取 **`text-whitespace.json`**:`hasWhitespaceRisk === true` 时,对 `items[].layoutMark` 命中的每个文本节点: -1. **保留空白序列**:单行文本用 `white-space: pre`(**替代** `nowrap`;`pre` 同样不换行且保留空白),或将连续空格逐个转为 ` `。**禁止**用 `nowrap`/默认 `normal` 直接承载该文案。`dom.md` 中对应节点带 `data-preserve-whitespace="true"` 且内联样式已给出 `white-space: pre`,照抄即可。 -2. **文案逐字保真**:包括空白字符在内逐字符来自 DSL(`items[].textVisible` 已将空白可视化,便于核对个数),禁止增删、合并空格。 +1. **编译后保留原文**:Vue 使用 `v-text="label"` 或 `{{ label }}`,其中 `label` 是逐字符来自 DSL 的字符串。不能仅把连续空格照抄进静态模板;`white-space: pre` 和 `v-pre` 都不能恢复编译时已丢失的空白。混排节点在各 `data-span-index` 元素中分别绑定对应原文,不得用 `v-text` 覆盖整个混排父节点。 +2. **CSS 保留空白序列**:单行文本用 `white-space: pre`(替代 `nowrap`,不自动换行且保留空白);多行按 DSL 使用 `pre`/`pre-wrap`。也可把每个普通空格逐个转为 ` `,此时 `nowrap`/`normal` 不会折叠 NBSP。`pre-line` 仅保留换行,仍会折叠普通空格/Tab。不得把 Tab、换行或全角空格转成普通空格。 +3. **运行时逐字核对**:对照 DSL 读取已挂载元素的原始 `textContent`,禁止通过 `trim()` 或合并空白后声称保真。普通空格和 NBSP 仅一对一等价;CRLF/CR 可规范为 LF,换行数量不变;其余字符及数量须一致。`items[].textVisible` 仅供人读,`items[].text` 才是原文。 **水平锁宽**(与「垂直 bbox 锁高」对称):`dom.md` 中 TEXT 有明确 `width` 时,文本**内容**渲染宽度须 ≈ 该值(允差 max(4 设计px, 2%))。写前验算:字号 × 字符宽度估算 ≈ DSL width;明显小于时优先排查空白折叠、字体回退(目标字体未注册时回退 PingFang 视觉偏窄)、letter-spacing 丢失。物料阶段会用 `d2c-geometry-check.cjs` 实测校验(见 `d-d2c-materials.md`),写代码时即按本规则自检可避免返工。 diff --git a/helixharness/skills/d-d2c/scripts/lib/d2c-geometry-check-core.cjs b/helixharness/skills/d-d2c/scripts/lib/d2c-geometry-check-core.cjs index d443987..acbf4d1 100644 --- a/helixharness/skills/d-d2c/scripts/lib/d2c-geometry-check-core.cjs +++ b/helixharness/skills/d-d2c/scripts/lib/d2c-geometry-check-core.cjs @@ -1,5 +1,7 @@ 'use strict' +const { detectWhitespaceRisk } = require('./dsl-layout-core.cjs') + /** * d2c-geometry-check 的判定核心(纯函数,不依赖浏览器)。 * @@ -32,6 +34,23 @@ function round2(value) { return Math.round(Number(value || 0) * 100) / 100 } +// HTML normalizes line endings; generated pages may replace each ASCII space +// with one NBSP. Neither allowance permits changing counts, tabs or U+3000. +function comparableWhitespace(text) { + return text.replace(/\r\n?/g, '\n').replace(/\u00a0/g, ' ') +} + +function collapsesWhitespace(text, whiteSpace) { + const normalized = text.replace(/\r\n?/g, '\n') + if (whiteSpace === 'pre-line') { + return /[ \t]{2,}|^[ \t]|[ \t]$|\t|[ \t]\n|\n[ \t]/.test(normalized) + } + if (whiteSpace === 'normal' || whiteSpace === 'nowrap') { + return / {2,}|^ | $|[\t\n]/.test(normalized) + } + return false +} + /** * @param {Array} textNodes 目标 TEXT 节点(含 layoutMark / text / w / absX / fontSize) * @param {object} measured 浏览器返回 { results, effectiveCssWidth, viewportCssWidth, measurementRegionCss } @@ -113,19 +132,37 @@ function evaluateGeometryTargets(textNodes, measured, options) { const tol = Math.max(tolPx, (t.w * tolPct) / 100) - // 1) 空白折叠(最高优先:根因类) - const hasConsecutiveWs = /[  ]{2,}|\t/.test(t.text) - const collapsingWs = ['normal', 'nowrap', 'pre-line'].includes(m.whiteSpace) - if (hasConsecutiveWs && collapsingWs) { - violations.push({ - layoutMark: t.layoutMark, - text: t.text, - kind: 'whitespace-collapsed', - expected: `保留 DSL 空白序列(white-space: pre 或  ),文案「${t.text.replace(/ /g, '␣')}」`, - actual: `computed white-space=${m.whiteSpace},连续空白被折叠 → 渲染宽度小于 DSL bbox,右端累积漂移`, - diffPx: round1(t.w - wDesign), - severityHint: 'major', - }) + // 1) Text matching normalizes whitespace, and a fixed element width cannot + // prove its contents survived template compilation. Check raw DOM evidence + // first, then CSS rendering semantics. NBSP and U+3000 do not collapse. + if (detectWhitespaceRisk(t.text).length) { + let whitespaceIssue = null + if (typeof m.domText !== 'string') { + whitespaceIssue = { + kind: 'whitespace-content-unavailable', + actual: '缺少原始 DOM textContent,无法验证 DSL 空白序列', + } + } else if (comparableWhitespace(t.text) !== comparableWhitespace(m.domText)) { + whitespaceIssue = { + kind: 'whitespace-content-mismatch', + actual: `DOM textContent=${JSON.stringify(m.domText)};空白序列或文案与 DSL 不符`, + } + } else if (collapsesWhitespace(m.domText, m.whiteSpace)) { + whitespaceIssue = { + kind: 'whitespace-collapsed', + actual: `computed white-space=${m.whiteSpace},原始 DOM 中的空白序列会被 CSS 折叠`, + } + } + if (whitespaceIssue) { + violations.push({ + layoutMark: t.layoutMark, + text: t.text, + ...whitespaceIssue, + expected: `逐字符保留 DSL 文案 ${JSON.stringify(t.text)}(普通空格可逐个替换为 NBSP;换行仅允许 CRLF/CR → LF)并使用保留所需空白的 CSS`, + diffPx: null, + severityHint: 'major', + }) + } } // 2) 宽度(文本左对齐时宽度差≈右端漂移) diff --git a/helixharness/skills/d-d2c/scripts/lib/dsl-layout-core.cjs b/helixharness/skills/d-d2c/scripts/lib/dsl-layout-core.cjs index 077c123..08bf150 100644 --- a/helixharness/skills/d-d2c/scripts/lib/dsl-layout-core.cjs +++ b/helixharness/skills/d-d2c/scripts/lib/dsl-layout-core.cjs @@ -76,6 +76,7 @@ const WS_PATTERN_DEFS = [ { key: 'fullwidth-space', re: / /, label: '全角空格 U+3000' }, { key: 'nbsp', re: / /, label: '不间断空格 U+00A0' }, { key: 'tab', re: /\t/, label: 'Tab 制表符' }, + { key: 'line-break', re: /[\r\n]/, label: '换行' }, ] function detectWhitespaceRisk(text) { @@ -90,6 +91,7 @@ function visualizeWhitespace(text) { .replace(/ /g, '⍽') .replace(/ /g, '【全角空格】') .replace(/\t/g, '⇥') + .replace(/\r\n?|\n/g, '↵') } /** 遍历布局树收集空白风险 TEXT 节点(供 text-whitespace.json) */ @@ -112,7 +114,7 @@ function buildTextWhitespaceManifest(markedNodes) { (k) => (WS_PATTERN_DEFS.find((p) => p.key === k) || {}).label || k ), suggestion: - '单行文本用 white-space: pre(替代 nowrap)保留空白序列,或将连续空格转  ;禁止 nowrap 直接承载该文案', + '逐字符保留原文;Vue 用 v-text 或字符串插值,单行用 white-space: pre,多行按 DSL 用 pre-wrap/pre;普通空格可逐个转  ,Tab/换行/全角空格不得替换;核对运行时 textContent,CSS 或 v-pre 不能恢复编译时丢失的空白', }) } } @@ -122,7 +124,7 @@ function buildTextWhitespaceManifest(markedNodes) { return { hasWhitespaceRisk: items.length > 0, count: items.length, - note: 'HTML 会折叠连续/前后空白:命中节点必须保留空白序列(white-space: pre 或  ),否则文本渲染宽度小于 DSL bbox,产生右端累积横向漂移。', + note: '空白必须在模板编译和 CSS 渲染后都保真。Vue 静态模板可能合并空白,须用 v-text/字符串插值保留原文并核对运行时 textContent;普通空格与 NBSP 仅逐个等价,CRLF/CR 可规范为 LF,Tab/换行/全角空格的种类与数量不可改变。', items, } } @@ -766,7 +768,7 @@ function buildStylesMarkdown(specs) { '- **itemSpacing**:flex 容器 `gap`', '- **文本**:`fontSize` / `fontWeight` / `lineHeightPx` / `letterSpacing` / `fontFamily` / `textDecoration` / `fontStyle`', '- **混排文本**:见同目录 **`mixed-text.json`**(`hasMixedText`);为 true 时读下方清单 + `dom.md` 的 `data-span-index`', - '- **空白保真**:见同目录 **`text-whitespace.json`**(`hasWhitespaceRisk`);命中节点须 `white-space: pre` 或 ` ` 保留空白序列,对应 `dom.md` 的 `data-preserve-whitespace`', + '- **空白保真**:见同目录 **`text-whitespace.json`**(`hasWhitespaceRisk`);Vue 用 `v-text`/字符串插值保留原文,再用 `white-space: pre`/`pre-wrap`(或将普通空格逐个转 ` `),并核对运行时 `textContent`;CSS 和 `v-pre` 无法恢复编译时已丢失的空白。对应 `dom.md` 的 `data-preserve-whitespace`', '', ] @@ -777,7 +779,7 @@ function buildStylesMarkdown(specs) { lines.push( `## 文本空白保真清单(代码生成前必查,共 ${whitespaceRows.length} 处)`, '', - '> ⚠️ 下列文案含 HTML 会折叠的空白(连续/前后/全角空格等)。`white-space: nowrap` 会把连续空格折叠成一个,导致渲染宽度小于 DSL bbox、右端逐字累积横向漂移。**必须** `white-space: pre`(单行)或将连续空格转 ` `。', + '> ⚠️ 下列文案含空白风险。Vue 静态模板会合并部分空白,先用 `v-text`/字符串插值保留 DSL 原文;再用 `white-space: pre`(单行)/`pre-wrap`(按 DSL 多行)或逐个替换普通空格为 ` `。Tab、换行、全角空格不得替换为普通空格;CSS 本身不折叠 NBSP/全角空格。最终必须核对运行时 `textContent` 的字符及数量。', '', '| layoutMark | 文案(空白可视化) | 空白类型 | DSL 宽度 |', '|---|---|---|---:|' diff --git a/helixharness/skills/d-d2c/scripts/tests/d2c-whitespace-fidelity.test.cjs b/helixharness/skills/d-d2c/scripts/tests/d2c-whitespace-fidelity.test.cjs new file mode 100644 index 0000000..275c313 --- /dev/null +++ b/helixharness/skills/d-d2c/scripts/tests/d2c-whitespace-fidelity.test.cjs @@ -0,0 +1,69 @@ +#!/usr/bin/env node +'use strict' + +const assert = require('assert') +const { evaluateGeometryTargets } = require('../lib/d2c-geometry-check-core.cjs') +const { buildTextWhitespaceManifest } = require('../lib/dsl-layout-core.cjs') + +// A matching fixed-width box must not hide text lost by a template compiler. +// Inputs are raw browser textContent, not normalized matching keys. +function check(text, domText, whiteSpace = 'pre', matchType = 'exact') { + const measurement = { + matched: true, matchType, whiteSpace, + rect: { left: 20, width: 240, height: 32 }, fontSizeCss: 14, + } + if (domText !== undefined) measurement.domText = domText + return evaluateGeometryTargets( + [{ layoutMark: 'L0.8', text, absX: 20, w: 240, fontSize: 14 }], + { results: [measurement], effectiveCssWidth: 1440 }, + { designFrameWidth: 1440, tolPx: 4, tolPct: 2 } + ).violations.map((entry) => entry.kind) +} + +const cases = [ + ['compiler-condensed footer', 'Synthetic fixture / 1440 × 900', 'Synthetic fixture / 1440 × 900', 'pre', ['whitespace-content-mismatch']], + ['preserved consecutive spaces', 'A / B', 'A / B', 'pre', []], + ['NBSP replacement preserves count', 'A / B', 'A\u00a0\u00a0/\u00a0\u00a0B', 'nowrap', []], + ['NBSP replacement loses count', 'A / B', 'A\u00a0/\u00a0B', 'nowrap', ['whitespace-content-mismatch']], + ['NBSP replacement adds count', 'A B', 'A\u00a0\u00a0\u00a0B', 'nowrap', ['whitespace-content-mismatch']], + ['CSS still collapses raw spaces', 'A B', 'A B', 'nowrap', ['whitespace-collapsed']], + ['mixed replacement still has collapsing run', 'A / B', 'A\u00a0\u00a0/ B', 'normal', ['whitespace-collapsed']], + ['fullwidth spaces do not collapse in CSS', 'A\u3000\u3000B', 'A\u3000\u3000B', 'normal', []], + ['fullwidth must not become ASCII', 'A\u3000B', 'A B', 'pre', ['whitespace-content-mismatch']], + ['Tab must not become spaces', 'A\tB', 'A B', 'pre', ['whitespace-content-mismatch']], + ['Tab preserved', 'A\tB', 'A\tB', 'pre-wrap', []], + ['Tab collapses under pre-line', 'A\tB', 'A\tB', 'pre-line', ['whitespace-collapsed']], + ['newline must not become space', 'A\nB', 'A B', 'pre', ['whitespace-content-mismatch']], + ['newlines preserved under pre-line', 'A\n\nB', 'A\n\nB', 'pre-line', []], + ['newline count must match', 'A\n\nB', 'A\nB', 'pre', ['whitespace-content-mismatch']], + ['HTML line ending normalization', 'A\r\nB', 'A\nB', 'pre', []], + ['newline collapses under normal', 'A\nB', 'A\nB', 'normal', ['whitespace-collapsed']], + ['spaces adjacent to newline collapse under pre-line', 'A \n B', 'A \n B', 'pre-line', ['whitespace-collapsed']], + ['leading ASCII space needs preserving CSS', ' A', ' A', 'normal', ['whitespace-collapsed']], + ['trailing ASCII space loss', 'A ', 'A', 'pre', ['whitespace-content-mismatch']], + ['leading and trailing NBSP replacements', ' A ', '\u00a0A\u00a0', 'normal', []], + ['break-spaces preserves', ' A B ', ' A B ', 'break-spaces', []], + ['risk node without raw DOM evidence', 'A B', undefined, 'pre', ['whitespace-content-unavailable']], + ['risk node with empty DOM text', 'A B', '', 'pre', ['whitespace-content-mismatch']], + ['ordinary text remains compatible without domText', 'A B', undefined, 'nowrap', []], +] + +let failures = 0 +for (const [name, text, domText, css, expected] of cases) { + try { assert.deepStrictEqual(check(text, domText, css), expected, name) } + catch (error) { failures += 1; console.error(`${name}: ${error.message}`) } +} +// Preserve the established matching confidence boundary: a guessed enclosing +// element's textContent cannot prove a risk node's exact text is wrong. +for (const type of ['contains', 'css-fallback', 'text-fuzzy', 'position-heuristic']) { + assert.deepStrictEqual(check('A B', 'something else', 'normal', type), [], type) +} +const manifest = buildTextWhitespaceManifest([ + { type: 'TEXT', _layoutMark: 'L0.1', text: [{ text: 'A\nB' }] }, +]) +try { + assert.strictEqual(manifest.hasWhitespaceRisk, true, 'DSL newline must enter the risk manifest') + assert.ok(manifest.items[0].patterns.includes('line-break')) +} catch (error) { failures += 1; console.error(error.message) } +assert.strictEqual(failures, 0, `${failures} whitespace fidelity cases failed`) +console.log(`d2c whitespace fidelity: ${cases.length + 5} cases passed`) diff --git a/helixharness/skills/feedback/SKILL.md b/helixharness/skills/feedback/SKILL.md index c17ad53..53df63e 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}` 必须来自当前 Skill 绑定的 Host Context;按当前宿主入口协议核验来源,不得搜索其他安装目录。`{current_platform}` 使用该 Host Context 的 canonical host ID:Claude Code 为 `claude-code`,Codex 为 `codex`,Cursor 为 `cursor`。Cursor 每次脚本调用按 `resources.runtime` 显式传入当前原生会话绑定;缺失时保留未知会话,不借用其他宿主或历史会话。 先准备草稿,不发送。参数必须安全转义: @@ -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 与 Cursor 使用同一 CLI(`feedback_submit.py`);反馈发送使用独立的内容与地址确认,不依赖统计 consent,也不由 hook 自动发送 +- 会话上下文采集当前仅支持 claude-code 会话;Codex 与 Cursor 仍可上报反馈元数据。请求附带会话时按返回的 `transcript_stats.supported=false` 和原因说明边界,不搜索私有会话补全 - 未注册宿主(`{current_platform}` 无法给出 canonical ID 时):`--platform unknown` 仍可上报,文档中 `host` 记为 `unknown` ## 注意事项 diff --git a/helixharness/templates/project-entry.md.tpl b/helixharness/templates/project-entry.md.tpl index d3eb846..b5d566c 100644 --- a/helixharness/templates/project-entry.md.tpl +++ b/helixharness/templates/project-entry.md.tpl @@ -11,11 +11,27 @@ {{PROJECT_CONTEXT}} + ## 常用命令 -`/helix:init`、`/helix:propose`、`/helix:apply`、`/helix:archive`、 -`/helix:ut`、`/helix:bug-fix`、`/helix:update`。 -`propose --loop` 按顺序执行 Propose → Apply → Archive。 +按当前宿主选择入口;同一项目可由多个宿主使用,保留两组指引。 + +| 命令 | Cursor | Claude Code / Codex | +| --- | --- | --- | +| 初始化 | `/helix-init` | `/helix:init` | +| 需求规划 | `/helix-propose` | `/helix:propose` | +| 执行实现 | `/helix-apply` | `/helix:apply` | +| 归档 | `/helix-archive` | `/helix:archive` | +| 单元测试 | `/helix-ut` | `/helix:ut` | +| 修复未归档需求 | `/helix-bug-fix` | `/helix:bug-fix` | +| 更新插件 | `/helix-update` | `/helix:update` | +| 查看状态 | `/helix-status` | `/helix:status` | +| 用户配置 | `/helix-config` | `/helix:config` | + +Cursor 使用 `/helix-propose --loop`;Claude Code / Codex 使用 +`/helix:propose --loop`,按顺序执行 Propose → Apply → Archive。 +仅入口写法不同;参数、路径、引号与命令适用范围保持一致。`bug-fix` 仅用于未归档的单仓需求。 + ## Agent 工作规则 diff --git a/helixharness/templates/workspace-entry.md.tpl b/helixharness/templates/workspace-entry.md.tpl index 18ee495..9d3f6ff 100644 --- a/helixharness/templates/workspace-entry.md.tpl +++ b/helixharness/templates/workspace-entry.md.tpl @@ -13,11 +13,24 @@ Workspace 初始化只生成根目录协调产物,不自动初始化或改写 各子仓独立执行完整 Single Propose/Apply/Archive,分别维护 `spec.md`、`tasks.md`、`verify-report.md`。 根目录不复制子仓工件、不维护独立 Ledger,不生成 proposal、design、verification 或 repo-plan 文件。 + ## 常用命令 -`/helix:init --workspace` 初始化根目录。`/helix:propose ` -建立需求;`--loop` 串联 Propose → Apply → Archive。`apply` 与 `archive` 按 Router 的 Workspace -范围调度子仓;其他命令的适用范围仍以各自 Router 和完整命令为准。 +按当前宿主选择入口;同一 Workspace 可由多个宿主使用,保留两组指引。 + +| 命令 | Cursor | Claude Code / Codex | +| --- | --- | --- | +| 初始化根目录 | `/helix-init --workspace` | `/helix:init --workspace` | +| 建立需求 | `/helix-propose ` | `/helix:propose ` | +| 执行实现 | `/helix-apply ` | `/helix:apply ` | +| 归档 | `/helix-archive ` | `/helix:archive ` | + +为 propose 增加 `--loop` 按顺序执行 Propose → Apply → Archive。Apply 与 Archive 按 Router 的 +Workspace 范围调度子仓;其他命令的适用范围仍以各自 Router 和完整命令为准。 +Workspace 根不支持 BugFix;需进入已初始化子仓,对未归档的单仓需求使用 +Cursor `/helix-bug-fix ` 或 Claude Code / Codex `/helix:bug-fix `。 +仅入口写法不同;参数、路径、引号与命令适用范围保持一致。 + ## Agent 工作规则 diff --git a/helixharness/workflows/single/apply.md b/helixharness/workflows/single/apply.md index 3c5318f..455c450 100644 --- a/helixharness/workflows/single/apply.md +++ b/helixharness/workflows/single/apply.md @@ -22,7 +22,7 @@ HelixHarness 只复用统一 consent 的当前结果,只使用当前 HelixHarn ## HelixHarness 统计(非阻塞) -此处 `{current_platform}` 表示当前 Agent 宿主,不是操作系统:Claude Code 固定为 `claude-code`,Codex 固定为 `codex`。禁止传入 `darwin`、`linux`、`windows` 等 OS 标识。该映射适用于本 workflow 内所有 `metrics.py --platform` 调用。 +此处 `{current_platform}` 必须取自已绑定 Host Context 的 `canonical_host_id`,表示当前 Agent 宿主,不是操作系统。禁止传入 `darwin`、`linux`、`windows` 等 OS 标识,也不得借用其他宿主身份。该规则适用于本 workflow 内所有 `metrics.py --platform` 调用;`telemetry=unsupported` 时按公共统计协议跳过,业务门禁保持不变。 调用 `start` 前,先按实际入口确定唯一的 `metrics_trigger`: diff --git a/helixharness/workflows/single/archive.md b/helixharness/workflows/single/archive.md index b7d6424..eeb0215 100644 --- a/helixharness/workflows/single/archive.md +++ b/helixharness/workflows/single/archive.md @@ -22,7 +22,7 @@ HelixHarness 只复用统一 consent 的当前结果,只使用当前 HelixHarn ## HelixHarness 统计(非阻塞) -此处 `{current_platform}` 表示当前 Agent 宿主,不是操作系统:Claude Code 固定为 `claude-code`,Codex 固定为 `codex`。禁止传入 `darwin`、`linux`、`windows` 等 OS 标识。该映射适用于本 workflow 内所有 `metrics.py --platform` 调用。 +此处 `{current_platform}` 必须取自已绑定 Host Context 的 `canonical_host_id`,表示当前 Agent 宿主,不是操作系统。禁止传入 `darwin`、`linux`、`windows` 等 OS 标识,也不得借用其他宿主身份。该规则适用于本 workflow 内所有 `metrics.py --platform` 调用;`telemetry=unsupported` 时按公共统计协议跳过,业务门禁保持不变。 调用 `start` 前,先按实际入口确定唯一的 `metrics_trigger`: diff --git a/helixharness/workflows/single/propose.md b/helixharness/workflows/single/propose.md index 9f617c2..ad05539 100644 --- a/helixharness/workflows/single/propose.md +++ b/helixharness/workflows/single/propose.md @@ -46,7 +46,7 @@ python3 "{plugin_root}/scripts/version_update.py" --platform "{current_platform} ## HelixHarness 统计(非阻塞) -此处 `{current_platform}` 表示当前 Agent 宿主,不是操作系统:Claude Code 固定为 `claude-code`,Codex 固定为 `codex`。禁止传入 `darwin`、`linux`、`windows` 等 OS 标识。该映射适用于本 workflow 内所有 `metrics.py --platform` 调用。 +此处 `{current_platform}` 必须取自已绑定 Host Context 的 `canonical_host_id`,表示当前 Agent 宿主,不是操作系统。禁止传入 `darwin`、`linux`、`windows` 等 OS 标识,也不得借用其他宿主身份。该规则适用于本 workflow 内所有 `metrics.py --platform` 调用;`telemetry=unsupported` 时按公共统计协议跳过,业务门禁保持不变。 调用 `start` 前,先按实际入口确定唯一的 `metrics_trigger`: From 17826a83879f2ce8491952d0aef70a67257a95b1 Mon Sep 17 00:00:00 2001 From: wuchunlin Date: Fri, 20 Nov 2026 18:16:23 +0800 Subject: [PATCH 02/37] feat(opencode): integrate preview host with Cursor branch Port OpenCode native V2 registration and fail-closed session binding onto the GitHub Cursor branch. Preserve Cursor runtime snapshot behavior and include only public OpenCode runtime files in managed bundles. Co-authored-by: masongyan --- .claude-plugin/marketplace.json | 4 +- README.md | 27 +- README.zh-CN.md | 27 +- docs/installation.md | 44 +- docs/user-guide.md | 37 +- docs/user-guide.zh-CN.md | 37 +- docs/workflow-architecture.md | 10 +- examples/README.md | 8 +- helixharness/.claude-plugin/marketplace.json | 4 +- helixharness/.claude-plugin/plugin.json | 2 +- helixharness/AGENTS.md | 2 +- helixharness/PLUGIN_USAGE.md | 12 +- helixharness/README.md | 14 +- .../hosts/opencode/command-projection.json | 15 + helixharness/hosts/opencode/host.json | 50 ++ helixharness/hosts/opencode/installer.md | 90 ++ helixharness/hosts/opencode/lifecycle.md | 19 + .../hosts/opencode/project-hooks.json | 8 + helixharness/hosts/opencode/project.json | 6 + helixharness/hosts/opencode/runtime.md | 84 ++ helixharness/hosts/opencode/subagent.md | 107 +++ helixharness/hosts/opencode/ut.md | 54 ++ .../hosts/opencode/workflow-transition.md | 14 + helixharness/opencode/core.ts | 781 ++++++++++++++++++ helixharness/opencode/index.ts | 18 + helixharness/opencode/tests/README.md | 54 ++ helixharness/opencode/tests/core.test.ts | 221 +++++ helixharness/opencode/tests/e2e.test.ts | 212 +++++ helixharness/opencode/tests/native-fixture.ts | 155 ++++ helixharness/opencode/tests/plugin.test.ts | 356 ++++++++ helixharness/package.json | 23 + helixharness/reference/eval-protocol.md | 2 + .../reference/eval-supplement-protocol.md | 2 +- helixharness/reference/host-api.md | 13 +- .../reference/host-runtime-protocol.md | 7 +- .../reference/version-update-protocol.md | 1 + .../reference/workflow-projection-protocol.md | 3 +- helixharness/scripts/feedback_submit.py | 6 +- .../tests/test_claude_command_scenarios.py | 2 +- .../tests/test_codex_update_scenarios.py | 2 +- .../tests/test_cursor_bundle_update.py | 37 + .../tests/test_cursor_command_scenarios.py | 2 +- .../scripts/tests/test_cursor_telemetry.py | 7 + .../scripts/tests/test_feedback_submit.py | 16 +- .../scripts/tests/test_opencode_host.py | 213 +++++ .../tests/test_public_workflow_router.py | 2 +- helixharness/scripts/update_hosts/cursor.py | 7 +- helixharness/scripts/update_hosts/opencode.py | 19 + helixharness/skills/feedback/SKILL.md | 6 +- helixharness/tsconfig.json | 13 + 50 files changed, 2762 insertions(+), 93 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/README.md create mode 100644 helixharness/opencode/tests/core.test.ts create mode 100644 helixharness/opencode/tests/e2e.test.ts create mode 100644 helixharness/opencode/tests/native-fixture.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..c0f23af 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, Cursor and OpenCode (Preview)" }, "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, Cursor and OpenCode (Preview) with commands and reusable skills", "source": "./helixharness", "version": "1.0.0", "license": "Apache-2.0" diff --git a/README.md b/README.md index dc79179..18bb397 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, Claude Code and Cursor.** 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, Cursor and OpenCode (Preview).** 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 / Cursor · Single repo / multi-repo Workspace · Apache-2.0** +**9 commands · Codex / Claude Code / Cursor / OpenCode (Preview) · 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, Claude Code or Cursor 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, Cursor or OpenCode installation (OpenCode v2.2.2+). Make sure the host is signed in or has its model configuration set up and is working normally. For macOS and native Windows setup, interpreter detection and host-specific requirements, see [platform support](docs/platform-support.md). Windows Codex uses PowerShell; Windows Claude Code uses Git for Windows Bash. Cursor native acceptance currently covers macOS; Windows Cursor is outside this release's verified scope. @@ -83,15 +83,26 @@ claude plugin install helix@helixharness-marketplace Cursor users install `helix` from their Cursor marketplace through **Customize → helix → Install**, then reload the window and open a new Agent. A team administrator first imports the published release repository into the team's marketplace. Cursor uses `/helix-init`, `/helix-propose`, etc. See [marketplace setup, optional Local installation and capability limits](docs/installation.md#cursor-preview). +```bash +# OpenCode v2.2.2+ +opencode plugin add 'github:didi/helixharness::path:helixharness' +``` + +**OpenCode Preview support (v2.2.2+):** The plugin registers native `helix:` commands, `helix-` method skills and `helix-` roles, binding Host Context to the current repository and session. Full Init → Propose → Apply → Archive acceptance with a real model remains unverified. Workspace Apply uses `helix-worker` for `may_delegate` RepoJobs and requires `experimental.subagent_depth >= 2`; independent reviewers remain read-only leaf jobs. Insufficient depth blocks the RepoJob rather than bypassing review. + +OpenCode has no native SessionStart/Stop/failure/session-end hooks or plan tool (`tasks.md` tracks the plan). Telemetry is unsupported (`unsupported_host`); `/helix:update` returns `continue_silently`, so update manually through OpenCode plugin management. Project hooks are unsupported: Init merges `AGENTS.md` without creating `.opencode/` settings. The d-d2c Claude skill-scoped Stop/PreToolUse guards do not run; use its no-hook / `--bare` semantics while retaining user decisions, visual acceptance and completion checks. + +See the [OpenCode installer](helixharness/hosts/opencode/installer.md) for binding checks and manual updates. + 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). ### 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 the commands for your host in the conversation. +Open a new agent session in the **application repository** you want to develop. On Claude Code, Codex and Cursor, review the plugin hooks through the host's native interface; OpenCode registers its surfaces from the plugin package. Then enter the commands for your host in the conversation. -Codex / Claude Code: +Codex / Claude Code / OpenCode: ```text /helix:init @@ -105,7 +116,7 @@ Cursor: /helix-propose task-filter ./requirements/task-filter.md --loop ``` -Cursor uses `/helix-` throughout; Codex and Claude Code use `/helix:`. Command arguments and workflows are the same. +Cursor uses `/helix-` throughout; Codex, Claude Code and OpenCode use `/helix:`. Command arguments and workflows are the same. Use the [self-contained task-filter example](examples/README.md) to get a starter project, requirement and acceptance check. `--loop` runs Propose → Apply → Archive, pausing for decisions or blockers. It does not publish or deploy your code. @@ -212,10 +223,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 to more hosts beyond Codex, Claude Code and Cursor so teams can use HelixHarness with more of their preferred tools. +- **More coding agents.** Extend support to more hosts beyond Codex, Claude Code, Cursor and OpenCode (Preview) 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 source supports Codex, Claude Code and Cursor, using the Propose → Apply → Archive workflow. Cursor native-client acceptance is tracked separately from automated contract tests. Share concrete use cases through the [contribution guide](CONTRIBUTING.md) to help shape these directions. +These are planned capabilities. The source supports Codex, Claude Code and Cursor, plus OpenCode in Preview, using the Propose → Apply → Archive workflow. Cursor native-client acceptance is tracked separately from automated contract tests. 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 39d8e5e..e349a08 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -6,11 +6,11 @@ > > 为适配而生,为进化而设计。让团队的工程 DNA,融入 AI 研发。 -**HelixHarness 帮助团队在 Codex、Claude Code 和 Cursor 上构建专属的 AI Coding Harness。** 将你的业务知识、工程规范与研发工作流带入 Agent 的工作过程,从需求分析、实现、测试、评审到归档,让 AI 按团队的方式开展研发,并将经验证的经验留在项目中,供下一个需求复用。 +**HelixHarness 帮助团队在 Codex、Claude Code、Cursor 与 OpenCode(预览)上构建专属的 AI Coding Harness。** 将你的业务知识、工程规范与研发工作流带入 Agent 的工作过程,从需求分析、实现、测试、评审到归档,让 AI 按团队的方式开展研发,并将经验证的经验留在项目中,供下一个需求复用。 从插件开始即可。当你希望改进 Harness 本身时,可选的 **helixharness-platform** 帮助框架维护者观测使用过程、对比框架版本,并在采纳候选改进前验证效果。 -**9 个命令 · Codex / Claude Code / Cursor · 单仓 / 多仓 Workspace · Apache-2.0** +**9 个命令 · Codex / Claude Code / Cursor / 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 或 Cursor。先确保宿主已完成登录或模型配置,能够正常使用。 +需要 Python 3.10+、Git,以及支持插件的 Codex、Claude Code、Cursor 或 OpenCode(v2.2.2+)。先确保宿主已完成登录或模型配置,能够正常使用。 macOS 与原生 Windows 的依赖、解释器探测及宿主要求见[跨平台说明](docs/platform-support.md)。Windows Codex 使用 PowerShell;Windows Claude Code 使用 Git for Windows Bash。Cursor 实机验收目前覆盖 macOS,Windows Cursor 不在本期已验证范围。 @@ -83,13 +83,24 @@ claude plugin install helix@helixharness-marketplace Cursor 用户通过 **Customize → helix → Install** 从市场安装,随后重载窗口并新建 Agent。团队管理员需先将已发布的发行仓库导入团队市场。Cursor 使用 `/helix-init`、`/helix-propose` 等入口,详见[市场安装、可选 Local 安装及能力限制](docs/installation.md#cursor-preview)。 +```bash +# OpenCode v2.2.2+ +opencode plugin add 'github:didi/helixharness::path:helixharness' +``` + +**OpenCode 预览支持(v2.2.2+):** 插件注册原生 `helix:` 命令、`helix-` 方法 Skill 和 `helix-` 角色,将 Host Context 绑定到当前仓库和会话。完整 Init → Propose → Apply → Archive 流程尚未完成真实模型验收。Workspace Apply 的 `may_delegate` RepoJob 使用 `helix-worker`,需要 `experimental.subagent_depth >= 2`;独立 reviewer 保持只读 leaf。深度不足时阻塞该 RepoJob,不得绕过评审。 + +OpenCode 没有原生 SessionStart/Stop/失败/会话结束 hooks,也没有原生计划工具(计划写入 `tasks.md`)。统计不支持(`unsupported_host`);`/helix:update` 返回 `continue_silently`,请通过 OpenCode 插件管理手动更新。项目 hooks 不支持:Init 只合并 `AGENTS.md`,不创建 `.opencode/` settings。d-d2c 的 Claude skill-scoped Stop/PreToolUse guard 不执行,采用无 hook / `--bare` 语义,仍须遵守用户决策、视觉验收和完成门禁。 + +绑定检查与手动更新步骤见 [OpenCode 安装说明](helixharness/hosts/opencode/installer.md)。 + 根市场会安装 `helixharness/` 插件,不会安装平台。发布前测试或修改插件时,使用[开发者安装(本地源码)](docs/installation.md#developer-installation)。详见[hooks 检查、更新与卸载](docs/installation.md)。 ### 2. 完成一个小需求 -在要开发的**业务仓库**新开 Agent 会话,通过宿主原生界面审阅插件 hooks,然后在对话中输入对应宿主的命令。 +在要开发的**业务仓库**新开 Agent 会话,Claude Code、Codex 和 Cursor 通过宿主原生界面审阅插件 hooks;OpenCode 由插件包注册入口。然后在对话中输入对应宿主的命令。 -Codex / Claude Code: +Codex / Claude Code / OpenCode: ```text /helix:init @@ -103,7 +114,7 @@ Cursor: /helix-propose task-filter ./requirements/task-filter.md --loop ``` -Cursor 全部使用 `/helix-`,Codex 和 Claude Code 使用 `/helix:`;命令参数和工作流相同。 +Cursor 全部使用 `/helix-`,Codex、Claude Code 和 OpenCode 使用 `/helix:`;命令参数和工作流相同。 [任务筛选示例](examples/README.md)提供起始项目、需求和独立验收脚本,可直接跟着操作。`--loop` 串联 Propose → Apply → Archive,遇到需要决策的问题或阻断时暂停,不包含代码发布或部署。 @@ -210,10 +221,10 @@ python -m web_ui.demo --port 7860 接下来计划围绕两个方向,让更多团队按自己的研发方式使用 HelixHarness: -- **支持更多 Coding Agent**:在 Codex、Claude Code 和 Cursor 的基础上继续扩展宿主适配,让团队能在更多熟悉的工具中使用 HelixHarness。 +- **支持更多 Coding Agent**:在 Codex、Claude Code、Cursor 与 OpenCode(预览)的基础上继续扩展宿主适配,让团队能在更多熟悉的工具中使用 HelixHarness。 - **支持工作流配置**:允许团队配置工作流阶段及其顺序,适配自身的研发流程。 -以上为规划方向。当前源码支持 Codex、Claude Code 和 Cursor,采用 Propose → Apply → Archive 工作流。Cursor 原生客户端验收与自动化合同测试分别记录。欢迎通过[贡献指南](CONTRIBUTING.md)分享具体使用场景,帮助完善这些方向。 +以上为规划方向。当前源码支持 Codex、Claude Code 和 Cursor,另提供 OpenCode 预览支持,采用 Propose → Apply → Archive 工作流。Cursor 原生客户端验收与自动化合同测试分别记录。欢迎通过[贡献指南](CONTRIBUTING.md)分享具体使用场景,帮助完善这些方向。 ## 文档与贡献 diff --git a/docs/installation.md b/docs/installation.md index b542195..ed58fa2 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -4,7 +4,7 @@ ## Requirements -Python 3.10+, Git and a plugin-capable Codex, Claude Code or Cursor installation are required. Make sure the host is signed in or has its model configuration set up and is working normally. The platform is optional. Cursor desktop support follows the release scope and limitations below. +Python 3.10+, Git and a plugin-capable Codex, Claude Code, Cursor or OpenCode installation (OpenCode v2.2.2+) are required. Make sure the host is signed in or has its model configuration set up and is working normally. The platform is optional. Cursor desktop support follows the release scope and limitations below. The shared runtime supports macOS, native Windows and Linux; see [platform support and verification](platform-support.md). Windows Codex uses the PowerShell entrypoint, while Claude Code hooks require Git for Windows Bash. Cursor native acceptance currently covers macOS; Windows Cursor is outside this release's verified scope. @@ -28,7 +28,18 @@ 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.2+ +opencode plugin add 'github:didi/helixharness::path:helixharness' +``` + +**OpenCode Preview support (v2.2.2+):** The plugin registers native `helix:` commands, `helix-` method skills and `helix-` roles, binding Host Context to the current repository and session. Full Init → Propose → Apply → Archive acceptance with a real model remains unverified. Workspace Apply uses `helix-worker` for `may_delegate` RepoJobs and requires `experimental.subagent_depth >= 2`; independent reviewers remain read-only leaf jobs. Insufficient depth blocks the RepoJob rather than bypassing review. + +OpenCode has no native SessionStart/Stop/failure/session-end hooks or plan tool (`tasks.md` tracks the plan). Telemetry is unsupported (`unsupported_host`); `/helix:update` returns `continue_silently`, so update manually through OpenCode plugin management. Project hooks are unsupported: Init merges `AGENTS.md` without creating `.opencode/` settings. The d-d2c Claude skill-scoped Stop/PreToolUse guards do not run; use its no-hook / `--bare` semantics while retaining user decisions, visual acceptance and completion checks. + +See the [OpenCode installer](../helixharness/hosts/opencode/installer.md) for host-specific checks. + +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 same `helixharness/` package directly through its `package.json` export, `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. @@ -50,19 +61,28 @@ claude plugin marketplace add "$HELIXHARNESS_SOURCE" claude plugin install helix@helixharness-marketplace ``` +For OpenCode local development, add the plugin subdirectory to project or global `opencode.json(c)`: + +```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` (Cursor: `/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. +On Claude Code, Codex and Cursor, review and trust the plugin's hooks through the host's native interface and confirm SessionStart identifies the host and installed plugin path. Command visibility alone does not prove hooks executed. OpenCode instead registers native commands, skills and agents; check a command expansion includes `canonical_host_id: opencode`, the intended `plugin_root`, and the current `repo_root` and session binding. It does not generate project hooks or `.opencode/` settings. Then run `/helix:init` (Cursor: `/helix-init`); check project documentation and, on hosts supporting them, generated project hooks 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. ### Start with an empty project -Run `/helix:init` (Cursor: `/helix-init`) in a Git repository root. For a new directory, run `git init` yourself first; an initial commit is not required. An empty or documentation-only repository skips code scans and gets a minimal project context, harness, specs directories, and host hooks. Unconfirmed project details stay as TODOs. Use `/helix:propose` and `/helix:apply` (Cursor: `/helix-propose` and `/helix-apply`) to develop the first feature. Init and Apply do not create a commit. +Run `/helix:init` (Cursor: `/helix-init`) in a Git repository root. For a new directory, run `git init` yourself first; an initial commit is not required. An empty or documentation-only repository skips code scans and gets a minimal project context, harness, specs directories, and host hooks where supported (OpenCode merges `AGENTS.md` only). Unconfirmed project details stay as TODOs. Use `/helix:propose` and `/helix:apply` (Cursor: `/helix-propose` and `/helix-apply`) to develop the first feature. Init and Apply do not create a commit. @@ -90,7 +110,7 @@ Statistics require explicit consent and current-session identity. Missing identi ## Updates -On Claude Code and Codex, run `/helix:update` in the host conversation. The plugin checks the configured marketplace, shows an available update and uses the host adapter after authorization. Cursor uses `/helix-update` for registered Helix-managed local installations on macOS/Linux, following the same check, confirmation and one-time authorization protocol. Manual copies and Cursor marketplace installations use their original update mechanism. +On Claude Code and Codex, run `/helix:update` in the host conversation. The plugin checks the configured marketplace, shows an available update and uses the host adapter after authorization. Cursor uses `/helix-update` for registered Helix-managed local installations on macOS/Linux, following the same check, confirmation and one-time authorization protocol. Manual copies and Cursor marketplace installations use their original update mechanism. OpenCode has `plugin_update=unsupported`; update manually with `opencode plugin update`, or update local source and reload. `/helix:update` returns `continue_silently`. - **Git source:** the host refreshes the configured repository; use the same marketplace for later versions. - **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. @@ -99,17 +119,21 @@ On Claude Code and Codex, run `/helix:update` in the host conversation. The plug ## 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`; OpenCode uses `opencode plugin remove` or removes the source from its `plugins` array. 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 或 Cursor。Cursor 使用上面的 [Cursor 独立安装流程](#cursor-preview)。先确保宿主已完成登录或模型配置,能够正常使用。平台不是安装插件的前置条件。共享运行时的 Windows 支持不代表 Windows Cursor 已完成验收;Cursor 实机验收目前覆盖 macOS。 +需要 Python 3.10+、Git,以及支持插件的 Codex、Claude Code、Cursor 或 OpenCode(v2.2.2+)。Cursor 使用上面的 [Cursor 独立安装流程](#cursor-preview)。先确保宿主已完成登录或模型配置,能够正常使用。平台不是安装插件的前置条件。共享运行时的 Windows 支持不代表 Windows Cursor 已完成验收;Cursor 实机验收目前覆盖 macOS。 + +**OpenCode 预览支持(v2.2.2+):** 插件注册原生 `helix:` 命令、`helix-` 方法 Skill 和 `helix-` 角色,将 Host Context 绑定到当前仓库和会话。完整 Init → Propose → Apply → Archive 流程尚未完成真实模型验收。Workspace Apply 的 `may_delegate` RepoJob 使用 `helix-worker`,需要 `experimental.subagent_depth >= 2`;独立 reviewer 保持只读 leaf。深度不足时阻塞该 RepoJob,不得绕过评审。 + +OpenCode 没有原生 SessionStart/Stop/失败/会话结束 hooks,也没有原生计划工具(计划写入 `tasks.md`)。统计不支持(`unsupported_host`);`/helix:update` 返回 `continue_silently`,请通过 OpenCode 插件管理手动更新。项目 hooks 不支持:Init 只合并 `AGENTS.md`,不创建 `.opencode/` settings。d-d2c 的 Claude skill-scoped Stop/PreToolUse guard 不执行,采用无 hook / `--bare` 语义,仍须遵守用户决策、视觉验收和完成门禁。 -正式发布后,Codex 与 Claude Code 使用上面的 GitHub 安装命令,Cursor 使用市场界面流程;这些市场安装方式无需先手动克隆源码。发布前测试或修改插件时,使用[开发者安装(本地源码)](#developer-installation):先下载或克隆源码,再从**包含两个子项目的根目录**添加本地市场。根市场指向 `./helixharness`,不会安装平台。独立插件副本仍可添加插件目录本身;同名市场只保留一个来源。 +正式发布后,Codex 与 Claude Code 使用上面的 GitHub 安装命令,Cursor 使用市场界面流程,OpenCode 使用上面的 `opencode plugin add`;这些市场安装方式无需先手动克隆源码。发布前测试或修改插件时,使用[开发者安装(本地源码)](#developer-installation):先下载或克隆源码,再从**包含两个子项目的根目录**添加本地市场。根市场指向 `./helixharness`,不会安装平台。独立插件副本仍可添加插件目录本身;同名市场只保留一个来源。 -安装后新开会话,确认九个命令可见、插件 hooks 已审阅并实际执行,再在业务仓库运行 `/helix:init`(Cursor 为 `/helix-init`)并检查项目 hooks。单仓 Init 还需检查非空的 `docs/harness/index.md`、`docs/knowledge/index.md`、`docs/knowledge/project-context.md` 及对应项目类型要求的其他产物,不能只看“已完成”回复。若出现 `plugin_source_mismatch`,先核对市场来源与当前安装插件,选定正确来源并新开会话,避免混用其他 checkout 或缓存版本。Claude Code/Codex 更新使用 `/helix:update`;本地来源需先自行更新源码,不能把版本识别成功当作已完成跨版本升级。Cursor 在 macOS/Linux 上使用 `/helix-update` 升级已登记的 Helix 托管本地安装,复用检查、确认与一次性授权协议;手工副本和原生市场安装仍通过原安装方式更新。 +安装后新开会话,确认九个命令可见;Claude Code/Codex/Cursor 检查插件 hooks 已审阅并实际执行,OpenCode 检查命令展开后的当前仓库/会话 Host Context 绑定,再在业务仓库运行 `/helix:init`(Cursor 为 `/helix-init`)并检查项目文档及宿主支持的项目 hooks(OpenCode 不生成项目 hooks)。单仓 Init 还需检查非空的 `docs/harness/index.md`、`docs/knowledge/index.md`、`docs/knowledge/project-context.md` 及对应项目类型要求的其他产物,不能只看“已完成”回复。若出现 `plugin_source_mismatch`,先核对市场来源与当前安装插件,选定正确来源并新开会话,避免混用其他 checkout 或缓存版本。Claude Code/Codex 更新使用 `/helix:update`;本地来源需先自行更新源码,不能把版本识别成功当作已完成跨版本升级。Cursor 在 macOS/Linux 上使用 `/helix-update` 升级已登记的 Helix 托管本地安装,复用检查、确认与一次性授权协议;手工副本和原生市场安装仍通过原安装方式更新。 -**从空项目开始:**在 Git 仓库根目录运行 `/helix:init`(Cursor 为 `/helix-init`)。新目录请先自行执行 `git init`,不需要首次提交。空仓库或纯文档仓库跳过代码扫描,生成最小项目上下文、约束、需求目录与宿主 hooks,未确认的信息标记 TODO。再用 `/helix:propose` 和 `/helix:apply`(Cursor 为 `/helix-propose` 和 `/helix-apply`)开发第一个需求。Init 和 Apply 不创建提交。 +**从空项目开始:**在 Git 仓库根目录运行 `/helix:init`(Cursor 为 `/helix-init`)。新目录请先自行执行 `git init`,不需要首次提交。空仓库或纯文档仓库跳过代码扫描,生成最小项目上下文、约束、需求目录与宿主支持的 hooks(OpenCode 只合并 `AGENTS.md`),未确认的信息标记 TODO。再用 `/helix:propose` 和 `/helix:apply`(Cursor 为 `/helix-propose` 和 `/helix-apply`)开发第一个需求。Init 和 Apply 不创建提交。 ## Windows local source / Windows 本地源码 diff --git a/docs/user-guide.md b/docs/user-guide.md index 400e7fd..563f57a 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, Claude Code and Cursor, with a companion platform for usage dashboards, version evaluation and evolution.** +**A development workflow for Codex, Claude Code, Cursor and OpenCode (Preview), 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 / Cursor · Single repo / multi-repo Workspace · Apache-2.0** +**9 public commands · 3 core stages · Codex / Claude Code / Cursor / OpenCode (Preview) · 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, Claude Code or Cursor 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, Cursor or OpenCode installation (OpenCode v2.2.2+) that is signed in or has its model configuration set up and works normally | | 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,6 +74,19 @@ claude plugin marketplace add https://github.com/didi/helixharness.git claude plugin install helix@helixharness-marketplace ``` +**OpenCode v2.2.2+** + +```bash +# OpenCode v2.2.2+ +opencode plugin add 'github:didi/helixharness::path:helixharness' +``` + +**OpenCode Preview support (v2.2.2+):** The plugin registers native `helix:` commands, `helix-` method skills and `helix-` roles, binding Host Context to the current repository and session. Full Init → Propose → Apply → Archive acceptance with a real model remains unverified. Workspace Apply uses `helix-worker` for `may_delegate` RepoJobs and requires `experimental.subagent_depth >= 2`; independent reviewers remain read-only leaf jobs. Insufficient depth blocks the RepoJob rather than bypassing review. + +OpenCode has no native SessionStart/Stop/failure/session-end hooks or plan tool (`tasks.md` tracks the plan). Telemetry is unsupported (`unsupported_host`); `/helix:update` returns `continue_silently`, so update manually through OpenCode plugin management. Project hooks are unsupported: Init merges `AGENTS.md` without creating `.opencode/` settings. The d-d2c Claude skill-scoped Stop/PreToolUse guards do not run; use its no-hook / `--bare` semantics while retaining user decisions, visual acceptance and completion checks. + +See the [OpenCode installation guide](../helixharness/hosts/opencode/installer.md) for setup and binding checks. + 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. **Cursor** @@ -82,7 +95,7 @@ Install `helix` through **Customize → helix → Install** after the release re ### 2. Build Your First Feature -Enter commands **in your coding agent's conversation**, not in a terminal shell. The examples below use the Codex / Claude Code prefix `/helix:`. In Cursor, replace that prefix with `/helix-`, keeping the command name and arguments unchanged; for example, `/helix:init` becomes `/helix-init`, and `/helix:bug-fix` becomes `/helix-bug-fix`. +Enter commands **in your coding agent's conversation**, not in a terminal shell. The examples below use the Codex / Claude Code / OpenCode prefix `/helix:`. In Cursor, replace that prefix with `/helix-`, keeping the command name and arguments unchanged; for example, `/helix:init` becomes `/helix-init`, and `/helix:bug-fix` becomes `/helix-bug-fix`. Initialize your application repository: @@ -90,7 +103,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. +Claude Code, Codex and Cursor initialization writes project documentation and host project settings. OpenCode merges `AGENTS.md` without creating `.opencode/` settings or project hooks. 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. Create a small, concrete requirement: @@ -153,7 +166,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 / Cursor sessions and application repositories | +| [`helixharness/`](../helixharness/README.md) | Developers using AI coding agents | Project initialization, requirements, implementation, testing, review, and archiving | Codex / Claude Code / Cursor / OpenCode (Preview) 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 @@ -182,7 +195,7 @@ Keep three directories distinct: **HelixHarness plugin source**, **application r ## Commands -There are nine public commands. `--loop` is an option on `propose`. The examples use `/helix:` for Codex / Claude Code; in Cursor, use the `/helix-` prefix with the same arguments. +There are nine public commands. `--loop` is an option on `propose`. The examples use `/helix:` for Codex / Claude Code / OpenCode; in Cursor, use the `/helix-` prefix with the same arguments. | Command | Purpose | Example | | --- | --- | --- | @@ -192,7 +205,7 @@ There are nine public commands. `--loop` is an option on `propose`. The examples | `archive` | Check completion evidence, update knowledge, and archive | `/helix:archive search-empty-state` | | `bug-fix` | Revise an active, unarchived single-repo feature | `/helix:bug-fix search-empty-state "Clearing filters does not reload the list"` | | `ut` | Generate and maintain unit tests | `/helix:ut` | -| `update` | Check and update the plugin from the host's configured source | `/helix:update` | +| `update` | Check and update supported host sources (OpenCode: manual update) | `/helix:update` | | `status` | Read feature progress, blockers, and the next suggested command | `/helix:status search-empty-state` | | `config` | Inspect and change telemetry consent, scope, and reporting addresses | `/helix:config` | @@ -404,7 +417,7 @@ Paths below are relative to your platform's base URL: ### Model Configuration -For everyday plugin use, configure models in Codex / Claude Code / Cursor. 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 / Cursor / OpenCode (Preview). 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. @@ -616,7 +629,7 @@ The repository contains two independently installable projects: ├── helixharness/ │ ├── commands/ # Nine public command entrypoints │ ├── workflows/ # single/ execution and workspace/ coordination -│ ├── hosts/ # Codex / Claude Code / Cursor adapters +│ ├── hosts/ # Codex / Claude Code / Cursor / OpenCode (Preview) adapters │ ├── skills/ # Reusable workflow methods │ └── scripts/ # Routing, artifact validation, and telemetry └── helixharness-platform/ @@ -639,7 +652,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 and Cursor each install 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 and Cursor each install these eight method skills alongside the nine public entry skills; Claude Code discovers the root `skills/` directly; OpenCode registers the same root files as `helix-` method skills. 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. @@ -664,6 +677,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 dd8f22e..c5e448e 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 与 Cursor 的研发工作流,以及提供数据看板、版本评测与自进化的配套平台。** +**面向 Codex、Claude Code、Cursor 与 OpenCode(预览)的研发工作流,以及提供数据看板、版本评测与自进化的配套平台。** 从一个需求到有验证依据的代码变更:明确边界、拆分任务、实现、测试、评审,再把结果归档到项目中。HelixHarness 将这些步骤作为可复用的工作流交给编码助手,需求和执行进度保存在仓库里,便于检查和续跑。 @@ -14,7 +14,7 @@ Propose → Apply → Archive └─ 测试 + 代码评审 + 验证依据 ``` -**9 个公开命令 · 3 个核心阶段 · Codex / Claude Code / Cursor · 单仓 / 多仓 Workspace · Apache-2.0** +**9 个公开命令 · 3 个核心阶段 · Codex / Claude Code / Cursor / OpenCode(预览) · 单仓 / 多仓 Workspace · Apache-2.0** 只做日常开发,安装 **HelixHarness** 即可。需要观测使用情况、评测和改进 **HelixHarness 框架本身**,再运行 **helixharness-platform**。开发场景的结果用于判断框架行为,平台不是通用的业务代码评分服务。 @@ -50,7 +50,7 @@ Propose → Apply → Archive | 用途 | 要求 | | --- | --- | -| 使用 HelixHarness | Python 3.10+、Git,以及支持插件的 Codex、Claude Code 或 Cursor;宿主已完成登录或模型配置,能够正常使用 | +| 使用 HelixHarness | Python 3.10+、Git,以及支持插件的 Codex、Claude Code、Cursor 或 OpenCode(v2.2.2+);宿主已完成登录或模型配置,能够正常使用 | | 运行平台 Demo / 使用看板 | Python 3.10+、Git;安装平台 `server` 依赖 | | 真实版本评测 | 平台依赖、可用的 Codex 执行环境、模型凭据、可访问的 Git 仓库,以及 Case 所需的构建与测试工具 | | 前端预览与视觉验证 | 项目自身的 Node.js、包管理器及浏览器工具;设计服务按实际使用情况配置 | @@ -75,6 +75,19 @@ claude plugin marketplace add https://github.com/didi/helixharness.git claude plugin install helix@helixharness-marketplace ``` +**OpenCode v2.2.2+** + +```bash +# OpenCode v2.2.2+ +opencode plugin add 'github:didi/helixharness::path:helixharness' +``` + +**OpenCode 预览支持(v2.2.2+):** 插件注册原生 `helix:` 命令、`helix-` 方法 Skill 和 `helix-` 角色,将 Host Context 绑定到当前仓库和会话。完整 Init → Propose → Apply → Archive 流程尚未完成真实模型验收。Workspace Apply 的 `may_delegate` RepoJob 使用 `helix-worker`,需要 `experimental.subagent_depth >= 2`;独立 reviewer 保持只读 leaf。深度不足时阻塞该 RepoJob,不得绕过评审。 + +OpenCode 没有原生 SessionStart/Stop/失败/会话结束 hooks,也没有原生计划工具(计划写入 `tasks.md`)。统计不支持(`unsupported_host`);`/helix:update` 返回 `continue_silently`,请通过 OpenCode 插件管理手动更新。项目 hooks 不支持:Init 只合并 `AGENTS.md`,不创建 `.opencode/` settings。d-d2c 的 Claude skill-scoped Stop/PreToolUse guard 不执行,采用无 hook / `--bare` 语义,仍须遵守用户决策、视觉验收和完成门禁。 + +安装与绑定检查见 [OpenCode 安装指南](../helixharness/hosts/opencode/installer.md)。 + 安装后,在你要开发的业务仓库中新开宿主会话,确认能找到 `helixharness` 的九个公开命令。宿主适配说明见 [Codex 安装指南](../helixharness/hosts/codex/installer.md) 和 [Claude Code 安装指南](../helixharness/hosts/claude-code/installer.md)。 **Cursor** @@ -83,7 +96,7 @@ claude plugin install helix@helixharness-marketplace ### 2. 完成第一个需求 -命令应**输入到编码助手会话中**,不是终端 Shell 命令。以下示例使用 Codex / Claude Code 的 `/helix:` 前缀;在 Cursor 中将该前缀替换为 `/helix-`,命令名和参数保持不变。例如 `/helix:init` 对应 `/helix-init`,`/helix:bug-fix` 对应 `/helix-bug-fix`。 +命令应**输入到编码助手会话中**,不是终端 Shell 命令。以下示例使用 Codex / Claude Code / OpenCode 的 `/helix:` 前缀;在 Cursor 中将该前缀替换为 `/helix-`,命令名和参数保持不变。例如 `/helix:init` 对应 `/helix-init`,`/helix:bug-fix` 对应 `/helix-bug-fix`。 先在业务仓库初始化项目: @@ -91,7 +104,7 @@ claude plugin install helix@helixharness-marketplace /helix:init ``` -初始化会写入项目文档和宿主项目配置。宿主提示当前项目配置目录的写权限时,确认本项目后授权。自动化运行也需显式响应授权:Claude Code 的 `acceptEdits` 模式不会自动批准 `.claude/settings.json`,保护 `.codex/` 的沙箱也可能使 Codex hooks 未完成。开始需求前先检查初始化结果。 +Claude Code、Codex 和 Cursor 初始化会写入项目文档和宿主项目配置。OpenCode 只合并 `AGENTS.md`,不创建 `.opencode/` settings 或项目 hooks。宿主提示当前项目配置目录的写权限时,确认本项目后授权。自动化运行也需显式响应授权:Claude Code 的 `acceptEdits` 模式不会自动批准 `.claude/settings.json`,保护 `.codex/` 的沙箱也可能使 Codex hooks 未完成。开始需求前先检查初始化结果。 再创建一个范围清晰的需求: @@ -154,7 +167,7 @@ python -m web_ui.demo --port 7860 --data-dir /path/to/demo-runtime | 项目 | 面向谁 | 负责什么 | 运行位置 | | --- | --- | --- | --- | -| [`helixharness/`](../helixharness/README.md) | 日常使用 AI 编码的开发者 | 初始化项目、收敛需求、实现、测试、评审、归档 | Codex / Claude Code / Cursor 会话及业务仓库 | +| [`helixharness/`](../helixharness/README.md) | 日常使用 AI 编码的开发者 | 初始化项目、收敛需求、实现、测试、评审、归档 | Codex / Claude Code / Cursor / OpenCode(预览) 会话及业务仓库 | | [`helixharness-platform/`](../helixharness-platform/README.md) | 观测和改进 HelixHarness 框架的维护者 | 数据看板、版本评测、自进化 | 独立 Python Web 服务与评测 Worker | ```mermaid @@ -183,7 +196,7 @@ flowchart LR ## 命令参考 -公开命令共九个,`--loop` 是 `propose` 的参数。表中示例使用 Codex / Claude Code 的 `/helix:`;在 Cursor 中使用 `/helix-` 前缀,参数相同。 +公开命令共九个,`--loop` 是 `propose` 的参数。表中示例使用 Codex / Claude Code / OpenCode 的 `/helix:`;在 Cursor 中使用 `/helix-` 前缀,参数相同。 | 命令 | 用途 | 示例 | | --- | --- | --- | @@ -193,7 +206,7 @@ flowchart LR | `archive` | 核验完成证据、更新知识并归档 | `/helix:archive search-empty-state` | | `bug-fix` | 修订尚未归档的单仓需求 | `/helix:bug-fix search-empty-state "清除筛选后没有重新加载列表"` | | `ut` | 生成和维护单元测试 | `/helix:ut` | -| `update` | 检查并更新宿主已配置来源的插件 | `/helix:update` | +| `update` | 检查并更新支持宿主的插件来源(OpenCode 手动更新) | `/helix:update` | | `status` | 只读查看需求进度、阻塞与下一步 | `/helix:status search-empty-state` | | `config` | 查看和修改统计授权、范围及上报地址 | `/helix:config` | @@ -405,7 +418,7 @@ DEFAULT_FEEDBACK_ENDPOINT = "" ### 模型配置 -日常使用插件时,模型由 Codex / Claude Code / Cursor 宿主配置。平台自身的模型配置用于平台发起的评测、分析等任务。 +日常使用插件时,模型由 Codex / Claude Code / Cursor / OpenCode(预览) 宿主配置。平台自身的模型配置用于平台发起的评测、分析等任务。 配置模板见 [`helixharness-platform/.env.example`](../helixharness-platform/.env.example)。服务读取**进程环境变量,不会自动加载 `.env.example`**;将真实值注入启动 Web 和 Worker 的环境。 @@ -617,7 +630,7 @@ Candidate 生成在普通用户(包括 macOS 本地用户)下默认使用 Co ├── helixharness/ │ ├── commands/ # 九个公共命令入口和路由 │ ├── workflows/ # single/ 单仓执行,workspace/ 多仓协调 -│ ├── hosts/ # Codex / Claude Code / Cursor 适配 +│ ├── hosts/ # Codex / Claude Code / Cursor / OpenCode(预览) 适配 │ ├── skills/ # 工作流复用的方法 │ └── scripts/ # 路由、工件校验与遥测 └── helixharness-platform/ @@ -640,7 +653,7 @@ Candidate 生成在普通用户(包括 macOS 本地用户)下默认使用 Co | [`systematic-debugging`](../helixharness/skills/systematic-debugging/SKILL.md) | 复现异常、验证假设、定位根因与验证修复 | 由用户明确调用,独立使用 | | [`feedback`](../helixharness/skills/feedback/SKILL.md) | 提交 HelixHarness 使用问题 | 独立辅助能力;需启动平台并配置地址 | -Codex 与 Cursor 安装目录各包含九个公开入口 Skill 和上述八个方法 Skill;Claude Code 直接发现根 `skills/`。四个生命周期命令继续使用工作流路由;`status`、`config` 与辅助 Skill 不增加研发阶段。正式 Spec/Tasks、执行进度和完成验证仍由对应研发阶段负责。 +Codex 与 Cursor 安装目录各包含九个公开入口 Skill 和上述八个方法 Skill;Claude Code 直接发现根 `skills/`;OpenCode 从相同根文件注册 `helix-` 方法 Skill。四个生命周期命令继续使用工作流路由;`status`、`config` 与辅助 Skill 不增加研发阶段。正式 Spec/Tasks、执行进度和完成验证仍由对应研发阶段负责。 `git-diff-impact` 无需 Init、活跃 feature 或平台服务。示例:“使用 HelixHarness git-diff-impact,分析当前未提交改动,--no-save”;也可明确提供两个提交或分支,以及 `--req` / `--design` 文档。默认保存 Markdown 到 `diff-impact-reports/`,`--out` 可指定位置。它不自动修复代码,也不改变评审结论。 @@ -665,6 +678,8 @@ Codex 与 Cursor 安装目录各包含九个公开入口 Skill 和上述八个 ```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 eccc602..e9131f9 100644 --- a/docs/workflow-architecture.md +++ b/docs/workflow-architecture.md @@ -22,14 +22,18 @@ Workspace 子任务从公共入口进入 Single 正文,根目录不写子仓 ## 宿主边界 [`Host API`](../helixharness/reference/host-api.md) 定义 manifest 和适配器合同。 -Claude Code 使用原生命令,Codex 与 Cursor 使用各自的 Skill 投影;宿主机制由 `hosts/{host-id}/` 提供。 -三个原生插件清单显式选择各自的 hook 配置。宿主入口负责固定身份和事件转换, +Claude Code 使用原生命令,Codex 与 Cursor 使用各自的 Skill 投影;OpenCode 由插件注册原生命令、方法 Skill 和 Agent,绑定当前仓库与会话的 Host Context;宿主机制由 `hosts/{host-id}/` 提供。 +Claude Code、Codex 与 Cursor 的原生插件清单显式选择各自的 hook 配置;OpenCode 不发布 hook manifest。宿主入口负责固定身份和事件转换, 共享生命周期逻辑不得根据平台名称、环境变量或缓存目录猜测宿主。 宿主 Init 入口加载 `project_config`、`project_hooks`;UT 入口加载 `ut`。 -单仓 Init 必须实际生成并校验当前 Host Kit 的项目 hooks,重复初始化保留用户配置并去重。 +支持项目 hooks 的宿主,单仓 Init 必须实际生成并校验当前 Host Kit 的项目 hooks,重复初始化保留用户配置并去重。 业务阶段显式记录 start/finish;会话 Stop 不是业务完成证据。 +**OpenCode 预览支持(v2.2.2+):** 插件注册原生 `helix:` 命令、`helix-` 方法 Skill 和 `helix-` 角色,将 Host Context 绑定到当前仓库和会话。完整 Init → Propose → Apply → Archive 流程尚未完成真实模型验收。Workspace Apply 的 `may_delegate` RepoJob 使用 `helix-worker`,需要 `experimental.subagent_depth >= 2`;独立 reviewer 保持只读 leaf。深度不足时阻塞该 RepoJob,不得绕过评审。 + +OpenCode 没有原生 SessionStart/Stop/失败/会话结束 hooks,也没有原生计划工具(计划写入 `tasks.md`)。统计不支持(`unsupported_host`);`/helix:update` 返回 `continue_silently`,请通过 OpenCode 插件管理手动更新。项目 hooks 不支持:Init 只合并 `AGENTS.md`,不创建 `.opencode/` settings。d-d2c 的 Claude skill-scoped Stop/PreToolUse guard 不执行,采用无 hook / `--bare` 语义,仍须遵守用户决策、视觉验收和完成门禁。 + ## 独立性与数据边界 - 只支持当前 Host API 和当前账本、轨迹 schema;不迁移旧版本数据,不接受已退役的工作流正文路径。 diff --git a/examples/README.md b/examples/README.md index 8b3514b..7280487 100644 --- a/examples/README.md +++ b/examples/README.md @@ -23,14 +23,16 @@ 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, Cursor or OpenCode (Preview) in the `$TASK_FILTER_DEMO` directory (run `pwd` in that terminal to see its path) and enter: ```text /helix:init /helix:propose task-filter ./requirements/task-filter.md --loop ``` -Allow the host's project-hook setup when prompted. For this example, choose telemetry **off** when asked. Review the proposed requirement boundaries and answer any clarification in the conversation. +Cursor uses `/helix-init` and `/helix-propose` with the same arguments. OpenCode v2.2.2+ uses the `/helix:` commands above; its support is Preview and this walkthrough does not establish real-model acceptance. OpenCode has no project hooks or telemetry; Init merges `AGENTS.md` and the telemetry choice does not apply. See the [OpenCode limits](../helixharness/hosts/opencode/installer.md). + +On hosts supporting hooks, allow the host's project-hook setup when prompted. For this example, choose telemetry **off** if asked. Review the proposed requirement boundaries and answer any clarification in the conversation. Expected workflow: @@ -62,6 +64,6 @@ This is a reproducible walkthrough, not a pre-recorded model run. No generated S ## 中文操作说明 -按第一步复制起始项目到独立临时目录并建立 Git 基线,两个基础测试应通过。在该业务目录打开宿主,依次执行 Init 和上面的 Propose 命令;示例可关闭统计,不需要平台地址。 +按第一步复制起始项目到独立临时目录并建立 Git 基线,两个基础测试应通过。在该业务目录打开宿主,依次执行 Init 和上面的 Propose 命令;Cursor 将 `/helix:` 前缀换为 `/helix-`。OpenCode v2.2.2+ 为预览支持,不生成项目 hooks、不采集统计,沿用 `/helix:`;本示例不代表已完成真实模型验收。支持统计的宿主可关闭统计,不需要平台地址。 检查需求是否保留六条验收标准,Apply 是否实现筛选并补充测试、评审,Archive 是否生成完整的 completed 工件。最后运行基础测试和独立验收脚本。起始代码运行独立验收会失败,这是因为筛选需求尚未实现;不要把教程中的预期工件当作已经发生的模型执行记录。 diff --git a/helixharness/.claude-plugin/marketplace.json b/helixharness/.claude-plugin/marketplace.json index f11670e..9c68a46 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, Cursor and OpenCode (Preview)" }, "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, Cursor and OpenCode (Preview) 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..549c7bf 100644 --- a/helixharness/.claude-plugin/plugin.json +++ b/helixharness/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "helix", - "description": "HelixHarness 面向 Agent 的双宿主研发工作流插件,提供命令与可复用技能。", + "description": "HelixHarness 面向 Claude Code、Codex、Cursor 与 OpenCode(预览)的研发工作流插件,提供命令与可复用技能。", "author": { "name": "HelixHarness contributors" }, diff --git a/helixharness/AGENTS.md b/helixharness/AGENTS.md index 8616fa5..4b75c64 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 f5b6207..89dcab8 100644 --- a/helixharness/PLUGIN_USAGE.md +++ b/helixharness/PLUGIN_USAGE.md @@ -1,10 +1,10 @@ # HelixHarness -面向 Codex、Claude Code 与 Cursor 的 HelixHarness 研发工作流。通过项目约束、知识库、Spec、任务和验证证据完成研发。 +面向 Codex、Claude Code、Cursor 与 OpenCode(预览)的 HelixHarness 研发工作流。通过项目约束、知识库、Spec、任务和验证证据完成研发。 ## 命令 -以下 `/helix:*` 为公共逻辑命令名,也是 Codex / Claude Code 的输入形式。Cursor 使用 `/helix-{command}`,从 `/helix-` 补全选择入口,参数和业务门禁相同。Cursor 默认通过市场安装,固定来源配置和托管 Local 作为可选方式;统计及更新的能力边界见 [Cursor 安装说明](hosts/cursor/installer.md)。 +以下 `/helix:*` 为公共逻辑命令名,也是 Codex / Claude Code / OpenCode 的输入形式。Cursor 使用 `/helix-{command}`,从 `/helix-` 补全选择入口,参数和业务门禁相同。Cursor 默认通过市场安装,固定来源配置和托管 Local 作为可选方式;统计及更新的能力边界见 [Cursor 安装说明](hosts/cursor/installer.md)。 - `/helix:init`:初始化当前项目;`--workspace` 初始化多仓目录。 - `/helix:propose `:收敛需求并生成 Spec/Tasks。 @@ -19,7 +19,11 @@ ## 安装 -需要 Python 3.10+、Git,以及 Codex、Claude Code 或 Cursor。Codex、Claude Code 可将本目录作为本地 marketplace 添加;Cursor 通过市场界面安装。宿主步骤见 [Codex](hosts/codex/installer.md)、[Claude Code](hosts/claude-code/installer.md) 和 [Cursor](hosts/cursor/installer.md) 安装说明。 +需要 Python 3.10+、Git,以及 Codex、Claude Code、Cursor 或 OpenCode(v2.2.2+)。Codex、Claude Code 可将本目录作为本地 marketplace 添加;Cursor 通过市场界面安装。宿主步骤见 [Codex](hosts/codex/installer.md)、[Claude Code](hosts/claude-code/installer.md)、[Cursor](hosts/cursor/installer.md) 和 [OpenCode](hosts/opencode/installer.md) 安装说明。OpenCode 将本插件目录加入 `plugins` 数组。 + +**OpenCode 预览支持(v2.2.2+):** 插件注册原生 `helix:` 命令、`helix-` 方法 Skill 和 `helix-` 角色,将 Host Context 绑定到当前仓库和会话。完整 Init → Propose → Apply → Archive 流程尚未完成真实模型验收。Workspace Apply 的 `may_delegate` RepoJob 使用 `helix-worker`,需要 `experimental.subagent_depth >= 2`;独立 reviewer 保持只读 leaf。深度不足时阻塞该 RepoJob,不得绕过评审。 + +OpenCode 没有原生 SessionStart/Stop/失败/会话结束 hooks,也没有原生计划工具(计划写入 `tasks.md`)。统计不支持(`unsupported_host`);`/helix:update` 返回 `continue_silently`,请通过 OpenCode 插件管理手动更新。项目 hooks 不支持:Init 只合并 `AGENTS.md`,不创建 `.opencode/` settings。d-d2c 的 Claude skill-scoped Stop/PreToolUse guard 不执行,采用无 hook / `--bare` 语义,仍须遵守用户决策、视觉验收和完成门禁。 ## 项目结构 @@ -37,6 +41,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 3efba79..1053485 100644 --- a/helixharness/README.md +++ b/helixharness/README.md @@ -2,11 +2,11 @@ 当前版本:**1.0.0**。 -面向 Codex、Claude Code 与 Cursor 的 HelixHarness 研发工作流。通过项目约束、知识库、Spec、任务和验证证据完成研发。 +面向 Codex、Claude Code、Cursor 与 OpenCode(预览)的 HelixHarness 研发工作流。通过项目约束、知识库、Spec、任务和验证证据完成研发。 ## 命令 -以下 `/helix:*` 为公共逻辑命令名,也是 Codex / Claude Code 的输入形式。Cursor 使用 `/helix-{command}`,从 `/helix-` 补全选择入口,参数和业务门禁相同。Cursor 默认通过市场安装,固定来源配置和托管 Local 作为可选方式;统计及更新的能力边界见 [Cursor 安装说明](hosts/cursor/installer.md)。 +以下 `/helix:*` 为公共逻辑命令名,也是 Codex / Claude Code / OpenCode 的输入形式。Cursor 使用 `/helix-{command}`,从 `/helix-` 补全选择入口,参数和业务门禁相同。Cursor 默认通过市场安装,固定来源配置和托管 Local 作为可选方式;统计及更新的能力边界见 [Cursor 安装说明](hosts/cursor/installer.md)。 - `/helix:init`:初始化当前项目;`--workspace` 初始化多仓目录。 - `/helix:propose `:收敛需求并生成 Spec/Tasks。 @@ -21,7 +21,11 @@ ## 安装 -需要 Python 3.10+、Git,以及 Codex、Claude Code 或 Cursor。Codex、Claude Code 可将本目录作为本地 marketplace 添加;Cursor 通过市场界面安装。宿主步骤见 [Codex](hosts/codex/installer.md)、[Claude Code](hosts/claude-code/installer.md) 和 [Cursor](hosts/cursor/installer.md) 安装说明。 +需要 Python 3.10+、Git,以及 Codex、Claude Code、Cursor 或 OpenCode(v2.2.2+)。Codex、Claude Code 可将本目录作为本地 marketplace 添加;Cursor 通过市场界面安装。宿主步骤见 [Codex](hosts/codex/installer.md)、[Claude Code](hosts/claude-code/installer.md)、[Cursor](hosts/cursor/installer.md) 和 [OpenCode](hosts/opencode/installer.md) 安装说明。OpenCode 将本插件目录加入 `plugins` 数组。 + +**OpenCode 预览支持(v2.2.2+):** 插件注册原生 `helix:` 命令、`helix-` 方法 Skill 和 `helix-` 角色,将 Host Context 绑定到当前仓库和会话。完整 Init → Propose → Apply → Archive 流程尚未完成真实模型验收。Workspace Apply 的 `may_delegate` RepoJob 使用 `helix-worker`,需要 `experimental.subagent_depth >= 2`;独立 reviewer 保持只读 leaf。深度不足时阻塞该 RepoJob,不得绕过评审。 + +OpenCode 没有原生 SessionStart/Stop/失败/会话结束 hooks,也没有原生计划工具(计划写入 `tasks.md`)。统计不支持(`unsupported_host`);`/helix:update` 返回 `continue_silently`,请通过 OpenCode 插件管理手动更新。项目 hooks 不支持:Init 只合并 `AGENTS.md`,不创建 `.opencode/` settings。d-d2c 的 Claude skill-scoped Stop/PreToolUse guard 不执行,采用无 hook / `--bare` 语义,仍须遵守用户决策、视觉验收和完成门禁。 ## 独立方案探索与调试 @@ -32,7 +36,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 与 Cursor 使用各自生成的宿主入口,Claude Code 直接发现根 `skills/`,OpenCode 注册 `helix-` 方法 Skill;详细示例见[使用指南](../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 和执行上下文,没有独立模式。 @@ -79,6 +83,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..52e8024 --- /dev/null +++ b/helixharness/hosts/opencode/installer.md @@ -0,0 +1,90 @@ +# 安装与更新 + +完整步骤见[安装指南](../../../docs/installation.md)。当前单仓源码使用插件目录的绝对路径; +公开发布后也可使用 `https://github.com/didi/helixharness.git`,记为 `HELIXHARNESS_SOURCE`。 +OpenCode V2 使用插件包根目录(本仓库的 `helixharness/`)中的 `package.json` 和 +`opencode/index.ts`。 + +## OpenCode 预览支持 + +当前为 Preview:已提供九个命令、方法 Skill、原生子代理及命令/Skill 的 Host Context 绑定, +完整 Init → Propose → Apply → Archive 工作流尚未完成真实客户端验收。 + +- 无原生 SessionStart/Stop/失败/会话结束 hooks;无原生计划工具,计划写入当前 Feature `tasks.md`。 +- 统计为 `unsupported`(脚本返回 `unsupported_host`);插件内更新为 `unsupported` + (`/helix:update` 返回 `continue_silently`),请通过 OpenCode 插件管理手动更新。 +- 项目 hooks 不支持;Init 只合并 `AGENTS.md`,不创建 `.opencode/` settings。 +- d-d2c 的 Claude skill-scoped Stop/PreToolUse guard 不执行,采用无 hook / `--bare` 语义; + 仍须完成 Skill 正文中的用户决策、视觉验收和完成门禁。 +- Workspace Apply 需要 `experimental.subagent_depth >= 2`,详见下方多仓配置。 + +## 从 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` 并使用 `helix-worker`,需要允许 child 继续派发 Single Apply 的只读评审角色。在该项目 +或全局 `opencode.json(c)` 中将 `experimental.subagent_depth` 设置为至少 `2`: + +```jsonc +{ + "experimental": { + "subagent_depth": 2 + } +} +``` + +不设置时 Single 仓流程仍可运行,但 Workspace Apply 必须如实报告深度不足并停止该 RepoJob,不能 +降级内联、由 Implementer 自审或伪造完成。原生 `subagent` 的执行和等待参数以当前暴露的 +schema 为准;等待真实结果或原生后台完成通知,`sessionID` 不是完成证据。 + +## 验收 + +新开 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 注入成功;必须检查一次命令展开后的正文。 + +开发者可运行[宿主集成测试](../../opencode/tests/README.md):使用真实 OpenCode 服务和本地脚本 +模型验证目录绑定、失败正文替换与子任务执行边界,不需要真实模型账号。该结果不替代完整需求的 +真实模型验收。 + +## 更新与卸载 + +- 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..6f9aba1 --- /dev/null +++ b/helixharness/hosts/opencode/runtime.md @@ -0,0 +1,84 @@ +# OpenCode 宿主运行时 + +本 Host Kit 面向 OpenCode V2(最低验证版本 2.2.2)。插件包在本安装的 `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` 按当前会话目录绑定。 + +命令执行和直接 Skill 调用均以请求会话的 `session.get().location.directory` 为目录来源, +校验为真实存在的绝对目录后绑定,不回退到插件目录、进程 cwd 或其他会话。查询失败报 +`repo_root_lookup_failed`;缺失、相对、不可解析或非目录的值报 `repo_root_invalid`。目录绑定 +失败时命令不提交 prompt;Skill 结果替换为相应的 `BLOCKED`,不交付未绑定的正文。 + +| 逻辑动作 | OpenCode 行为 | +|---|---| +| `read_file` | 使用原生 `read` 工具读取确定路径 | +| `edit_file` | 使用原生 `edit`、`write` 或 `patch`,并保留当前写域与单写者约束 | +| `run_command` | 使用原生 `shell` 工具并保留真实退出状态;需要执行目录、超时或后台控制时,只使用当前暴露的 `shell` schema 支持的选项 | +| `invoke_skill` | 使用原生 `skill` 工具;把 `invoke_skill(name)` 映射为 `helix-` | +| `spawn_job` | 保持已解析的 `delegation_policy`;普通 leaf 使用 `general`,通用 may_delegate 使用 `helix-worker`,Init/UT 使用 canonical `helix-` leaf | +| `wait_job` | 遵循当前暴露的原生 `subagent` schema;等待真实完成结果或后台完成通知,再校验结果与产物;`sessionID` 本身不代表完成 | +| `ask_user` | 使用原生 `question` 工具并等待真实回答 | +| `update_plan` | OpenCode 无原生计划工具,更新当前 Feature 的 `tasks.md` | +| `stage_finish` | 在命令内按真实终态显式调用 HelixHarness 生命周期脚本 | +| `project_entry` | 生成或合并根 `AGENTS.md` | +| `project_hooks` | OpenCode 无项目 settings hook 契约;声明 `unsupported`,不创建替代文件 | + +Workspace Apply 的 RepoJob 需要 `experimental.subagent_depth >= 2` 才能派发 Single Apply 的 +独立只读 leaf reviewer。深度或权限不足时返回具体 `BLOCKED`,不得内联降级、自审或虚构 +review 完成。前台/后台参数随 OpenCode 版本变化,不能假设所有 V2 都有 `background` 选择器。 + +## 命令与参数 + +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..1c7140a --- /dev/null +++ b/helixharness/hosts/opencode/subagent.md @@ -0,0 +1,107 @@ +# 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` 和 + `interaction_mode=host_native`。保持 job 已解析的策略:缺省为 `leaf`;只有命令明确声明的 + job 才能使用 `may_delegate`,不得把 Workspace Apply RepoJob 强制改为 leaf。 +- 按当前版本实际暴露的原生 `subagent` schema 选择执行与等待方式。不同 OpenCode V2 版本 + 不保证提供相同的前台/后台参数;不得假设默认前台执行,也不得传入 schema 不支持的 + `background` 参数。提供前台执行时等待真实返回结果;后台派发时等待原生完成通知,再读取 + child 的真实结果。不得用固定轮询或文件出现代替终态。 +- `helix-worker` 是 Host Kit 注册的通用运行角色,只执行 dispatch prompt,不承载业务步骤。 + 内建 `general` 默认禁止 `subagent`,因此不能用于 `may_delegate` 的 RepoJob。插件为所有 + canonical `helix-*` 角色追加 `subagent` deny 权限,保持 Init 与 UT 角色的 `leaf`;只有 + `helix-worker` 保留派发能力。RepoJob 派发的独立 reviewer 仍为只读 leaf,不得继续派生。 +- 返回值中的 `sessionID` 只表示 child 会话引用,不能证明完成;只在本次逻辑 job 中用于继续 + 同一 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)` 中设置 +`experimental.subagent_depth` 至少为 `2`: + +```jsonc +{ + "experimental": { + "subagent_depth": 2 + } +} +``` + +该设置只允许 RepoJob child 继续派发其 Single Apply 所需的只读评审角色。未设置或深度不足时, +child 必须返回具体缺口并由父流程按 blocked 语义处理,不得把 depth 限制当作“subagent 不可用” +而降级内联,不得由 Implementer 自审或绕过独立评审,也不得虚构已完成的 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..11db9bc --- /dev/null +++ b/helixharness/hosts/opencode/ut.md @@ -0,0 +1,54 @@ +# 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`,按当前暴露的原生 schema 选择派发方式。在宿主支持的 + 并行或后台执行方式下派发无写域冲突的 ready job;若仅支持前台执行,等待真实结果后再派发。 + 不假定默认前台执行,不要求或传入 schema 不支持的 `background` 等参数;不假定固定并发 + 上限,不预计算 slot,不把容量暂满当不可用。 +- runtime handle 只保存在当前调用内存,不写业务工件;队列 `Agent ID` 列写 `-`。 +- `wait_worker` 按当前 schema 等待前台真实结果,或后台 child 的原生完成通知并读取真实结果; + `sessionID` 本身不是完成证据。不按固定频率轮询文件,不因静默自动中断或重试。收到终态后 + 父流程再校验 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..ee67ab9 --- /dev/null +++ b/helixharness/opencode/core.ts @@ -0,0 +1,781 @@ +/** + * 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. Preserve the resolved `delegation_policy` from the command's Dispatch Contract. Generic `leaf` jobs use `general`; generic `may_delegate` jobs use `helix-worker` (currently Workspace Apply RepoJobs). Registered Init and UT roles use `helix-` and remain leaves.", + "- Follow the exposed native `subagent` schema for execution and waiting; do not assume every OpenCode V2 release supports a foreground/background selector. `wait_job` waits for a real completed result or the native background-completion notice, then validates the returned result and artifacts. A returned `sessionID` alone is not completion.", + "- `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.", + "- Preserve the resolved `delegation_policy` from the dispatch. When `delegation_policy=may_delegate`, delegate only the independent review roles required by the routed Single Apply through the native `subagent` tool; reviewer jobs remain read-only leaves with `delegation_policy=leaf`. Otherwise stay a leaf and do not spawn children.", + "- Workspace Apply requires `experimental.subagent_depth >= 2`. If the native nesting depth or permissions do not permit the required delegation, return the concrete gap and `BLOCKED` reason to the parent. Never self-review or inline a required independent review, or invent a completed 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, + ); +} + +function hasRepoRootToken(result: ToolAfterEvent["result"]): boolean { + const content = result?.content; + if (typeof content === "string") return content.includes(REPO_ROOT_TOKEN); + return content?.some( + (item) => item.type === "text" && item.text?.includes(REPO_ROOT_TOKEN), + ) ?? false; +} + +type RepoRootErrorCode = "repo_root_lookup_failed" | "repo_root_invalid"; + +class RepoRootError extends Error { + constructor(readonly code: RepoRootErrorCode) { + super(`${code}: Cannot bind the requesting session directory.`); + } +} + +async function resolveRepoRoot( + ctx: PluginContext, + sessionID: string, +): Promise { + let session: Awaited>; + try { + session = await ctx.session.get({ sessionID }); + } catch { + throw new RepoRootError("repo_root_lookup_failed"); + } + const directory = session?.location?.directory; + if (typeof directory !== "string" || !directory.trim() || !path.isAbsolute(directory)) { + throw new RepoRootError("repo_root_invalid"); + } + try { + const resolved = realpath(directory); + if (!fs.statSync(resolved).isDirectory()) throw new Error(); + return resolved; + } catch { + throw new RepoRootError("repo_root_invalid"); + } +} + +/** + * 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()); + + // Skill content is not safe to expose until the session-binding hook exists. + if (!ctx.tool || typeof ctx.tool.hook !== "function") { + throw new Error("repo_root_hook_unavailable: Session directory binding is required."); + } + await ctx.tool.hook("execute.after", async (event) => { + if (event.tool !== "skill" || event.status !== "completed" || !hasRepoRootToken(event.result)) return; + try { + const repoRoot = await resolveRepoRoot(ctx, event.sessionID); + replaceToolResultContent(event.result, repoRoot); + } catch (error) { + const failure = error instanceof RepoRootError + ? error + : new RepoRootError("repo_root_invalid"); + event.result = { content: `BLOCKED: ${failure.message}` }; + } + }); + + 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); + 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); + }); + }); +} 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/README.md b/helixharness/opencode/tests/README.md new file mode 100644 index 0000000..fe858fc --- /dev/null +++ b/helixharness/opencode/tests/README.md @@ -0,0 +1,54 @@ +# OpenCode adapter verification / OpenCode 适配验收 + +Run these commands from the plugin directory (`helixharness/`). + +```bash +bun install --ignore-scripts +bun test opencode/tests +bun run typecheck +``` + +The default suite skips native-server tests. To exercise an installed OpenCode V2 binary: + +```bash +HELIXHARNESS_OPENCODE_E2E=1 bun test opencode/tests/e2e.test.ts +``` + +If it is not on `PATH`, select the executable explicitly: + +```bash +HELIXHARNESS_OPENCODE_BIN=/absolute/path/to/opencode \ + HELIXHARNESS_OPENCODE_E2E=1 bun test opencode/tests/e2e.test.ts +``` + +`native-fixture.ts` starts the real OpenCode server with temporary project/home/config/data/cache/state +directories and a loopback OpenAI-compatible scripted model. It forwards no model-account environment +variables and uses only synthetic messages and fixture authentication. It stops both servers and removes +the temporary directories when each fixture finishes. An OpenCode account or paid model is not needed. + +The tests verify registration and command admission, per-session directory binding, command rejection +after a directory disappears, successful Skill binding and complete replacement of failed Skill output +before the next model call. They also verify native worker → two independent reviewer dispatches, +leaf-role denial and depth-limit failures. The assertions observe actual native execution results; +a tool's presence in the advertised catalog is not proof that it can execute. + +These are adapter integration tests. Scripted model responses do not establish that a real model can +complete Init → Propose → Apply → Archive, produce correct business code, or follow all ownership rules. +OpenCode remains Preview until that separate acceptance is completed. + +## 中文说明 + +在插件目录运行上面的 Bun 单元测试与类型检查。默认跳过真实宿主测试;设置 +`HELIXHARNESS_OPENCODE_E2E=1` 后,使用 `PATH` 上的 OpenCode,或通过 +`HELIXHARNESS_OPENCODE_BIN` 指定实际可执行文件。最低验证版本为 OpenCode 2.2.2。 + +测试启动真实 OpenCode 服务,但模型是本机回环地址上的脚本模型;项目、宿主测试 home、配置、数据、缓存和 +状态均使用临时目录,不传递模型账号环境变量,不需要真实账号或付费模型。测试结束后关闭 +服务并清理临时目录。 + +验收覆盖注册、命令提交、跨会话目录绑定、目录失效后的阻塞、Skill 正文绑定与失败结果替换, +以及 worker 的两路独立派发、leaf 角色拒绝委派和深度不足拦截。必须检查真实调用结果,不能仅凭 +工具出现在列表中判断权限有效。 + +这些结果证明宿主适配链路可用;真实模型执行完整需求、业务实现正确性及全部所有权规则的 +验收仍需单独完成,因此支持级别保持 Preview。 diff --git a/helixharness/opencode/tests/core.test.ts b/helixharness/opencode/tests/core.test.ts new file mode 100644 index 0000000..de640ee --- /dev/null +++ b/helixharness/opencode/tests/core.test.ts @@ -0,0 +1,221 @@ +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("Host Context preserves dispatch policy and selects a delegating generic worker", () => { + const plugin = loadPluginResources(PLUGIN_ROOT); + const prompt = buildCommandPrompt( + plugin.commands.find((command) => command.name === "apply")!, + hostContextFor(plugin, "/repo"), + "--feature demo", + ); + const bindings = prompt.split("## OpenCode runtime bindings")[1]!.split("---")[0]!; + + expect(bindings).toContain("Preserve the resolved `delegation_policy`"); + expect(bindings).toContain("Generic `leaf` jobs use `general`"); + expect(bindings).toContain("`may_delegate` jobs use `helix-worker`"); + expect(bindings).toContain("Follow the exposed native `subagent` schema"); + expect(bindings).toContain("`sessionID` alone is not completion"); + expect(bindings).not.toContain("Set `background: true`"); + }); + + 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("Preserve the resolved `delegation_policy`"); + expect(system).toContain("reviewer jobs remain read-only leaves"); + expect(system).toContain("`experimental.subagent_depth >= 2`"); + expect(system).toContain("Never self-review or inline a required independent review"); + 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..8471558 --- /dev/null +++ b/helixharness/opencode/tests/e2e.test.ts @@ -0,0 +1,212 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import fs from "node:fs"; +import path from "node:path"; +import { eventually, startNativeFixture } from "./native-fixture.ts"; + +const PLUGIN_ROOT = path.resolve(import.meta.dir, "../.."); +const ENABLED = process.env.HELIXHARNESS_OPENCODE_E2E === "1"; +let fixture: Awaited>; + +async function request(_port: number, route: string, init: RequestInit = {}): Promise { + return fixture.request(route, init.body ? JSON.parse(String(init.body)) : undefined); +} + +describe.skipIf(!ENABLED)("installed OpenCode plugin", () => { + let directory = ""; + const port = 0; + + beforeAll(async () => { + fixture = await startNativeFixture(PLUGIN_ROOT); + directory = fixture.directory; + }, 30_000); + + afterAll(async () => { await fixture?.stop(); }); + + 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); + + test("commands bind the requesting session rather than the plugin location", async () => { + const target = path.join(directory, "repo with spaces"); + fs.mkdirSync(target); + const session = await fixture.session("Synthetic second repo", target); + const response = await fixture.request(`/api/session/${session.id}/command`, { name: "helix:status", text: "--help" }); + expect(response.ok).toBe(true); + const context = JSON.stringify(await fixture.context(session.id)); + expect(context).toContain(`repo_root: \`${fs.realpathSync(target)}\``); + expect(context).not.toContain(`repo_root: \`${fs.realpathSync(directory)}\``); + }, 20_000); + + test("a vanished session directory rejects the command without admission", async () => { + const target = path.join(directory, "deleted-command-repo"); + fs.mkdirSync(target); + const session = await fixture.session("Synthetic deleted repo", target); + // Activate this session's location before removing its directory. + await fixture.request(`/api/session/${session.id}/command`, { name: "helix:status", text: "--help" }); + fs.rmSync(target, { recursive: true }); + const before = JSON.stringify(await fixture.context(session.id)); + const response = await fixture.request(`/api/session/${session.id}/command`, { name: "helix:apply", text: "synthetic-must-not-admit" }); + expect(response.ok).toBe(false); + expect(await response.text()).toContain("repo_root_invalid"); + const after = JSON.stringify(await fixture.context(session.id)); + expect(after).not.toContain("synthetic-must-not-admit"); + expect(before).not.toContain("synthetic-must-not-admit"); + }, 20_000); + + test("native skill tool results bind the requesting repo before the next model call", async () => { + const target = path.join(directory, "skill-repo"); + fs.mkdirSync(target); + const session = await fixture.session("Synthetic skill", target); + await fixture.prompt(session.id, "HELIX_E2E_SKILL"); + const observation = await eventually(async () => fixture.observations.find((x) => x.tag === "HELIX_E2E_SKILL" && x.results !== "[]"), Boolean); + expect(observation!.results).toContain("HelixHarness Host Context"); + expect(observation!.results).toContain(fs.realpathSync(target)); + expect(observation!.results).not.toContain("@@HELIXHARNESS_REPO_ROOT@@"); + }, 20_000); + + test("native skill failure replaces the result instead of returning its original body", async () => { + const target = path.join(directory, "deleted-skill-repo"); + fs.mkdirSync(target); + const session = await fixture.session("Synthetic skill failure", target); + fixture.deleteBeforeSkill(target); + await fixture.prompt(session.id, "HELIX_E2E_MISSING_ROOT"); + const observation = await eventually(async () => fixture.observations.find((x) => x.tag === "HELIX_E2E_MISSING_ROOT" && x.results !== "[]"), Boolean); + expect(observation!.results).toContain("BLOCKED: repo_root_invalid"); + expect(observation!.results).not.toContain("HelixHarness Host Context"); + expect(observation!.results).not.toContain("@@HELIXHARNESS_REPO_ROOT@@"); + expect(observation!.results).not.toContain("红灯"); + }, 20_000); + + test("the native worker can launch two independent leaf reviewers at depth two", async () => { + const session = await fixture.session("Synthetic nested review"); + await fixture.prompt(session.id, "HELIX_E2E_PARENT"); + await eventually(async () => fixture.observations, (items) => + ["STANDARDS", "SPEC"].every((axis) => items.some((item) => item.tag === `HELIX_E2E_REVIEW_${axis}`)), + ); + const worker = fixture.observations.find((x) => x.tag === "HELIX_E2E_WORKER")!; + expect(worker.tools).toContain("subagent"); + for (const axis of ["STANDARDS", "SPEC"]) { + const reviewer = fixture.observations.find((x) => x.tag === `HELIX_E2E_REVIEW_${axis}`)!; + expect(reviewer).toBeDefined(); + const agents = await fixture.data("/api/agent"); + const general = agents.find((agent: any) => agent.id === "general"); + expect(general.permissions.some((rule: any) => rule.action === "subagent" && rule.effect === "deny")).toBe(true); + } + }, 20_000); + + test("leaf roles refuse further delegation even when nesting depth permits it", async () => { + for (const role of ["GENERAL", "CANONICAL"]) { + const session = await fixture.session(`Synthetic ${role} leaf`); + await fixture.prompt(session.id, `HELIX_E2E_${role}_PARENT`); + const leaf = await eventually(async () => fixture.observations.find((x) => x.tag === `HELIX_E2E_LEAF_${role}` && x.results !== "[]"), Boolean); + expect(leaf!.results).toMatch(/denied|not allowed|No tool named/i); + } + expect(fixture.observations.some((x) => x.tag === "HELIX_E2E_FORBIDDEN_CHILD")).toBe(false); + }, 20_000); + +}); + + +describe.skipIf(!ENABLED)("OpenCode default nesting limit", () => { + test("depth one does not let the RepoJob start reviewer grandchildren", async () => { + const limited = await startNativeFixture(PLUGIN_ROOT, 1); + try { + const session = await limited.session("Synthetic depth-one blocker"); + await limited.prompt(session.id, "HELIX_E2E_PARENT"); + const worker = await eventually(async () => limited.observations.find((x) => x.tag === "HELIX_E2E_WORKER" && x.results !== "[]"), Boolean); + expect(worker!.results).toContain("Subagent depth limit reached (1)"); + const context = await eventually(async () => JSON.stringify(await limited.context(session.id)), (x) => x.includes("native_depth_unavailable")); + expect(context).toContain("BLOCKED"); + expect(limited.observations.some((x) => x.tag.startsWith("HELIX_E2E_REVIEW_"))).toBe(false); + } finally { await limited.stop(); } + }, 30_000); +}); diff --git a/helixharness/opencode/tests/native-fixture.ts b/helixharness/opencode/tests/native-fixture.ts new file mode 100644 index 0000000..2b4407c --- /dev/null +++ b/helixharness/opencode/tests/native-fixture.ts @@ -0,0 +1,155 @@ +/** Isolated real-server transport fixture. The model is scripted, never a live account. */ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +export interface ModelObservation { + tag: string; + tools: string[]; + results: string; +} + +export async function eventually(read: () => Promise, ready: (value: T) => boolean): Promise { + const deadline = Date.now() + 15_000; + while (true) { + const value = await read(); + if (ready(value)) return value; + if (Date.now() >= deadline) throw new Error("Synthetic native fixture did not reach the expected state"); + await Bun.sleep(50); + } +} + +export async function startNativeFixture(pluginRoot: string, depth = 2) { + const executable = Bun.which(process.env.HELIXHARNESS_OPENCODE_BIN ?? "opencode"); + if (!executable) throw new Error("OpenCode E2E requires opencode or HELIXHARNESS_OPENCODE_BIN"); + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "helix-opencode-e2e-")); + const observations: ModelObservation[] = []; + let removeBeforeSkill: string | undefined; + const model = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + async fetch(request) { + const body = await request.json() as any; + const tag = JSON.stringify(body.messages.filter((m: any) => m.role === "user")) + .match(/HELIX_E2E_[A-Z_]+/)?.[0] ?? "command"; + const tools = (body.tools ?? []).map((tool: any) => tool.function.name) as string[]; + const results = JSON.stringify(body.messages.filter((m: any) => m.role === "tool")); + observations.push({ tag, tools, results }); + const calls: Array<{ name: string; arguments: Record }> = []; + let text = results.includes("Subagent depth limit reached") + ? "BLOCKED: native_depth_unavailable" : "Synthetic transport completed"; + if (/denied|not allowed|No tool named/i.test(results)) text = "BLOCKED: leaf_delegation_denied"; + if (results === "[]") { + if (tag === "HELIX_E2E_SKILL" || tag === "HELIX_E2E_MISSING_ROOT") { + if (removeBeforeSkill) { + fs.rmSync(removeBeforeSkill, { recursive: true, force: true }); + removeBeforeSkill = undefined; + } + calls.push({ name: "skill", arguments: { id: "helix-tdd" } }); + } else if (tag === "HELIX_E2E_PARENT") { + calls.push({ name: "subagent", arguments: { + agent: "helix-worker", description: "Synthetic RepoJob", + prompt: "HELIX_E2E_WORKER delegation_policy=may_delegate; dispatch two read-only leaf reviewers.", + } }); + } else if (tag === "HELIX_E2E_WORKER") { + for (const axis of ["STANDARDS", "SPEC"]) calls.push({ name: "subagent", arguments: { + agent: "general", description: `Synthetic ${axis} review`, + prompt: `HELIX_E2E_REVIEW_${axis} delegation_policy=leaf; read-only synthetic review.`, + } }); + } else if (tag === "HELIX_E2E_GENERAL_PARENT" || tag === "HELIX_E2E_CANONICAL_PARENT") { + const role = tag === "HELIX_E2E_GENERAL_PARENT" ? "general" : "helix-scan-tech"; + calls.push({ name: "subagent", arguments: { + agent: role, description: "Synthetic leaf permission check", + prompt: `HELIX_E2E_LEAF_${role === "general" ? "GENERAL" : "CANONICAL"} delegation_policy=leaf`, + } }); + } else if (tag.startsWith("HELIX_E2E_LEAF_")) { + calls.push({ name: "subagent", arguments: { + agent: "general", description: "Must not run", prompt: "HELIX_E2E_FORBIDDEN_CHILD", + } }); + } + } + const toolCalls = calls.map((call, index) => ({ + index, id: `synthetic-${observations.length}-${index}`, type: "function", + function: { name: call.name, arguments: JSON.stringify(call.arguments) }, + })); + const delta = calls.length ? { role: "assistant", tool_calls: toolCalls } : { role: "assistant", content: text }; + const chunks = [ + { choices: [{ index: 0, delta, finish_reason: null }] }, + { choices: [{ index: 0, delta: {}, finish_reason: calls.length ? "tool_calls" : "stop" }], + usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } }, + ].map((chunk) => ({ id: "synthetic", object: "chat.completion.chunk", model: "scripted", ...chunk })); + return new Response(chunks.map((chunk) => `data: ${JSON.stringify(chunk)}\n\n`).join("") + "data: [DONE]\n\n", { + headers: { "content-type": "text/event-stream" }, + }); + }, + }); + fs.writeFileSync(path.join(directory, "opencode.json"), JSON.stringify({ + plugins: [pluginRoot], model: "helix-test/scripted", + providers: { "helix-test": { + name: "Synthetic transport fixture", package: "@opencode/ai/providers/openai-compatible", + settings: { baseURL: `http://127.0.0.1:${model.port}/v1`, apiKey: "synthetic" }, + models: { scripted: { name: "Synthetic", capabilities: { tools: true } } }, + } }, + permissions: [ + { action: "execute", resource: "*", effect: "deny" }, + { action: "skill", resource: "*", effect: "allow" }, + ], + experimental: { subagent_depth: depth }, + })); + const reservation = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response() }); + const port = reservation.port; + reservation.stop(true); + const server = Bun.spawn([ + executable, "serve", "--port", String(port), + ], { + cwd: directory, + env: { + PATH: process.env.PATH ?? "", TMPDIR: os.tmpdir(), LANG: "en_US.UTF-8", + ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}), + OPENCODE_TEST_HOME: path.join(directory, "home"), + XDG_CONFIG_HOME: path.join(directory, "config"), XDG_DATA_HOME: path.join(directory, "data"), + XDG_CACHE_HOME: path.join(directory, "cache"), XDG_STATE_HOME: path.join(directory, "state"), + OPENCODE_PASSWORD: "synthetic-e2e-password", + }, + stdout: "ignore", stderr: "ignore", + }); + async function request(route: string, body?: unknown) { + return fetch(`http://127.0.0.1:${port}${route}`, { + method: body === undefined ? "GET" : "POST", + headers: { authorization: `Basic ${btoa("opencode:synthetic-e2e-password")}`, "content-type": "application/json" }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }); + } + async function data(route: string, body?: unknown): Promise { + const response = await request(route, body); + if (!response.ok) throw new Error(`Synthetic native request failed: ${response.status} ${route}`); + return (await response.json() as any).data; + } + async function stop() { + server.kill(); + await server.exited; + model.stop(true); + fs.rmSync(directory, { recursive: true, force: true }); + } + try { + await eventually(async () => { + try { + const agents = await data("/api/agent"); + return Array.isArray(agents) && agents.some((agent) => agent.id === "helix-worker"); + } catch { return false; } + }, Boolean); + } catch (error) { + await stop(); + throw error; + } + return { + directory, observations, request, data, stop, + deleteBeforeSkill(target: string) { removeBeforeSkill = target; }, + async session(name: string, location?: string) { + return data("/api/session", { title: name, model: { providerID: "helix-test", id: "scripted" }, + ...(location ? { location: { directory: location } } : {}) }); + }, + async prompt(sessionID: string, text: string) { await data(`/api/session/${sessionID}/prompt`, { text }); }, + async context(sessionID: string) { return data(`/api/session/${sessionID}/context`); }, + }; +} diff --git a/helixharness/opencode/tests/plugin.test.ts b/helixharness/opencode/tests/plugin.test.ts new file mode 100644 index 0000000..5778c60 --- /dev/null +++ b/helixharness/opencode/tests/plugin.test.ts @@ -0,0 +1,356 @@ +import { afterAll, describe, expect, test } from "bun:test"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { + REPO_ROOT_TOKEN, + type PluginContext, + registerHelixHarness, +} from "../core.ts"; + +const PLUGIN_ROOT = path.resolve(import.meta.dir, "../.."); +const FIXTURE_ROOT = fs.mkdtempSync(path.join(os.tmpdir(), "helix-directory-binding-")); +const SESSION_ROOT = fs.mkdirSync(path.join(FIXTURE_ROOT, "session repo's directory"), { recursive: true })!; +const LOCATION_ROOT = fs.mkdirSync(path.join(FIXTURE_ROOT, "plugin-location"), { recursive: true })!; +afterAll(() => fs.rmSync(FIXTURE_ROOT, { recursive: true, force: true })); + +interface Captured { + commands: Array>; + skills: Array>; + agents: Array<{ id: string; draft: Record }>; + prompts: Array>; + toolHooks: Array<(event: any) => Promise | void>; + sessionGets: string[]; + registrationOrder: string[]; +} + +function createContext(options: { + location?: string; + sessionDirectory?: string; + getSession?: (sessionID: string) => Promise; + hookError?: Error; +} = {}): { ctx: PluginContext; captured: Captured } { + const captured: Captured = { + commands: [], + skills: [], + agents: [], + prompts: [], + toolHooks: [], + sessionGets: [], + registrationOrder: [], + }; + const ctx = { + location: { directory: options.location ?? LOCATION_ROOT }, + command: { + async transform(callback: (editor: any) => void) { + captured.registrationOrder.push("command"); + callback({ add: (command: any) => captured.commands.push(command) }); + }, + }, + skill: { + async transform(callback: (editor: any) => void) { + captured.registrationOrder.push("skill"); + callback({ add: (skill: any) => captured.skills.push(skill) }); + }, + }, + agent: { + async transform(callback: (editor: any) => void) { + captured.registrationOrder.push("agent"); + 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.registrationOrder.push("hook"); + if (options.hookError) throw options.hookError; + captured.toolHooks.push(callback); + }, + }, + session: { + async get({ sessionID }: { sessionID: string }) { + captured.sessionGets.push(sessionID); + if (options.getSession) return options.getSession(sessionID); + return { + location: { directory: options.sessionDirectory ?? SESSION_ROOT }, + }; + }, + 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" }], agents: [{ id: "synthetic-agent" }], skills: [{ id: "synthetic-skill" }] }, + 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.agents).toEqual([{ id: "synthetic-agent" }]); + expect(prompt.skills).toEqual([{ id: "synthetic-skill" }]); + 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: \`${fs.realpathSync(SESSION_ROOT)}\``); + 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: \`${fs.realpathSync(SESSION_ROOT)}\``); + + 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 ${fs.realpathSync(SESSION_ROOT)}`); + + const untouched = { content: "no marker" }; + await captured.toolHooks[0]({ + tool: "read", + sessionID: "ses_test", + status: "completed", + result: untouched, + }); + expect(untouched.content).toBe("no marker"); + }); +}); + +describe("session directory binding fails closed", () => { + const filePath = path.join(FIXTURE_ROOT, "ordinary-file"); + fs.writeFileSync(filePath, "synthetic"); + const deletedDirectory = fs.mkdtempSync(path.join(FIXTURE_ROOT, "deleted-")); + fs.rmdirSync(deletedDirectory); + const invalidSessions = [ + ["missing session", undefined], + ["missing location", {}], + ["missing directory", { location: {} }], + ["empty directory", { location: { directory: "" } }], + ["blank directory", { location: { directory: " " } }], + ["relative directory", { location: { directory: "." } }], + ["deleted directory", { location: { directory: deletedDirectory } }], + ["file directory", { location: { directory: filePath } }], + ] as const; + + for (const [name, session] of invalidSessions) { + test(`commands reject ${name} before prompting`, async () => { + const { ctx, captured } = createContext({ getSession: async () => session }); + await registerHelixHarness(ctx, { pluginRoot: PLUGIN_ROOT }); + const init = captured.commands.find((command) => command.name === "helix:init")!; + await expect(init.execute({ sessionID: "invalid", prompt: { text: "--synthetic" } })) + .rejects.toThrow("repo_root_invalid"); + expect(captured.prompts).toHaveLength(0); + }); + } + + test("commands hide lookup errors and never fall back to the plugin location", async () => { + const { ctx, captured } = createContext({ + getSession: async () => { throw new Error("private synthetic lookup details /secret/path"); }, + }); + await registerHelixHarness(ctx, { pluginRoot: PLUGIN_ROOT }); + const init = captured.commands.find((command) => command.name === "helix:init")!; + let failure: unknown; + try { await init.execute({ sessionID: "failed", prompt: { text: "" } }); } catch (error) { failure = error; } + expect(failure).toBeInstanceOf(Error); + expect((failure as Error).message).toContain("repo_root_lookup_failed"); + for (const forbidden of ["private synthetic", "/secret/path", LOCATION_ROOT]) { + expect((failure as Error).message).not.toContain(forbidden); + } + expect(captured.prompts).toHaveLength(0); + }); + + for (const shape of ["string", "blocks"] as const) { + for (const failure of ["lookup", "invalid"] as const) { + test(`skill ${shape} ${failure} failure discards the whole result`, async () => { + const { ctx, captured } = createContext({ + getSession: async () => { + if (failure === "lookup") throw new Error("private synthetic details"); + return { location: { directory: filePath } }; + }, + }); + await registerHelixHarness(ctx, { pluginRoot: PLUGIN_ROOT }); + const original = `unsafe original ${REPO_ROOT_TOKEN}`; + const event = { + tool: "skill", sessionID: "failed", status: "completed", + result: { + content: shape === "string" ? original : [ + { type: "text", text: original }, + { type: "file", uri: "file:///synthetic-private-attachment" }, + ], + metadata: { original: "synthetic metadata" }, + }, + }; + await captured.toolHooks[0](event); + const result = JSON.stringify(event.result); + expect(result).toContain("BLOCKED"); + expect(result).toContain(failure === "lookup" ? "repo_root_lookup_failed" : "repo_root_invalid"); + for (const forbidden of [REPO_ROOT_TOKEN, "unsafe original", "synthetic-private-attachment", "metadata", "private synthetic", filePath]) { + expect(result).not.toContain(forbidden); + } + }); + } + } + + test("unrelated tool results skip session lookup and remain unchanged", async () => { + const { ctx, captured } = createContext({ getSession: async () => { throw new Error("must not look up"); } }); + await registerHelixHarness(ctx, { pluginRoot: PLUGIN_ROOT }); + const events = [ + { tool: "read", status: "completed", result: { content: REPO_ROOT_TOKEN } }, + { tool: "skill", status: "error", result: { content: REPO_ROOT_TOKEN } }, + { tool: "skill", status: "completed", result: { content: "unrelated skill" } }, + { tool: "skill", status: "completed", result: { content: [{ type: "file", uri: REPO_ROOT_TOKEN }] } }, + { tool: "skill", status: "completed", result: {} }, + { tool: "skill", status: "completed" }, + ]; + for (const event of events) { + const invocation = { ...event, sessionID: "unrelated" }; + const before = JSON.stringify(invocation); + await captured.toolHooks[0](invocation); + expect(JSON.stringify(invocation)).toBe(before); + } + expect(captured.sessionGets).toEqual([]); + }); + + test("interleaved command and skill invocations resolve their own directories without a cache", async () => { + const repoB = fs.mkdirSync(path.join(FIXTURE_ROOT, 'repo B "quoted"'), { recursive: true })!; + const linkA = path.join(FIXTURE_ROOT, "repo A symlink"); + fs.symlinkSync(SESSION_ROOT, linkA, "dir"); + let currentA = linkA; + let releaseA!: () => void; + const gate = new Promise((resolve) => { releaseA = resolve; }); + const { ctx, captured } = createContext({ getSession: async (sessionID) => { + if (sessionID === "A") { await gate; return { location: { directory: currentA } }; } + return { location: { directory: repoB } }; + } }); + await registerHelixHarness(ctx, { pluginRoot: PLUGIN_ROOT }); + const init = captured.commands.find((command) => command.name === "helix:init")!; + const commandA = init.execute({ sessionID: "A", prompt: { text: "A" } }); + const fileBlock = { type: "file", uri: "file:///synthetic-attachment" }; + const resultB = { content: [fileBlock, { type: "text", text: `B ${REPO_ROOT_TOKEN}` }] }; + await captured.toolHooks[0]({ tool: "skill", sessionID: "B", status: "completed", result: resultB }); + releaseA(); + await commandA; + expect(captured.prompts[0].text).toContain(`repo_root: \`${fs.realpathSync(SESSION_ROOT)}\``); + expect(resultB.content[1]).toEqual({ type: "text", text: `B ${fs.realpathSync(repoB)}` }); + expect(resultB.content[0]).toBe(fileBlock); + currentA = repoB; + await init.execute({ sessionID: "A", prompt: { text: "A moved" } }); + expect(captured.prompts[1].text).toContain(`repo_root: \`${fs.realpathSync(repoB)}\``); + expect(captured.sessionGets).toEqual(["A", "B", "A"]); + }); + + test("skill binding keeps replacement metacharacters in directory names literal", async () => { + const directory = fs.mkdirSync(path.join(FIXTURE_ROOT, "repo $& $$ $` $'"), { recursive: true })!; + const { ctx, captured } = createContext({ sessionDirectory: directory }); + await registerHelixHarness(ctx, { pluginRoot: PLUGIN_ROOT }); + const result = { content: `before ${REPO_ROOT_TOKEN} after` }; + await captured.toolHooks[0]({ tool: "skill", sessionID: "literal", status: "completed", result }); + expect(result.content).toBe(`before ${fs.realpathSync(directory)} after`); + expect(result.content).not.toContain(REPO_ROOT_TOKEN); + }); + + test("required hook is registered before command, skill or agent surfaces", async () => { + const { ctx, captured } = createContext(); + await registerHelixHarness(ctx, { pluginRoot: PLUGIN_ROOT }); + expect(captured.registrationOrder).toEqual(["hook", "command", "skill", "agent"]); + }); + + for (const missing of [true, false]) { + test(`${missing ? "missing" : "rejecting"} required hook prevents all surface registration`, async () => { + const { ctx, captured } = createContext({ hookError: missing ? undefined : new Error("synthetic unsupported hook") }); + if (missing) delete ctx.tool; + await expect(registerHelixHarness(ctx, { pluginRoot: PLUGIN_ROOT })).rejects.toThrow(); + expect(captured.commands).toEqual([]); + expect(captured.skills).toEqual([]); + expect(captured.agents).toEqual([]); + }); + } +}); 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 f855872..ce742cc 100644 --- a/helixharness/reference/eval-protocol.md +++ b/helixharness/reference/eval-protocol.md @@ -26,6 +26,8 @@ Codex: ${CODEX_HOME:-$HOME/.codex}/helixharness/telemetry-consent-cache.json Cursor: ${HELIXHARNESS_CURSOR_HOME:-$HOME/.cursor}/helixharness/telemetry-consent-cache.json ``` +OpenCode 声明 `telemetry=unsupported`,没有 consent 缓存路径;统计脚本返回 `unsupported_host` 后继续业务,不读写上述缓存或借用其他宿主授权。 + 用户主动查询和修改配置使用 `/helix:config`,通过 `scripts/user_config.py` 复用本协议 API;默认查看不触发 CLI resolve 的清理副作用,显式修改仍由既有授权 API 管理 scope、epoch 和清理。 Config 开启统计使用两阶段 CLI:首次明确开启请求返回只读 `notice_required` 和本文件固定说明,不改授权;Agent 先在单独用户可见消息中逐字展示 `notice.text`,下一次调用才附加内部 `--telemetry-notice-shown {notice.sha256}` 与 `--user-confirmed` 执行。说明 digest 只核对内容版本,不能证明 UI 已展示,也不代替用户授权;旧 digest 不允许开启。不得并行或合并准备与修改调用,不通过直接 set/choose 绕过 Config 入口。关闭、地址设置与普通查询不需要此内部标记;Init/Propose 保持各自既有授权交互合同。 diff --git a/helixharness/reference/eval-supplement-protocol.md b/helixharness/reference/eval-supplement-protocol.md index 38859da..8ca4957 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 与 Cursor 均注册 Adapter。CLI 输入仅做大小写规范化,并接受已安装 manifest 明确声明的 aliases;不能根据模型名、包装标签或包含 `claude` / `codex` 的子串猜测宿主。公开 Ledger 与 Supplement 始终只落 canonical ID。Cursor 通过授权后的原生 hooks 维护自有事件源,不读取私有数据库或 transcript。会话身份和 workspace roots 必须来自当前 sessionStart,显式绑定每次命令;缺失时按 `cursor_session_context_unavailable` 跳过本次统计,业务继续。新增统计能力在 `scripts/telemetry_hosts/` 实现 `HostAdapter`(含统一 Supplement 窗口),由 Host Kit manifest 绑定;不得修改业务正文,也不得在 Ledger、Collector 或 Schema 中增加平台分支。 +业务合同与统计支持集相互独立:业务正文和三工件不记录宿主,同一需求可以跨宿主继续;`current_platform` 只用于本次 Telemetry Adapter 选择。当前 Claude Code、Codex 与 Cursor 均注册 Adapter。OpenCode 声明 `telemetry=unsupported`,按 `unsupported_host` 跳过本次统计并继续业务,不借用其他宿主授权或事件源。CLI 输入仅做大小写规范化,并接受已安装 manifest 明确声明的 aliases;不能根据模型名、包装标签或包含 `claude` / `codex` 的子串猜测宿主。公开 Ledger 与 Supplement 始终只落 canonical ID。Cursor 通过授权后的原生 hooks 维护自有事件源,不读取私有数据库或 transcript。会话身份和 workspace roots 必须来自当前 sessionStart,显式绑定每次命令;缺失时按 `cursor_session_context_unavailable` 跳过本次统计,业务继续。新增统计能力在 `scripts/telemetry_hosts/` 实现 `HostAdapter`(含统一 Supplement 窗口),由 Host Kit manifest 绑定;不得修改业务正文,也不得在 Ledger、Collector 或 Schema 中增加平台分支。 Cursor 的输入/输出 Token 只使用原生 hook 中实际存在的非负整数,同一 conversation/generation 的 afterAgentResponse 与 stop 快照去重。只有完整落在阶段内的轮次才数值归属;正常单轮命令的 prompt 可能早于 start、终值晚于 finish,不能伪造阶段差值。用量保留 `collection_status=collected|partial|unavailable`、`unavailable_reason`、`scope=parent_only`、`attribution=complete_generations_within_stage`、`input_tokens_include_cache=true` 与 `generations`。缓存是 input 的明细,total=input+output;不把缺失计数填成 0,也不把父代理数值称为子代理总量。基础阶段/工具统计仍可用,平台部分采集显示小计并保留范围与原因。 diff --git a/helixharness/reference/host-api.md b/helixharness/reference/host-api.md index 86f0c3e..2f267e1 100644 --- a/helixharness/reference/host-api.md +++ b/helixharness/reference/host-api.md @@ -1,6 +1,6 @@ # HelixHarness Host API 1.1 / 1.2 -HelixHarness 提供 Claude Code、Codex 和 Cursor Host Kit。公共业务契约与宿主运行机制保持解耦: +HelixHarness 提供 Claude Code、Codex、Cursor 和 OpenCode Host Kit。公共业务契约与宿主运行机制保持解耦: `commands/`、`workflows/`、共享 `skills/`、`agents/` 和 `templates/` 定义业务结果,`hosts/{host-id}/` 只定义如何在某个宿主中安装、发现和执行。 @@ -13,11 +13,13 @@ HelixHarness 提供 Claude Code、Codex 和 Cursor Host Kit。公共业务契约 当前 Registry 必须只发现: - `claude-code`:原生命令、Hook 生命周期、原生 Agent、Claude marketplace; -- `codex`:Skill 命令投影、独立启动/结束 Hook 与命令驱动阶段生命周期、Codex subagent、Codex marketplace。 -- `cursor`:独立 Skill 投影、Cursor 原生 hooks、Task 子代理与 Cursor plugin 分发;Stable(桌面范围)。 +- `codex`:Skill 命令投影、独立启动/结束 Hook 与命令驱动阶段生命周期、Codex subagent、Codex marketplace; +- `cursor`:独立 Skill 投影、Cursor 原生 hooks、Task 子代理与 Cursor plugin 分发;Stable(桌面范围); +- `opencode`:插件注册原生命令/Skill/Agent、绑定当前仓库与会话 Host Context、原生 subagent 和 OpenCode plugin 分发;Host API 1.1 / Preview(v2.2.2+)。 Claude Code 与 Codex 保持 Host API 1.1 / Stable;Cursor 使用向后兼容的 1.2 / Stable。 Cursor 的会话统计和插件更新为 `emulated`:原生 hook 提供有边界的事件/用量证据,登记的托管本地安装通过批准后的原子交换升级。本次正式支持范围为桌面研发工作流;原生自动升级等限制与已接受的验证缺口见 Cursor 安装说明。 +OpenCode 的 `telemetry`、`plugin_update` 和 `project_hooks` 为 `unsupported`,完整真实模型工作流尚未验收。Workspace Apply 的 `may_delegate` RepoJob 使用 `helix-worker` 且需要 `experimental.subagent_depth >= 2`,reviewer 仍为只读 leaf;深度不足阻塞,不绕过评审。 未知宿主必须关闭失败,不能回退到 Claude Code 或借用 Codex 资源。 ## 共享核心与 Host Kit @@ -141,9 +143,10 @@ Context,不在每条命令中启动 Python 重新识别。 ## 插件 Hook 分发 -所有宿主的原生 plugin manifest 都必须显式声明 `hosts/{host-id}/hooks.json`。 +Claude Code、Codex 与 Cursor 的原生 plugin manifest 必须显式声明 `hosts/{host-id}/hooks.json`。 不得发布根目录默认 `hooks/hooks.json`,以免客户端自动装载另一个宿主的入口。 +OpenCode 不发布 hook manifest;`opencode/index.ts` 在插件 setup 中注册入口,按 `hosts/opencode/lifecycle.md` 声明 `session_start=emulated`、`session_events=unsupported`。 Hook 入口位于对应 Host Kit,绑定自身安装目录的规范 manifest,转换宿主事件与环境持久化。 共享 `scripts/lifecycle_service.py` 只消费显式 HostManifest 和规范事件,不猜平台。 -项目级检查 hooks 独立使用 `project_hooks` 合同;单仓 Init 的实际 settings 缺失或重复必须阻断。 +项目级检查 hooks 独立使用 `project_hooks` 合同;支持项目 hooks 时,单仓 Init 的实际 settings 缺失或重复必须阻断;OpenCode `settings_file=null`,只合并 `AGENTS.md`。 遥测 adapter 统一通过该 Registry 的 manifest Python 引用装载,不维护第二份平台注册表。 diff --git a/helixharness/reference/host-runtime-protocol.md b/helixharness/reference/host-runtime-protocol.md index 63b8eb4..d29473c 100644 --- a/helixharness/reference/host-runtime-protocol.md +++ b/helixharness/reference/host-runtime-protocol.md @@ -11,7 +11,8 @@ Host Context 在 command/Skill 进入业务工作流前由安装分发或宿主 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`; -3. Cursor 的 `hosts/cursor/skills/{entry}/SKILL.md` plugin Skill 表面绑定 `hosts/cursor/host.json`。 +3. Cursor 的 `hosts/cursor/skills/{entry}/SKILL.md` plugin Skill 表面绑定 `hosts/cursor/host.json`; +4. OpenCode 的 `opencode/index.ts` 注册原生命令和方法 Skill,绑定 `hosts/opencode/host.json` 以及当前仓库与会话;只通过 TypeScript 注册和注入 Host Context,不借用其他宿主的启动 hooks。 “分发表面绑定”是一种确定性入口绑定,不要求宿主额外设置环境变量或在目标项目 生成 settings:当前产品加载 `resources.command_projection` 已声明的原生命令或宿主 Skill @@ -102,7 +103,7 @@ command 中的 `Read`、`Write`、`Edit`、`Bash`、`AskUserQuestion`、`TodoWri ## 5. 未来宿主扩展契约 -当前仓库提供 Claude Code、Codex、Cursor。未来接入新宿主时,正常改动范围应限制为: +当前仓库提供 Claude Code、Codex、Cursor 与 OpenCode(Preview)。OpenCode 的 `telemetry`、`plugin_update` 和 `project_hooks` 为 `unsupported`。未来接入新宿主时,正常改动范围应限制为: - `hosts/{host-id}/host.json`; - 该 Host Kit 引用的分发、安装、入口投影、启动、工具映射、生命周期、项目配置、遥测或更新适配器; @@ -110,5 +111,5 @@ command 中的 `Read`、`Write`、`Edit`、`Bash`、`AskUserQuestion`、`TodoWri 如果接入必须修改 `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/version-update-protocol.md b/helixharness/reference/version-update-protocol.md index 5374a56..4c0c5e0 100644 --- a/helixharness/reference/version-update-protocol.md +++ b/helixharness/reference/version-update-protocol.md @@ -18,6 +18,7 @@ update 与 eval 分别使用动态 Host Registry,并保持独立 capability、cache 和生命周期。update 是否 可用只看当前 Host Kit 的 `plugin_update=native|emulated|unsupported`;公共协议不维护宿主白名单。 Claude Code/Codex adapter 提供原生更新能力。Cursor 的 `plugin_update=emulated`,仅更新通过 Helix installer 登记的 macOS/Linux 本地安装;未登记副本或原生市场缓存不被接管。 +OpenCode 明确声明 `plugin_update=unsupported`,`/helix:update` 的 check 返回 `continue_silently`;通过 OpenCode 插件管理手动更新,不创建 Helix 更新授权或接管其他宿主安装。 任何未注册宿主或未启用更新能力的宿主执行 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 d09a6e2..c7377fb 100644 --- a/helixharness/reference/workflow-projection-protocol.md +++ b/helixharness/reference/workflow-projection-protocol.md @@ -10,7 +10,7 @@ `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`;无子任务命令不得 @@ -43,6 +43,7 @@ `/helix-{command}` 是原生 Skill 表面,公共 `/helix:{command}` 是相同命令的逻辑标识;转场按当前 `resources.workflow_transition` 内联执行唯一 contract,不依赖 UI 别名。方法入口只投影调用意图, 不携带 Claude hooks 或 Codex metadata;D2C 的宿主门禁由 Cursor runtime 明确执行。 +- OpenCode 插件在命令执行和方法 Skill 加载时注入含绝对路径的 Host Context;直接使用绑定资源,不读取项目 `.opencode/` 同名副本,也不枚举安装目录。不执行 Claude skill-scoped hooks;d-d2c 按无 hook / `--bare` 语义保留用户决策、视觉验收和完成门禁。 - 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..12c25dc 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 @@ -362,9 +363,8 @@ 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: - # Unregistered hosts still may submit; the schema only admits - # registered host ids plus the explicit "unknown" marker. + if adapter is None and HostRegistry.discover(PLUGIN_ROOT / "hosts").get(platform) is None: + # Feedback identity is independent from telemetry support. platform = "unknown" session = "unknown" context = None diff --git a/helixharness/scripts/tests/test_claude_command_scenarios.py b/helixharness/scripts/tests/test_claude_command_scenarios.py index 718fb18..050bb8f 100644 --- a/helixharness/scripts/tests/test_claude_command_scenarios.py +++ b/helixharness/scripts/tests/test_claude_command_scenarios.py @@ -25,7 +25,7 @@ PLUGIN = Path(__file__).resolve().parents[2] REPOSITORY = PLUGIN.parent COMMANDS = {"init", "propose", "apply", "archive", "bug-fix", "ut", "update", "status", "config"} -PUBLIC_ROOTS = {".claude-plugin", ".codex-plugin", ".cursor-plugin", "scripts", "hosts", "commands", "workflows", "reference", "skills", "agents", "templates"} +PUBLIC_ROOTS = {".claude-plugin", ".codex-plugin", ".cursor-plugin", "package.json", "scripts", "hosts", "commands", "workflows", "reference", "skills", "agents", "templates"} PRIVATE_PARTS = {".git", ".codex", ".claude", ".cursor", ".agents", ".aws", "output", "temp", "runtime", "sessions", "rollouts", "cache", ".cache", "__pycache__", ".pytest_cache", "node_modules", ".venv", "venv"} diff --git a/helixharness/scripts/tests/test_codex_update_scenarios.py b/helixharness/scripts/tests/test_codex_update_scenarios.py index f8d1230..ae02fc0 100644 --- a/helixharness/scripts/tests/test_codex_update_scenarios.py +++ b/helixharness/scripts/tests/test_codex_update_scenarios.py @@ -17,7 +17,7 @@ PLUGIN = Path(__file__).resolve().parents[2] REPOSITORY = PLUGIN.parent -PUBLIC_ROOTS = {".codex-plugin", ".claude-plugin", ".cursor-plugin", "scripts", "hosts", "commands", "workflows", "reference", "skills", "agents", "templates"} +PUBLIC_ROOTS = {".codex-plugin", ".claude-plugin", ".cursor-plugin", "package.json", "scripts", "hosts", "commands", "workflows", "reference", "skills", "agents", "templates"} PRIVATE_PARTS = {".git", ".codex", ".claude", ".cursor", ".agents", ".aws", "output", "temp", "runtime", "sessions", "rollouts", "cache", ".cache", "__pycache__", ".pytest_cache", "node_modules", ".venv", "venv"} NATIVE_STUB = r''' import json, os, sys diff --git a/helixharness/scripts/tests/test_cursor_bundle_update.py b/helixharness/scripts/tests/test_cursor_bundle_update.py index 54b9c12..0c554e5 100644 --- a/helixharness/scripts/tests/test_cursor_bundle_update.py +++ b/helixharness/scripts/tests/test_cursor_bundle_update.py @@ -20,6 +20,16 @@ @unittest.skipUnless(shutil.which("git") and sys.platform in {"darwin", "linux"}, "Git and atomic directory exchange required") class CursorFullBundleUpdateTests(unittest.TestCase): + def test_native_opencode_distribution_includes_runtime_without_dependencies_or_private_files(self): + for name in ("package.json", "opencode/index.ts", "opencode/core.ts"): + with self.subTest(name=name): + self.assertTrue(_distributed(PurePosixPath(name))) + for name in ("bun.lock", "node_modules/dependency/index.ts", "opencode/node_modules/dependency/index.ts", + "opencode/.bun/cache/index.ts", "opencode/.env.local", "opencode/credentials.json", + "opencode/output/session.json", "opencode/tests/native-fixture.ts", "opencode/runtime/session.json"): + with self.subTest(name=name): + self.assertFalse(_distributed(PurePosixPath(name))) + def test_installed_bundle_runs_without_checkout_pythonpath_and_updates_itself(self): with tempfile.TemporaryDirectory(prefix="helix-cursor-bundle-") as temporary: root = Path(temporary).resolve() @@ -48,6 +58,10 @@ def test_installed_bundle_runs_without_checkout_pythonpath_and_updates_itself(se selected.add(relative.as_posix()) self.assertIn("scripts/update_hosts/cursor.py", selected) self.assertIn("hosts/cursor/hooks.json", selected) + native_files = ("package.json", "opencode/index.ts", "opencode/core.ts") + for name in native_files: + self.assertIn(name, selected) + native_contents = {name: (PLUGIN / name).read_bytes() for name in native_files} root_manifest = source / ".cursor-plugin/marketplace.json" root_manifest.parent.mkdir() root_manifest.write_bytes((REPOSITORY / ".cursor-plugin/marketplace.json").read_bytes()) @@ -55,6 +69,13 @@ def test_installed_bundle_runs_without_checkout_pythonpath_and_updates_itself(se def git(*arguments): return subprocess.run(["git", "-c", "core.hooksPath=/dev/null", "-c", "user.name=Synthetic Bundle", "-c", "user.email=bundle@example.invalid", "-C", str(source), *arguments], env=environment, check=True, capture_output=True, text=True, timeout=15).stdout.strip() + excluded_native_files = ("node_modules/synthetic/index.ts", "opencode/.bun/cache/index.ts", + "opencode/.env.local", "opencode/credentials.json", "opencode/runtime/session.json") + for name in excluded_native_files: + synthetic = source / "helixharness" / name + synthetic.parent.mkdir(parents=True, exist_ok=True) + synthetic.write_text("synthetic excluded packaging fixture") + def run(script, *arguments, input_data=None, expected=0, env=None, structured=True): process = subprocess.run([sys.executable, str(script), *arguments], cwd=workspace, env=env or environment, input=json.dumps(input_data) if input_data is not None else None, capture_output=True, text=True, timeout=45) self.assertEqual(process.returncode, expected, process.stdout + process.stderr) @@ -81,13 +102,23 @@ def release(version): return git("rev-parse", "HEAD") git("init", "--template=", "-b", "main") + git("add", "--force", *["helixharness/" + name for name in excluded_native_files]) release("1.0.0") installed = run(source / "helixharness/scripts/cursor_managed_install.py", "install", "--source", str(source), "--ref", "main", "--user-confirmed") plugin = Path(installed["plugin_root"]) + for name, content in native_contents.items(): + self.assertEqual((plugin / name).read_bytes(), content) + for name in excluded_native_files: + self.assertFalse((plugin / name).exists(), name) environment["HELIXHARNESS_BOUND_PLUGIN_ROOT"] = str(plugin) runtime = run(plugin / "scripts/host_runtime_cli.py", "resolve", "--platform", "cursor", "--expected-plugin-root", str(plugin)) self.assertEqual(runtime["plugin_root"], str(plugin)) self.assertEqual(runtime["host_id"], "cursor") + # Resolve every installed host using the shipped CLI; this validates + # the OpenCode package resource together with the existing kits. + for host in ("claude-code", "codex", "opencode"): + resolved = run(plugin / "scripts/host_runtime_cli.py", "resolve", "--platform", host, "--expected-plugin-root", str(plugin)) + self.assertEqual(resolved["host_id"], host) for generator in ("cursor_skill_projection.py", "codex_skill_projection.py"): run(plugin / "scripts" / generator, "--check", structured=False) commands = json.loads((plugin / "hosts/cursor/command-projection.json").read_text())["entrypoints"] @@ -118,6 +149,12 @@ def release(version): self.assertEqual(updated["verified_commit"], approved_commit) self.assertEqual(updated["verified_version"], "1.0.1") self.assertEqual((plugin / "reference/cursor-synthetic-release.txt").read_text(), "1.0.1") + for name, content in native_contents.items(): + self.assertEqual((plugin / name).read_bytes(), content) + for directory in ("node_modules", ".bun", "opencode/tests", "opencode/runtime"): + self.assertFalse((plugin / directory).exists(), directory) + for name in excluded_native_files: + self.assertFalse((plugin / name).exists(), name) self.assertTrue(updated["authorization_consumed"]) self.assertNotIn("PYTHONPATH", environment) for generator in ("cursor_skill_projection.py", "codex_skill_projection.py"): diff --git a/helixharness/scripts/tests/test_cursor_command_scenarios.py b/helixharness/scripts/tests/test_cursor_command_scenarios.py index 922460c..5e18c23 100644 --- a/helixharness/scripts/tests/test_cursor_command_scenarios.py +++ b/helixharness/scripts/tests/test_cursor_command_scenarios.py @@ -25,7 +25,7 @@ PLUGIN = Path(__file__).resolve().parents[2] REPOSITORY = PLUGIN.parent COMMANDS = {"init", "propose", "apply", "archive", "bug-fix", "ut", "update", "status", "config"} -PUBLIC_ROOTS = {".claude-plugin", ".codex-plugin", ".cursor-plugin", "scripts", "hosts", "commands", "workflows", "reference", "skills", "agents", "templates"} +PUBLIC_ROOTS = {".claude-plugin", ".codex-plugin", ".cursor-plugin", "package.json", "scripts", "hosts", "commands", "workflows", "reference", "skills", "agents", "templates"} PRIVATE_PARTS = {".git", ".codex", ".claude", ".cursor", ".agents", ".aws", "output", "temp", "runtime", "sessions", "rollouts", "cache", ".cache", "__pycache__", ".pytest_cache", "node_modules", ".venv", "venv"} diff --git a/helixharness/scripts/tests/test_cursor_telemetry.py b/helixharness/scripts/tests/test_cursor_telemetry.py index e578c79..d7a729d 100644 --- a/helixharness/scripts/tests/test_cursor_telemetry.py +++ b/helixharness/scripts/tests/test_cursor_telemetry.py @@ -212,8 +212,15 @@ def test_archive_seals_source_and_delivery_releases_only_unreferenced_owned_jour self.assertTrue(Path(final["path"]).is_file()) def test_clean_installed_runtime_uses_snapshot_for_all_hosts_without_checkout_imports(self): + from host_runtime import HostRegistry + + self.assertEqual(set(HostRegistry.discover(ROOT / "hosts").supported_ids()), {"claude-code", "codex", "cursor", "opencode"}) + snapshot = build_runtime_snapshot(ROOT) + self.assertEqual({host["host_id"] for host in snapshot["hosts"]}, {"claude-code", "codex", "cursor"}) telemetry_async.install_runtime(ROOT, self.home) runtime = self.home / "runtime" + self.assertEqual(json.loads((runtime / RUNTIME_SNAPSHOT_NAME).read_text()), snapshot) + self.assertFalse((self.home / "package.json").exists()) code = ( "import json,sys;sys.path.insert(0,sys.argv[1]);" "from telemetry_hosts import get_host_adapter,supported_host_ids;" diff --git a/helixharness/scripts/tests/test_feedback_submit.py b/helixharness/scripts/tests/test_feedback_submit.py index 6d77b79..8aa290e 100644 --- a/helixharness/scripts/tests/test_feedback_submit.py +++ b/helixharness/scripts/tests/test_feedback_submit.py @@ -55,10 +55,11 @@ class Adapter: def current_session_context(self, repo): return {"session_id": "raw-session-abc", "session_cwd": str(repo)} - with mock.patch.object(feedback, "get_host_adapter", return_value=Adapter()): - draft = self.prepare(platform="claude-code") - document = draft["item"]["document"] - self.assertEqual(_session_hash("raw-session-abc"), document["session"]) + for platform in ("claude-code", "codex", "cursor"): + with self.subTest(platform=platform), mock.patch.object(feedback, "get_host_adapter", return_value=Adapter()): + draft = self.prepare(platform=platform) + document = draft["item"]["document"] + self.assertEqual(_session_hash("raw-session-abc"), document["session"]) # 旧 ses_<24hex> 格式已从 schema 移除,必须被 prepare 校验拒绝,防止格式回流 document["session"] = "ses_" + "0123456789abcdef01234567" with self.assertRaisesRegex(feedback.FeedbackError, "violates schema"): @@ -84,6 +85,13 @@ 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_preserves_feedback_identity(self): + self.assertIsNone(feedback.get_host_adapter("opencode")) + draft = self.prepare(platform="opencode") + self.assertEqual("opencode", draft["item"]["document"]["host"]) + self.assertEqual("unknown", draft["item"]["document"]["session"]) + self.assertEqual("unknown", self.prepare(platform="unregistered-host")["item"]["document"]["host"]) + 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 474f8b0..c23fc79 100644 --- a/helixharness/scripts/tests/test_public_workflow_router.py +++ b/helixharness/scripts/tests/test_public_workflow_router.py @@ -237,4 +237,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','cursor'}) + self.assertEqual(set(registry.supported_ids()),{'codex','claude-code','cursor','opencode'}) diff --git a/helixharness/scripts/update_hosts/cursor.py b/helixharness/scripts/update_hosts/cursor.py index 002e962..1350cdb 100644 --- a/helixharness/scripts/update_hosts/cursor.py +++ b/helixharness/scripts/update_hosts/cursor.py @@ -32,8 +32,9 @@ REGISTRATION_KEYS = {"schema_version", "kind", "install_id", "install_root", "source", "ref", "plugin_source"} BINDING_KEYS = {"schema_version", "kind", "install_id", "registration_sha256", "install_root", "source", "ref", "plugin_source", "current_tree", "target_commit", "target_tree", "target_version"} RECEIPT_KEYS = {"schema_version", "install_id", "registration_sha256", "version", "commit", "tree_sha256"} -DISTRIBUTION_DIRS = {".claude-plugin", ".codex-plugin", ".cursor-plugin", "agents", "commands", "hosts", "reference", "scripts", "skills", "templates", "workflows"} -DISTRIBUTION_FILES = {"AGENTS.md", "CLAUDE.md", "LICENSE", "NOTICE", "PLUGIN_USAGE.md", "README.md", "README.zh-CN.md", "SKILL.md", "THIRD_PARTY_NOTICES.md", ".gitignore"} +DISTRIBUTION_DIRS = {".claude-plugin", ".codex-plugin", ".cursor-plugin", "agents", "commands", "hosts", "opencode", "reference", "scripts", "skills", "templates", "workflows"} +DISTRIBUTION_FILES = {"AGENTS.md", "CLAUDE.md", "LICENSE", "NOTICE", "PLUGIN_USAGE.md", "README.md", "README.zh-CN.md", "SKILL.md", "THIRD_PARTY_NOTICES.md", ".gitignore", "package.json"} +OPENCODE_RUNTIME_FILES = {"opencode/index.ts", "opencode/core.ts"} EXCLUDED_PARTS = {".git", ".env", ".cursor", ".claude", ".codex", ".agents", ".aws", "output", "temp", "node_modules", "__pycache__", ".pytest_cache", ".venv", "venv"} MAX_ARCHIVE_BYTES = 256 * 1024 * 1024 MAX_FILE_BYTES = 32 * 1024 * 1024 @@ -78,6 +79,8 @@ def _distributed(relative: PurePosixPath) -> bool: return False if relative.name in {"credentials.json", ".npmrc", RECEIPT} or relative.suffix in {".pyc", ".log"}: return False + if parts[0] == "opencode": + return relative.as_posix() in OPENCODE_RUNTIME_FILES return (len(parts) == 1 and parts[0] in DISTRIBUTION_FILES) or (len(parts) > 1 and parts[0] in DISTRIBUTION_DIRS) 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 21d8086..bcc8ddd 100644 --- a/helixharness/skills/feedback/SKILL.md +++ b/helixharness/skills/feedback/SKILL.md @@ -97,7 +97,7 @@ $ARGUMENTS ### Step 3: 准备、确认并发送 -`{plugin_root}` 必须来自当前 Skill 绑定的 Host Context;按当前宿主入口协议核验来源,不得搜索其他安装目录。`{current_platform}` 使用该 Host Context 的 canonical host ID:Claude Code 为 `claude-code`,Codex 为 `codex`,Cursor 为 `cursor`。Cursor 每次脚本调用按 `resources.runtime` 显式传入当前原生会话绑定;缺失时保留未知会话,不借用其他宿主或历史会话。 +`{plugin_root}` 必须来自当前 Skill 绑定的 Host Context;按当前宿主入口协议核验来源,不得搜索其他安装目录。`{current_platform}` 使用该 Host Context 的 canonical host ID:Claude Code 为 `claude-code`,Codex 为 `codex`,Cursor 为 `cursor`,OpenCode 为 `opencode`。不得根据操作系统或客户端别名猜测。Cursor 每次脚本调用按 `resources.runtime` 显式传入当前原生会话绑定;缺失时保留未知会话,不借用其他宿主或历史会话。 先准备草稿,不发送。参数必须安全转义: @@ -138,8 +138,8 @@ $ARGUMENTS ## 宿主适配说明 -- Claude Code、Codex 与 Cursor 使用同一 CLI(`feedback_submit.py`);反馈发送使用独立的内容与地址确认,不依赖统计 consent,也不由 hook 自动发送 -- 会话上下文采集当前仅支持 claude-code 会话;Codex 与 Cursor 仍可上报反馈元数据。请求附带会话时按返回的 `transcript_stats.supported=false` 和原因说明边界,不搜索私有会话补全 +- Claude Code、Codex、Cursor 与 OpenCode 使用同一 CLI(`feedback_submit.py`);反馈发送使用独立的内容与地址确认,不依赖统计 consent,也不由 hook 自动发送 +- 会话上下文采集当前仅支持 claude-code 会话;Codex、Cursor 与 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"] +} From fbb7508bb427d3a2581598b291fff30fda784bd2 Mon Sep 17 00:00:00 2001 From: acderchenjunwei Date: Sat, 21 Nov 2026 15:19:04 +0800 Subject: [PATCH 03/37] fix(runtime): honor Claude Bash shell on Windows Select the command shell in the Claude Host Kit, normalize Bash path arguments, and handle CRLF Python version output. Preserve Codex PowerShell behavior and add shell, preflight, and native Windows regression coverage. --- helixharness/hosts/claude-code/hook_entry.py | 4 +- helixharness/scripts/lifecycle_service.py | 30 ++++--- helixharness/scripts/python_runtime.sh | 3 + .../tests/test_cursor_entry_repairs.py | 18 +++- .../scripts/tests/test_lifecycle_shell.py | 87 +++++++++++++++++++ .../scripts/tests/test_runtime_preflight.py | 25 ++++++ .../scripts/tests/test_windows_runtime.py | 72 +++++++++++++++ 7 files changed, 226 insertions(+), 13 deletions(-) create mode 100644 helixharness/scripts/tests/test_lifecycle_shell.py diff --git a/helixharness/hosts/claude-code/hook_entry.py b/helixharness/hosts/claude-code/hook_entry.py index 6f2b005..1940ea6 100755 --- a/helixharness/hosts/claude-code/hook_entry.py +++ b/helixharness/hosts/claude-code/hook_entry.py @@ -49,7 +49,7 @@ def main() -> int: return 0 from host_runtime_cli import _context manifest = HostRegistry.discover(ROOT / "hosts").get("claude-code") - output = startup_context(manifest) + output = startup_context(manifest, command_shell="bash") specific = output["hookSpecificOutput"] specific["hookEventName"] = event specific["additionalContext"] += ( @@ -68,7 +68,7 @@ def main() -> int: return 0 if payload["hook_event_name"] in {"SessionStart", "CwdChanged"}: persist_environment(payload) - handle_event(HostRegistry.discover(ROOT / "hosts").get("claude-code"), payload) + handle_event(HostRegistry.discover(ROOT / "hosts").get("claude-code"), payload, command_shell="bash") except (OSError, ValueError): return 0 return 0 diff --git a/helixharness/scripts/lifecycle_service.py b/helixharness/scripts/lifecycle_service.py index 04c6a2a..f463748 100644 --- a/helixharness/scripts/lifecycle_service.py +++ b/helixharness/scripts/lifecycle_service.py @@ -12,8 +12,13 @@ from host_runtime import HostManifest -def startup_context_text(manifest: HostManifest) -> str: - """Return host-neutral binding text for the installed entrypoint.""" +def startup_context_text(manifest: HostManifest, *, command_shell: str | None = None) -> str: + """Render binding text for the Host Kit's command shell, not the Hook's OS alone.""" + + if command_shell is None: + command_shell = "powershell" if os.name == "nt" else "bash" + if command_shell not in {"bash", "powershell"}: + raise ValueError(f"Unsupported command shell: {command_shell}") root = manifest.root.parent.parent binding = { @@ -21,7 +26,7 @@ def startup_context_text(manifest: HostManifest) -> str: "plugin_root": str(root), "host_manifest": str(manifest.root / "host.json"), } - if os.name == "nt": + if command_shell == "powershell": def literal(value: str) -> str: return "'" + value.replace("'", "''") + "'" @@ -36,12 +41,14 @@ def literal(value: str) -> str: ) guard_description = "Only ok=true allows the PowerShell exec step to run. " else: - launcher = "sh " + shlex.quote(str(root / "scripts/runtime_preflight.sh")) + # Git Bash accepts drive/UNC paths with forward slashes. Keep the + # native paths in the binding JSON; normalize only shell arguments. + launcher = "sh " + shlex.quote((root / "scripts/runtime_preflight.sh").as_posix()) guarded = ( launcher + " require && " + launcher + " exec " - + shlex.quote(str(root / "scripts/host_runtime_cli.py")) + + shlex.quote((root / "scripts/host_runtime_cli.py").as_posix()) + " resolve --platform " + shlex.quote(manifest.host_id) - + " --expected-plugin-root " + shlex.quote(str(root)) + + " --expected-plugin-root " + shlex.quote(root.as_posix()) ) guard_description = "Only ok=true allows the resolver after && to run; do not replace && with a separator. " return ( @@ -64,13 +71,13 @@ def literal(value: str) -> str: ) -def startup_context(manifest: HostManifest) -> dict: +def startup_context(manifest: HostManifest, *, command_shell: str | None = None) -> dict: """Preserve the existing nested response used by the 1.1 Host Kits.""" return { "hookSpecificOutput": { "hookEventName": "SessionStart", - "additionalContext": startup_context_text(manifest), + "additionalContext": startup_context_text(manifest, command_shell=command_shell), } } @@ -117,10 +124,13 @@ def cleanup_session(manifest: HostManifest, data: dict) -> int: return removed -def handle_event(manifest: HostManifest, data: dict, *, emit_startup_context: bool = True) -> None: +def handle_event( + manifest: HostManifest, data: dict, *, emit_startup_context: bool = True, + command_shell: str | None = None, +) -> None: event = data.get("hook_event_name") if event == "SessionStart" and emit_startup_context: - print(json.dumps(startup_context(manifest), ensure_ascii=False)) + print(json.dumps(startup_context(manifest, command_shell=command_shell), ensure_ascii=False)) try: if event in {"SessionStart", "CwdChanged"}: repair_session(manifest, data) diff --git a/helixharness/scripts/python_runtime.sh b/helixharness/scripts/python_runtime.sh index d003a93..efd2e62 100644 --- a/helixharness/scripts/python_runtime.sh +++ b/helixharness/scripts/python_runtime.sh @@ -11,6 +11,9 @@ probe_helix_python() { PYTHON_PROBE=$1 fi python_version=$("$@" -c 'import sys; print("%d.%d.%d" % sys.version_info[:3])' /dev/null) || return 1 + # Command substitution removes LF but leaves Windows Python's trailing CR. + # Strip only that one terminator; reject embedded or repeated control bytes. + python_version=${python_version%"$(printf '\r')"} case "$python_version" in *[!0-9.]*|''|.*|*.|*..*) return 1 ;; esac python_major=${python_version%%.*} python_minor_patch=${python_version#*.} diff --git a/helixharness/scripts/tests/test_cursor_entry_repairs.py b/helixharness/scripts/tests/test_cursor_entry_repairs.py index 8842cb9..15898fa 100644 --- a/helixharness/scripts/tests/test_cursor_entry_repairs.py +++ b/helixharness/scripts/tests/test_cursor_entry_repairs.py @@ -17,6 +17,7 @@ import unittest from dataclasses import replace from pathlib import Path +from types import SimpleNamespace from unittest.mock import patch from host_runtime import HostRegistry @@ -62,7 +63,7 @@ def runtimes(self, python: str | None = "3.12.0", git: bool = True): def command(self, host: str) -> str: manifest = replace(self.registry.require(host), root=self.plugin / "hosts" / host) - context = startup_context_text(manifest) + context = startup_context_text(manifest, command_shell="bash" if host == "claude-code" else None) commands = [line for line in context.splitlines() if line.startswith("sh ")] self.assertEqual(1, len(commands)) return commands[0] @@ -116,6 +117,21 @@ def test_missing_git_stops_before_resolver_even_when_python_ready(self): self.runtimes(git=False) self.assert_blocked_all_hosts("ready", "missing") + def test_windows_claude_bash_gate_blocks_failures_and_accepts_crlf(self): + # Synthetic Windows selection executed by a real POSIX shell. Native + # Git Bash path/argv behavior is covered separately on Windows CI. + with patch("lifecycle_service.os", SimpleNamespace(name="nt")): + for version, git, code in (("3.12.0\r", True, 0), ("3.9.6\r", True, 2), + ("broken\r", True, 2), (None, True, 2), + ("3.12.0\r", False, 2)): + with self.subTest(version=version, git=git): + for path in (self.bin / "python3", self.bin / "git", self.marker): + path.unlink(missing_ok=True) + self.runtimes(python=version, git=git) + result = self.run_command("claude-code") + self.assertEqual(code, result.returncode, result.stderr) + self.assertEqual(code == 0, self.marker.exists()) + def test_check_keeps_diagnostic_exit_contract_while_require_gates(self): self.runtimes(python=None, git=False) outputs = [] diff --git a/helixharness/scripts/tests/test_lifecycle_shell.py b/helixharness/scripts/tests/test_lifecycle_shell.py new file mode 100644 index 0000000..cb63a44 --- /dev/null +++ b/helixharness/scripts/tests/test_lifecycle_shell.py @@ -0,0 +1,87 @@ +"""Host-selected shell contracts; Windows paths are synthetic on POSIX.""" + +import importlib.util +import io +import json +import os +import shlex +import subprocess +import sys +import unittest +from contextlib import redirect_stdout +from dataclasses import replace +from pathlib import Path, PureWindowsPath +from types import SimpleNamespace +from unittest.mock import patch + +from host_runtime import HostRegistry +from lifecycle_service import startup_context_text + +ROOT = Path(__file__).resolve().parents[2] + + +class LifecycleShellTest(unittest.TestCase): + def setUp(self): + self.registry = HostRegistry.discover(ROOT / "hosts") + + def test_windows_bash_paths_preserve_arguments_and_native_binding(self): + for root in (PureWindowsPath("C:/插件 'quoted' $cash/install"), + PureWindowsPath("//server/share/插件 'quoted'/install")): + with self.subTest(root=root): + manifest = replace(self.registry.require("claude-code"), root=root / "hosts/claude-code") + with patch("lifecycle_service.os", SimpleNamespace(name="nt")): + context = startup_context_text(manifest, command_shell="bash") + binding = json.loads(context.split(": ", 1)[1].split("\n", 1)[0]) + self.assertEqual(str(root), binding["plugin_root"]) + command = next(line for line in context.splitlines() if line.startswith("sh ")) + launcher = (root / "scripts/runtime_preflight.sh").as_posix() + self.assertEqual(shlex.split(command), [ + "sh", launcher, "require", "&&", "sh", launcher, "exec", + (root / "scripts/host_runtime_cli.py").as_posix(), "resolve", + "--platform", "claude-code", "--expected-plugin-root", root.as_posix(), + ]) + if os.name != "nt": + result = subprocess.run(["/bin/bash", "-n", "-c", command], capture_output=True) + self.assertEqual(0, result.returncode, result.stderr) + + def test_claude_real_hook_selects_bash_for_start_and_command_events(self): + spec = importlib.util.spec_from_file_location("synthetic_claude_shell", ROOT / "hosts/claude-code/hook_entry.py") + entry = importlib.util.module_from_spec(spec) + spec.loader.exec_module(entry) + payloads = [ + {"hook_event_name": "SessionStart"}, + {"hook_event_name": "PreToolUse", "tool_name": "Skill", "tool_input": {"skill": "helix:status"}}, + {"hook_event_name": "UserPromptExpansion", "command_name": "helix:status"}, + ] + for payload in payloads: + with self.subTest(event=payload["hook_event_name"]): + output = io.StringIO() + with patch.object(sys, "stdin", io.StringIO(json.dumps(payload))), \ + patch.object(entry, "persist_environment"), \ + patch("lifecycle_service.os", SimpleNamespace(name="nt")), \ + redirect_stdout(output): + self.assertEqual(0, entry.main()) + specific = json.loads(output.getvalue())["hookSpecificOutput"] + self.assertEqual(payload["hook_event_name"], specific["hookEventName"]) + context = specific["additionalContext"] + self.assertIn(" require && sh ", context) + self.assertNotIn("$helixPreflight", context) + + def test_default_windows_codex_and_cursor_keep_powershell(self): + for host in ("codex", "cursor"): + with self.subTest(host=host), patch("lifecycle_service.os", SimpleNamespace(name="nt")): + context = startup_context_text(self.registry.require(host)) + self.assertIn("$helixPreflight = & ", context) + self.assertIn("if (-not ($helixPreflight | ConvertFrom-Json).ok) { exit 2 }", context) + self.assertNotIn("require &&", context) + + def test_posix_default_and_explicit_bash_are_identical_for_all_hosts(self): + for host in self.registry.supported_ids(): + with self.subTest(host=host), patch("lifecycle_service.os", SimpleNamespace(name="posix")): + manifest = self.registry.require(host) + self.assertEqual(startup_context_text(manifest), + startup_context_text(manifest, command_shell="bash")) + + def test_invalid_shell_is_rejected(self): + with self.assertRaises(ValueError): + startup_context_text(self.registry.require("claude-code"), command_shell="cmd") diff --git a/helixharness/scripts/tests/test_runtime_preflight.py b/helixharness/scripts/tests/test_runtime_preflight.py index c5f6301..9bb0a21 100644 --- a/helixharness/scripts/tests/test_runtime_preflight.py +++ b/helixharness/scripts/tests/test_runtime_preflight.py @@ -121,6 +121,31 @@ def test_python_312_is_ready(self) -> None: self.assertEqual(payload["python"]["status"], "ready") self.assertEqual(payload["next_action"], "continue") + def test_crlf_version_output_retains_minimum_and_strict_validation(self) -> None: + for version, status in (("3.12.0\r", "ready"), ("3.9.6\r", "unsupported_version"), + ("3.12.0\r\r", "unusable"), ("3.\r12.0", "unusable"), + ("3.12.0\t", "unusable"), ("banner\n3.12.0\r", "unusable")): + with self.subTest(version=version): + self.assertEqual(status, self.check(version)["python"]["status"]) + + def test_crlf_runtime_exec_and_hook_preserve_stdin_and_exit_code(self) -> None: + interpreter = self.bin_dir / "python3" + interpreter.write_text( + '#!/bin/sh\nif [ "$1" = -c ]; then printf "3.12.0\\r\\n"; exit 0; fi\n' + + "exec " + shlex.quote(sys.executable) + ' "$@"\n', encoding="utf-8", + ) + script = self.bin_dir / "stdin echo.py" + script.write_text("import sys; print(sys.stdin.read(), end=''); sys.exit(7)", encoding="utf-8") + for launcher, action in ((SCRIPT, "exec"), (HOOK, "SessionStart")): + with self.subTest(action=action): + result = subprocess.run( + ["/bin/sh", str(launcher), action, str(script)], + input="合成 Hook 输入\n", env=dict(os.environ, PATH=str(self.bin_dir)), + text=True, capture_output=True, timeout=10, + ) + self.assertEqual(7, result.returncode, result.stderr) + self.assertEqual("合成 Hook 输入\n", result.stdout) + def test_unusable_python3_falls_back_and_exec_uses_the_selected_runtime(self) -> None: (self.bin_dir / "python3").write_text("#!/bin/sh\nexit 1\n") fallback = self.bin_dir / "python" diff --git a/helixharness/scripts/tests/test_windows_runtime.py b/helixharness/scripts/tests/test_windows_runtime.py index eb4f75d..70eaf88 100644 --- a/helixharness/scripts/tests/test_windows_runtime.py +++ b/helixharness/scripts/tests/test_windows_runtime.py @@ -2,6 +2,7 @@ import json import os +import shlex import shutil import subprocess import sys @@ -9,6 +10,9 @@ import unittest from pathlib import Path +from host_runtime import HostRegistry +from lifecycle_service import startup_context_text + ROOT = Path(__file__).resolve().parents[2] @@ -20,6 +24,26 @@ def setUp(self): self.base = [self.powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(ROOT / "scripts/runtime_preflight.ps1")] + def test_generated_codex_binding_runs_in_native_powershell(self): + manifest = HostRegistry.discover(ROOT / "hosts").require("codex") + context = startup_context_text(manifest) + command = context.split("(the preflight must run first):\n", 1)[1].split("\nThe first JSON", 1)[0] + with tempfile.TemporaryDirectory() as temporary: + script = Path(temporary) / "binding.ps1" + # Windows PowerShell 5.1 needs a BOM to decode non-ASCII script paths. + script.write_text(command, encoding="utf-8-sig") + result = subprocess.run( + [self.powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(script)], + capture_output=True, text=True, encoding="utf-8", timeout=30, + ) + self.assertEqual(0, result.returncode, result.stderr) + decoder = json.JSONDecoder() + check, offset = decoder.raw_decode(result.stdout.lstrip()) + resolved = json.loads(result.stdout.lstrip()[offset:].lstrip()) + self.assertTrue(check["ok"]) + self.assertEqual("resolved", resolved["status"]) + self.assertEqual("codex", resolved["host_id"]) + def test_preflight_and_exec_preserve_unicode_spaces_and_exit_code(self): result = subprocess.run([*self.base, "check"], capture_output=True, text=True, encoding="utf-8", timeout=20) self.assertEqual(result.returncode, 0, result.stderr) @@ -106,5 +130,53 @@ def test_preflight_discovers_managed_python_without_uv_on_path(self): self.assertTrue(Path(payload["python"]["executable"]).is_file()) +@unittest.skipUnless(os.name == "nt", "requires native Windows Git Bash") +class WindowsGitBashRuntimeTest(unittest.TestCase): + def setUp(self): + self.shell = shutil.which("sh.exe") + self.assertIsNotNone(self.shell, "Windows CI must expose Git Bash") + temporary = tempfile.TemporaryDirectory(prefix="helix-bash-") + self.addCleanup(temporary.cleanup) + self.base = Path(temporary.name) + self.plugin = self.base / "plugin 中文 'quoted' $literal" + shutil.copytree(ROOT, self.plugin, ignore=shutil.ignore_patterns("__pycache__")) + self.environment = dict(os.environ, PATH=str(Path(sys.executable).parent) + os.pathsep + os.environ["PATH"]) + self.environment.pop("CLAUDE_ENV_FILE", None) + self.environment.pop("HELIXHARNESS_BOUND_PLUGIN_ROOT", None) + + def run_bash(self, command, *, payload="", code=0): + result = subprocess.run( + [self.shell, "-c", command], env=self.environment, input=payload, + capture_output=True, text=True, encoding="utf-8", timeout=30, + ) + self.assertEqual(code, result.returncode, result.stderr + result.stdout) + return result.stdout + + def test_claude_startup_then_generated_binding_from_quoted_installation(self): + self.environment["CLAUDE_PLUGIN_ROOT"] = self.plugin.as_posix() + hooks = json.loads((self.plugin / "hosts/claude-code/hooks.json").read_text(encoding="utf-8")) + command = hooks["hooks"]["SessionStart"][0]["hooks"][0]["command"] + output = self.run_bash(command, payload=json.dumps({"hook_event_name": "SessionStart"})) + context = json.loads(output)["hookSpecificOutput"]["additionalContext"] + command = next(line for line in context.splitlines() if line.startswith("sh ")) + output = self.run_bash(command) + decoder = json.JSONDecoder() + check, offset = decoder.raw_decode(output.lstrip()) + resolved = json.loads(output.lstrip()[offset:].lstrip()) + self.assertTrue(check["ok"]) + self.assertEqual("resolved", resolved["status"]) + self.assertEqual("claude-code", resolved["host_id"]) + self.assertEqual(self.plugin.resolve(), Path(resolved["plugin_root"]).resolve()) + + def test_native_python_crlf_probe_exec_and_hook_keep_stdin_and_exit_status(self): + script = self.base / "echo 中文 'quoted'.py" + script.write_text("import sys; print(sys.stdin.read(), end=''); sys.exit(7)", encoding="utf-8") + for launcher, action in (("runtime_preflight.sh", "exec"), ("python_hook_bootstrap.sh", "SessionStart")): + with self.subTest(action=action): + command = shlex.join(["sh", (self.plugin / "scripts" / launcher).as_posix(), action, script.as_posix()]) + output = self.run_bash(command, payload="合成输入\n", code=7) + self.assertEqual("合成输入\n", output) + + if __name__ == "__main__": unittest.main() From ed08751ab1fdc7bab0c2e5df26d28e5c24441301 Mon Sep 17 00:00:00 2001 From: wuchunlin Date: Tue, 24 Nov 2026 11:29:51 +0800 Subject: [PATCH 04/37] fix(opencode): harden host workflows and managed distribution Bind command and skill context to the requesting session, enforce package resource boundaries, and add project checks and receipt-based task updates. Protect UT artifacts with atomic publication and evidence-based findings. Support consent-bound stage telemetry and guarded Git updates, preserve canonical host contracts, and share explicit D2C evidence validation. Include both OpenCode runtime modules in Cursor managed installs and upgrades. Validate the integrated tree with 4 managed-bundle checks, 146 OpenCode tests and 515 assertions, and TypeScript type checking. The identical candidate also passed 913 Python tests with 10 platform skips and targeted OpenCode 2.3.2 real-model verification of checks, telemetry, UT writes, and Status. --- .claude-plugin/marketplace.json | 4 +- README.md | 21 +- README.zh-CN.md | 21 +- docs/installation.md | 58 +- docs/opencode-testing.md | 75 +++ docs/user-guide.md | 27 +- docs/user-guide.zh-CN.md | 27 +- docs/workflow-architecture.md | 6 +- examples/README.md | 6 +- helixharness/.claude-plugin/marketplace.json | 4 +- helixharness/PLUGIN_USAGE.md | 10 +- helixharness/README.md | 10 +- helixharness/agents/unit-test-worker.md | 24 +- helixharness/commands/status.md | 24 +- helixharness/commands/ut.md | 54 +- helixharness/hosts/codex/ut.md | 4 +- helixharness/hosts/cursor/d2c_gate.cjs | 164 +---- helixharness/hosts/cursor/ut.md | 2 +- helixharness/hosts/opencode/capabilities.md | 35 + helixharness/hosts/opencode/d2c_gate.cjs | 11 + helixharness/hosts/opencode/host.json | 28 +- helixharness/hosts/opencode/installer.md | 98 ++- helixharness/hosts/opencode/lifecycle.md | 15 +- helixharness/hosts/opencode/runtime.md | 96 ++- helixharness/hosts/opencode/subagent.md | 14 + helixharness/hosts/opencode/ut.md | 28 +- .../hosts/opencode/workflow-transition.md | 4 +- helixharness/opencode/core.ts | 260 ++++++-- helixharness/opencode/project-checks.ts | 82 +++ helixharness/opencode/tests/README.md | 146 ++++- helixharness/opencode/tests/core.test.ts | 6 +- helixharness/opencode/tests/e2e.test.ts | 230 +++++++ .../opencode/tests/managed-bundle-probe.ts | 69 ++ helixharness/opencode/tests/native-fixture.ts | 65 +- helixharness/opencode/tests/plugin.test.ts | 322 +++++++++- .../opencode/tests/project-checks.test.ts | 72 +++ .../tests/resource-boundaries.test.ts | 105 +++ helixharness/opencode/tests/ut-state.test.ts | 58 ++ helixharness/opencode/ut-state.ts | 30 + helixharness/reference/eval-protocol.md | 2 +- .../reference/eval-supplement-protocol.md | 2 +- helixharness/reference/host-api.md | 4 +- .../reference/host-runtime-protocol.md | 4 +- .../reference/ut-artifact-protocol.md | 99 +++ .../reference/version-update-protocol.md | 7 +- .../reference/workspace-repo-dispatch.md | 16 + helixharness/scripts/task_plan.py | 135 ++++ helixharness/scripts/telemetry_collector.py | 80 ++- .../scripts/telemetry_hosts/opencode.py | 51 ++ helixharness/scripts/telemetry_ledger.py | 5 + .../tests/test_cursor_bundle_update.py | 47 +- .../scripts/tests/test_cursor_telemetry.py | 4 +- .../scripts/tests/test_feedback_submit.py | 6 +- .../scripts/tests/test_opencode_d2c_gate.py | 597 ++++++++++++++++++ .../scripts/tests/test_opencode_host.py | 45 +- .../scripts/tests/test_opencode_telemetry.py | 105 +++ .../scripts/tests/test_opencode_update.py | 161 +++++ .../tests/test_project_status_regressions.py | 123 ++++ helixharness/scripts/tests/test_task_plan.py | 87 +++ .../scripts/tests/test_ut_artifacts.py | 189 ++++++ .../scripts/tests/test_ut_precompile.py | 250 ++++++++ helixharness/scripts/tests/test_workflow.py | 89 ++- helixharness/scripts/tests/test_workspace.py | 155 +++++ helixharness/scripts/update_hosts/cursor.py | 5 +- helixharness/scripts/update_hosts/opencode.py | 195 +++++- helixharness/scripts/ut_artifacts.py | 280 ++++++++ helixharness/scripts/ut_precompile.py | 108 ++++ helixharness/scripts/workspace.py | 20 + .../scripts/d2c-print-fidelity-report.cjs | 3 +- .../d-d2c/scripts/d2c-workflow-checkpoint.cjs | 13 +- .../scripts/lib/d2c-explicit-gate-core.cjs | 304 +++++++++ .../d-d2c/scripts/lib/d2c-png-evidence.cjs | 105 +++ .../scripts/lib/d2c-runtime-health-core.cjs | 11 +- .../scripts/lib/d2c-workflow-guard-core.cjs | 66 +- 74 files changed, 5178 insertions(+), 510 deletions(-) create mode 100644 docs/opencode-testing.md create mode 100644 helixharness/hosts/opencode/capabilities.md create mode 100644 helixharness/hosts/opencode/d2c_gate.cjs create mode 100644 helixharness/opencode/project-checks.ts create mode 100644 helixharness/opencode/tests/managed-bundle-probe.ts create mode 100644 helixharness/opencode/tests/project-checks.test.ts create mode 100644 helixharness/opencode/tests/resource-boundaries.test.ts create mode 100644 helixharness/opencode/tests/ut-state.test.ts create mode 100644 helixharness/opencode/ut-state.ts create mode 100644 helixharness/reference/ut-artifact-protocol.md create mode 100644 helixharness/scripts/task_plan.py create mode 100644 helixharness/scripts/telemetry_hosts/opencode.py create mode 100644 helixharness/scripts/tests/test_opencode_d2c_gate.py create mode 100644 helixharness/scripts/tests/test_opencode_telemetry.py create mode 100644 helixharness/scripts/tests/test_opencode_update.py create mode 100644 helixharness/scripts/tests/test_project_status_regressions.py create mode 100644 helixharness/scripts/tests/test_task_plan.py create mode 100644 helixharness/scripts/tests/test_ut_artifacts.py create mode 100644 helixharness/scripts/tests/test_ut_precompile.py create mode 100644 helixharness/scripts/ut_artifacts.py create mode 100644 helixharness/scripts/ut_precompile.py create mode 100644 helixharness/skills/d-d2c/scripts/lib/d2c-explicit-gate-core.cjs create mode 100644 helixharness/skills/d-d2c/scripts/lib/d2c-png-evidence.cjs diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index c0f23af..eabad90 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, Codex, Cursor and OpenCode (Preview)" + "description": "Plugin marketplace for the HelixHarness repository, exposing the helixharness workflow plugin for Claude Code, Codex, Cursor and OpenCode (macOS 2.3.2 Stable)" }, "plugins": [ { "name": "helix", - "description": "HelixHarness workflow plugin for Claude Code, Codex, Cursor and OpenCode (Preview) with commands and reusable skills", + "description": "HelixHarness workflow plugin for Claude Code, Codex, Cursor and OpenCode (macOS 2.3.2 Stable) with commands and reusable skills", "source": "./helixharness", "version": "1.0.0", "license": "Apache-2.0" diff --git a/README.md b/README.md index 18bb397..ebfe578 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, Claude Code, Cursor and OpenCode (Preview).** 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, Cursor and [OpenCode (macOS Stable)](docs/opencode-testing.md).** 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 / Cursor / OpenCode (Preview) · Single repo / multi-repo Workspace · Apache-2.0** +**9 commands · Codex / Claude Code / Cursor / [OpenCode (macOS Stable)](docs/opencode-testing.md) · 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, Claude Code, Cursor or OpenCode installation (OpenCode v2.2.2+). 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, Cursor or OpenCode installation (macOS, 2.3.2; see the [support matrix](docs/opencode-testing.md)). Make sure the host is signed in or has its model configuration set up and is working normally. For macOS and native Windows setup, interpreter detection and host-specific requirements, see [platform support](docs/platform-support.md). Windows Codex uses PowerShell; Windows Claude Code uses Git for Windows Bash. Cursor native acceptance currently covers macOS; Windows Cursor is outside this release's verified scope. @@ -83,14 +83,13 @@ claude plugin install helix@helixharness-marketplace Cursor users install `helix` from their Cursor marketplace through **Customize → helix → Install**, then reload the window and open a new Agent. A team administrator first imports the published release repository into the team's marketplace. Cursor uses `/helix-init`, `/helix-propose`, etc. See [marketplace setup, optional Local installation and capability limits](docs/installation.md#cursor-preview). -```bash -# OpenCode v2.2.2+ -opencode plugin add 'github:didi/helixharness::path:helixharness' -``` +OpenCode installation was verified with 2.3.2: clone this repository and configure the absolute `helixharness/` subdirectory in `opencode.json(c)`. Follow the [local-directory installation steps](docs/installation.md#opencode-local-directory-installation-verified-with-232); this repository is not installed with native `plugin add`. + +**OpenCode Stable support (macOS, 2.3.2):** See the [support matrix](docs/opencode-testing.md) for the current source candidate’s scope and boundaries. OpenCode 2.2.2 and 2.3.0 have automated compatibility coverage only. -**OpenCode Preview support (v2.2.2+):** The plugin registers native `helix:` commands, `helix-` method skills and `helix-` roles, binding Host Context to the current repository and session. Full Init → Propose → Apply → Archive acceptance with a real model remains unverified. Workspace Apply uses `helix-worker` for `may_delegate` RepoJobs and requires `experimental.subagent_depth >= 2`; independent reviewers remain read-only leaf jobs. Insufficient depth blocks the RepoJob rather than bypassing review. +The plugin registers native `helix:` commands, `helix-` method skills and `helix-` roles. Commands, native `skill` tool results, Skill mentions and native Skill activation bind the requesting session's repository. Unbound Skill content is blocked when session lookup or directory validation fails. On 2026-11-20, OpenCode 2.3.2 with DeepSeek completed one synthetic single-repository Init → Propose → Apply → Archive lifecycle, with operator confirmations and a controlled contract amendment. On 2026-11-23, OpenCode 2.3.2 with DeepSeek also completed assisted synthetic two-repository Workspace and standalone UT runs; UT classification validation and protected atomic publication were subsequently fixed and passed a fresh real-model UT run without corrective operator prompts. [Targeted real-model tests on synthetic Workspaces](helixharness/opencode/tests/README.md#recovery-and-auxiliary-workflow-acceptance-2026-11-23) also verified native Apply and partial Archive cancellation followed by fresh-session recovery, plus dependent-dispatch blocking after an injected native context-hook failure. Full production-project acceptance, unattended protocol compliance and full TUI/desktop UI acceptance remain outstanding; see [targeted terminal UI acceptance](helixharness/opencode/tests/README.md#targeted-terminal-ui-acceptance-2026-11-23) for the tested scope. Workspace Apply uses `helix-worker` for `may_delegate` RepoJobs and requires `experimental.subagent_depth >= 2`; independent reviewers remain read-only leaf jobs. Insufficient depth blocks the RepoJob rather than bypassing review. -OpenCode has no native SessionStart/Stop/failure/session-end hooks or plan tool (`tasks.md` tracks the plan). Telemetry is unsupported (`unsupported_host`); `/helix:update` returns `continue_silently`, so update manually through OpenCode plugin management. Project hooks are unsupported: Init merges `AGENTS.md` without creating `.opencode/` settings. The d-d2c Claude skill-scoped Stop/PreToolUse guards do not run; use its no-hook / `--bare` semantics while retaining user decisions, visual acceptance and completion checks. +The adapter uses native tool/session hooks but provides no equivalent SessionStart/Stop/failure/session-end business guarantee. `scripts/task_plan.py` atomically updates the canonical `tasks.md`. Explicitly consented telemetry records stage facts and workflow traces only; native conversations, token usage and unobserved tool counts remain unavailable. `/helix:update` uses the existing confirmation protocol for clean source checkouts with an explicit Git upstream, pins the approved commit and only fast-forwards. Dirty, detached or package-managed copies are not automatically updated. Init merges `AGENTS.md` without `.opencode/` settings; plugin-level checks run existing project linters after successful native write/edit/patch. Shell changes still require explicit checks. The d-d2c Claude skill-scoped Stop/PreToolUse guards do not run. Its [explicit OpenCode gate](helixharness/hosts/opencode/runtime.md) binds a fresh checkpoint to the actual native session and checks completion evidence; invoke it at the documented workflow transitions. It does not intercept arbitrary stops or establish browser/MasterGo authenticity. Mutation entry preflight observes registered tools and session-move API availability; permissions still require actual execution, and effective delegation depth remains unknown until native admission. See the [OpenCode installer](helixharness/hosts/opencode/installer.md) for binding checks and manual updates. @@ -223,10 +222,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 to more hosts beyond Codex, Claude Code, Cursor and OpenCode (Preview) so teams can use HelixHarness with more of their preferred tools. +- **More coding agents.** Extend support to more hosts beyond Codex, Claude Code, Cursor and [OpenCode (macOS Stable)](docs/opencode-testing.md) 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 source supports Codex, Claude Code and Cursor, plus OpenCode in Preview, using the Propose → Apply → Archive workflow. Cursor native-client acceptance is tracked separately from automated contract tests. Share concrete use cases through the [contribution guide](CONTRIBUTING.md) to help shape these directions. +These are planned capabilities. The source supports Codex, Claude Code and Cursor, plus [OpenCode within its macOS Stable scope](docs/opencode-testing.md), using the Propose → Apply → Archive workflow. Cursor native-client acceptance is tracked separately from automated contract tests. 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 e349a08..c2ebc06 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -6,11 +6,11 @@ > > 为适配而生,为进化而设计。让团队的工程 DNA,融入 AI 研发。 -**HelixHarness 帮助团队在 Codex、Claude Code、Cursor 与 OpenCode(预览)上构建专属的 AI Coding Harness。** 将你的业务知识、工程规范与研发工作流带入 Agent 的工作过程,从需求分析、实现、测试、评审到归档,让 AI 按团队的方式开展研发,并将经验证的经验留在项目中,供下一个需求复用。 +**HelixHarness 帮助团队在 Codex、Claude Code、Cursor 与 [OpenCode(macOS Stable)](docs/opencode-testing.md)上构建专属的 AI Coding Harness。** 将你的业务知识、工程规范与研发工作流带入 Agent 的工作过程,从需求分析、实现、测试、评审到归档,让 AI 按团队的方式开展研发,并将经验证的经验留在项目中,供下一个需求复用。 从插件开始即可。当你希望改进 Harness 本身时,可选的 **helixharness-platform** 帮助框架维护者观测使用过程、对比框架版本,并在采纳候选改进前验证效果。 -**9 个命令 · Codex / Claude Code / Cursor / OpenCode(预览) · 单仓 / 多仓 Workspace · Apache-2.0** +**9 个命令 · Codex / Claude Code / Cursor / [OpenCode(macOS Stable)](docs/opencode-testing.md) · 单仓 / 多仓 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、Cursor 或 OpenCode(v2.2.2+)。先确保宿主已完成登录或模型配置,能够正常使用。 +需要 Python 3.10+、Git,以及支持插件的 Codex、Claude Code、Cursor 或 OpenCode(macOS、2.3.2;见[支持矩阵](docs/opencode-testing.md))。先确保宿主已完成登录或模型配置,能够正常使用。 macOS 与原生 Windows 的依赖、解释器探测及宿主要求见[跨平台说明](docs/platform-support.md)。Windows Codex 使用 PowerShell;Windows Claude Code 使用 Git for Windows Bash。Cursor 实机验收目前覆盖 macOS,Windows Cursor 不在本期已验证范围。 @@ -83,14 +83,13 @@ claude plugin install helix@helixharness-marketplace Cursor 用户通过 **Customize → helix → Install** 从市场安装,随后重载窗口并新建 Agent。团队管理员需先将已发布的发行仓库导入团队市场。Cursor 使用 `/helix-init`、`/helix-propose` 等入口,详见[市场安装、可选 Local 安装及能力限制](docs/installation.md#cursor-preview)。 -```bash -# OpenCode v2.2.2+ -opencode plugin add 'github:didi/helixharness::path:helixharness' -``` +OpenCode 安装已在 2.3.2 验证:克隆本仓库后,在 `opencode.json(c)` 中配置 `helixharness/` 子目录的绝对路径。详见[本地目录安装步骤](docs/installation.md#opencode-local-directory-installation-verified-with-232);本仓库不使用原生 `plugin add` 安装。 + +**OpenCode Stable 支持(macOS、2.3.2):** 当前源码候选的支持范围与边界见[支持矩阵](docs/opencode-testing.md)。OpenCode 2.2.2、2.3.0 仅有自动化兼容覆盖。 -**OpenCode 预览支持(v2.2.2+):** 插件注册原生 `helix:` 命令、`helix-` 方法 Skill 和 `helix-` 角色,将 Host Context 绑定到当前仓库和会话。完整 Init → Propose → Apply → Archive 流程尚未完成真实模型验收。Workspace Apply 的 `may_delegate` RepoJob 使用 `helix-worker`,需要 `experimental.subagent_depth >= 2`;独立 reviewer 保持只读 leaf。深度不足时阻塞该 RepoJob,不得绕过评审。 +插件注册原生 `helix:` 命令、`helix-` 方法 Skill 和 `helix-` 角色。命令、原生 `skill` 工具结果、Skill mention 与原生 Skill 激活均按请求会话绑定仓库目录;会话查询或目录校验失败时阻断未绑定的 Skill 正文。2026-11-20 已在 OpenCode 2.3.2 + DeepSeek 上完成一次合成单仓 Init → Propose → Apply → Archive 真实模型闭环,包含操作者确认和一次受控合同修订;2026-11-23 又完成了 OpenCode 2.3.2 + DeepSeek 的操作者辅助合成双仓 Workspace 与独立 UT 验证;后续已修复 UT 分类校验与原子发布保护,并通过无纠正提醒的真实模型复验。[合成 Workspace 的专项真实模型验证](helixharness/opencode/tests/README.md#recovery-and-auxiliary-workflow-acceptance-2026-11-23)还覆盖了 Apply 与部分 Archive 原生取消后新会话恢复,以及注入原生 context hook 故障后阻断依赖派发。完整生产业务项目、无人干预时的协议遵守与完整 TUI/桌面 UI 验收仍未完成;已覆盖范围见[定向终端 UI 验收](helixharness/opencode/tests/README.md#targeted-terminal-ui-acceptance-2026-11-23)。Workspace Apply 的 `may_delegate` RepoJob 使用 `helix-worker`,需要 `experimental.subagent_depth >= 2`;独立 reviewer 保持只读 leaf。深度不足时阻塞该 RepoJob,不得绕过评审。 -OpenCode 没有原生 SessionStart/Stop/失败/会话结束 hooks,也没有原生计划工具(计划写入 `tasks.md`)。统计不支持(`unsupported_host`);`/helix:update` 返回 `continue_silently`,请通过 OpenCode 插件管理手动更新。项目 hooks 不支持:Init 只合并 `AGENTS.md`,不创建 `.opencode/` settings。d-d2c 的 Claude skill-scoped Stop/PreToolUse guard 不执行,采用无 hook / `--bare` 语义,仍须遵守用户决策、视觉验收和完成门禁。 +OpenCode 适配使用原生工具和会话 Hook,但未提供等价的 SessionStart/Stop/失败/会话结束业务保证。任务跟踪通过 `scripts/task_plan.py` 原子更新同一份 `tasks.md`。统计在明确授权后记录阶段事实和工作流轨迹,不采集原始会话,token 和未观察到的工具次数保持未知。`/helix:update` 对有明确 Git upstream 的干净源码安装执行既有确认协议,锁定 commit 并仅快进;有本地修改、游离版本或包管理安装时不自动更新。Init 合并 `AGENTS.md`,不创建 `.opencode/` settings;插件在原生 write/edit/patch 成功后执行已有项目巡检,shell 修改仍需显式检查。d-d2c 的 Claude skill-scoped Stop/PreToolUse guard 不执行。[OpenCode 显式门禁](helixharness/hosts/opencode/runtime.md) 将新检查点绑定到实际原生会话并校验完成证据,须在文档指定的流程节点主动调用;它不拦截任意停止,也不认证浏览器/MasterGo 的真实性。写入型命令的入口预检观察工具注册和会话移动 API 是否存在;权限仍须实际执行验证,有效委派深度在原生准入前保持未知。 绑定检查与手动更新步骤见 [OpenCode 安装说明](helixharness/hosts/opencode/installer.md)。 @@ -221,10 +220,10 @@ python -m web_ui.demo --port 7860 接下来计划围绕两个方向,让更多团队按自己的研发方式使用 HelixHarness: -- **支持更多 Coding Agent**:在 Codex、Claude Code、Cursor 与 OpenCode(预览)的基础上继续扩展宿主适配,让团队能在更多熟悉的工具中使用 HelixHarness。 +- **支持更多 Coding Agent**:在 Codex、Claude Code、Cursor 与 [OpenCode(macOS Stable)](docs/opencode-testing.md)的基础上继续扩展宿主适配,让团队能在更多熟悉的工具中使用 HelixHarness。 - **支持工作流配置**:允许团队配置工作流阶段及其顺序,适配自身的研发流程。 -以上为规划方向。当前源码支持 Codex、Claude Code 和 Cursor,另提供 OpenCode 预览支持,采用 Propose → Apply → Archive 工作流。Cursor 原生客户端验收与自动化合同测试分别记录。欢迎通过[贡献指南](CONTRIBUTING.md)分享具体使用场景,帮助完善这些方向。 +以上为规划方向。当前源码支持 Codex、Claude Code 和 Cursor,另提供 [OpenCode macOS Stable 支持](docs/opencode-testing.md),采用 Propose → Apply → Archive 工作流。Cursor 原生客户端验收与自动化合同测试分别记录。欢迎通过[贡献指南](CONTRIBUTING.md)分享具体使用场景,帮助完善这些方向。 ## 文档与贡献 diff --git a/docs/installation.md b/docs/installation.md index ed58fa2..5d73e39 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -4,7 +4,7 @@ ## Requirements -Python 3.10+, Git and a plugin-capable Codex, Claude Code, Cursor or OpenCode installation (OpenCode v2.2.2+) are required. Make sure the host is signed in or has its model configuration set up and is working normally. The platform is optional. Cursor desktop support follows the release scope and limitations below. +Python 3.10+, Git and a plugin-capable Codex, Claude Code, Cursor or OpenCode installation (macOS, 2.3.2; see the [support matrix](opencode-testing.md)) are required. Make sure the host is signed in or has its model configuration set up and is working normally. The platform is optional. Cursor desktop support follows the release scope and limitations below. The shared runtime supports macOS, native Windows and Linux; see [platform support and verification](platform-support.md). Windows Codex uses the PowerShell entrypoint, while Claude Code hooks require Git for Windows Bash. Cursor native acceptance currently covers macOS; Windows Cursor is outside this release's verified scope. @@ -28,18 +28,35 @@ claude plugin marketplace add https://github.com/didi/helixharness.git claude plugin install helix@helixharness-marketplace ``` +## OpenCode local-directory installation (verified with 2.3.2) + +The plugin package lives in this repository's `helixharness/` subdirectory. In the tested OpenCode 2.3.2 client, native `plugin add` accepts npm/Git package specifications, but not an absolute local directory or a Git subdirectory suffix. Clone the repository after publication (replace the destination placeholder), then configure the plugin directory: + ```bash -# OpenCode v2.2.2+ -opencode plugin add 'github:didi/helixharness::path:helixharness' +git clone https://github.com/didi/helixharness.git /absolute/path/to/helixharness-source +``` + +Merge this entry into the existing `plugins` array in project or global `opencode.json(c)`, preserving other settings and plugins: + +```jsonc +{ + "$schema": "https://opencode.ai/config.json", + "plugins": ["/absolute/path/to/helixharness-source/helixharness"] +} ``` -**OpenCode Preview support (v2.2.2+):** The plugin registers native `helix:` commands, `helix-` method skills and `helix-` roles, binding Host Context to the current repository and session. Full Init → Propose → Apply → Archive acceptance with a real model remains unverified. Workspace Apply uses `helix-worker` for `may_delegate` RepoJobs and requires `experimental.subagent_depth >= 2`; independent reviewers remain read-only leaf jobs. Insufficient depth blocks the RepoJob rather than bypassing review. +Use the directory containing the plugin's `package.json`, not the repository root or a single `.ts` file. This package has no runtime npm dependencies; an independent source copy loads without `node_modules` or `bun install`. Restart or reload OpenCode and open a new session after configuring it. These installation observations apply to 2.3.2; other client versions need their own verification. + -OpenCode has no native SessionStart/Stop/failure/session-end hooks or plan tool (`tasks.md` tracks the plan). Telemetry is unsupported (`unsupported_host`); `/helix:update` returns `continue_silently`, so update manually through OpenCode plugin management. Project hooks are unsupported: Init merges `AGENTS.md` without creating `.opencode/` settings. The d-d2c Claude skill-scoped Stop/PreToolUse guards do not run; use its no-hook / `--bare` semantics while retaining user decisions, visual acceptance and completion checks. +**OpenCode Stable support (macOS, 2.3.2):** See the [support matrix](opencode-testing.md) for the current source candidate’s scope and boundaries. OpenCode 2.2.2 and 2.3.0 have automated compatibility coverage only. + +The plugin registers native `helix:` commands, `helix-` method skills and `helix-` roles. Commands, native `skill` tool results, Skill mentions and native Skill activation bind the requesting session's repository. Unbound Skill content is blocked when session lookup or directory validation fails. On 2026-11-20, OpenCode 2.3.2 with DeepSeek completed one synthetic single-repository Init → Propose → Apply → Archive lifecycle, with operator confirmations and a controlled contract amendment. On 2026-11-23, OpenCode 2.3.2 with DeepSeek also completed assisted synthetic two-repository Workspace and standalone UT runs; UT classification validation and protected atomic publication were subsequently fixed and passed a fresh real-model UT run without corrective operator prompts. [Targeted real-model tests on synthetic Workspaces](../helixharness/opencode/tests/README.md#recovery-and-auxiliary-workflow-acceptance-2026-11-23) also verified native Apply and partial Archive cancellation followed by fresh-session recovery, plus dependent-dispatch blocking after an injected native context-hook failure. Full production-project acceptance, unattended protocol compliance and full TUI/desktop UI acceptance remain outstanding; see [targeted terminal UI acceptance](../helixharness/opencode/tests/README.md#targeted-terminal-ui-acceptance-2026-11-23) for the tested scope. Workspace Apply uses `helix-worker` for `may_delegate` RepoJobs and requires `experimental.subagent_depth >= 2`; independent reviewers remain read-only leaf jobs. Insufficient depth blocks the RepoJob rather than bypassing review. + +The adapter uses native tool/session hooks but provides no equivalent SessionStart/Stop/failure/session-end business guarantee. `scripts/task_plan.py` atomically updates the canonical `tasks.md`. Explicitly consented telemetry records stage facts and workflow traces only; native conversations, token usage and unobserved tool counts remain unavailable. `/helix:update` uses the existing confirmation protocol for clean source checkouts with an explicit Git upstream, pins the approved commit and only fast-forwards. Dirty, detached or package-managed copies are not automatically updated. Init merges `AGENTS.md` without `.opencode/` settings; plugin-level checks run existing project linters after successful native write/edit/patch. Shell changes still require explicit checks. The d-d2c Claude skill-scoped Stop/PreToolUse guards do not run; use its no-hook / `--bare` semantics while retaining user decisions, visual acceptance and completion checks. See the [OpenCode installer](../helixharness/hosts/opencode/installer.md) for host-specific checks. -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 same `helixharness/` package directly through its `package.json` export, `opencode/index.ts`. The platform is not installed by these commands. +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 loads the configured local `helixharness/` package through its `package.json` export, `opencode/index.ts`. These installation routes do not install the platform. 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. @@ -61,14 +78,7 @@ claude plugin marketplace add "$HELIXHARNESS_SOURCE" claude plugin install helix@helixharness-marketplace ``` -For OpenCode local development, add the plugin subdirectory to project or global `opencode.json(c)`: - -```jsonc -{ - "$schema": "https://opencode.ai/config.json", - "plugins": ["/absolute/path/to/helixharness/helixharness"] -} -``` +For OpenCode local development, use the same [local-directory configuration](#opencode-local-directory-installation-verified-with-232) with the absolute plugin subdirectory of your source copy; no native `plugin add` step is used. 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. @@ -110,29 +120,33 @@ Statistics require explicit consent and current-session identity. Missing identi ## Updates -On Claude Code and Codex, run `/helix:update` in the host conversation. The plugin checks the configured marketplace, shows an available update and uses the host adapter after authorization. Cursor uses `/helix-update` for registered Helix-managed local installations on macOS/Linux, following the same check, confirmation and one-time authorization protocol. Manual copies and Cursor marketplace installations use their original update mechanism. OpenCode has `plugin_update=unsupported`; update manually with `opencode plugin update`, or update local source and reload. `/helix:update` returns `continue_silently`. +On Claude Code and Codex, run `/helix:update` in the host conversation. The plugin checks the configured marketplace, shows an available update and uses the host adapter after authorization. Cursor uses `/helix-update` for registered Helix-managed local installations on macOS/Linux, following the same check, confirmation and one-time authorization protocol. Manual copies and Cursor marketplace installations use their original update mechanism. OpenCode's `/helix:update` supports clean source checkouts with an explicit Git upstream through the same confirmation protocol, pins the approved commit and only fast-forwards. Dirty, detached or package-managed copies require their original manual mechanism. Restart or reload OpenCode and open a new session after an update. Rollback remains an explicit source-revision selection, not an automatic reset; see the [OpenCode update and rollback steps](../helixharness/hosts/opencode/installer.md#更新回退与卸载). -- **Git source:** the host refreshes the configured repository; use the same marketplace for later versions. -- **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. +- **Marketplace Git source (Codex/Claude Code):** the host refreshes the configured repository; use the same marketplace for later versions. OpenCode's clone-based directory configuration follows the local-source steps below. +- **Local source:** update the source copy yourself first, then restart or reload the host. 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`; OpenCode uses `opencode plugin remove` or removes the source from its `plugins` array. 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 this repository's OpenCode directory configuration, remove only its entry from the `plugins` array and restart or reload OpenCode. 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、Cursor 或 OpenCode(v2.2.2+)。Cursor 使用上面的 [Cursor 独立安装流程](#cursor-preview)。先确保宿主已完成登录或模型配置,能够正常使用。平台不是安装插件的前置条件。共享运行时的 Windows 支持不代表 Windows Cursor 已完成验收;Cursor 实机验收目前覆盖 macOS。 +需要 Python 3.10+、Git,以及支持插件的 Codex、Claude Code、Cursor 或 OpenCode(macOS、2.3.2;见[支持矩阵](opencode-testing.md))。Cursor 使用上面的 [Cursor 独立安装流程](#cursor-preview)。先确保宿主已完成登录或模型配置,能够正常使用。平台不是安装插件的前置条件。共享运行时的 Windows 支持不代表 Windows Cursor 已完成验收;Cursor 实机验收目前覆盖 macOS。 -**OpenCode 预览支持(v2.2.2+):** 插件注册原生 `helix:` 命令、`helix-` 方法 Skill 和 `helix-` 角色,将 Host Context 绑定到当前仓库和会话。完整 Init → Propose → Apply → Archive 流程尚未完成真实模型验收。Workspace Apply 的 `may_delegate` RepoJob 使用 `helix-worker`,需要 `experimental.subagent_depth >= 2`;独立 reviewer 保持只读 leaf。深度不足时阻塞该 RepoJob,不得绕过评审。 +**OpenCode Stable 支持(macOS、2.3.2):** 当前源码候选的支持范围与边界见[支持矩阵](opencode-testing.md)。OpenCode 2.2.2、2.3.0 仅有自动化兼容覆盖。 -OpenCode 没有原生 SessionStart/Stop/失败/会话结束 hooks,也没有原生计划工具(计划写入 `tasks.md`)。统计不支持(`unsupported_host`);`/helix:update` 返回 `continue_silently`,请通过 OpenCode 插件管理手动更新。项目 hooks 不支持:Init 只合并 `AGENTS.md`,不创建 `.opencode/` settings。d-d2c 的 Claude skill-scoped Stop/PreToolUse guard 不执行,采用无 hook / `--bare` 语义,仍须遵守用户决策、视觉验收和完成门禁。 +插件注册原生 `helix:` 命令、`helix-` 方法 Skill 和 `helix-` 角色。命令、原生 `skill` 工具结果、Skill mention 与原生 Skill 激活均按请求会话绑定仓库目录;会话查询或目录校验失败时阻断未绑定的 Skill 正文。2026-11-20 已在 OpenCode 2.3.2 + DeepSeek 上完成一次合成单仓 Init → Propose → Apply → Archive 真实模型闭环,包含操作者确认和一次受控合同修订;2026-11-23 又完成了 OpenCode 2.3.2 + DeepSeek 的操作者辅助合成双仓 Workspace 与独立 UT 验证;后续已修复 UT 分类校验与原子发布保护,并通过无纠正提醒的真实模型复验。[合成 Workspace 的专项真实模型验证](../helixharness/opencode/tests/README.md#recovery-and-auxiliary-workflow-acceptance-2026-11-23)还覆盖了 Apply 与部分 Archive 原生取消后新会话恢复,以及注入原生 context hook 故障后阻断依赖派发。完整生产业务项目、无人干预时的协议遵守与完整 TUI/桌面 UI 验收仍未完成;已覆盖范围见[定向终端 UI 验收](../helixharness/opencode/tests/README.md#targeted-terminal-ui-acceptance-2026-11-23)。Workspace Apply 的 `may_delegate` RepoJob 使用 `helix-worker`,需要 `experimental.subagent_depth >= 2`;独立 reviewer 保持只读 leaf。深度不足时阻塞该 RepoJob,不得绕过评审。 -正式发布后,Codex 与 Claude Code 使用上面的 GitHub 安装命令,Cursor 使用市场界面流程,OpenCode 使用上面的 `opencode plugin add`;这些市场安装方式无需先手动克隆源码。发布前测试或修改插件时,使用[开发者安装(本地源码)](#developer-installation):先下载或克隆源码,再从**包含两个子项目的根目录**添加本地市场。根市场指向 `./helixharness`,不会安装平台。独立插件副本仍可添加插件目录本身;同名市场只保留一个来源。 +OpenCode 适配使用原生工具和会话 Hook,但未提供等价的 SessionStart/Stop/失败/会话结束业务保证。任务跟踪通过 `scripts/task_plan.py` 原子更新同一份 `tasks.md`。统计在明确授权后记录阶段事实和工作流轨迹,不采集原始会话,token 和未观察到的工具次数保持未知。`/helix:update` 对有明确 Git upstream 的干净源码安装执行既有确认协议,锁定 commit 并仅快进;有本地修改、游离版本或包管理安装时不自动更新。Init 合并 `AGENTS.md`,不创建 `.opencode/` settings;插件在原生 write/edit/patch 成功后执行已有项目巡检,shell 修改仍需显式检查。d-d2c 的 Claude skill-scoped Stop/PreToolUse guard 不执行,采用无 hook / `--bare` 语义,仍须遵守用户决策、视觉验收和完成门禁。 + +正式发布后,Codex 与 Claude Code 使用上面的 GitHub 安装命令,Cursor 使用市场界面流程,这些市场安装方式无需先手动克隆源码。OpenCode 的安装已在 2.3.2 验证:按[本地目录安装步骤](#opencode-local-directory-installation-verified-with-232)先克隆本仓库,再将 `helixharness/` 子目录的绝对路径加入项目或全局 `opencode.json(c)` 的 `plugins`;保留已有配置和其他插件,无需 `bun install`,随后重启或重新加载并新开会话。该版本原生 `plugin add` 不接受绝对本地目录或 Git 子目录后缀;其他版本须另行核验。发布前测试或修改插件时,使用[开发者安装(本地源码)](#developer-installation):先下载或克隆源码;Codex/Claude Code 从**包含两个子项目的根目录**添加本地市场,OpenCode 继续使用上述本地目录配置。根市场指向 `./helixharness`,不会安装平台。独立插件副本仍可添加插件目录本身;同名市场只保留一个来源。 安装后新开会话,确认九个命令可见;Claude Code/Codex/Cursor 检查插件 hooks 已审阅并实际执行,OpenCode 检查命令展开后的当前仓库/会话 Host Context 绑定,再在业务仓库运行 `/helix:init`(Cursor 为 `/helix-init`)并检查项目文档及宿主支持的项目 hooks(OpenCode 不生成项目 hooks)。单仓 Init 还需检查非空的 `docs/harness/index.md`、`docs/knowledge/index.md`、`docs/knowledge/project-context.md` 及对应项目类型要求的其他产物,不能只看“已完成”回复。若出现 `plugin_source_mismatch`,先核对市场来源与当前安装插件,选定正确来源并新开会话,避免混用其他 checkout 或缓存版本。Claude Code/Codex 更新使用 `/helix:update`;本地来源需先自行更新源码,不能把版本识别成功当作已完成跨版本升级。Cursor 在 macOS/Linux 上使用 `/helix-update` 升级已登记的 Helix 托管本地安装,复用检查、确认与一次性授权协议;手工副本和原生市场安装仍通过原安装方式更新。 +OpenCode 的本仓库安装由用户自行更新源码并重启或重新加载;回退时在源码副本切换到此前批准的版本,不能用原生 `plugin update` 替代。卸载只移除 `plugins` 中本插件的目录条目,不删除业务仓库的知识、需求或代码。固定版本与回退示例见 [OpenCode 安装说明](../helixharness/hosts/opencode/installer.md#更新回退与卸载)。 + **从空项目开始:**在 Git 仓库根目录运行 `/helix:init`(Cursor 为 `/helix-init`)。新目录请先自行执行 `git init`,不需要首次提交。空仓库或纯文档仓库跳过代码扫描,生成最小项目上下文、约束、需求目录与宿主支持的 hooks(OpenCode 只合并 `AGENTS.md`),未确认的信息标记 TODO。再用 `/helix:propose` 和 `/helix:apply`(Cursor 为 `/helix-propose` 和 `/helix-apply`)开发第一个需求。Init 和 Apply 不创建提交。 ## Windows local source / Windows 本地源码 diff --git a/docs/opencode-testing.md b/docs/opencode-testing.md new file mode 100644 index 0000000..faeacaf --- /dev/null +++ b/docs/opencode-testing.md @@ -0,0 +1,75 @@ +# OpenCode support and verification / OpenCode 支持与验证 + +## Release decision / 发布结论 + +The 2026-11-23 maintainer-directed assessment classifies the current source candidate as **Stable within the scope below**. The primary verified environment is macOS 15.7.1 arm64 with OpenCode **2.3.2**, local CLI/server and selected PTY interactions. This is a scoped integration-support decision based on the recorded acceptance, not a claim that every model, operating system or UI path is accepted. The candidate includes local uncommitted fixes; this decision does not publish a release, tag or remote commit. + +2026-11-23 按维护者授权完成支持范围评定:当前源码候选在下列范围内为 **Stable(稳定支持)**。主要已验环境为 macOS 15.7.1 arm64、OpenCode **2.3.2**、本地 CLI/server 与所列 PTY 交互。这是根据已有验收作出的集成支持声明,不代表任意模型、平台和 UI 路径均已验收。候选包含本地未提交修复;本次评定不创建发布、Tag 或远端提交。 + +OpenCode 2.2.2 and 2.3.0 passed automated native-server compatibility tests. Those results are retained separately; they do not extend the primary real-model/installation Stable envelope to every version from 2.2.2 onward. Unlisted versions require compatibility checks before that envelope is extended. + +OpenCode 2.2.2、2.3.0 已通过自动化原生服务兼容检查;该证据单独保留,不将主要真实模型/安装验收范围外推为“2.2.2 起所有版本均 Stable”。未列版本须先验证兼容性,再扩展支持矩阵。 + +## Supported scope / 支持矩阵 + +| Area / 范围 | Supported behavior and evidence / 已验行为与证据 | Boundary / 边界 | +| --- | --- | --- | +| Environment / 环境 | macOS 15.7.1 arm64, OpenCode 2.3.2, Python 3.10+ contract (actual runs: 3.14.3), Git; JVM samples used Java 17. / Python 合同为 3.10+,已记录执行版本为 3.14.3,JVM 样本使用 Java 17。 | No native Windows/Linux, desktop GUI or unlisted-version acceptance. / Windows、Linux 原生会话、桌面图形与未列版本未验收。 | +| Installation / 安装 | A checked-out nested plugin configured by its absolute package directory loads without runtime npm dependencies. Independent copies resolve nine commands, eight method Skills and seventeen roles to their installed roots. / checkout 后配置绝对包目录,无运行时 npm 依赖;独立副本的命令、Skill、角色及路径绑定通过。 | This repository's monorepo Git subdirectory spec and native CLI add of an absolute directory are unsupported on the tested build; use the [installation guide](installation.md). / 已测版本采用安装指南中的目录配置路径。 | +| Single workflows / 单仓流程 | Recorded synthetic real-model Init, Propose, Apply, Archive, active Single BugFix, readonly Status and independent native review. Existing Java tests/build files remain protected. / 合成真实模型覆盖核心阶段、活跃 BugFix、只读 Status 和独立评审,并核验既有测试/构建文件。 | Normal product, task, Advisory and knowledge-scope choices remain interactive. This is not an unattended-production reliability guarantee. / 正常产品、任务、Advisory 和知识范围决策仍需交互,不保证无人干预生产可靠性。 | +| Workspace / 多仓 | Synthetic two-repository workflows, actual native ownership-root moves, readonly repositories, dependency blocking, Apply cancellation/fresh-session recovery and partial Archive recovery are recorded. / 双仓流程、原生切仓、只读仓库、依赖阻断与定向恢复已记录。 | Workspace Apply requires effective nested delegation depth at least 2 and actual admission of independent leaf reviewers. Unknown depth is not a pass; blockers must not trigger inline/self-review fallback. / depth 至少 2,须实际准入;未知不算通过,不内联或自审。 | +| Unit tests / 单测 | Java 17 Maven/Gradle samples, existing tests, incremental precompile, structured classification and single-file atomic publication were checked. / Java 17 Maven/Gradle、既有测试、增量预编译、结构化分类与单文件原子发布已验证。 | Default class discovery is root-project-only; custom/multi-module paths require explicit verification. Real Kotlin/Groovy compilation and a naturally elapsed one-hour timeout remain unaccepted. Native write/edit guards are not a shell sandbox or multi-file transaction. / 不承诺自动发现多模块;未验真实 Kotlin/Groovy、一小时自然超时或多文件事务。 | +| Native surfaces / 原生入口 | Nine commands, eight method Skills and seventeen roles are registered. Direct mentions, Skill activation, cross-session binding, resource confinement and prerequisite failures have automated native coverage. / 九命令、八方法 Skill、十七角色,原生 mention/激活、跨会话绑定和失败阻断有自动化覆盖。 | Config still needs separate full interaction acceptance; source update, stage telemetry and task adapters have their own scoped checks. / Config 完整设置交互另需验收;源码更新、阶段统计和任务适配分别有专项验证。 | +| Targeted PTY / 定向终端 | Native question choice, permission Reject, double-Escape shell interruption, session-history reattachment, command menu and Status were exercised through a real PTY client. / 真实 PTY 验证问答、拒绝权限、双 Escape 中断、历史重连、菜单与 Status。 | Terminal byte streams/reconstructed text are interaction evidence, not pixel screenshots or full desktop/TUI coverage. / 文本重建仅证明交互,不是像素或完整图形界面验收。 | +| Models / 模型 | Recorded real-model runs used DeepSeek with tool support; other native tests used a loopback scripted model. / 真实模型使用支持工具调用的 DeepSeek,其余原生回归使用回环脚本模型。 | Arbitrary provider/model behavior is not guaranteed. A correct script receipt can still be misdescribed by a model; Status has a closed empty-output contract but no final-text interceptor. / 不保证任意模型行为;Status 展示受合同约束,不是最终文本硬拦截。 | + +## Assessment gates and evidence / 评定门槛与依据 + +The scoped decision requires: (1) native registration/binding and confinement checks pass; (2) core workflow and independent-review acceptance is recorded; (3) selected failure/cancellation paths fail closed and preserve completed work; (4) the documented installation path works independently of the development checkout; (5) current relevant regressions pass; (6) unsupported and unverified capabilities remain explicit. No unresolved high/medium finding in the recorded reviews was waived by renaming it an unsupported feature. + +本次门槛为:原生注册/绑定/边界检查通过;核心流程和独立评审有记录;所列故障/取消场景保留完成进度并阻断后续错误执行;文档安装路径可脱离开发工作树运行;当前相关回归通过;不支持和未验收项保持明确。没有将已记录审查中未解决的高/中等级问题改名为“不支持”而放行。 + +Public summaries are in the [adapter verification record](../helixharness/opencode/tests/README.md), especially [recovery and auxiliary acceptance](../helixharness/opencode/tests/README.md#recovery-and-auxiliary-workflow-acceptance-2026-11-23), [targeted terminal acceptance](../helixharness/opencode/tests/README.md#targeted-terminal-ui-acceptance-2026-11-23), and [existing Java-project acceptance](../helixharness/opencode/tests/README.md#existing-java-project-acceptance-2026-11-23). Raw synthetic traces remain local and ignored; no credentials, session transcripts or runtime dumps are published here. The manifest's optional machine-E2E receipt remains null; this document is a scoped support assessment, not a fabricated new machine receipt. + +公开摘要见上述适配验收记录及三个专项章节。原始合成轨迹只保存在本地忽略目录,不在此发布凭据、会话正文或运行时转储。manifest 的可选机器 E2E receipt 保持 null;本文是支持范围评定,不伪装为新生成的机器验收回执。 + +Historical checkpoints include 888 Python cases (881 passed, seven skipped), and 136 Bun tests / 483 assertions on each of 2.2.2, 2.3.0 and 2.3.2. The final delivery follow-up reran 136 native-enabled Bun tests on 2.3.2, 18 readonly/user-command tests and 34 host/reference tests, plus typecheck and links. These suites overlap and must not be added together. The release-declaration change receives fresh related checks; it does not relabel old logs as newly executed full suites. + +历史检查点包括 Python 888 项(881 通过、7 跳过),三个版本各 136 项 Bun 测试/483 次断言。交付收尾复跑 2.3.2 的 136 项原生开启 Bun 测试、18 项只读/命令及 34 项宿主/引用检查,另有类型与链接检查。检查有重叠,不累加;本次声明调整另跑相关检查,不把旧日志写成新全量。 + +## Explicit exclusions / 明确排除 + +- [Helix-owned capability adapters](../helixharness/hosts/opencode/capabilities.md) cover consented stage facts, canonical task progress, plugin-level edit checks and consented pinned fast-forward source updates. Native project settings hooks and equivalent Stop/failure/session-end business hooks remain unsupported. / 已补齐授权阶段统计、canonical 任务进度、插件编辑后巡检和确认后锁定 commit 的源码快进更新;原生项目设置 Hook 和等价 Stop/失败/会话结束业务 Hook 仍未提供。 +- Full D2C/MasterGo/browser provenance and visual-fidelity acceptance are outside this Stable scope. Existing explicit evidence gates remain available with their documented audit limits; remaining D2C work stays paused. / 完整 D2C、浏览器来源认证与视觉还原不在本次 Stable 范围,既有门禁保留,剩余工作暂停。 +- Controlled standalone Git-package install/update/rollback used local synthetic Git transport. Public GitHub transport, arbitrary registries, marketplace GUI and every source-conflict combination are not accepted. / 独立根包 Git 验收使用本地受控传输,不外推公开网络、市场 GUI 或任意来源冲突。 +- Existing Java acceptance used controlled synthetic planning inputs and a clean copy after an unborn-Git dirty-baseline blocker. It is not an uninterrupted unattended production run. / 存量 Java 验收包含夹具准备、正常决策及干净副本,不是连续无人干预生产运行。 + +## Reassessment rules / 后续升级与降级 + +Reassess before expanding operating systems, OpenCode versions, model claims, build layouts, distribution channels or unsupported capabilities. A reproducible break in the supported scope's repository/session binding, readonly ownership, independent-review admission, publication integrity or completed-work recovery blocks release until repaired or explicitly removed from the support scope. Feature-specific evidence gaps outside the matrix do not silently broaden the Stable promise. Preserve failed attempts and distinguish test-environment repairs from product fixes. + +扩展平台、OpenCode 版本、模型声明、构建布局、分发渠道或原不支持能力前重新评定。已支持范围内若复现目录/会话绑定、只读所有权、独立评审准入、发布完整性或完成进度恢复缺陷,应阻断发布,修复后验证或明确收缩支持范围。矩阵外的缺口不自动扩大 Stable 承诺;保留失败记录,区分夹具排错与产品修复。 + + +## Declaration-check rerun / 声明检查复跑 + +The 2026-11-23 declaration change passed 11 OpenCode Host Kit tests, 20 Host Registry tests, 136 native-enabled Bun tests on OpenCode 2.3.2 (483 assertions), and typecheck. Business runtime and capability flags were unchanged. These are new declaration/compatibility checks, not new paid-model lifecycle acceptance. + +本次声明变更复跑通过 11 项 OpenCode Host Kit、20 项 Host Registry、OpenCode 2.3.2 下的 136 项原生开启 Bun 测试(483 次断言)及类型检查;业务运行代码与能力标志未改。这是新的声明/兼容检查,不是新增付费模型全流程验收。 + +From repository root with Python 3.10+ / 在仓库根目录运行: + +```bash +PYTHONPATH=helixharness/scripts python3 -m unittest discover -s helixharness/scripts/tests -p test_opencode_host.py +PYTHONPATH=helixharness/scripts python3 -m unittest discover -s helixharness/scripts/tests -p test_host_runtime_registry.py +``` + +Then from the plugin directory with development dependencies available / 然后在插件目录、具备开发检查依赖时运行: + +```bash +cd helixharness +HELIXHARNESS_OPENCODE_BIN=/absolute/path/to/opencode-2.3.2 HELIXHARNESS_OPENCODE_E2E=1 bun test opencode/tests +bun run typecheck +``` + +Native fixtures use isolated homes and scripted loopback models and clean their own services. Use the declared runtime version; checking a different version does not automatically expand this Stable matrix. / 原生夹具隔离 home、使用回环脚本模型并清理自有服务;使用已声明的宿主版本,其他版本的单次检查不会自动扩展本矩阵。 diff --git a/docs/user-guide.md b/docs/user-guide.md index 563f57a..b10d331 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, Claude Code, Cursor and OpenCode (Preview), with a companion platform for usage dashboards, version evaluation and evolution.** +**A development workflow for Codex, Claude Code, Cursor and [OpenCode (macOS Stable)](opencode-testing.md), 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 / Cursor / OpenCode (Preview) · Single repo / multi-repo Workspace · Apache-2.0** +**9 public commands · 3 core stages · Codex / Claude Code / Cursor / [OpenCode (macOS Stable)](opencode-testing.md) · 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,12 +49,12 @@ Install **HelixHarness** for everyday development. Add **helixharness-platform** | Use case | Requirements | | --- | --- | -| HelixHarness plugin | Python 3.10+, Git, and a plugin-capable Codex, Claude Code, Cursor or OpenCode installation (OpenCode v2.2.2+) 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, Cursor or OpenCode installation (macOS, 2.3.2; see the [support matrix](opencode-testing.md)) that is signed in or has its model configuration set up and works normally | | 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 | -The terminal examples below use Bash / Zsh. GitHub plugin installation does not require a manual clone. Running the platform or developing the plugin requires a source checkout. +The terminal examples below use Bash / Zsh. Codex/Claude Code marketplace installation does not require a manual clone. The OpenCode 2.3.2 route below uses a source clone and local-directory configuration; running the platform or developing the plugin also requires a source checkout. ### 1. Install the Plugin @@ -74,16 +74,15 @@ claude plugin marketplace add https://github.com/didi/helixharness.git claude plugin install helix@helixharness-marketplace ``` -**OpenCode v2.2.2+** +**OpenCode (installation verified with 2.3.2)** -```bash -# OpenCode v2.2.2+ -opencode plugin add 'github:didi/helixharness::path:helixharness' -``` +Clone this repository and configure its absolute `helixharness/` subdirectory in project or global `opencode.json(c)`. Follow the [local-directory installation steps](installation.md#opencode-local-directory-installation-verified-with-232). Native `plugin add` does not install this repository layout in the verified client. + +**OpenCode Stable support (macOS, 2.3.2):** See the [support matrix](opencode-testing.md) for the current source candidate’s scope and boundaries. OpenCode 2.2.2 and 2.3.0 have automated compatibility coverage only. -**OpenCode Preview support (v2.2.2+):** The plugin registers native `helix:` commands, `helix-` method skills and `helix-` roles, binding Host Context to the current repository and session. Full Init → Propose → Apply → Archive acceptance with a real model remains unverified. Workspace Apply uses `helix-worker` for `may_delegate` RepoJobs and requires `experimental.subagent_depth >= 2`; independent reviewers remain read-only leaf jobs. Insufficient depth blocks the RepoJob rather than bypassing review. +The plugin registers native `helix:` commands, `helix-` method skills and `helix-` roles. Commands, native `skill` tool results, Skill mentions and native Skill activation bind the requesting session's repository. Unbound Skill content is blocked when session lookup or directory validation fails. On 2026-11-20, OpenCode 2.3.2 with DeepSeek completed one synthetic single-repository Init → Propose → Apply → Archive lifecycle, with operator confirmations and a controlled contract amendment. On 2026-11-23, OpenCode 2.3.2 with DeepSeek also completed assisted synthetic two-repository Workspace and standalone UT runs; UT classification validation and protected atomic publication were subsequently fixed and passed a fresh real-model UT run without corrective operator prompts. [Targeted real-model tests on synthetic Workspaces](../helixharness/opencode/tests/README.md#recovery-and-auxiliary-workflow-acceptance-2026-11-23) also verified native Apply and partial Archive cancellation followed by fresh-session recovery, plus dependent-dispatch blocking after an injected native context-hook failure. Full production-project acceptance, unattended protocol compliance and full TUI/desktop UI acceptance remain outstanding; see [targeted terminal UI acceptance](../helixharness/opencode/tests/README.md#targeted-terminal-ui-acceptance-2026-11-23) for the tested scope. Workspace Apply uses `helix-worker` for `may_delegate` RepoJobs and requires `experimental.subagent_depth >= 2`; independent reviewers remain read-only leaf jobs. Insufficient depth blocks the RepoJob rather than bypassing review. -OpenCode has no native SessionStart/Stop/failure/session-end hooks or plan tool (`tasks.md` tracks the plan). Telemetry is unsupported (`unsupported_host`); `/helix:update` returns `continue_silently`, so update manually through OpenCode plugin management. Project hooks are unsupported: Init merges `AGENTS.md` without creating `.opencode/` settings. The d-d2c Claude skill-scoped Stop/PreToolUse guards do not run; use its no-hook / `--bare` semantics while retaining user decisions, visual acceptance and completion checks. +The adapter uses native tool/session hooks but provides no equivalent SessionStart/Stop/failure/session-end business guarantee. `scripts/task_plan.py` atomically updates the canonical `tasks.md`. Explicitly consented telemetry records stage facts and workflow traces only; native conversations, token usage and unobserved tool counts remain unavailable. `/helix:update` uses the existing confirmation protocol for clean source checkouts with an explicit Git upstream, pins the approved commit and only fast-forwards. Dirty, detached or package-managed copies are not automatically updated. Init merges `AGENTS.md` without `.opencode/` settings; plugin-level checks run existing project linters after successful native write/edit/patch. Shell changes still require explicit checks. The d-d2c Claude skill-scoped Stop/PreToolUse guards do not run; use its no-hook / `--bare` semantics while retaining user decisions, visual acceptance and completion checks. See the [OpenCode installation guide](../helixharness/hosts/opencode/installer.md) for setup and binding checks. @@ -166,7 +165,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 / Cursor / OpenCode (Preview) sessions and application repositories | +| [`helixharness/`](../helixharness/README.md) | Developers using AI coding agents | Project initialization, requirements, implementation, testing, review, and archiving | Codex / Claude Code / Cursor / [OpenCode (macOS Stable)](opencode-testing.md) 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 @@ -417,7 +416,7 @@ Paths below are relative to your platform's base URL: ### Model Configuration -For everyday plugin use, configure models in Codex / Claude Code / Cursor / OpenCode (Preview). 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 / Cursor / [OpenCode (macOS Stable)](opencode-testing.md). 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. @@ -629,7 +628,7 @@ The repository contains two independently installable projects: ├── helixharness/ │ ├── commands/ # Nine public command entrypoints │ ├── workflows/ # single/ execution and workspace/ coordination -│ ├── hosts/ # Codex / Claude Code / Cursor / OpenCode (Preview) adapters +│ ├── hosts/ # Codex / Claude Code / Cursor / OpenCode (macOS Stable) adapters │ ├── skills/ # Reusable workflow methods │ └── scripts/ # Routing, artifact validation, and telemetry └── helixharness-platform/ diff --git a/docs/user-guide.zh-CN.md b/docs/user-guide.zh-CN.md index c5e448e..7d3bc3f 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、Cursor 与 OpenCode(预览)的研发工作流,以及提供数据看板、版本评测与自进化的配套平台。** +**面向 Codex、Claude Code、Cursor 与 [OpenCode(macOS Stable)](opencode-testing.md)的研发工作流,以及提供数据看板、版本评测与自进化的配套平台。** 从一个需求到有验证依据的代码变更:明确边界、拆分任务、实现、测试、评审,再把结果归档到项目中。HelixHarness 将这些步骤作为可复用的工作流交给编码助手,需求和执行进度保存在仓库里,便于检查和续跑。 @@ -14,7 +14,7 @@ Propose → Apply → Archive └─ 测试 + 代码评审 + 验证依据 ``` -**9 个公开命令 · 3 个核心阶段 · Codex / Claude Code / Cursor / OpenCode(预览) · 单仓 / 多仓 Workspace · Apache-2.0** +**9 个公开命令 · 3 个核心阶段 · Codex / Claude Code / Cursor / [OpenCode(macOS Stable)](opencode-testing.md) · 单仓 / 多仓 Workspace · Apache-2.0** 只做日常开发,安装 **HelixHarness** 即可。需要观测使用情况、评测和改进 **HelixHarness 框架本身**,再运行 **helixharness-platform**。开发场景的结果用于判断框架行为,平台不是通用的业务代码评分服务。 @@ -50,12 +50,12 @@ Propose → Apply → Archive | 用途 | 要求 | | --- | --- | -| 使用 HelixHarness | Python 3.10+、Git,以及支持插件的 Codex、Claude Code、Cursor 或 OpenCode(v2.2.2+);宿主已完成登录或模型配置,能够正常使用 | +| 使用 HelixHarness | Python 3.10+、Git,以及支持插件的 Codex、Claude Code、Cursor 或 OpenCode(macOS、2.3.2;见[支持矩阵](opencode-testing.md));宿主已完成登录或模型配置,能够正常使用 | | 运行平台 Demo / 使用看板 | Python 3.10+、Git;安装平台 `server` 依赖 | | 真实版本评测 | 平台依赖、可用的 Codex 执行环境、模型凭据、可访问的 Git 仓库,以及 Case 所需的构建与测试工具 | | 前端预览与视觉验证 | 项目自身的 Node.js、包管理器及浏览器工具;设计服务按实际使用情况配置 | -下面的终端示例使用 Bash / Zsh。从 GitHub 安装插件无需先手动克隆源码;运行平台或开发插件时才需要源码副本。 +下面的终端示例使用 Bash / Zsh。Codex/Claude Code 的市场安装无需先手动克隆源码;下方 OpenCode 2.3.2 安装步骤采用源码克隆与本地目录配置,运行平台或开发插件也需要源码副本。 ### 1. 安装 HelixHarness 插件 @@ -75,16 +75,15 @@ claude plugin marketplace add https://github.com/didi/helixharness.git claude plugin install helix@helixharness-marketplace ``` -**OpenCode v2.2.2+** +**OpenCode(安装已在 2.3.2 验证)** -```bash -# OpenCode v2.2.2+ -opencode plugin add 'github:didi/helixharness::path:helixharness' -``` +克隆本仓库后,在项目或全局 `opencode.json(c)` 中配置 `helixharness/` 子目录的绝对路径。详见[本地目录安装步骤](installation.md#opencode-local-directory-installation-verified-with-232)。已验证客户端的原生 `plugin add` 不支持本仓库布局。 + +**OpenCode Stable 支持(macOS、2.3.2):** 当前源码候选的支持范围与边界见[支持矩阵](opencode-testing.md)。OpenCode 2.2.2、2.3.0 仅有自动化兼容覆盖。 -**OpenCode 预览支持(v2.2.2+):** 插件注册原生 `helix:` 命令、`helix-` 方法 Skill 和 `helix-` 角色,将 Host Context 绑定到当前仓库和会话。完整 Init → Propose → Apply → Archive 流程尚未完成真实模型验收。Workspace Apply 的 `may_delegate` RepoJob 使用 `helix-worker`,需要 `experimental.subagent_depth >= 2`;独立 reviewer 保持只读 leaf。深度不足时阻塞该 RepoJob,不得绕过评审。 +插件注册原生 `helix:` 命令、`helix-` 方法 Skill 和 `helix-` 角色。命令、原生 `skill` 工具结果、Skill mention 与原生 Skill 激活均按请求会话绑定仓库目录;会话查询或目录校验失败时阻断未绑定的 Skill 正文。2026-11-20 已在 OpenCode 2.3.2 + DeepSeek 上完成一次合成单仓 Init → Propose → Apply → Archive 真实模型闭环,包含操作者确认和一次受控合同修订;2026-11-23 又完成了 OpenCode 2.3.2 + DeepSeek 的操作者辅助合成双仓 Workspace 与独立 UT 验证;后续已修复 UT 分类校验与原子发布保护,并通过无纠正提醒的真实模型复验。[合成 Workspace 的专项真实模型验证](../helixharness/opencode/tests/README.md#recovery-and-auxiliary-workflow-acceptance-2026-11-23)还覆盖了 Apply 与部分 Archive 原生取消后新会话恢复,以及注入原生 context hook 故障后阻断依赖派发。完整生产业务项目、无人干预时的协议遵守与完整 TUI/桌面 UI 验收仍未完成;已覆盖范围见[定向终端 UI 验收](../helixharness/opencode/tests/README.md#targeted-terminal-ui-acceptance-2026-11-23)。Workspace Apply 的 `may_delegate` RepoJob 使用 `helix-worker`,需要 `experimental.subagent_depth >= 2`;独立 reviewer 保持只读 leaf。深度不足时阻塞该 RepoJob,不得绕过评审。 -OpenCode 没有原生 SessionStart/Stop/失败/会话结束 hooks,也没有原生计划工具(计划写入 `tasks.md`)。统计不支持(`unsupported_host`);`/helix:update` 返回 `continue_silently`,请通过 OpenCode 插件管理手动更新。项目 hooks 不支持:Init 只合并 `AGENTS.md`,不创建 `.opencode/` settings。d-d2c 的 Claude skill-scoped Stop/PreToolUse guard 不执行,采用无 hook / `--bare` 语义,仍须遵守用户决策、视觉验收和完成门禁。 +OpenCode 适配使用原生工具和会话 Hook,但未提供等价的 SessionStart/Stop/失败/会话结束业务保证。任务跟踪通过 `scripts/task_plan.py` 原子更新同一份 `tasks.md`。统计在明确授权后记录阶段事实和工作流轨迹,不采集原始会话,token 和未观察到的工具次数保持未知。`/helix:update` 对有明确 Git upstream 的干净源码安装执行既有确认协议,锁定 commit 并仅快进;有本地修改、游离版本或包管理安装时不自动更新。Init 合并 `AGENTS.md`,不创建 `.opencode/` settings;插件在原生 write/edit/patch 成功后执行已有项目巡检,shell 修改仍需显式检查。d-d2c 的 Claude skill-scoped Stop/PreToolUse guard 不执行,采用无 hook / `--bare` 语义,仍须遵守用户决策、视觉验收和完成门禁。 安装与绑定检查见 [OpenCode 安装指南](../helixharness/hosts/opencode/installer.md)。 @@ -167,7 +166,7 @@ python -m web_ui.demo --port 7860 --data-dir /path/to/demo-runtime | 项目 | 面向谁 | 负责什么 | 运行位置 | | --- | --- | --- | --- | -| [`helixharness/`](../helixharness/README.md) | 日常使用 AI 编码的开发者 | 初始化项目、收敛需求、实现、测试、评审、归档 | Codex / Claude Code / Cursor / OpenCode(预览) 会话及业务仓库 | +| [`helixharness/`](../helixharness/README.md) | 日常使用 AI 编码的开发者 | 初始化项目、收敛需求、实现、测试、评审、归档 | Codex / Claude Code / Cursor / [OpenCode(macOS Stable)](opencode-testing.md) 会话及业务仓库 | | [`helixharness-platform/`](../helixharness-platform/README.md) | 观测和改进 HelixHarness 框架的维护者 | 数据看板、版本评测、自进化 | 独立 Python Web 服务与评测 Worker | ```mermaid @@ -418,7 +417,7 @@ DEFAULT_FEEDBACK_ENDPOINT = "" ### 模型配置 -日常使用插件时,模型由 Codex / Claude Code / Cursor / OpenCode(预览) 宿主配置。平台自身的模型配置用于平台发起的评测、分析等任务。 +日常使用插件时,模型由 Codex / Claude Code / Cursor / [OpenCode(macOS Stable)](opencode-testing.md) 宿主配置。平台自身的模型配置用于平台发起的评测、分析等任务。 配置模板见 [`helixharness-platform/.env.example`](../helixharness-platform/.env.example)。服务读取**进程环境变量,不会自动加载 `.env.example`**;将真实值注入启动 Web 和 Worker 的环境。 @@ -630,7 +629,7 @@ Candidate 生成在普通用户(包括 macOS 本地用户)下默认使用 Co ├── helixharness/ │ ├── commands/ # 九个公共命令入口和路由 │ ├── workflows/ # single/ 单仓执行,workspace/ 多仓协调 -│ ├── hosts/ # Codex / Claude Code / Cursor / OpenCode(预览) 适配 +│ ├── hosts/ # Codex / Claude Code / Cursor / OpenCode(macOS Stable) 适配 │ ├── skills/ # 工作流复用的方法 │ └── scripts/ # 路由、工件校验与遥测 └── helixharness-platform/ diff --git a/docs/workflow-architecture.md b/docs/workflow-architecture.md index e9131f9..887fec7 100644 --- a/docs/workflow-architecture.md +++ b/docs/workflow-architecture.md @@ -30,9 +30,11 @@ Claude Code、Codex 与 Cursor 的原生插件清单显式选择各自的 hook 支持项目 hooks 的宿主,单仓 Init 必须实际生成并校验当前 Host Kit 的项目 hooks,重复初始化保留用户配置并去重。 业务阶段显式记录 start/finish;会话 Stop 不是业务完成证据。 -**OpenCode 预览支持(v2.2.2+):** 插件注册原生 `helix:` 命令、`helix-` 方法 Skill 和 `helix-` 角色,将 Host Context 绑定到当前仓库和会话。完整 Init → Propose → Apply → Archive 流程尚未完成真实模型验收。Workspace Apply 的 `may_delegate` RepoJob 使用 `helix-worker`,需要 `experimental.subagent_depth >= 2`;独立 reviewer 保持只读 leaf。深度不足时阻塞该 RepoJob,不得绕过评审。 +**OpenCode Stable 支持(macOS、2.3.2):** 当前源码候选的支持范围与边界见[支持矩阵](opencode-testing.md)。OpenCode 2.2.2、2.3.0 仅有自动化兼容覆盖。 -OpenCode 没有原生 SessionStart/Stop/失败/会话结束 hooks,也没有原生计划工具(计划写入 `tasks.md`)。统计不支持(`unsupported_host`);`/helix:update` 返回 `continue_silently`,请通过 OpenCode 插件管理手动更新。项目 hooks 不支持:Init 只合并 `AGENTS.md`,不创建 `.opencode/` settings。d-d2c 的 Claude skill-scoped Stop/PreToolUse guard 不执行,采用无 hook / `--bare` 语义,仍须遵守用户决策、视觉验收和完成门禁。 +插件注册原生 `helix:` 命令、`helix-` 方法 Skill 和 `helix-` 角色。命令、原生 `skill` 工具结果、Skill mention 与原生 Skill 激活均按请求会话绑定仓库目录;会话查询或目录校验失败时阻断未绑定的 Skill 正文。2026-11-20 已在 OpenCode 2.3.2 + DeepSeek 上完成一次合成单仓 Init → Propose → Apply → Archive 真实模型闭环,包含操作者确认和一次受控合同修订;2026-11-23 又完成了 OpenCode 2.3.2 + DeepSeek 的操作者辅助合成双仓 Workspace 与独立 UT 验证;后续已修复 UT 分类校验与原子发布保护,并通过无纠正提醒的真实模型复验。[合成 Workspace 的专项真实模型验证](../helixharness/opencode/tests/README.md#recovery-and-auxiliary-workflow-acceptance-2026-11-23)还覆盖了 Apply 与部分 Archive 原生取消后新会话恢复,以及注入原生 context hook 故障后阻断依赖派发。完整生产业务项目、无人干预时的协议遵守与完整 TUI/桌面 UI 验收仍未完成;已覆盖范围见[定向终端 UI 验收](../helixharness/opencode/tests/README.md#targeted-terminal-ui-acceptance-2026-11-23)。Workspace Apply 的 `may_delegate` RepoJob 使用 `helix-worker`,需要 `experimental.subagent_depth >= 2`;独立 reviewer 保持只读 leaf。深度不足时阻塞该 RepoJob,不得绕过评审。 + +OpenCode 适配使用原生工具和会话 Hook,但未提供等价的 SessionStart/Stop/失败/会话结束业务保证。任务跟踪通过 `scripts/task_plan.py` 原子更新同一份 `tasks.md`。统计在明确授权后记录阶段事实和工作流轨迹,不采集原始会话,token 和未观察到的工具次数保持未知。`/helix:update` 对有明确 Git upstream 的干净源码安装执行既有确认协议,锁定 commit 并仅快进;有本地修改、游离版本或包管理安装时不自动更新。Init 合并 `AGENTS.md`,不创建 `.opencode/` settings;插件在原生 write/edit/patch 成功后执行已有项目巡检,shell 修改仍需显式检查。d-d2c 的 Claude skill-scoped Stop/PreToolUse guard 不执行,采用无 hook / `--bare` 语义,仍须遵守用户决策、视觉验收和完成门禁。 ## 独立性与数据边界 diff --git a/examples/README.md b/examples/README.md index 7280487..53f8893 100644 --- a/examples/README.md +++ b/examples/README.md @@ -23,14 +23,14 @@ The baseline has two passing tests. It returns all titles but does not yet accep ## 2. Run HelixHarness -Open Codex, Claude Code, Cursor or OpenCode (Preview) in the `$TASK_FILTER_DEMO` directory (run `pwd` in that terminal to see its path) and enter: +Open Codex, Claude Code, Cursor or [OpenCode (macOS Stable)](../docs/opencode-testing.md) in the `$TASK_FILTER_DEMO` directory (run `pwd` in that terminal to see its path) and enter: ```text /helix:init /helix:propose task-filter ./requirements/task-filter.md --loop ``` -Cursor uses `/helix-init` and `/helix-propose` with the same arguments. OpenCode v2.2.2+ uses the `/helix:` commands above; its support is Preview and this walkthrough does not establish real-model acceptance. OpenCode has no project hooks or telemetry; Init merges `AGENTS.md` and the telemetry choice does not apply. See the [OpenCode limits](../helixharness/hosts/opencode/installer.md). +Cursor uses `/helix-init` and `/helix-propose` with the same arguments. OpenCode 2.3.2 on macOS uses the `/helix:` commands above, within the [Stable support matrix](../docs/opencode-testing.md); 2.2.2 and 2.3.0 have automated compatibility coverage only. This walkthrough does not establish real-model acceptance. OpenCode has no project hooks or telemetry; Init merges `AGENTS.md` and the telemetry choice does not apply. See the [OpenCode limits](../helixharness/hosts/opencode/installer.md). On hosts supporting hooks, allow the host's project-hook setup when prompted. For this example, choose telemetry **off** if asked. Review the proposed requirement boundaries and answer any clarification in the conversation. @@ -64,6 +64,6 @@ This is a reproducible walkthrough, not a pre-recorded model run. No generated S ## 中文操作说明 -按第一步复制起始项目到独立临时目录并建立 Git 基线,两个基础测试应通过。在该业务目录打开宿主,依次执行 Init 和上面的 Propose 命令;Cursor 将 `/helix:` 前缀换为 `/helix-`。OpenCode v2.2.2+ 为预览支持,不生成项目 hooks、不采集统计,沿用 `/helix:`;本示例不代表已完成真实模型验收。支持统计的宿主可关闭统计,不需要平台地址。 +按第一步复制起始项目到独立临时目录并建立 Git 基线,两个基础测试应通过。在该业务目录打开宿主,依次执行 Init 和上面的 Propose 命令;Cursor 将 `/helix:` 前缀换为 `/helix-`。macOS 上 OpenCode 2.3.2 按 [Stable 支持矩阵](../docs/opencode-testing.md)沿用 `/helix:`;2.2.2、2.3.0 仅有自动化兼容覆盖。不生成项目 hooks、不采集统计;本示例不代表已完成真实模型验收。支持统计的宿主可关闭统计,不需要平台地址。 检查需求是否保留六条验收标准,Apply 是否实现筛选并补充测试、评审,Archive 是否生成完整的 completed 工件。最后运行基础测试和独立验收脚本。起始代码运行独立验收会失败,这是因为筛选需求尚未实现;不要把教程中的预期工件当作已经发生的模型执行记录。 diff --git a/helixharness/.claude-plugin/marketplace.json b/helixharness/.claude-plugin/marketplace.json index 9c68a46..d9d4f4c 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, Codex, Cursor and OpenCode (Preview)" + "description": "Plugin marketplace for the HelixHarness repository, exposing the helixharness workflow plugin for Claude Code, Codex, Cursor and OpenCode (macOS 2.3.2 Stable)" }, "plugins": [ { "name": "helix", - "description": "HelixHarness workflow plugin for Claude Code, Codex, Cursor and OpenCode (Preview) with commands and reusable skills", + "description": "HelixHarness workflow plugin for Claude Code, Codex, Cursor and OpenCode (macOS 2.3.2 Stable) with commands and reusable skills", "source": ".", "version": "1.0.0" } diff --git a/helixharness/PLUGIN_USAGE.md b/helixharness/PLUGIN_USAGE.md index 89dcab8..c41a686 100644 --- a/helixharness/PLUGIN_USAGE.md +++ b/helixharness/PLUGIN_USAGE.md @@ -1,6 +1,6 @@ # HelixHarness -面向 Codex、Claude Code、Cursor 与 OpenCode(预览)的 HelixHarness 研发工作流。通过项目约束、知识库、Spec、任务和验证证据完成研发。 +面向 Codex、Claude Code、Cursor 与 [OpenCode(macOS Stable)](../docs/opencode-testing.md)的 HelixHarness 研发工作流。通过项目约束、知识库、Spec、任务和验证证据完成研发。 ## 命令 @@ -19,11 +19,13 @@ ## 安装 -需要 Python 3.10+、Git,以及 Codex、Claude Code、Cursor 或 OpenCode(v2.2.2+)。Codex、Claude Code 可将本目录作为本地 marketplace 添加;Cursor 通过市场界面安装。宿主步骤见 [Codex](hosts/codex/installer.md)、[Claude Code](hosts/claude-code/installer.md)、[Cursor](hosts/cursor/installer.md) 和 [OpenCode](hosts/opencode/installer.md) 安装说明。OpenCode 将本插件目录加入 `plugins` 数组。 +需要 Python 3.10+、Git,以及 Codex、Claude Code、Cursor 或 OpenCode(macOS、2.3.2;见[支持矩阵](../docs/opencode-testing.md))。Codex、Claude Code 可将本目录作为本地 marketplace 添加;Cursor 通过市场界面安装。宿主步骤见 [Codex](hosts/codex/installer.md)、[Claude Code](hosts/claude-code/installer.md)、[Cursor](hosts/cursor/installer.md) 和 [OpenCode](hosts/opencode/installer.md) 安装说明。OpenCode 将本插件目录加入 `plugins` 数组。 -**OpenCode 预览支持(v2.2.2+):** 插件注册原生 `helix:` 命令、`helix-` 方法 Skill 和 `helix-` 角色,将 Host Context 绑定到当前仓库和会话。完整 Init → Propose → Apply → Archive 流程尚未完成真实模型验收。Workspace Apply 的 `may_delegate` RepoJob 使用 `helix-worker`,需要 `experimental.subagent_depth >= 2`;独立 reviewer 保持只读 leaf。深度不足时阻塞该 RepoJob,不得绕过评审。 +**OpenCode Stable 支持(macOS、2.3.2):** 当前源码候选的支持范围与边界见[支持矩阵](../docs/opencode-testing.md)。OpenCode 2.2.2、2.3.0 仅有自动化兼容覆盖。 -OpenCode 没有原生 SessionStart/Stop/失败/会话结束 hooks,也没有原生计划工具(计划写入 `tasks.md`)。统计不支持(`unsupported_host`);`/helix:update` 返回 `continue_silently`,请通过 OpenCode 插件管理手动更新。项目 hooks 不支持:Init 只合并 `AGENTS.md`,不创建 `.opencode/` settings。d-d2c 的 Claude skill-scoped Stop/PreToolUse guard 不执行,采用无 hook / `--bare` 语义,仍须遵守用户决策、视觉验收和完成门禁。 +插件注册原生 `helix:` 命令、`helix-` 方法 Skill 和 `helix-` 角色。命令、原生 `skill` 工具结果、Skill mention 与原生 Skill 激活均按请求会话绑定仓库目录;会话查询或目录校验失败时阻断未绑定的 Skill 正文。2026-11-20 已在 OpenCode 2.3.2 + DeepSeek 上完成一次合成单仓 Init → Propose → Apply → Archive 真实模型闭环,包含操作者确认和一次受控合同修订;2026-11-23 又完成了 OpenCode 2.3.2 + DeepSeek 的操作者辅助合成双仓 Workspace 与独立 UT 验证;后续已修复 UT 分类校验与原子发布保护,并通过无纠正提醒的真实模型复验。[合成 Workspace 的专项真实模型验证](opencode/tests/README.md#recovery-and-auxiliary-workflow-acceptance-2026-11-23)还覆盖了 Apply 与部分 Archive 原生取消后新会话恢复,以及注入原生 context hook 故障后阻断依赖派发。完整生产业务项目、无人干预时的协议遵守与完整 TUI/桌面 UI 验收仍未完成;已覆盖范围见[定向终端 UI 验收](opencode/tests/README.md#targeted-terminal-ui-acceptance-2026-11-23)。Workspace Apply 的 `may_delegate` RepoJob 使用 `helix-worker`,需要 `experimental.subagent_depth >= 2`;独立 reviewer 保持只读 leaf。深度不足时阻塞该 RepoJob,不得绕过评审。 + +OpenCode 适配使用原生工具和会话 Hook,但未提供等价的 SessionStart/Stop/失败/会话结束业务保证。任务跟踪通过 `scripts/task_plan.py` 原子更新同一份 `tasks.md`。统计在明确授权后记录阶段事实和工作流轨迹,不采集原始会话,token 和未观察到的工具次数保持未知。`/helix:update` 对有明确 Git upstream 的干净源码安装执行既有确认协议,锁定 commit 并仅快进;有本地修改、游离版本或包管理安装时不自动更新。Init 合并 `AGENTS.md`,不创建 `.opencode/` settings;插件在原生 write/edit/patch 成功后执行已有项目巡检,shell 修改仍需显式检查。d-d2c 的 Claude skill-scoped Stop/PreToolUse guard 不执行,采用无 hook / `--bare` 语义,仍须遵守用户决策、视觉验收和完成门禁。 ## 项目结构 diff --git a/helixharness/README.md b/helixharness/README.md index 1053485..285cf4d 100644 --- a/helixharness/README.md +++ b/helixharness/README.md @@ -2,7 +2,7 @@ 当前版本:**1.0.0**。 -面向 Codex、Claude Code、Cursor 与 OpenCode(预览)的 HelixHarness 研发工作流。通过项目约束、知识库、Spec、任务和验证证据完成研发。 +面向 Codex、Claude Code、Cursor 与 [OpenCode(macOS Stable)](../docs/opencode-testing.md)的 HelixHarness 研发工作流。通过项目约束、知识库、Spec、任务和验证证据完成研发。 ## 命令 @@ -21,11 +21,13 @@ ## 安装 -需要 Python 3.10+、Git,以及 Codex、Claude Code、Cursor 或 OpenCode(v2.2.2+)。Codex、Claude Code 可将本目录作为本地 marketplace 添加;Cursor 通过市场界面安装。宿主步骤见 [Codex](hosts/codex/installer.md)、[Claude Code](hosts/claude-code/installer.md)、[Cursor](hosts/cursor/installer.md) 和 [OpenCode](hosts/opencode/installer.md) 安装说明。OpenCode 将本插件目录加入 `plugins` 数组。 +需要 Python 3.10+、Git,以及 Codex、Claude Code、Cursor 或 OpenCode(macOS、2.3.2;见[支持矩阵](../docs/opencode-testing.md))。Codex、Claude Code 可将本目录作为本地 marketplace 添加;Cursor 通过市场界面安装。宿主步骤见 [Codex](hosts/codex/installer.md)、[Claude Code](hosts/claude-code/installer.md)、[Cursor](hosts/cursor/installer.md) 和 [OpenCode](hosts/opencode/installer.md) 安装说明。OpenCode 将本插件目录加入 `plugins` 数组。 -**OpenCode 预览支持(v2.2.2+):** 插件注册原生 `helix:` 命令、`helix-` 方法 Skill 和 `helix-` 角色,将 Host Context 绑定到当前仓库和会话。完整 Init → Propose → Apply → Archive 流程尚未完成真实模型验收。Workspace Apply 的 `may_delegate` RepoJob 使用 `helix-worker`,需要 `experimental.subagent_depth >= 2`;独立 reviewer 保持只读 leaf。深度不足时阻塞该 RepoJob,不得绕过评审。 +**OpenCode Stable 支持(macOS、2.3.2):** 当前源码候选的支持范围与边界见[支持矩阵](../docs/opencode-testing.md)。OpenCode 2.2.2、2.3.0 仅有自动化兼容覆盖。 -OpenCode 没有原生 SessionStart/Stop/失败/会话结束 hooks,也没有原生计划工具(计划写入 `tasks.md`)。统计不支持(`unsupported_host`);`/helix:update` 返回 `continue_silently`,请通过 OpenCode 插件管理手动更新。项目 hooks 不支持:Init 只合并 `AGENTS.md`,不创建 `.opencode/` settings。d-d2c 的 Claude skill-scoped Stop/PreToolUse guard 不执行,采用无 hook / `--bare` 语义,仍须遵守用户决策、视觉验收和完成门禁。 +插件注册原生 `helix:` 命令、`helix-` 方法 Skill 和 `helix-` 角色。命令、原生 `skill` 工具结果、Skill mention 与原生 Skill 激活均按请求会话绑定仓库目录;会话查询或目录校验失败时阻断未绑定的 Skill 正文。2026-11-20 已在 OpenCode 2.3.2 + DeepSeek 上完成一次合成单仓 Init → Propose → Apply → Archive 真实模型闭环,包含操作者确认和一次受控合同修订;2026-11-23 又完成了 OpenCode 2.3.2 + DeepSeek 的操作者辅助合成双仓 Workspace 与独立 UT 验证;后续已修复 UT 分类校验与原子发布保护,并通过无纠正提醒的真实模型复验。[合成 Workspace 的专项真实模型验证](opencode/tests/README.md#recovery-and-auxiliary-workflow-acceptance-2026-11-23)还覆盖了 Apply 与部分 Archive 原生取消后新会话恢复,以及注入原生 context hook 故障后阻断依赖派发。完整生产业务项目、无人干预时的协议遵守与完整 TUI/桌面 UI 验收仍未完成;已覆盖范围见[定向终端 UI 验收](opencode/tests/README.md#targeted-terminal-ui-acceptance-2026-11-23)。Workspace Apply 的 `may_delegate` RepoJob 使用 `helix-worker`,需要 `experimental.subagent_depth >= 2`;独立 reviewer 保持只读 leaf。深度不足时阻塞该 RepoJob,不得绕过评审。 + +OpenCode 适配使用原生工具和会话 Hook,但未提供等价的 SessionStart/Stop/失败/会话结束业务保证。任务跟踪通过 `scripts/task_plan.py` 原子更新同一份 `tasks.md`。统计在明确授权后记录阶段事实和工作流轨迹,不采集原始会话,token 和未观察到的工具次数保持未知。`/helix:update` 对有明确 Git upstream 的干净源码安装执行既有确认协议,锁定 commit 并仅快进;有本地修改、游离版本或包管理安装时不自动更新。Init 合并 `AGENTS.md`,不创建 `.opencode/` settings;插件在原生 write/edit/patch 成功后执行已有项目巡检,shell 修改仍需显式检查。d-d2c 的 Claude skill-scoped Stop/PreToolUse guard 不执行,采用无 hook / `--bare` 语义,仍须遵守用户决策、视觉验收和完成门禁。 ## 独立方案探索与调试 diff --git a/helixharness/agents/unit-test-worker.md b/helixharness/agents/unit-test-worker.md index 99d7838..b08d7b5 100644 --- a/helixharness/agents/unit-test-worker.md +++ b/helixharness/agents/unit-test-worker.md @@ -2,6 +2,9 @@ description: "单测 worker agent。由 /helix:ut 调用,负责处理单个类的完整单元测试维护。包含 Ralph Loop 6 阶段完整执行、经验库复用、缺陷发现、覆盖率达标保证。" --- +> **工件与分类门禁**:首个业务写入前完整读取 `reference/ut-artifact-protocol.md`。最终必须通过 `scripts/ut_artifacts.py findings` 生成自己的分类 JSON 与 defects 报告,再通过 write 原子发布 result。只有有规范/机械失败依据和实际反例的 confirmed_defect 计缺陷;未确认风险与改进分别保留,不能混算或据此高危退出。 + + # unit-test-worker 执行手册 ## 文档摘要 @@ -259,7 +262,7 @@ Loop 执行状态在内存中跟踪(见 §2.2),关键规则: 1. 验证 Bash 权限:执行 `echo "permission test"` 2. 验证 Write/Read/Delete 权限:使用父流程传入的 `{WorkerTempPath}`,先执行下方 §4.2.2 的本 Worker 目录准备,再在该目录内创建唯一命名的临时文件,验证读写删除。后续构建与清理始终使用同一路径,不重新解析系统临时目录。若未传入绝对路径,返回父流程补齐参数,不自行回退到其他目录。 3. 验证项目目录 Write 权限:在 `docs/specs/active/{feature}/` 下创建临时文件,验证读写删除 -4. 确认业务写域边界(自检声明,不做物理写入试探):主项目 sandbox 实际允许写入(Loop 4 同步测试文件需要),「主项目只读」是业务约束而非宿主边界。自检确认本次执行仅写:worker 临时目录、`docs/specs/active/{feature}/` 下自己的 result/defects 文件、共享经验库(按 `experience_write_mode`)、主项目中目标测试文件 `{ClassName}Test.java`;除此之外主项目任何路径一律不写 +4. 确认业务写域边界(自检声明,不做物理写入试探):主项目 sandbox 实际允许写入(Loop 4 同步测试文件需要),「主项目只读」是业务约束而非宿主边界。自检确认本次执行仅写:worker 临时目录、`docs/specs/active/{feature}/` 下自己的 result/defects/findings JSON 及同名 `.tmp` staging 文件、共享经验库(按 `experience_write_mode`)、主项目中目标测试文件 `{ClassName}Test.java`;除此之外主项目任何路径一律不写 5. 任何验证失败:立即写入失败结果文件,说明阻断点,追加 `权限托管异常,请重新运行 /helix:ut` #### 4.2.2 前置清理与检查 @@ -279,6 +282,11 @@ Loop 执行状态在内存中跟踪(见 §2.2),关键规则: 5. 仅编译测试:worker 的构建只编译 `src/test/java`,被测类通过外部引用 6. 版本一致:所有依赖版本、插件版本与主项目严格一致 +父流程必须附入本轮 `ut_precompile.py` 的 `status=compile_ready`、`ready=true` 回执和 +`class_directories` 实际路径。旧 class 目录存在不是源码已编译的证明;缺失回执或发现预编译后 +目标源码已变化时返回父流程重新预编译,Worker 不自行在主项目编译,也不把旧字节码当成本轮实现。 +该回执只证明主源码编译就绪,不能替代本 Worker 的测试、覆盖率或最终统一验证。 + **执行步骤**: 1. **复用父流程传入的临时目录**: @@ -396,7 +404,7 @@ Loop 0 完成:已理解 {ClassName} 按格式记录缺陷到内存,缺陷统一记录规则: - Loop 1 和 Loop 3 发现的缺陷都写入同一内存清单 -- 最终合并后写入 `worker-{ID}-defects.md` +- 最终按 `reference/ut-artifact-protocol.md` 发布 `worker-{ID}-findings.json`,由脚本生成 `worker-{ID}-defects.md`;缺陷总数只取 normalized confirmed_defect 数。 - High 缺陷触发提前退出流程,Medium/Low 记录后继续 **缺陷记录格式**: @@ -760,11 +768,11 @@ Loop 4 完成:{ClassName} 覆盖率达标与文件同步 - 如有多次重试循环:只需要保留最后一次完整循环的证据,或者保留关键的补充用例部分 6. 完整性检查通过后才能继续下一步 -#### 9.3.2 第 1 步:向独立缺陷文件写入缺陷(如发现缺陷) +#### 9.3.2 第 1 步:发布分类记录(无观察也必须执行) -- 如 Loop 1 和 Loop 3 中发现了任何缺陷: - - 创建/覆盖独立缺陷文件 `worker-{ID}-defects.md` - - 写入本类发现的缺陷(标记类名、方法名、缺陷描述、严重程度、处理状态"已记录,待后续处理") +- 将 Loop 1/3 观察按 confirmed_defect / unconfirmed_risk / optional_improvement 记录到自己的 findings.json.tmp;无观察也写空列表。 +- 运行 `ut_artifacts.py findings`,检查退出码和 normalized counts。脚本生成分类 JSON 与 defects.md;不直接 Write 两个最终文件。 +- result 与 final 中的缺陷数只使用 confirmed_defect;分别报告风险和建议,不能使用被自动降级前的提议数。 #### 9.3.3 第 2 步:按适配模式沉淀新经验(如解决了新问题) @@ -960,11 +968,11 @@ Loop 5 完成:{ClassName} 结果报告与完整性检查 写文件必须按以下顺序,确保 ut.md 能正确检测状态: -1. **第 1 步**:如有缺陷 → 写入 `worker-{ID}-defects.md` +1. **第 1 步**:发布 `worker-{ID}-findings.json` 与脚本生成的 `worker-{ID}-defects.md`(空观察也执行) 2. **第 2 步**:如有新经验 → 按 `experience_write_mode` 锁追加或加入 final 经验候选 3. **第 3 步**:**最后写入** `worker-{ID}-result.md`(无论成功或失败),**必须使用原子写协议**: - 先写入临时文件 `worker-{ID}-result.md.tmp` - - 再 `mv` 原子重命名为 `worker-{ID}-result.md` + - 按 `reference/ut-artifact-protocol.md` 运行 `ut_artifacts.py write --name worker-{ID}-result.md --source ...`,由脚本 fsync + 原子 replace 发布 - **严禁**直接 Write 到目标文件(父流程在原生终态后读取 result,非原子写入可能暴露不完整证据) ### 12.2 结果文件必选规则 diff --git a/helixharness/commands/status.md b/helixharness/commands/status.md index 2056c5e..452b6cd 100644 --- a/helixharness/commands/status.md +++ b/helixharness/commands/status.md @@ -31,9 +31,31 @@ $ARGUMENTS 按实际参数追加 `--feature "{feature}"`、`--completed`,安全传参;只运行当前插件捆绑脚本。默认列出全部 active,不启动 Router 或其他命令。 +## 输出 + +展示内容只来自本次脚本回执及已绑定仓库,不补写脚本未检查的目录、推测原因或额外操作建议。 +先按本次回执选择以下唯一输出分支;不沿用会话中先前的结果或操作建议。 + +### 空结果:`empty=true` + +最终回复只输出以下三项,替换查询范围后结束本命令: + +```text +查询范围:{已绑定仓库及本次实际查询范围}。 +结果:当前查询范围内没有需求。 +依据已有工件检查,未重跑测试和模型评审。 +``` + +查询范围只描述本次已执行查询的 active/completed 范围及可选 feature,不列其他查询方式。 +此分支不展示表格、占位需求行、建议命令、命令示例、其他筛选参数或后续操作段落,也不追加追问。 + +### 非空结果:`empty=false` + 用结构化输出展示简洁表格:需求、执行范围、记录阶段、已完成/总任务数、问题、建议命令。Workspace 展示各参与仓库的进度与依赖,不以根 Spec 状态替代子仓事实。 +建议命令只取各行非空的 `next_command`;值为 null 时不生成替代建议。 +所有行都没有非空 `next_command` 时,省略建议命令列和后续操作段落,不补充命令示例或其他筛选方式。 +不引导执行 Bug Fix 创建需求;Bug Fix 只修订既有 active 单仓需求。 -- `empty=true`:说明查询范围内没有需求,不擅自 Init 或新建需求。 - `tasks=null`:展示“尚无任务数据/不适用”,不能当作 0/0 完成。 - `issues` 是实际检查发现的问题;`blocked_tasks` 只展示工件记录的任务与依赖,不编造阻塞原因。 - `next_command` 是建议,不执行。存在问题时先说明需要处理的问题,不能把建议称为已通过所有执行门禁。 diff --git a/helixharness/commands/ut.md b/helixharness/commands/ut.md index 93f3512..690ce27 100644 --- a/helixharness/commands/ut.md +++ b/helixharness/commands/ut.md @@ -20,6 +20,8 @@ description: "单元测试生成与维护命令。基于知识库和活跃需求 $ARGUMENTS ``` +> **工件门禁**:首次写入 UT 文件前完整读取 `reference/ut-artifact-protocol.md`。所有状态初始化/更新通过绑定插件的 `scripts/ut_artifacts.py` 原子发布;分类记录及缺陷汇总由该脚本生成,不由模型自由计数或直接覆盖。 + ## 参数说明 > 本命令支持两种入口:**显式参数入口**(`--packages` 与 `--concurrency` 一次给齐)和**交互补全入口**。 @@ -257,7 +259,7 @@ Phase 0-1:项目完整知识库加载 #### 4.1.5 检查项目测试基础设施 -**推导项目名**:当前工作目录 basename,替换特殊字符为 `-`,转小写 +**推导项目名**:当前工作目录 basename 转小写,再将 `[a-z0-9._-]` 之外的字符逐个替换为 `-`;与 `ut_artifacts.py` 的证据根解析一致 **全新开始时**:清理跨平台临时目录中的残留 worker 目录(保留共享缓存) 检查内容:项目类型、测试框架、Lombok 配置、测试目录结构、覆盖率配置 @@ -265,15 +267,35 @@ Phase 0-1:项目完整知识库加载 #### 4.1.6 预编译主项目(所有模块) **强制执行**:无论任何执行模式,进入 Phase 1 前必须确保主项目已预编译 -**继续执行/增量补充快速路径**:验证编译产物目录存在,存在则跳过,否则重新编译 +全新开始、继续执行和增量补充每轮都必须调用当前构建工具核验源码新鲜度;旧产物目录存在 +不能证明新增包或改动源码已经编译,不得据此跳过构建。 **目标**:预编译所有模块主源码,避免每个 worker 重复编译;**同时提前发现并解决Java版本等环境级问题**,确保worker启动后环境可用。 -**只编译主源码,不编译测试**: -- Gradle:`./gradlew clean classes --no-daemon --no-parallel --no-watch-fs -q`(如无 wrapper 则使用 `gradle`) -- Maven:`./mvnw clean compile --batch-mode -q`(如无 wrapper 则使用 `mvn`) +执行确定性门禁(只编译主源码,不编译测试): + +```bash +{helix_python} "{plugin_root}/scripts/ut_precompile.py" --repo-root "{MainProjectPath}" +``` -验证:检查 `build/classes/java/main` 或 `target/classes` 目录存在 +脚本从根 `build.gradle(.kts)` / `settings.gradle(.kts)` 或 `pom.xml` 确定构建工具,优先执行主项目 +绝对路径 wrapper,无 wrapper 才使用当前环境的系统工具;不复制或修改 wrapper、构建配置和业务源码。 +Gradle 每次执行 `classes --no-daemon --no-parallel --no-watch-fs -q`,Maven 每次执行 +`compile --batch-mode -q`,由构建工具检查源码、依赖和构建配置的新鲜度;不执行 `clean`, +保留已有测试源码和运行产物。必须同时检查命令退出码和实际 `build/classes/{java,kotlin,groovy}/main` / +`target/classes` 输出目录。无额外参数时只校验根项目的标准输出,JSON 标记 +`class_directory_scope=standard_root_only`,不递归搜索示例、历史目录或猜测活跃模块。 +多模块或自定义布局时,父流程从当前已读取的构建配置和项目结构确认本次活跃模块及其实际 main 输出, +为每个所需输出追加一个 `--class-directory "{repo-relative-or-absolute-directory}"`; +例如 `--class-directory "api/target/classes" --class-directory "service/target/classes"`。 +脚本要求这些明确指定的目录全部位于项目根内、不经过符号链接且在构建成功后存在, +以 `class_directory_scope=explicit` 返回。无法确认活跃模块/实际输出时停止,不递归搜到旧目录后继续, +也不声称已自动核验所有模块覆盖。只把本轮 JSON 的 `class_directories` 实际列表传给 worker。 + +只有本轮脚本退出码为 0 且 JSON `status=compile_ready`、`ready=true` 才能进入新 worker 派发。 +`ready=false`、非零退出、构建工具缺失/冲突或输出目录缺失时,保留 `stdout` / `stderr` 诊断并停止; +不得启动新 worker,不得复用旧 class 目录掩盖编译失败,也不修改业务源码或构建配置来绕过门禁。 +主源码编译就绪不是测试通过;所有原有 worker 测试、覆盖率和 Phase 2-5 统一验证仍须执行。 **关键责任**: - Phase 0 预编译是确保 worker 环境可用的第一道防线 @@ -514,9 +536,12 @@ Phase 0-1:项目完整知识库加载 | 分支 | 操作 | |------|------| -| **继续执行** | 确保目录存在,验证主项目编译产物存在(缺失则重新执行 §4.1.6 预编译),托管权限,验证已有文件完整性,确定下一个 Worker ID | -| **全新开始** | 确保目录存在,会话文件已创建,初始化共享经验库;仅 `child_locked_append` 按 §7 确保锁目录不存在,`parent_finalize` 不检查、不创建、不删除锁。初始化空主结果文件,初始化任务队列,执行 §4.1.6 预编译,托管权限 | -| **增量补充** | 确保目录存在,验证主项目编译产物存在(缺失则重新执行 §4.1.6 预编译),托管权限,验证已有文件完整性,确定下一个 Worker ID | +| **继续执行** | 确保目录存在,复用本轮 §4.1.6 `compile_ready` 回执,托管权限,验证已有文件完整性,确定下一个 Worker ID | +| **全新开始** | 确保目录存在,会话文件已创建,初始化共享经验库;仅 `child_locked_append` 按 §7 确保锁目录不存在,`parent_finalize` 不检查、不创建、不删除锁。初始化空主结果文件,初始化任务队列,复用本轮 §4.1.6 `compile_ready` 回执,托管权限 | +| **增量补充** | 确保目录存在,复用本轮 §4.1.6 `compile_ready` 回执,托管权限,验证已有文件完整性,确定下一个 Worker ID | + +本轮回执缺失、或预编译之后源码/依赖/构建配置发生变化时,先重新执行 §4.1.6; +上下文恢复不能只检查旧 class 目录,新 worker 启动前仍须有当前输入的编译就绪事实。 **关键**:权限托管必须执行(见 §5) @@ -649,7 +674,8 @@ Agent( - 主项目路径:{MainProjectPath} - 系统临时目录:{系统临时目录的绝对路径} - Worker 临时目录:{WorkerTempPath}(父流程解析的 `{系统临时目录}/{ProjectName}/worker-{ID}/` 绝对路径) -- 主项目编译产物路径:{MainProjectPath}/build/classes/java/main 或 {MainProjectPath}/target/classes +- 本轮主项目预编译回执:{ut_precompile.py 的 compile_ready JSON,含实际命令与退出码} +- 主项目编译产物路径:{回执 class_directories 中的实际绝对路径列表,含子模块} - 共享经验库路径:docs/specs/active/{feature}/unittest-experience.md - 共享经验库锁目录:docs/specs/active/{feature}/unittest-experience.lock(`child_locked_append` 使用; `parent_finalize` 只把它列为 forbidden scope,不检查、不创建、不删除) @@ -716,16 +742,16 @@ Agent( #### 4.3.4 Phase 2-4:汇总所有 worker 输出 **执行步骤(单线程)**: -1. **先收集缺陷文件**:按 Worker ID 顺序检查 `worker-{ID}-defects.md`,存在则读取并暂存 +1. **先收集分类记录**:按 Worker ID 读取 `worker-{ID}-findings.json` 和脚本生成的 `worker-{ID}-defects.md`;新 worker 无观察也要求空 observations JSON。旧会话/超时代写缺少分类时按 `reference/ut-artifact-protocol.md` 保留原记录并标为分类未核验,counts=null,不能算零;JSON 损坏/身份不合法,或 result 与有效分类均不存在时阻断,不能以模型手写缺陷数替代。 2. **再收集结果文件**:按 Worker ID 顺序读取所有 `worker-{ID}-result.md` 3. **超时结果核验**:对队列中 `备注` 含 `timeout` 的任务,重新读取 result 文件首行,如 worker 已覆盖为成功/失败,以 worker 最新结果为准,并通过原子写协议更新队列中对应行的状态为 `completed` 或 `failed`,清除 `备注` 中的 `timeout`;即使仍为超时,也要检查 defects.md 是否存在 4. **重试记录去重**:对存在重试关系的任务(队列 `备注` 列含 `retry:N|orig:W{ID}`),按类名分组: - 同一类存在多条记录时,仅保留最终态的任务结果进入主文件(优先级:`completed` > `failed`) - 被去重的行在队列 `备注` 中追加 `(已归档)`,不在主结果文件中重复出现 - Worker 输出文件(result + defects)均按最终态 Worker ID 引用,原始失败 Worker 的文件在归档步骤中一并处理 -5. 汇总写入:将去重后的结果和缺陷汇总写入主文件 +5. 汇总写入:按 `reference/ut-artifact-protocol.md` 对去重后的最终 Worker ID 运行 `ut_artifacts.py aggregate`,在临时证据清理前生成主分类报告;results/summary 的缺陷/风险/建议三类数字取其返回 counts,分别统计,不混算。其他主文件通过 `ut_artifacts.py write` 原子发布。 6. 经验库校验:`child_locked_append` 读取 `unittest-experience.md` 并统计本次已追加经验;`parent_finalize` 先校验各 worker final 的有界经验候选,再由父流程串行、去重、原子合并后统计 -7. 归档 worker 文件:将已汇总的 worker 文件(含被去重的原始失败文件)重命名为 `archived-worker-*.md` +7. 归档 worker 文件:将已汇总的 worker 文件(含被去重的原始失败文件)重命名为 `archived-worker-*.md`;同时归档对应 `worker-*-findings.json`,保留扩展名 8. `child_locked_append` 按 §7 清理符合条件的残留锁目录(使用跨平台删除方式);`parent_finalize` 不检查、不创建、不删除任何经验锁 #### 4.3.5 Phase 2-5:主项目统一验证(串行) @@ -814,7 +840,7 @@ ownership 可验证的配置或临时授权,不删除用户已有配置,并 2. 再 `mv` 原子重命名为目标文件名 3. 如目标文件已存在,根据场景决定是跳过还是覆盖 -**适用文件**:`unittest-queue.md`、`unittest-session.md`、`worker-{ID}-result.md`(ut.md 超时代写时)、主结果文件 +**适用文件**:`unittest-queue.md`、`unittest-session.md`、共享经验、`worker-{ID}-result.md`(含 ut.md 超时代写)、所有主结果报告。包括首次空表和最后完成状态,统一按 `reference/ut-artifact-protocol.md` 的 `ut_artifacts.py write` 发布;分类 JSON/defects 用 findings/aggregate 生成。不能只对队列或经验库执行。 ### 6.3 任务状态机 diff --git a/helixharness/hosts/codex/ut.md b/helixharness/hosts/codex/ut.md index 177e1af..f2f9604 100644 --- a/helixharness/hosts/codex/ut.md +++ b/helixharness/hosts/codex/ut.md @@ -28,9 +28,9 @@ permission_cleanup: not_required |---|---| | `prompt_source` | `agents/unit-test-worker.md`,worker 首个业务动作前完整读取 | | `depends_on` | 目标测试路径或共享 fixture 写域冲突时依赖前一 job | -| `write_scope` | worker 临时目录、自己的 result/defects、唯一目标测试文件 | +| `write_scope` | worker 临时目录、自己的 result/defects/findings JSON 及同名 `.tmp` staging、唯一目标测试文件 | | `forbidden_scope` | 业务源码、构建配置、共享 queue/session/summary/experience、其他 worker 路径 | -| `expected_artifacts` | result;成功时目标测试文件;有缺陷时 defects | +| `expected_artifacts` | result、findings JSON 与生成的分类 defects;成功时目标测试文件 | | `validation` | 原生终态、公共 final、写域、结果结构、6 Loop、测试和覆盖率 | | `unavailable_fallback` | 仅确认子代理能力不可用时,父流程按同一 prompt 串行内联 | diff --git a/helixharness/hosts/cursor/d2c_gate.cjs b/helixharness/hosts/cursor/d2c_gate.cjs index 593bb99..7d3fc60 100644 --- a/helixharness/hosts/cursor/d2c_gate.cjs +++ b/helixharness/hosts/cursor/d2c_gate.cjs @@ -1,163 +1,7 @@ #!/usr/bin/env node 'use strict' -// Explicit Cursor gate: check this invocation's checkpoint, never read transcripts. -const fs = require('fs') -const path = require('path') -const { decideStop, isHeadlessEnv } = require('../../skills/d-d2c/scripts/lib/d2c-workflow-guard-core.cjs') - -function within(root, candidate) { - const relative = path.relative(root, candidate) - return relative !== '' && relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative) -} - -function readInside(root, candidate, optional = false) { - if (optional && !fs.existsSync(candidate)) return null - const real = fs.realpathSync(candidate) - if (!within(root, real)) throw new Error('checkpoint path escapes its state directory') - const value = JSON.parse(fs.readFileSync(real, 'utf8')) - if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('checkpoint must be an object') - return value -} - -function parseArgs(argv) { - const args = { headless: false } - const values = new Set(['--repo-root', '--page-dir', '--started-at', '--action', '--session-id']) - for (let index = 0; index < argv.length; index += 1) { - const key = argv[index] - if (key === '--headless' && !args.headless) { - args.headless = true - } else if (values.has(key) && !Object.prototype.hasOwnProperty.call(args, key) && argv[index + 1] && !argv[index + 1].startsWith('--')) { - args[key] = argv[++index] - } else { - throw new Error(`invalid or duplicate argument: ${key}`) - } - } - for (const key of ['--repo-root', '--page-dir', '--started-at', '--action']) { - if (!args[key]) throw new Error(`required argument: ${key}`) - } - if (!['stop', 'ask'].includes(args['--action'])) throw new Error('action must be stop or ask') - if (!Number.isFinite(Date.parse(args['--started-at']))) throw new Error('started-at must be a timestamp') - return args -} - -function timestamp(value) { - return typeof value === 'string' ? Date.parse(value) : NaN -} - -function currentInvocationState(state, startedAt) { - const phases = {} - for (const phase of [0, 1, 2, 3, 4, 6]) { - const entry = state.phases[phase] - if (!entry || !Number.isFinite(timestamp(entry.enteredAt)) || timestamp(entry.enteredAt) < startedAt) continue - if (entry.status === 'completed' && (!Number.isFinite(timestamp(entry.completedAt)) || timestamp(entry.completedAt) < timestamp(entry.enteredAt))) continue - // The canonical checkpoint CLI retains previous phases on --enter 0. - // A retained phase 6 must never outrank the new current phase. - if (phase === 6 && Number(state.currentPhase) !== 6) continue - phases[phase] = entry - } - return { ...state, phases } -} - -function currentInvocationHandoff(handoff, startedAt) { - if (!handoff || !Number.isFinite(timestamp(handoff.updatedAt)) || timestamp(handoff.updatedAt) < startedAt) return null - if (handoff.status === 'awaiting-user' && (!Number.isFinite(timestamp(handoff.browserReadyAt)) || timestamp(handoff.browserReadyAt) < startedAt)) return null - // The canonical guard prioritizes handoff over workflowPause. Old handoff - // state must neither authorize this invocation nor hide its explicit pause. - return handoff -} - -function requireFresh(value, startedAt, label) { - const time = timestamp(value) - if (!Number.isFinite(time) || time < startedAt) throw new Error(`${label} is missing or belongs to an earlier invocation`) - return time -} - -function validateCompletedPhases(state, phases, startedAt) { - let previousEnd = startedAt - for (const phase of phases) { - const entry = state.phases[phase] - if (!entry || entry.status !== 'completed') throw new Error(`phase ${phase} has no completed evidence for this invocation`) - const entered = requireFresh(entry.enteredAt, previousEnd, `phase ${phase} entry`) - previousEnd = requireFresh(entry.completedAt, entered, `phase ${phase} completion`) - } - return previousEnd -} - -function validateAllowedDecision(decision, state, handoff, startedAt) { - if (!decision.allow) return - const kind = decision.action && decision.action.kind - if (state.workflowPause) { - const pause = state.workflowPause - requireFresh(pause.createdAt, startedAt, 'workflow pause') - if (!['external-input', 'user-cancelled'].includes(pause.kind) || !pause.reason) throw new Error('invalid workflow pause') - if (pause.kind === 'external-input' && !pause.detail && !pause.evidence) throw new Error('external-input pause needs evidence or detail') - const pauseKind = pause.kind === 'external-input' ? 'wait-external-input' : 'aborted' - if (kind === pauseKind && decision.reason === pause.reason) return - } - if (kind === 'done') { - if (Number(state.currentPhase) !== 6) throw new Error('only the current phase 6 can complete this invocation') - validateCompletedPhases(state, [0, 1, 2, 3, 4, 6], startedAt) - if (state.phases[4].decision !== 'cancel') throw new Error('phase 4 must authorize finalization') - } else if (kind === 'wait-user-decision') { - const previousEnd = validateCompletedPhases(state, [0, 1, 2, 3], startedAt) - const phase = state.phases[4] - if (Number(state.currentPhase) !== 4 || !phase || phase.status !== 'in_progress') throw new Error('no current phase 4 decision') - requireFresh(phase.enteredAt, previousEnd, 'phase 4 entry') - } else if (handoff && ['wait-browser', 'wait-outer-runner', 'wait-external-input', 'aborted'].includes(kind)) { - requireFresh(handoff.updatedAt, startedAt, 'browser handoff') - if (kind === 'wait-browser') requireFresh(handoff.browserReadyAt, startedAt, 'browser readiness') - } else { - throw new Error('no current invocation evidence authorizes this decision') - } -} - -function check(args) { - const root = fs.realpathSync(args['--repo-root']) - const stateDir = fs.realpathSync(path.join(root, 'd-d2c/temp')) - if (!within(root, stateDir)) throw new Error('state directory escapes repository') - const marker = readInside(stateDir, path.join(stateDir, '.active-workflow.json')) - if (marker.pageDir !== args['--page-dir'] || marker.workflowStartedAt !== args['--started-at']) { - throw new Error('checkpoint does not belong to this invocation') - } - if (marker.ownerSessionId && marker.ownerSessionId !== args['--session-id']) { - throw new Error('checkpoint belongs to another or unidentified session') - } - const pageDir = path.resolve(stateDir, marker.pageDir) - if (!within(stateDir, pageDir)) throw new Error('invalid checkpoint page directory') - const stateFile = fs.realpathSync(marker.stateFile || path.join(pageDir, 'workflow-state.json')) - if (stateFile !== fs.realpathSync(path.join(pageDir, 'workflow-state.json'))) { - throw new Error('checkpoint state does not match page directory') - } - const storedState = readInside(stateDir, stateFile) - if (!storedState.phases || !storedState.phases[0] || storedState.phases[0].enteredAt !== args['--started-at']) { - throw new Error('phase 0 does not match this invocation') - } - const startedAt = timestamp(args['--started-at']) - const state = currentInvocationState(storedState, startedAt) - const handoff = currentInvocationHandoff(readInside(stateDir, path.join(pageDir, 'browser-handoff.json'), true), startedAt) - const decision = decideStop({ root, stateDir, marker, state, handoff }, { - sessionId: args['--session-id'], - headless: args.headless || isHeadlessEnv(process.env), - scoreThreshold: process.env.D2C_SCORE_THRESHOLD, - }) - validateAllowedDecision(decision, state, handoff, startedAt) - if (args['--action'] === 'ask' && !(decision.allow && decision.action && decision.action.askUser)) { - return { ...decision, allow: false, reason: 'user interaction is not permitted at this checkpoint' } - } - return decision -} - -function main(argv = process.argv.slice(2)) { - let result - try { - result = check(parseArgs(argv)) - } catch (error) { - result = { allow: false, reason: 'cursor_d2c_gate_failed', detail: error.message } - } - process.stdout.write(`${JSON.stringify(result)}\n`) - return result.allow ? 0 : 2 -} - -if (require.main === module) process.exitCode = main() -module.exports = { check, main, parseArgs } +// Keep Cursor's existing explicit checkpoint contract and error reason. +const core = require('../../skills/d-d2c/scripts/lib/d2c-explicit-gate-core.cjs') +if (require.main === module) process.exitCode = core.main() +module.exports = core diff --git a/helixharness/hosts/cursor/ut.md b/helixharness/hosts/cursor/ut.md index 2544979..bbf70fe 100644 --- a/helixharness/hosts/cursor/ut.md +++ b/helixharness/hosts/cursor/ut.md @@ -16,7 +16,7 @@ permission_cleanup: not_required 清理为 `not_required`,不删除用户设置。 每个 worker 映射为 `ut_worker_` 逻辑 job,并完整读取当前安装的 -`agents/unit-test-worker.md`。只授权 worker 自己的临时目录、result/defects、唯一目标测试文件; +`agents/unit-test-worker.md`。只授权 worker 自己的临时目录、result/defects/findings JSON 及同名 `.tmp` staging、唯一目标测试文件; 业务源码、构建配置、共享 queue/session/summary/experience 与其他 worker 路径禁止写入。 冲突目标测试或 fixture 必须串行,任务数和验证要求不变。 diff --git a/helixharness/hosts/opencode/capabilities.md b/helixharness/hosts/opencode/capabilities.md new file mode 100644 index 0000000..28cbe96 --- /dev/null +++ b/helixharness/hosts/opencode/capabilities.md @@ -0,0 +1,35 @@ +# OpenCode capability adapters / 能力适配 + +These are HelixHarness adapters over OpenCode 2.3.2. An unsupported adapter is not a claim that the host has no such APIs. Native tool/session hooks are already used. Session idle is not Stop, session end or stage completion. + +这些能力由 HelixHarness 适配实现,不支持项不等于 OpenCode 没有相关 API。插件已使用原生工具和会话 Hook;会话空闲不代表 Stop、会话结束或阶段完成。 + +| Capability / 能力 | Implementation / 实现 | Boundary / 边界 | +|---|---|---| +| Task tracking / 任务跟踪 | `scripts/task_plan.py` reads and atomically updates the existing Feature `tasks.md`, with a content receipt and dependency validation. / 读取同一份任务表,凭内容回执校验并原子更新进度。 | Does not invent a second plan store, change the Spec, close a stage or replace verification. / 不增加第二份计划,不修改 Spec,不代替阶段验收。 | +| Telemetry / 交付统计 | Existing consent, stage ledger, workflow trace, asynchronous outbox and archive seal. / 复用授权、阶段账本、工作流轨迹、异步队列和归档封口。 | Stage facts only. No transcripts; usage/execution remain unknown. Consent never authorizes commit/push. / 仅阶段事实,不读取会话日志;未采集数据保持未知;授权不包含提交或推送。 | +| Project checks / 项目巡检 | Plugin `execute.after` runs existing `invariant-check` and `spec-sync-check` linters after successful native write/edit/patch, with bounded time and output. / 原生编辑成功后运行已有巡检,限制时间和输出。 | No `.opencode/` settings merge. Failed/non-edit tools do not trigger checks. Failures are feedback, not automatic stage failure or rollback. Shell changes still need explicit checks. / 不创建项目 Hook 设置;失败反馈不撤销编辑,也不自动改变阶段状态;shell 修改仍需显式检查。 | +| Source updates / 源码更新 | Existing `check → prepare → decide → install`; exact approved commit, clean attached checkout, explicit upstream, fast-forward only, hooks disabled and version/revision verification. / 复用确认链路,只更新干净且有 upstream 的分支,锁定批准 commit,仅快进并核验。 | No automatic update of dirty/detached/package-managed copies, no force/reset/stash/commit/push. Restart OpenCode afterwards. / 不自动处理本地改动、游离版本或包管理缓存,不重置、暂存、提交或推送;更新后重启。 | + +## Plan operations / 计划操作 + +Run Python preflight first. Use the requesting session's repository and the routed Feature; do not guess another Feature. / 先执行 Python preflight,使用当前会话仓库和 Router 确定的 Feature。 + +```text +{helix_python} "{plugin_root}/scripts/task_plan.py" --repo-root "{repo_root}" --feature example show +{helix_python} "{plugin_root}/scripts/task_plan.py" --repo-root "{repo_root}" --feature example update --task T-01 --status in_progress --expected-receipt {receipt_sha256} +``` + +A stale receipt, unfinished dependency, ambiguous row, unsafe path or closed plan blocks mutation. A read-only `show` creates no state files. Existing Apply/Archive checks remain authoritative. / 旧回执、未完成依赖、歧义行、不安全路径或关闭的计划均阻断写入;show 不创建状态文件,Apply/Archive 门禁仍为最终依据。 + +## Identity and collection / 身份与采集 + +Invoke the installed plugin's telemetry scripts by absolute path through native `shell`. The plugin binds `HELIXHARNESS_SESSION_ID` and `HELIXHARNESS_SESSION_CWD` to that shell invocation from `session.get`, without changing the server environment. Missing/foreign identity skips collection. Direct external CLI callers must explicitly bind these same values from their own native session; an inherited other-host identity is rejected. / 通过原生 shell 以绝对路径调用本安装统计脚本;插件从 session.get 绑定本次进程的真实会话和目录,不修改服务器全局环境。身份缺失或不匹配时跳过。外部 CLI 调用者须显式绑定,不能借用其他宿主身份。 + +Consent is off by default. The adapter never reads native conversation storage. Stage-only supplements carry empty `usage`/`execution` objects and explicit unavailable conversation evidence, including after Archive. / 默认关闭统计;不读取原生会话存储,归档前后均保持未采集指标未知。 + +## Updating / 更新 + +Use `/helix:update --check` to inspect. Checks use version-policy.json releases; source changes without a version release do not trigger an upgrade. Checks may fetch the configured upstream into a temporary Git ref and inspect an isolated snapshot; they do not switch HEAD or alter source files. `/helix:update` requires the existing structured user confirmation before install. The approved target stays pinned if upstream advances. Local changes, divergence, changed branch/HEAD or target-version mismatch block installation. / 检查按 version-policy.json 的发布版本判断升级,同版本源码变化不触发升级;可拉取已配置 upstream 的临时引用并检查隔离快照,不切换 HEAD 或修改源码。安装前须按现有协议确认;上游后续变化不改变批准目标,本地修改、分叉、分支/HEAD 漂移或目标版本不符时停止。 + +Standalone package installations can still use OpenCode's own package management. This adapter deliberately does not infer their specifier or read private global configuration. / 独立包仍可使用 OpenCode 自身的包管理;本适配不猜测包标识,也不读取私有全局配置。 diff --git a/helixharness/hosts/opencode/d2c_gate.cjs b/helixharness/hosts/opencode/d2c_gate.cjs new file mode 100644 index 0000000..6968da2 --- /dev/null +++ b/helixharness/hosts/opencode/d2c_gate.cjs @@ -0,0 +1,11 @@ +#!/usr/bin/env node +'use strict' + +// Explicit CLI only: OpenCode has no native Stop hook for this workflow. +const core = require('../../skills/d-d2c/scripts/lib/d2c-explicit-gate-core.cjs') +const options = { host: 'opencode', allowClaim: true, requireOwnership: true, requireVisualEvidence: true } +const parseArgs = (argv) => core.parseArgs(argv, options) +const check = (args) => core.check(args, options) +const main = (argv = process.argv.slice(2)) => core.main(argv, options) +if (require.main === module) process.exitCode = main() +module.exports = { check, main, parseArgs } diff --git a/helixharness/hosts/opencode/host.json b/helixharness/hosts/opencode/host.json index c72ad96..a38ffa8 100644 --- a/helixharness/hosts/opencode/host.json +++ b/helixharness/hosts/opencode/host.json @@ -3,16 +3,19 @@ "host_api_version": "1.1", "aliases": [], "support": { - "level": "preview", + "level": "stable", "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.", + "Stable scope: macOS 15.7.1 arm64, OpenCode 2.3.2 local CLI/server and targeted PTY. 2.2.2/2.3.0 have automated compatibility coverage only; other platforms/versions are unverified.", + "The adapter has no equivalent SessionStart/Stop/failure/session-end business hook guarantee. Native tool/session hooks are used for binding and project diagnostics; idle never completes a stage.", + "Telemetry is consent-gated stage facts and workflow traces only. Native conversation, token usage and unobserved tool counts remain unavailable; no transcript files are read.", + "Task tracking is emulated by scripts/task_plan.py over canonical tasks.md, with optimistic receipts, dependency validation and atomic updates; stage completion still requires workflow verification.", + "Native project settings hooks remain unsupported (settings_file=null). Plugin-level project_checks run existing invariant/spec-sync linters after successful native write/edit/patch; shell changes still require explicit checks.", "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." + "D2C has an explicit owner-bound evidence gate; native skill-scoped Stop/question hooks are not provided. The audit does not authenticate browser provenance or replace visual acceptance.", + "Absolute-directory installation is supported. /helix:update can update clean attached Git checkouts with an explicit upstream through the consent protocol, pinned to an immutable fast-forward target. Dirty/detached/package-managed copies require manual handling; restart after updating.", + "Production projects, unattended model reliability, full desktop UI, full D2C visual fidelity, and real Kotlin/Groovy or multi-module compiler acceptance are outside this Stable scope." ] }, "capabilities": { @@ -25,12 +28,13 @@ "workflow_transition": "emulated", "subagents": "native", "unit_test_workflow": "native", - "task_tracking": "unsupported", + "task_tracking": "emulated", "project_hooks": "unsupported", + "project_checks": "emulated", "session_events": "unsupported", - "telemetry": "unsupported", + "telemetry": "emulated", "plugin_install": "native", - "plugin_update": "unsupported", + "plugin_update": "emulated", "session_end": "unsupported" }, "adapters": { @@ -45,6 +49,10 @@ "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" + "telemetry_protocol": "resource:hosts/shared/telemetry.md", + "telemetry": "python:telemetry_hosts.opencode:OpenCodeAdapter", + "version": "python:update_hosts.opencode:plugin_version", + "update": "python:update_hosts.opencode:OpenCodeUpdateAdapter", + "d2c_gate": "resource:hosts/opencode/d2c_gate.cjs" } } diff --git a/helixharness/hosts/opencode/installer.md b/helixharness/hosts/opencode/installer.md index 52e8024..1268834 100644 --- a/helixharness/hosts/opencode/installer.md +++ b/helixharness/hosts/opencode/installer.md @@ -5,43 +5,58 @@ OpenCode V2 使用插件包根目录(本仓库的 `helixharness/`)中的 `package.json` 和 `opencode/index.ts`。 -## OpenCode 预览支持 +## OpenCode Stable 支持范围 + +当前源码候选在 **macOS、OpenCode 2.3.2** 的[支持矩阵](../../../docs/opencode-testing.md)范围内为 Stable。 +OpenCode 2.2.2、2.3.0 仅有自动化原生服务兼容覆盖,不外推为全部版本或平台均已验收。 + +已提供九个命令、方法 Skill 和原生子代理。命令、原生 `skill` 工具结果、 +Skill mention 与原生 Skill 激活均按请求会话绑定仓库目录;查询或目录校验失败时阻断 +未绑定的 Skill 正文。2026-11-20 已在 +OpenCode 2.3.2 + DeepSeek 上完成一次合成单仓 Init → Propose → Apply → Archive 真实模型闭环, +包含操作者确认和一次受控合同修订;2026-11-23 又完成了 OpenCode 2.3.2 + DeepSeek 的操作者辅助合成双仓 Workspace 与独立 UT 验证;后续已修复 UT 分类校验与原子发布保护,并通过无纠正提醒的真实模型复验。[合成 Workspace 的专项真实模型验证](../../opencode/tests/README.md#recovery-and-auxiliary-workflow-acceptance-2026-11-23)还覆盖了 Apply 与部分 Archive 原生取消后新会话恢复,以及注入原生 context hook 故障后阻断依赖派发。完整生产业务项目、无人干预时的协议遵守与完整 TUI/桌面 UI 验收仍未完成;已覆盖范围见[定向终端 UI 验收](../../opencode/tests/README.md#targeted-terminal-ui-acceptance-2026-11-23)。 + +2026-11-23 已修复并回归 Skill mention 绑定和资源符号链接边界:在读取文件或枚举目录前, +同时校验字面路径与真实路径;拒绝插件外部、悬空和环状链接,允许插件内部链接。 +原生宿主回归覆盖 OpenCode 2.2.2、2.3.0、2.3.2;使用本地脚本模型检查实际请求,不代替 +完整业务场景的真实模型验收,也不扩展上述 Stable 支持范围。 + +- 已使用原生工具/会话 Hook,但未提供等价的 SessionStart/Stop/失败/会话结束业务保证。 +- 任务进度由 `scripts/task_plan.py` 操作同一份 `tasks.md`;统计在明确授权后仅记录阶段事实和轨迹。 +- `/helix:update` 对有明确 upstream 的干净 Git 源码安装执行确认后、锁定 commit 的快进更新; + 本地改动、游离版本和包管理安装不自动处理,更新后仍须重启或重新加载 OpenCode。 +- Init 不创建 `.opencode/` settings;插件在原生编辑成功后运行已有项目巡检。见[能力适配](capabilities.md)。 +- d-d2c 的 Claude skill-scoped Stop/PreToolUse guard 不执行;通过 `resources.d2c_gate` 提供 + owner 绑定的显式证据检查。每个请求须重新初始化并认领 checkpoint;它不等价于原生 Stop Hook, + 不认证浏览器来源,也不替代用户决策或完整视觉验收,详见[运行时协议](runtime.md)。 +- Workspace Apply 需要 `experimental.subagent_depth >= 2`,详见下方多仓配置。 -当前为 Preview:已提供九个命令、方法 Skill、原生子代理及命令/Skill 的 Host Context 绑定, -完整 Init → Propose → Apply → Archive 工作流尚未完成真实客户端验收。 +## 克隆并配置本地目录(OpenCode 2.3.2 已验证) -- 无原生 SessionStart/Stop/失败/会话结束 hooks;无原生计划工具,计划写入当前 Feature `tasks.md`。 -- 统计为 `unsupported`(脚本返回 `unsupported_host`);插件内更新为 `unsupported` - (`/helix:update` 返回 `continue_silently`),请通过 OpenCode 插件管理手动更新。 -- 项目 hooks 不支持;Init 只合并 `AGENTS.md`,不创建 `.opencode/` settings。 -- d-d2c 的 Claude skill-scoped Stop/PreToolUse guard 不执行,采用无 hook / `--bare` 语义; - 仍须完成 Skill 正文中的用户决策、视觉验收和完成门禁。 -- Workspace Apply 需要 `experimental.subagent_depth >= 2`,详见下方多仓配置。 +本仓库的插件包位于 `helixharness/` 子目录。实际验证的 OpenCode 2.3.2 原生 `plugin add` +接受 npm/Git 包 spec,不接受绝对本地目录,也不解析 Git 子目录后缀;不能用该命令直接安装 +本仓库布局。其他客户端版本需要另行核验。 -## 从 Git 安装 +公开发布后,先克隆源码;将以下目的目录占位值替换成你选择的路径: ```bash -opencode plugin add 'github:didi/helixharness::path:helixharness' +git clone https://github.com/didi/helixharness.git /absolute/path/to/helixharness-source ``` -Git 安装支持分支、Tag 和完整提交;需要固定版本时使用完整提交或 npm 版本。安装后 OpenCode -加载 `package.json` 的 `exports["."]`;插件只使用 Bun 内置模块和 OpenCode 提供的插件上下文, -没有运行时 npm 依赖,因此本地源码副本也无需先执行 `bun install`。开发时运行 -`bun install` 只是为了 `bun test` 和 `tsc` 的类型检查。 - -## 本地源码 - -本地插件目录必须配置为目录,不能指向单个 `.ts` 文件。将绝对路径加入项目或全局 -`opencode.json(c)`: +将插件子目录的绝对路径合并到项目或全局 `opencode.json(c)` 的 `plugins` 数组,保留其他配置 +和插件条目: ```jsonc { "$schema": "https://opencode.ai/config.json", - "plugins": ["/absolute/path/to/helixharness"] + "plugins": ["/absolute/path/to/helixharness-source/helixharness"] } ``` -本地源码修改后按 OpenCode 要求重启服务或重新加载插件。 +路径须指向含 `package.json` 的插件目录,不能指向仓库根或单个 `.ts` 文件。独立插件副本也可 +配置其包根目录。OpenCode 加载 `package.json` 的 `exports["."]`;插件没有运行时 npm 依赖, +已验证独立副本在无 `node_modules`、未执行 `bun install` 时可加载。开发依赖仅供 +`bun test` 和 `tsc` 类型检查使用。配置或源码改变后,重启服务或重新加载插件并新开会话。 ## 多仓 Workspace @@ -61,6 +76,12 @@ OpenCode 默认子代理嵌套深度为一。Workspace Apply 的 RepoJob 使用 降级内联、由 Implementer 自审或伪造完成。原生 `subagent` 的执行和等待参数以当前暴露的 schema 为准;等待真实结果或原生后台完成通知,`sessionID` 不是完成证据。 +## 入口预检边界 + +变更型命令会观察允许名单中的原生工具登记,已知缺少 read/shell 时在 prompt 准入前阻断; +不会自动修改全局配置或批准权限。登记不证明执行权限,嵌套深度当前仍报告 unknown; +Workspace Apply 的 depth ≥ 2 要求和真实派发门禁继续有效。Status/Config 不依赖登记查询。 + ## 验收 新开 OpenCode 会话并确认: @@ -78,13 +99,28 @@ schema 为准;等待真实结果或原生后台完成通知,`sessionID` 不 模型验证目录绑定、失败正文替换与子任务执行边界,不需要真实模型账号。该结果不替代完整需求的 真实模型验收。 -## 更新与卸载 +## 更新、回退与卸载 + +本仓库在 OpenCode 2.3.2 使用上述本地目录配置,更新和回退都由用户操作源码副本: + +1. 先检查工作树,保留自己的修改,并记录当前完整 commit 供回退;通过正常 Git 流程取得并核对 + 要使用的批准版本。以下占位值必须替换为已核对的完整 commit,不表示已发布的 Tag: + + ```bash + git -C /absolute/path/to/helixharness-source checkout --detach "" + ``` + +2. 重启或重新加载 OpenCode,新开会话并核对实际插件目录与入口。回退时由用户在该源码副本 + 执行同样的 `git checkout --detach`,将占位值替换为先前记录且已批准的完整 commit,随后再次 + 重载和核对。不要覆盖未保存的本地修改。 +3. 卸载时只在项目或全局 `plugins` 数组中移除该插件目录,再重启或重新加载。保留其他插件、 + 业务仓库中的 `docs/harness/`、`docs/knowledge/`、`docs/specs/` 和业务代码。 -- Git 来源:使用 `opencode plugin update`,或重新执行 `opencode plugin add` 并指定目标版本。 -- 本地来源:先自行更新源码,再重启或重新加载 OpenCode。 -- 卸载:使用 `opencode plugin remove`,或在 `plugins` 数组中移除该目录。插件卸载不删除业务 - 仓库中的 `docs/harness/`、`docs/knowledge/`、`docs/specs/` 或业务代码。 +原生 `opencode plugin add` / `update` / `remove` 是 npm/Git 包管理入口;Git 形式要求仓库根 +本身就是可直接导出的独立插件包,不适用于本仓库的子目录配置。它们不能替代上述源码更新、 +回退或配置移除。此区别已在 2.3.2 核验,不推定其他版本行为。 -`/helix:update` 在 OpenCode 上返回 `continue_silently`,因为当前 `plugin_update=unsupported`; -这不影响手动更新。OpenCode 不会创建 `.opencode/` 项目设置或项目 hooks;Init 只合并 -`AGENTS.md`。 +源码 checkout 可使用 `/helix:update --check` 检查,再按 `/helix:update` 的既有确认流程安装; +检查不切换 HEAD,安装只允许已批准 commit 的快进,不 stash/reset/commit/push。不是干净且有 +upstream 的分支时,保留手动更新方式,不把未知版本当作最新。Init 仍只合并 `AGENTS.md`, +不创建 `.opencode/` 项目设置;项目巡检由插件事件触发。 diff --git a/helixharness/hosts/opencode/lifecycle.md b/helixharness/hosts/opencode/lifecycle.md index c2b9790..380ac57 100644 --- a/helixharness/hosts/opencode/lifecycle.md +++ b/helixharness/hosts/opencode/lifecycle.md @@ -9,11 +9,14 @@ OpenCode 不需要 plugin hook manifest。`opencode/index.ts` 的 `setup` 在插 阶段完成。 - `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`,不调用其他宿主的安装命令。 +- 项目设置 hooks 仍由 `project-hooks.json` 声明为 `unsupported`;Init 不创建 `.opencode/` + 设置。`project_checks=emulated` 通过原生 `execute.after` 在 write/edit/patch 成功后运行已有 + invariant/spec-sync 巡检;错误作为反馈,不撤销编辑、不自动完成或失败一个业务阶段。 +- `telemetry=emulated`:仅明确授权后记录阶段账本和工作流轨迹,可经已有异步队列提交;不读取原始 + 会话,未采集指标保持未知。统计关闭或异常均不改变工作流完成门禁。 +- `plugin_update=emulated`:`/helix:update` 复用既有授权协议,对有明确 upstream 的干净源码 + 安装执行锁定 commit 的快进更新;本地修改、游离版本或不受管理的包安装不自动处理。 - 修改插件源码或局部依赖后按 OpenCode 要求重启服务或重新加载会话;更新后新开会话确认九个 `helix:*` 命令、`helix-*` 方法 Skill 和子任务角色可见。 + +任务进度由 `scripts/task_plan.py` 对 canonical `tasks.md` 原子更新;完整边界见[能力适配](capabilities.md)。 diff --git a/helixharness/hosts/opencode/runtime.md b/helixharness/hosts/opencode/runtime.md index 6f9aba1..a5d7587 100644 --- a/helixharness/hosts/opencode/runtime.md +++ b/helixharness/hosts/opencode/runtime.md @@ -7,12 +7,15 @@ - 方法 Skill 注册为 `helix-`,正文仍来自根 `skills//SKILL.md`; - 子任务角色注册为 `helix-`,正文仍来自根 `agents/.md`。 -命令执行与 Skill 加载时由插件注入预绑定 Host Context(`canonical_host_id=opencode`、 +命令执行、原生 `skill` 工具结果与 Skill mention 模型请求由插件注入预绑定 Host Context(`canonical_host_id=opencode`、 `plugin_root`、`repo_root`、`host_manifest`、`capabilities` 和全部资源绝对路径)。这等价实现 -`session_start=emulated`;不得从环境变量、项目文件或其他插件缓存重新识别宿主。直接调用方法 -Skill 时,`repo_root` 由 `tool.execute.after` 按当前会话目录绑定。 +`session_start=emulated`;不得从环境变量、项目文件或其他插件缓存重新识别宿主。通过原生工具调用方法 +Skill 时,`repo_root` 由 `tool.execute.after` 按当前会话目录绑定。Skill mention、命令附件 +与原生 Skill 激活则在 `context` 请求 hook 中绑定;`compaction`、`generate`、`title` +请求复用同一绑定逻辑。只替换本安装注册的完整 Skill 正文中的占位符,用户字面输入、其他 +Skill、媒体与元数据保持不变;不修改持久化的源消息,也不缓存某个会话的目录。 -命令执行和直接 Skill 调用均以请求会话的 `session.get().location.directory` 为目录来源, +命令执行和原生 `skill` 工具调用均以请求会话的 `session.get().location.directory` 为目录来源, 校验为真实存在的绝对目录后绑定,不回退到插件目录、进程 cwd 或其他会话。查询失败报 `repo_root_lookup_failed`;缺失、相对、不可解析或非目录的值报 `repo_root_invalid`。目录绑定 失败时命令不提交 prompt;Skill 结果替换为相应的 `BLOCKED`,不交付未绑定的正文。 @@ -26,10 +29,14 @@ Skill 时,`repo_root` 由 `tool.execute.after` 按当前会话目录绑定。 | `spawn_job` | 保持已解析的 `delegation_policy`;普通 leaf 使用 `general`,通用 may_delegate 使用 `helix-worker`,Init/UT 使用 canonical `helix-` leaf | | `wait_job` | 遵循当前暴露的原生 `subagent` schema;等待真实完成结果或后台完成通知,再校验结果与产物;`sessionID` 本身不代表完成 | | `ask_user` | 使用原生 `question` 工具并等待真实回答 | -| `update_plan` | OpenCode 无原生计划工具,更新当前 Feature 的 `tasks.md` | +| `update_plan` | `scripts/task_plan.py show/update` 操作当前 Feature 的 `tasks.md`;更新须带最新内容回执 | | `stage_finish` | 在命令内按真实终态显式调用 HelixHarness 生命周期脚本 | | `project_entry` | 生成或合并根 `AGENTS.md` | -| `project_hooks` | OpenCode 无项目 settings hook 契约;声明 `unsupported`,不创建替代文件 | +| `project_hooks` | 当前不合并项目 settings hooks;插件级 `project_checks` 通过原生编辑事件运行,不创建替代配置文件 | + +原生子会话继承父目录;跨仓 RepoJob 必须先用当前原生会话切换能力绑定 `ownership_root`, +再进入 repo-local 命令或 Skill。prompt 的路径字段与 shell `cd` 不能替代会话目录切换; +具体映射与失败处理见 `resources.subagent_protocol`。 Workspace Apply 的 RepoJob 需要 `experimental.subagent_depth >= 2` 才能派发 Single Apply 的 独立只读 leaf reviewer。深度或权限不足时返回具体 `BLOCKED`,不得内联降级、自审或虚构 @@ -44,7 +51,10 @@ OpenCode 原生命令执行器收到的是用户输入的原始参数字符串 命令生命周期。 用户附件、agent mention 和 skill mention 原样转发到展开后的 prompt;`delivery` 保持调用方 -给定的 `steer|queue`。`metadata` 只记录逻辑命令名,不进入业务事实。 +给定的 `steer|queue`。Skill mention 正文在模型请求前按请求会话目录绑定;查询失败或目录无效时中止该请求, +不向模型交付未绑定的 Skill 正文。所需工具结果与模型请求 hooks 必须先于公开入口注册, +任一必需 hook 不可用时插件装载失败。 +`metadata` 只记录逻辑命令名,不进入业务事实。 ## 用户决策与等待 @@ -60,25 +70,73 @@ OpenCode 原生命令执行器收到的是用户输入的原始参数字符串 - `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 正文只在本插件内解析,不读取项目中的同名 +资源加载在读取文件或枚举目录前同时校验字面路径和 `realpath` 解析后的边界, +覆盖 manifest、adapters、commands、skills 与 agents。插件内部链接允许使用; +外部链接、悬空链接和环状链接均拒绝。资源缺失、越界、宿主 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 缺失跳过视觉验收或完成条件。 +执行 Python preflight。`telemetry=emulated` 复用明确授权、阶段账本、工作流轨迹和异步队列。 +通过原生 shell 以绝对路径调用本安装统计脚本,插件给该进程绑定真实会话 ID 和目录;缺失或 +不匹配时跳过,不借用其他宿主授权。不读取会话日志,token/未观察到的工具信息保持未知。 +`plugin_update=emulated` 复用 check/prepare/decide/install 授权链路,对有明确 upstream 的干净 +源码安装执行锁定 commit 的快进更新;其余安装不自动修改。详细操作见[能力适配](capabilities.md)。 + +## D2C 显式检查与 owner 绑定 + +OpenCode 不执行 Claude 的 skill-scoped Stop / PreToolUse Hook。采用 canonical Skill 的无 hook +执行语义;下方显式检查不拦截 OpenCode 自身的任意停止动作,也不认证浏览器或模型报告的真实性。 + +方法 Skill 的工具加载、mention 与原生激活会把本次请求的 `native_session_id` 注入 Host Context。 +只能使用该原生身份,不得猜测 ID、借用父/其他会话的 ID,或用手工构造的上下文冒充绑定。 +每个新的 D2C 请求先按 canonical checkpoint CLI 执行 `--enter 0`;从本次 marker 取得 +`pageDir` 与 `workflowStartedAt`,立即执行一次 owner claim,再开展后续阶段: + +```bash +node "{plugin_root}/hosts/opencode/d2c_gate.cjs" --repo-root "{repo_root}" --page-dir "{pageDir}" --started-at "{workflowStartedAt}" --session-id "{native_session_id}" --action claim +``` + +claim 只用于新初始化的未认领 phase 0;超时或旧状态不能在完成时重新认领,须从新的 phase 0 开始。 +需要停止并报告结果前,以相同 page/start/session 参数执行 `--action stop`;需要交互前执行 +`--action ask`。只有脚本退出 0 且 `allow=true` 才消费其 `action.kind`:`done` 才是完成, +合法外部输入、浏览器 handoff 或用户取消不等于完成。退出 2、损坏/缺失工件、跨 owner 或旧轮次 +均保留阻断原因并按原流程修复/恢复,不通过手工改 marker/状态/报告绕过。后续阶段继续执行 +canonical checkpoint 校验,不能把单独的门禁通过当作完整视觉验收。 + +证据审计有明确容量上限:PNG 文件 32 MiB、解压后像素扫描行 128 MiB、评估报告 8 MiB。 +超限返回容量诊断并阻断本次审计,不将大图判定为视觉不合格;须提供容量内的受支持截图。 +评估报告读取 canonical Markdown 中的 fenced JSON,并核对本页、本轮、分数与物料; +支持仓库内的自定义报告路径,不接受任意非空文本代替评估结果。 +canonical 状态更新与 owner 认领并发时可能返回 busy;等当前写入结束后重试,不手动删除活动锁。 +锁使用进程唯一条目;下次写入会回收已终止进程的遗留。canonical 的仅警告测量仍可通过, +门禁会在 `evidenceAudit.warnings` 返回这些警告,不能把它们表述为测量全部匹配。 + +## 入口能力预检 + +变更型命令在提交 prompt 前读取原生 `tool.list` 的允许名单,仅注入登记工具名和 session move +API 是否存在,不读取或输出 providers、headers、凭据或全量配置。已知缺少 canonical `read` / +`shell` 时返回 `opencode_preflight_tools_unavailable`,尚不写需求或派发任务。查询不可用、失败或 +返回未知结构时标为 `unavailable`,保留现有命令入口;Status/Config 不依赖该查询。 + +登记与 API 存在不代表当前权限已经批准,也不证明实际执行成功。当前 SDK 未提供有效嵌套深度的 +直接查询,因此 `native_delegation_depth=unknown`;不得将其写成检查通过或自动修改配置。 +公共 Router 确定 scope 后、任何 Workspace 状态更新和 repo 派发前,按该阶段检查: + +- Workspace 需要切换到不同 ownership_root:核对当前暴露的 session move schema。登记目录中缺少 + `opencode_session_move` 且 SDK move API 也不可用时,返回具体目录切换 blocker;未知时保持真实 + schema 发现和返回位置校验,不假设 shell cd 等于切仓。 +- Apply 的独立评审/Workspace 嵌套评审:核对实际 subagent 能力、权限与 depth。深度未知须明确提示 + Workspace 配置要求至少 2,并保留原生准入检查;不自审、不降级内联、不把未知当成功。 +- 执行阶段需要的 read/shell/question/skill 等以实际 schema 和权限为准,缺失时给出具体缺口, + 不调用其他宿主工具或更改全局审批模式。Python/Git/Node 等进程依赖仍由既有 runtime preflight + 及 D2C 入口检查负责,工具登记不能代替可执行文件探测。 ## 项目配置 `resources.project_config` 固定 `entry_file=AGENTS.md`、`settings_file=null`。Init 只合并 `AGENTS.md` 并生成公共工件,不创建 `.opencode/` 设置或虚构 hook 配置。 +原生 write/edit/patch 成功后,插件会运行已生成的项目 invariant/spec-sync linters;没有巡检目录 +时跳过。失败或超时作为工具反馈,保存的编辑保留;shell 修改仍须执行公共工作流的显式检查。 diff --git a/helixharness/hosts/opencode/subagent.md b/helixharness/hosts/opencode/subagent.md index 1c7140a..5cbc892 100644 --- a/helixharness/hosts/opencode/subagent.md +++ b/helixharness/hosts/opencode/subagent.md @@ -36,6 +36,20 @@ dispatch_mode: native_job 运行时明确没有暴露且无法发现 `subagent` 能力,并且命令 Dispatch Contract 允许时,才按同一 prompt 串行内联一次。 +## RepoJob 会话目录绑定 + +原生 child 默认继承父会话目录。Dispatch prompt 中的 `cwd` / `ownership_root` 只声明目标, +不会自动修改 native session location;仅在 `shell` 中 `cd` 也不会改变后续命令和 Skill 的绑定。 +当 RepoJob 的 `ownership_root` 与继承目录不同时,在任何 repo-local 读取、写入、命令或 Skill +之前,按当前暴露的 schema 使用原生会话目录切换能力(2.3.2 的 Code Mode 可调用 `tools.opencode.session_move`;直接工具表面可能显示为 +`opencode_session_move`,以当前 schema 为准), +目标为规范化的 `ownership_root` 绝对路径。确认返回位置与目标一致后,才继续公共命令 Router +与 Single workflow。后续 reviewer 继承已切换的 repo 目录,仍保留原始父子关联与委派深度。 + +不得伪造 `subagent` 的 `cwd` / `directory` 参数,不得通过替换 prompt 中的 `repo_root` +掩盖真实会话目录不符。目录切换能力未暴露、被拒绝或结果不一致时返回 +`BLOCKED: native_session_location_unavailable`;父流程保留该 job,不代写子仓工件或降级内联。 + ## 工作区深化 OpenCode 默认子代理嵌套深度为一。Workspace Apply 的 RepoJob 明确声明 diff --git a/helixharness/hosts/opencode/ut.md b/helixharness/hosts/opencode/ut.md index 11db9bc..9dcae46 100644 --- a/helixharness/hosts/opencode/ut.md +++ b/helixharness/hosts/opencode/ut.md @@ -21,6 +21,22 @@ permission_cleanup: not_required OpenCode 原生审批流程。未获得时保存证据并按公共命令标记 blocked/failed。 - `permission_cleanup` 固定返回 `not_required`,因为本适配器不写项目权限文件。 +## 临时目录与原子写映射 + +- 公共命令的“系统临时目录”使用当前进程真实的 `TMPDIR` / 平台临时目录发现结果; + 不把项目内或其相邻的自建目录冒充系统临时目录。派发前确认每个 worker 的绝对路径与写域, + 只清理本次拥有的目录;系统临时目录权限不足时走原生审批,未获授权则保留 blocker。 +- 公共命令要求原子写的 queue、session、主结果与共享经验等文件,先完整读取公共 + `reference/ut-artifact-protocol.md`,使用原生 `write` 写入 + **目标同目录的临时文件**,再用 `shell` 调用绑定插件的 `scripts/ut_artifacts.py write` 完成原子替换。 + 插件必需的 `tool.execute.before` 会在原生 write/edit 执行前拒绝直接写最终 UT 状态文件, + 返回 `ut_atomic_write_required` 并给出脚本入口;按同一合同自行恢复,不需要操作者提醒。 + 该保护覆盖 native write/edit,不声称是对任意 shell 或外部工具的通用文件系统沙箱。 + 直接 `write` / `edit` 目标文件不构成该原子写证据。该映射同样适用于父流程最终报告收口, + 不能只对 worker result 或经验合并执行;具体适用文件仍服从公共 UT 命令。 +- 发现先前使用直接写入时,如实保留不符合项,再按公共合同纠正后续操作;不得把最终 + 原子替换追述为此前所有写入均合规。 + ## Worker Dispatch Contract 每个逻辑 Worker ID 建立 `ut_worker_` job: @@ -30,9 +46,9 @@ permission_cleanup: not_required | `prompt_source` | `agents/unit-test-worker.md`,worker 首个业务动作前完整读取 | | `agent` | `helix-unit-test-worker`;不可用时使用内建 `general` 并传入同一完整 prompt | | `depends_on` | 目标测试路径或共享 fixture 写域冲突时依赖前一 job | -| `write_scope` | worker 临时目录、自己的 result/defects、唯一目标测试文件 | +| `write_scope` | worker 临时目录、自己的 result/defects/findings JSON 及同名 `.tmp` staging、唯一目标测试文件 | | `forbidden_scope` | 业务源码、构建配置、共享 queue/session/summary/experience、其他 worker 路径 | -| `expected_artifacts` | result;成功时目标测试文件;有缺陷时 defects | +| `expected_artifacts` | result、findings JSON 与生成的分类 defects;成功时目标测试文件 | | `validation` | 原生终态、公共 final、写域、结果结构、6 Loop、测试和覆盖率 | | `unavailable_fallback` | 仅确认子代理能力不可用时,父流程按同一 prompt 串行内联 | @@ -52,3 +68,11 @@ permission_cleanup: not_required 结构合法的 worker 业务失败(包括高危 Bug)仍按公共 UT 状态机处理,不等同于宿主原生 job 失败。 只有确认当前运行时没有暴露且无法发现 `subagent` 能力时才允许 inline fallback,并记录 `WARN:opencode_subagent_unavailable`;容量暂满、等待中、单个 job 失败或取消不得触发 fallback。 + +## UT 直接写入守卫范围 + +保留工件路径按大小写不敏感识别;原生 Write/Edit 不得直接覆盖。相对符号链接检查仅在已注册 +`/helix:ut` 的活跃父会话或 `helix-unit-test-worker` 内解析当前 session 目录。普通会话的普通相对 +编辑不查询 session API;绝对路径别名和显式保留路径仍受检查。父会话无后台任务而进入 idle, +或切换到其他 Helix 命令后释放 UT 范围;中断/失败后重新执行命令可重建范围,不缓存 cwd。 +该守卫只覆盖原生 write/edit,不能当作 shell 沙箱;所有宿主仍须遵守公共原子发布合同。 diff --git a/helixharness/hosts/opencode/workflow-transition.md b/helixharness/hosts/opencode/workflow-transition.md index 051cd61..bee025d 100644 --- a/helixharness/hosts/opencode/workflow-transition.md +++ b/helixharness/hosts/opencode/workflow-transition.md @@ -10,5 +10,5 @@ Apply 的双轴评审完整执行 `skills/code-review/SKILL.md`,通过原生 ` Apply Stage,不创建独立 Review 阶段,也不提前 finish coding entry。 当前阶段的 start、trace-event、finish 均以所选工作流及 `resources.telemetry_protocol` 为准。 -OpenCode 的 `telemetry=unsupported`,统计脚本返回 `unsupported_host` 时跳过统计并继续业务; -不得因此跳过评审、验证或完成门禁。 +OpenCode 的 `telemetry=emulated` 仅在明确授权后记录阶段事实和工作流轨迹;未授权、会话身份 +不可用或统计异常时跳过统计并继续业务,不得因此跳过评审、验证或完成门禁。空闲事件不等于 finish。 diff --git a/helixharness/opencode/core.ts b/helixharness/opencode/core.ts index ee67ab9..d142118 100644 --- a/helixharness/opencode/core.ts +++ b/helixharness/opencode/core.ts @@ -10,10 +10,13 @@ import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; +import { guardUtStateWrite, type UtWriteEvent } from "./ut-state.ts"; +import { runProjectChecks } from "./project-checks.ts"; export const HOST_ID = "opencode"; export const HOST_API_VERSION = "1.1"; export const PLUGIN_ID = "helixharness"; +export const SESSION_ID_TOKEN = "@@HELIXHARNESS_SESSION_ID@@"; export const REPO_ROOT_TOKEN = "@@HELIXHARNESS_REPO_ROOT@@"; export const WORKER_AGENT_ID = "helix-worker"; @@ -95,7 +98,16 @@ export interface LoadedPlugin { capabilities: Record; } +interface NativePreflight { + registeredTools: string[] | null; + toolCatalog: "available" | "unavailable"; + sessionMoveApi: "available" | "unavailable"; + delegationDepth: "unknown"; +} + export interface HostContext { + nativePreflight?: NativePreflight; + sessionId?: string; canonicalHostId: string; pluginRoot: string; repoRoot?: string; @@ -142,9 +154,29 @@ export interface ToolAfterEvent { tool: string; sessionID: string; status: "completed" | "error"; + input?: unknown; + id?: string; result?: { content?: string | ReadonlyArray }; } +export type SessionBindingHook = "context" | "compaction" | "generate" | "title"; + +interface RequestTextPart { + type: string; + text?: string; + [key: string]: unknown; +} + +export interface SessionBindingEvent { + sessionID: string; + system: Array<{ text: string; [key: string]: unknown }>; + messages: Array<{ + role: string; + content: string | ReadonlyArray; + [key: string]: unknown; + }>; +} + /** * The subset of the OpenCode plugin context used by this package. Keeping the * shape structural makes the registration logic testable without a server. @@ -184,12 +216,20 @@ export interface PluginContext { ): Promise; }; tool?: { + list?(input: { sessionID: string }): Promise>; + hook(name: "execute.before", callback: (event: UtWriteEvent) => Promise | void): Promise; hook( name: "execute.after", callback: (event: ToolAfterEvent) => Promise | void, ): Promise; }; session: { + move?: unknown; + hook?( + name: SessionBindingHook, + callback: (event: SessionBindingEvent) => Promise | void, + ): Promise; + hook?(name: "experimental.idle", callback: (event: { sessionID: string; background: ReadonlyArray }) => Promise | void): Promise; get(input: { sessionID: string }): Promise<{ location?: { directory?: string } }>; prompt(input: { sessionID: string; @@ -227,6 +267,28 @@ function assertInside(root: string, candidate: string, label: string): string { throw new Error(`${label} escapes the plugin root: ${resolved}`); } +/** Check both boundaries before reading a file or enumerating a directory. */ +function resolvePluginPath(root: string, candidate: string, label: string): string { + const lexical = assertInside(root, candidate, label); + let resolved: string; + try { + resolved = realpath(lexical); + } catch { + throw new Error(`${label} does not exist or cannot be resolved: ${lexical}`); + } + return assertInside(root, resolved, label); +} + +function requirePluginFile(root: string, candidate: string, label: string): string { + return requireFile(resolvePluginPath(root, candidate, label), label); +} + +function requirePluginDirectory(root: string, candidate: string, label: string): string { + const resolved = resolvePluginPath(root, candidate, label); + if (!fs.statSync(resolved).isDirectory()) throw new Error(`${label} is not a directory`); + return resolved; +} + function requireFile(filePath: string, label: string): string { let stat: fs.Stats; try { @@ -305,8 +367,9 @@ export function loadManifest(pluginRoot: string): { resources: Record; } { const root = realpath(pluginRoot); - const manifestPath = path.join(root, "hosts", HOST_ID, "host.json"); - requireFile(manifestPath, "OpenCode host manifest"); + const manifestPath = requirePluginFile( + root, path.join(root, "hosts", HOST_ID, "host.json"), "OpenCode host manifest", + ); const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8")) as HostManifest; if (manifest.host_id !== HOST_ID) { throw new Error( @@ -337,8 +400,7 @@ export function loadManifest(pluginRoot: string): { 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}`); + resources[name] = requirePluginFile(root, path.join(root, target), `OpenCode resource ${name}`); } for (const name of REQUIRED_RESOURCE_ADAPTERS) { @@ -353,8 +415,8 @@ export function loadManifest(pluginRoot: string): { export function loadCommands(pluginRoot: string): CommandSource[] { const root = realpath(pluginRoot); return COMMAND_NAMES.map((name) => { - const filePath = requireFile( - path.join(root, "commands", `${name}.md`), + const filePath = requirePluginFile( + root, path.join(root, "commands", `${name}.md`), `HelixHarness command ${name}`, ); const document = parseMarkdown(fs.readFileSync(filePath, "utf8"), filePath); @@ -369,16 +431,20 @@ export function loadCommands(pluginRoot: string): CommandSource[] { export function loadSkills(pluginRoot: string): SkillSource[] { const root = realpath(pluginRoot); - const skillsRoot = path.join(root, "skills"); + const skillsRoot = requirePluginDirectory(root, path.join(root, "skills"), "HelixHarness skills"); const entries = fs .readdirSync(skillsRoot, { withFileTypes: true }) - .filter((entry) => entry.isDirectory()) + .filter((entry) => entry.isDirectory() || entry.isSymbolicLink()) .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 skillDirectory = resolvePluginPath(root, path.join(skillsRoot, directory), `HelixHarness skill ${directory}`); + if (!fs.statSync(skillDirectory).isDirectory()) continue; + const candidate = path.join(skillDirectory, "SKILL.md"); + // A missing optional Skill is fine; a dangling link is an invalid resource. + if (!fs.lstatSync(candidate, { throwIfNoEntry: false })) continue; + const filePath = requirePluginFile(root, candidate, `HelixHarness skill ${directory}`); const document = parseMarkdown(fs.readFileSync(filePath, "utf8"), filePath); const description = typeof document.frontmatter.description === "string" && @@ -398,14 +464,14 @@ export function loadSkills(pluginRoot: string): SkillSource[] { export function loadAgents(pluginRoot: string): AgentSource[] { const root = realpath(pluginRoot); - const agentsRoot = path.join(root, "agents"); + const agentsRoot = requirePluginDirectory(root, path.join(root, "agents"), "HelixHarness agents"); const files = fs .readdirSync(agentsRoot, { withFileTypes: true }) - .filter((entry) => entry.isFile() && entry.name.endsWith(".md")) + .filter((entry) => (entry.isFile() || entry.isSymbolicLink()) && 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 filePath = requirePluginFile(root, path.join(agentsRoot, file), `HelixHarness agent ${file}`); const document = parseMarkdown(fs.readFileSync(filePath, "utf8"), filePath); const agentName = file.slice(0, -".md".length); const description = @@ -439,8 +505,10 @@ export function loadPluginResources(pluginRoot: string = pluginRootFromModule()) export function hostContextFor( plugin: LoadedPlugin, repoRoot?: string, + sessionId?: string, ): HostContext { return { + sessionId, canonicalHostId: plugin.manifest.host_id, pluginRoot: plugin.pluginRoot, repoRoot, @@ -480,7 +548,16 @@ export function renderHostContext(context: HostContext): string { if (context.repoRoot) { lines.push(`- repo_root: \`${context.repoRoot}\``); } + if (context.sessionId) lines.push(`- native_session_id: \`${context.sessionId}\``); lines.push(`- host_manifest: \`${context.hostManifest}\``); + if (context.nativePreflight) { + const observed = context.nativePreflight; + lines.push(`- native_tool_catalog: \`${observed.toolCatalog}\``); + lines.push(`- registered_native_tools: \`${JSON.stringify(observed.registeredTools)}\``); + lines.push(`- native_session_move_api: \`${observed.sessionMoveApi}\``); + lines.push(`- native_delegation_depth: \`${observed.delegationDepth}\``); + } + lines.push("", "## Capabilities", "", ...renderCapabilities(context.capabilities)); lines.push("", "## Resolved resources", "", ...renderResources(context.resources)); lines.push( @@ -494,10 +571,11 @@ export function renderHostContext(context: HostContext): string { "- `spawn_job` uses the native `subagent` tool. Preserve the resolved `delegation_policy` from the command's Dispatch Contract. Generic `leaf` jobs use `general`; generic `may_delegate` jobs use `helix-worker` (currently Workspace Apply RepoJobs). Registered Init and UT roles use `helix-` and remain leaves.", "- Follow the exposed native `subagent` schema for execution and waiting; do not assume every OpenCode V2 release supports a foreground/background selector. `wait_job` waits for a real completed result or the native background-completion notice, then validates the returned result and artifacts. A returned `sessionID` alone is not completion.", "- `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.", + "- `update_plan` is emulated by `scripts/task_plan.py --repo-root --feature show` and `update --task --status --expected-receipt `. Use the same canonical tasks.md; dependency and receipt failures require a fresh read. This progress update never substitutes for stage verification.", "- `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.", + "- `stage_finish` calls the HelixHarness lifecycle scripts from the command body. Telemetry uses the existing explicit-consent protocol and records stage facts only; no native transcript or token usage is collected. Invoke the bound plugin's telemetry scripts by absolute path; native shell hooks bind the real session ID and directory to that subprocess, without changing process-global environment.", + "- Successful native write/edit/patch notifications run existing project invariant/spec-sync linters when installed. Failure feedback does not undo edits or complete stages; shell-based changes still require the explicit workflow checks.", + "- `/helix:update` uses the existing check/prepare/decide/install consent protocol for clean source checkouts with an explicit Git upstream. Targets are immutable commits and installation is fast-forward only. Dirty/detached/unregistered package copies are not modified. Restart OpenCode after an update.", "", "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.", ); @@ -567,7 +645,7 @@ export function buildCommandPrompt( } export function buildSkillContent(skill: SkillSource, plugin: LoadedPlugin): string { - const context = hostContextFor(plugin, REPO_ROOT_TOKEN); + const context = hostContextFor(plugin, REPO_ROOT_TOKEN, SESSION_ID_TOKEN); return [ renderHostContext(context), "", @@ -616,34 +694,43 @@ export function buildWorkerSystem(plugin: LoadedPlugin): string { export function replaceRepoRootToken( content: string, repoRoot: string, + sessionId?: string, ): string { - return content.replaceAll(REPO_ROOT_TOKEN, () => repoRoot); + const bound = content.replaceAll(REPO_ROOT_TOKEN, () => repoRoot); + return sessionId === undefined ? bound : bound.replaceAll(SESSION_ID_TOKEN, () => sessionId); +} + +function bindOwnedSkillText(text: string, skillTexts: ReadonlyArray, repoRoot: string, sessionId: string): string { + return skillTexts.reduce( + (result, skill) => result.replaceAll(skill, () => replaceRepoRootToken(skill, repoRoot, sessionId)), text, + ); +} + +function hasOwnedSkillResult(result: ToolAfterEvent["result"], skillTexts: ReadonlyArray): boolean { + const owns = (text: string) => skillTexts.some(skill => text.includes(skill)); + const content = result?.content; + if (typeof content === "string") return owns(content); + return content?.some(item => item.type === "text" && typeof item.text === "string" && owns(item.text)) ?? false; } function replaceToolResultContent( result: ToolAfterEvent["result"], repoRoot: string, + sessionId: string, + skillTexts: ReadonlyArray, ): void { if (!result || result.content === undefined) return; if (typeof result.content === "string") { - result.content = replaceRepoRootToken(result.content, repoRoot); + result.content = bindOwnedSkillText(result.content, skillTexts, repoRoot, sessionId); return; } result.content = result.content.map((item) => item.type === "text" && item.text !== undefined - ? { ...item, text: replaceRepoRootToken(item.text, repoRoot) } + ? { ...item, text: bindOwnedSkillText(item.text, skillTexts, repoRoot, sessionId) } : item, ); } -function hasRepoRootToken(result: ToolAfterEvent["result"]): boolean { - const content = result?.content; - if (typeof content === "string") return content.includes(REPO_ROOT_TOKEN); - return content?.some( - (item) => item.type === "text" && item.text?.includes(REPO_ROOT_TOKEN), - ) ?? false; -} - type RepoRootErrorCode = "repo_root_lookup_failed" | "repo_root_invalid"; class RepoRootError extends Error { @@ -675,6 +762,57 @@ async function resolveRepoRoot( } } +/** Observe registration only. This is not a permission/depth or execution probe. */ +async function observeNativePreflight(ctx: PluginContext, sessionID: string): Promise { + const result: NativePreflight = { + registeredTools: null, toolCatalog: "unavailable", + sessionMoveApi: typeof ctx.session.move === "function" ? "available" : "unavailable", + delegationDepth: "unknown", + }; + if (typeof ctx.tool?.list !== "function") return result; + try { + const tools = await ctx.tool.list({ sessionID }); + if (!Array.isArray(tools) || tools.some(tool => !tool || typeof tool.id !== "string" || !tool.id)) return result; + const allowed = new Set(["read", "write", "edit", "patch", "shell", "question", "skill", "subagent", "opencode_session_move"]); + result.registeredTools = [...new Set(tools.map(tool => tool.id).filter((id): id is string => typeof id === "string" && allowed.has(id)))].sort(); + result.toolCatalog = "available"; + } catch { /* Native config/error bodies can contain private values; keep only availability. */ } + return result; +} + +/** Bind only this installation's registered Skill bodies, never user literals. */ +async function bindSkillRequest( + ctx: PluginContext, + event: SessionBindingEvent, + skillTexts: ReadonlyArray, +): Promise { + const owns = (text: string) => text.includes(REPO_ROOT_TOKEN) && skillTexts.some(skill => text.includes(skill)); + const eligible = (message: SessionBindingEvent["messages"][number]) => + message.role === "user" || message.role === "system"; + const containsSkill = event.system.some(part => owns(part.text)) || event.messages.some(message => + eligible(message) && (typeof message.content === "string" + ? owns(message.content) + : message.content.some(part => part.type === "text" && typeof part.text === "string" && owns(part.text))), + ); + if (!containsSkill) return; + + // Do not mutate the projected source messages or reuse another request's root. + // Throwing aborts delivery if lookup or directory validation fails. + const repoRoot = await resolveRepoRoot(ctx, event.sessionID); + const bind = (text: string) => bindOwnedSkillText(text, skillTexts, repoRoot, event.sessionID); + event.system = event.system.map(part => owns(part.text) ? { ...part, text: bind(part.text) } : part); + event.messages = event.messages.map(message => { + if (!eligible(message)) return message; + if (typeof message.content === "string") { + return owns(message.content) ? { ...message, content: bind(message.content) } : message; + } + return { ...message, content: message.content.map(part => + part.type === "text" && typeof part.text === "string" && owns(part.text) + ? { ...part, text: bind(part.text) } : part, + ) }; + }); +} + /** * Registers every HelixHarness command, method skill and subagent role with an * OpenCode plugin context. Commands execute the canonical `commands/*.md` @@ -687,15 +825,17 @@ export async function registerHelixHarness( ): Promise { const plugin = loadPluginResources(options.pluginRoot ?? pluginRootFromModule()); - // Skill content is not safe to expose until the session-binding hook exists. - if (!ctx.tool || typeof ctx.tool.hook !== "function") { + // Neither tool results nor mentions may be exposed without their binding hooks. + if (!ctx.tool || typeof ctx.tool.hook !== "function" || typeof ctx.session.hook !== "function") { throw new Error("repo_root_hook_unavailable: Session directory binding is required."); } + const skillTexts = [...new Set(plugin.skills.map(skill => buildSkillContent(skill, plugin).trimEnd()))]; await ctx.tool.hook("execute.after", async (event) => { - if (event.tool !== "skill" || event.status !== "completed" || !hasRepoRootToken(event.result)) return; + await runProjectChecks(event, plugin.pluginRoot, () => resolveRepoRoot(ctx, event.sessionID)); + if (event.tool !== "skill" || event.status !== "completed" || !hasOwnedSkillResult(event.result, skillTexts)) return; try { const repoRoot = await resolveRepoRoot(ctx, event.sessionID); - replaceToolResultContent(event.result, repoRoot); + replaceToolResultContent(event.result, repoRoot, event.sessionID, skillTexts); } catch (error) { const failure = error instanceof RepoRootError ? error @@ -704,6 +844,27 @@ export async function registerHelixHarness( } }); + const utSessions = new Set(); + + // Publication checks run before native write/edit can expose partial UT state. + await ctx.tool.hook("execute.before", async event => { + await guardUtStateWrite(event, () => resolveRepoRoot(ctx, event.sessionID), utSessions.has(event.sessionID) || event.agent === "helix-unit-test-worker"); + const input = event.input as { command?: unknown } | undefined; + if (event.tool === "shell" && typeof input?.command === "string" && + input.command.includes(plugin.pluginRoot) && /(?:metrics|telemetry_consent|telemetryctl)\.py\b/.test(input.command)) { + const root = await resolveRepoRoot(ctx, event.sessionID); + input.command = `export HELIXHARNESS_SESSION_ID=${shellQuote(event.sessionID)} HELIXHARNESS_SESSION_CWD=${shellQuote(root)};\n${input.command}`; + } + }); + + for (const hook of ["context", "compaction", "generate", "title"] as const) { + await ctx.session.hook(hook, event => bindSkillRequest(ctx, event, skillTexts)); + } + + await ctx.session.hook("experimental.idle", event => { + if (event.background.length === 0) utSessions.delete(event.sessionID); + }); + await ctx.command.transform((editor) => { for (const command of plugin.commands) { editor.add({ @@ -711,21 +872,36 @@ export async function registerHelixHarness( description: command.description, async execute(input) { const repoRoot = await resolveRepoRoot(ctx, input.sessionID); - const context = hostContextFor(plugin, repoRoot); + const context = hostContextFor(plugin, repoRoot, input.sessionID); + if (["init", "propose", "apply", "archive", "ut", "bug-fix"].includes(command.name)) { + context.nativePreflight = await observeNativePreflight(ctx, input.sessionID); + if (context.nativePreflight.toolCatalog === "available") { + const missing = ["read", "shell"].filter(name => !context.nativePreflight!.registeredTools!.includes(name)); + if (missing.length) throw new Error(`opencode_preflight_tools_unavailable: ${missing.join(",")}`); + } + } 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 } : {}), - }); + const wasUt = utSessions.has(input.sessionID); + if (command.name === "ut") utSessions.add(input.sessionID); + else utSessions.delete(input.sessionID); + try { + 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 } : {}), + }); + } catch (error) { + if (wasUt) utSessions.add(input.sessionID); else utSessions.delete(input.sessionID); + throw error; + } }, }); } diff --git a/helixharness/opencode/project-checks.ts b/helixharness/opencode/project-checks.ts new file mode 100644 index 0000000..a33af9a --- /dev/null +++ b/helixharness/opencode/project-checks.ts @@ -0,0 +1,82 @@ +/** Native edit notifications reuse the generated project linters; no lifecycle inference. */ +import fs from "node:fs"; +import path from "node:path"; +import { spawn } from "node:child_process"; + +export interface CheckEvent { + tool: string; + status: "completed" | "error"; + sessionID: string; + id?: string; + input?: unknown; + result?: { content?: string | ReadonlyArray<{ type: "text" | "file"; text?: string }> }; +} +interface CheckResult { code: number; output: string; } + +export async function runBounded(command: string[], options: { timeoutMs?: number; maxBytes?: number } = {}): Promise { + return new Promise(resolve => { + const limit = options.maxBytes ?? 12 * 1024; + let size = 0; + const chunks: Buffer[] = []; + let reason = ""; + const child = spawn(command[0]!, command.slice(1), { detached: process.platform !== "win32", stdio: ["ignore", "pipe", "pipe"] }); + const stop = () => { + try { if (process.platform !== "win32" && child.pid) process.kill(-child.pid, "SIGKILL"); else child.kill("SIGKILL"); } catch { /* already exited */ } + }; + const timer = setTimeout(() => { reason = "timeout"; stop(); }, options.timeoutMs ?? 5000); + const drain = (data: Buffer) => { + const available = Math.max(0, limit - size); + chunks.push(data.subarray(0, available)); + size += Math.min(data.length, available); + if (data.length > available) { reason = "output_limit"; stop(); } + }; + child.stdout.on("data", drain); child.stderr.on("data", drain); + child.on("error", () => { clearTimeout(timer); resolve({ code: 1, output: "runtime_unavailable" }); }); + child.on("close", code => { + clearTimeout(timer); stop(); + resolve({ code: reason ? 1 : code ?? 1, output: Buffer.concat(chunks).toString("utf8") + (reason ? `\n${reason}` : "") }); + }); + }); +} + +function append(event: CheckEvent, text: string): void { + if (!event.result) return; + const content = event.result.content; + event.result.content = typeof content === "string" ? `${content}\n\n${text}` : + [...(content ?? []), { type: "text", text }]; +} + +function contained(root: string, target: string): boolean { + const relative = path.relative(root, target); + return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative); +} + +export async function runProjectChecks(event: CheckEvent, pluginRoot: string, + resolveRoot: () => Promise, run: (command: string[]) => Promise = runBounded): Promise { + if (event.status !== "completed" || !["write", "edit", "patch"].includes(event.tool)) return; + try { + const root = await resolveRoot(); + const input = event.input as { path?: unknown } | undefined; + if (typeof input?.path === "string" && !contained(root, path.resolve(root, input.path))) return; + const folder = path.join(root, "docs/harness/linters"); + if (!fs.existsSync(folder)) return; // Uninitialized repositories are unaffected. + if (!contained(root, fs.realpathSync(folder))) { + append(event, "WARN:project_check_unavailable: linter directory escapes the repository."); return; + } + const failures: string[] = []; + for (const name of ["invariant-check", "spec-sync-check"]) { + const candidates = [path.join(folder, `${name}.py`), path.join(folder, `${name}.sh`)]; + const script = candidates.find(candidate => fs.existsSync(candidate)); + if (!script || !fs.statSync(script).isFile() || !contained(root, fs.realpathSync(script))) { + failures.push(`${name}: missing or unsafe project linter`); continue; + } + const result = await run([process.env.HELIXHARNESS_OPENCODE_PYTHON || "python3", "-X", "utf8", + path.join(pluginRoot, "scripts/project_linter.py"), "--repo-root", root, "--linter", name]); + if (result.code !== 0) failures.push(`${name}: exit=${result.code}\n${result.output.slice(0, 6000)}`); + } + if (failures.length) append(event, `WARN:project_check_failed\n${failures.join("\n")}\nRepair the findings and rerun the project checks. This edit notification does not complete a workflow stage.`); + } catch { + // Optional diagnostics never expose native API errors or change edit success. + append(event, "WARN:project_check_unavailable: project checks could not run; run them explicitly before stage completion."); + } +} diff --git a/helixharness/opencode/tests/README.md b/helixharness/opencode/tests/README.md index fe858fc..a25330b 100644 --- a/helixharness/opencode/tests/README.md +++ b/helixharness/opencode/tests/README.md @@ -1,5 +1,9 @@ # OpenCode adapter verification / OpenCode 适配验收 +Current release support: **Stable on macOS with OpenCode 2.3.2**, within the [support matrix](../../../docs/opencode-testing.md). OpenCode 2.2.2 and 2.3.0 have automated compatibility coverage only. The dated checkpoints below retain their original acceptance boundaries and historical Preview decisions; they are not fresh test runs. + +当前发布支持:**macOS 上的 OpenCode 2.3.2 为 Stable**,范围以[支持矩阵](../../../docs/opencode-testing.md)为准。OpenCode 2.2.2、2.3.0 仅有自动化兼容覆盖。下列历史检查点保留当次验收边界与 Preview 决定,不代表本次重新执行了这些测试。 + Run these commands from the plugin directory (`helixharness/`). ```bash @@ -34,7 +38,22 @@ a tool's presence in the advertised catalog is not proof that it can execute. These are adapter integration tests. Scripted model responses do not establish that a real model can complete Init → Propose → Apply → Archive, produce correct business code, or follow all ownership rules. -OpenCode remains Preview until that separate acceptance is completed. +A separate assisted run on 2026-11-20 used OpenCode 2.3.2 and DeepSeek to complete one synthetic single-repository lifecycle, including a controlled contract amendment and fresh parallel Standards/Spec review. The project suite passed 13 tests; an independent acceptance suite passed 14. Operator confirmations were supplied through the native form API. This does not establish TUI/desktop UI or real-model Workspace acceptance. + +A separate assisted run on 2026-11-23 completed one synthetic two-repository Workspace Init → Propose → Apply → Archive on OpenCode 2.3.2 with DeepSeek. Both RepoJobs moved their native sessions to their ownership roots; nested leaf reviewers exercised depth 2. A provider MUST_FIX was repaired and both axes rerun. The repository suites passed 10 and 19 tests, plus 5 independent cross-repository acceptance groups. Standalone Maven UT used two concurrent native workers with full six-loop evidence and a second run under the actual OS temporary directory: 40 tests passed with 100% line/branch coverage for both classes; business sources and pom.xml were unchanged. The acceptance harness supplied synthetic choices through native forms/prompts. It also corrected report classification and parent atomic finalization; this is not unattended protocol-compliance evidence. Workspace read-only repositories, cancellation/recovery, UT Gradle/incremental/retry paths, D2C and TUI/desktop UI remain outside this run. + +At that checkpoint, OpenCode remained Preview. On 2026-11-23, regression tests verified the fixes for Skill mention repository binding and symbolic-link resource containment. Unit tests cover all four request hooks (context, compaction, generate, title), source-message preservation, literal input, registration failures, and internal/external/dangling/cyclic resource links. Native tests on OpenCode 2.2.2, 2.3.0 and 2.3.2 inspect actual model requests for direct mentions, command attachments, native activation, cross-session roots and literal preservation. Fault-injected session lookup/validation failures must stop before the model receives a request. Auxiliary request hooks have unit-level coverage; those scripted regressions alone do not establish real-model workflow or TUI/desktop UI acceptance. + +## UT classification and atomic-state regression + +`scripts/ut_artifacts.py` validates structured observation evidence, separates confirmed defects, risks and optional improvements, and generates classification counts/reports. State publication reuses the same-directory fsync/replace writer. OpenCode requires an execute.before guard that blocks native write/edit of final UT state, including directory/file aliases within active registered UT parent/canonical worker scope and absolute aliases; reserved names match case-insensitively. Ordinary relative editing outside UT does not query the session API; staging and the explicit publisher remain available. This is not a sandbox for arbitrary shell code, and source-reference validation does not prove every business interpretation. + +After the fixes were frozen on 2026-11-23, a fresh OpenCode 2.3.2 + DeepSeek Maven UT run used two native workers and full six-loop evidence. The operator answered only the normal task-list form. All 29 tests passed, both classes reached 100% line/branch coverage, and main sources/pom.xml stayed unchanged. The generated counts were 0 confirmed defects, 2 risks and 2 optional improvements. All 15 observed atomic publication receipts succeeded; there were no direct-target write attempts and no corrective prompts. The fixture had no prior tests or experience. This is one synthetic acceptance case, not a reliability guarantee for all projects. + +After the seven compatibility fixes, the suite passes 122 Bun tests (435 assertions), including 21 native tests on each of 2.2.2, 2.3.0 and 2.3.2. The Python suite passes 821 tests with 7 skips, including 27 classification/publication regressions. Coverage includes legacy/timeout unknown totals, coherent active/archived cohorts, saved-record corruption, evidence cleanup, reproduced ClassCastException and non-JVM source references, existing POSIX modes, host ownership, ordinary editing under session faults and casing. JDK/Python runtime probes retain actual ClassCastException/ZeroDivisionError as confirmed High observations. Windows matching is unit-only; ACL/xattr and multi-file transactions are not guaranteed. Typecheck passes. + + +A second fresh OpenCode 2.3.2 + DeepSeek acceptance run after these seven compatibility fixes completed both native workers and all six loops: 38 test executions passed, both classes reached 100% line/branch coverage, and source/pom hashes stayed unchanged. Counts were 0 confirmed defects, 2 risks and 3 optional improvements. All 15 atomic publication receipts succeeded, with no direct-target write attempts or corrective prompts; only the normal task confirmation was answered. Published schema-2 snapshots remained valid after worker cleanup. The three synthetic sessions were archived and the isolated server stopped. ## 中文说明 @@ -50,5 +69,126 @@ OpenCode remains Preview until that separate acceptance is completed. 以及 worker 的两路独立派发、leaf 角色拒绝委派和深度不足拦截。必须检查真实调用结果,不能仅凭 工具出现在列表中判断权限有效。 -这些结果证明宿主适配链路可用;真实模型执行完整需求、业务实现正确性及全部所有权规则的 -验收仍需单独完成,因此支持级别保持 Preview。 +另一次于 2026-11-20 执行的辅助验收使用 OpenCode 2.3.2 + DeepSeek,完成了合成单仓的 +Init → Propose → Apply → Archive 闭环,期间有操作者原生问答确认、一次受控合同修订和 +新一轮并行 Standards/Spec 评审。项目测试 13 项、独立验收 14 项通过。这不覆盖 TUI/桌面 UI +或多仓 Workspace 的真实模型验收,也不能外推全部业务场景与所有权规则。 + +2026-11-23 另一次操作者辅助验证在 OpenCode 2.3.2 + DeepSeek 上完成合成双仓 Workspace +Init → Propose → Apply → Archive。RepoJob 先切换真实会话目录到 ownership_root,depth=2 +派发独立 leaf reviewer;provider 的 MUST_FIX 修复后重新双轴评审通过。两仓分别通过 +10/19 项测试,外部独立验收通过 5 组。独立 Maven UT 用两个并发原生 worker 执行完整 +6 Loop,并在实际 OS 临时目录重跑:40 项测试通过,两类行/分支覆盖率 100%,业务源码和 +pom.xml 未变。验收脚本通过真实 form/prompt 提供合成选择,并纠正了报告误报分类与父流程 +原子写收口;这不能证明无人干预时始终遵守协议。本轮未覆盖 read-only repo、取消/恢复、 +UT Gradle/增量/失败重试、D2C 或 TUI/桌面 UI。 + +当次验收时,支持级别保持 Preview。2026-11-23 的回归已验证 Skill mention 绑定与资源符号链接边界修复: +单元测试覆盖 context/compaction/generate/title 四类请求 hook、源消息保留、用户字面输入、 +注册失败,以及内部/外部/悬空/环状资源链接。OpenCode 2.2.2、2.3.0、2.3.2 的原生测试 +检查直接 mention、命令附件、原生 Skill 激活、跨会话目录与用户字面输入的实际模型请求; +故障注入时,查询或目录校验失败必须在模型收到请求前阻断。辅助请求 hook 为单元级覆盖; +上述脚本模型回归本身不构成真实模型业务闭环或 TUI/桌面 UI 验收。 + +## UT 分类与原子状态回归 + +`scripts/ut_artifacts.py` 校验结构化观察的来源/反例,分别统计已证实缺陷、未确认风险与可选改进, +生成分类报告;UT 状态通过同目录 fsync/replace 原子发布。OpenCode 的必需 execute.before +保护在 native write/edit 执行前拒绝直接写最终 UT 工件,保留路径按大小写不敏感匹配;绝对别名及活跃注册 UT 父会话/规范 worker 内的相对别名受检, +非 UT 普通相对编辑不查询会话 API;不声称是任意 +shell 的文件系统沙箱,引用校验也不等于机械证明所有业务语义。 + +2026-11-23 冻结修复后,使用 OpenCode 2.3.2 + DeepSeek 在无旧测试/经验的全新 Maven 夹具 +完成两个原生 worker 的完整 6 Loop。操作者只回答任务清单确认:29 项测试通过,两类行/分支 +覆盖率 100%,业务源码与 pom.xml 不变;分类为 0 缺陷 / 2 风险 / 2 改进。15 次原子发布回执 +均成功,无直接目标写入尝试,无分类或原子写纠正提示。这是一轮合成场景验收,不外推全部项目。 + +七项兼容修复后:122 项 Bun 测试、435 个断言;2.2.2/2.3.0/2.3.2 各 21 项原生测试通过。 +Python 全量 821 项(7 跳过)通过,含 27 项分类/发布回归:旧会话/超时未知计数、当前与归档 +整组选择、旧记录损坏、证据清理、ClassCastException 与非 JVM 源码引用、原文件 mode、宿主 +写域、会话查询故障下的普通编辑、大小写绕过。JDK/Python 实际异常探针均保留已证实 High。 +Windows 仅单元级覆盖;不承诺 ACL/xattr、多文件事务。类型检查通过。 + +七项兼容修复后的第二轮全新 OpenCode 2.3.2 + DeepSeek 验收:两个原生 worker 完成全部 6 Loop, +38 次测试执行通过,两类行/分支覆盖率 100%,业务源码与 pom 哈希不变。分类 0 缺陷 / 2 风险 / +3 改进;15 次原子回执全部成功,无直接目标写入或纠正提示,仅回答正常任务确认。worker 清理后 +schema-2 分类快照仍校验通过;3 个合成会话已归档,隔离服务已停止。 + + +## Recovery and auxiliary workflow acceptance (2026-11-23) + +The follow-up suite ran 852 Python tests: 845 passed and 7 skipped, including 31 new recovery, precompile and read-only regressions. Each of OpenCode 2.2.2, 2.3.0 and 2.3.2 passed 122 Bun tests (435 assertions); typecheck passed. + +Real-model OpenCode 2.3.2 + DeepSeek acceptance verified a read-only Workspace repository, native Apply cancellation followed by fresh-session recovery, partial Archive cancellation followed by recovery that skipped the already archived repository, and an injected native context-hook failure that blocked dependent dispatch without inline fallback. Active Single BugFix reproduced an injected Unicode regression, preserved the original Apply baseline, obtained new independent reviews and archived with 9 tests passing. Status covered empty, active, blocked and completed fixtures without changing files. + +Gradle UT preserved an existing sentinel test: the first run passed 14 test executions, and the incremental run passed 31 across three classes with 100% line/branch coverage. A synthetic imported ordinary failure was retried under a new Worker ID; an imported timeout remained terminal and unretried. Those historical records are synthetic inputs, not claims of prior native execution or an actual one-hour wait. Incomplete classification remained unknown. The combined UT/Status trace contained 33 successful atomic publication receipts and no native direct-final-target write attempts. Main sources/build files/wrappers and existing tests stayed unchanged within each request. + +The [UT precompile guard](../../scripts/ut_precompile.py) runs the build tool on every invocation. Default output validation is limited to standard root-project directories; active multi-module/custom directories must be verified by the parent and supplied explicitly using repeated `--class-directory` arguments. It does not recursively guess active modules or establish test success. Real Kotlin/Groovy compilation, Windows execution, TUI/desktop UI and a naturally elapsed one-hour worker timeout remain outside this acceptance. At that checkpoint, support remained Preview. + +## 恢复与辅助流程补充验收(2026-11-23) + +Python 全量 852 项:845 通过、7 跳过,新增 31 项恢复、预编译和只读回归。OpenCode 2.2.2、2.3.0、2.3.2 各通过 122 项 Bun 测试(435 断言),类型检查通过。 + +OpenCode 2.3.2 + DeepSeek 真实模型验证了只读仓库、Apply 原生取消后新会话恢复、部分 Archive 取消后跳过已归档仓库,以及原生 context hook 故障时阻断依赖、不降级内联。Active Single BugFix 复现注入的 Unicode 回归,保留原 Apply 基线,取得全新独立双轴评审并完成无提交归档,9 项测试通过。Status 的空仓、活跃、阻塞、已归档四种状态均未修改文件。 + +Gradle UT 保留既有哨兵测试:首轮 14 次测试执行通过,增量最终 31 次通过,三个类行/分支覆盖率均为 100%。合成导入的普通失败由新 Worker ID 重试成功,导入的 timeout 保持终态、不重试;这些历史工件不代表实际旧原生执行,也不代表实等一小时。分类不全时继续显示未知。UT/Status 合计观察到 33 次成功原子发布,无 native 直接写最终目标的尝试;每次请求内业务源码、构建文件、wrapper 与既有测试不变。 + +[UT 预编译门禁](../../scripts/ut_precompile.py) 每轮均调用构建工具;默认仅验证根项目标准输出目录,多模块/自定义目录须由父流程核实后通过重复的 `--class-directory` 显式传入。不递归猜测活动模块,不把编译就绪当测试通过。真实 Kotlin/Groovy 编译、Windows、TUI/桌面 UI 和自然经过一小时的 worker 超时仍未验收;当次验收时,支持等级保持 Preview。 + + +## Explicit D2C evidence gate and entry preflight (2026-11-23) + +The OpenCode adapter now exposes an [explicit D2C gate](../../hosts/opencode/runtime.md), reusing the canonical checkpoint/guard. A new request enters phase 0 and immediately claims it using the actual native session identity. Completion checks require the same owner, current invocation, healthy source/capture fingerprint, valid PNG, canonical measurements and the fenced JSON in the Markdown fidelity report. This is an explicit audit, not a native Stop interceptor or proof that screenshots came from an authenticated browser/MasterGo session. Audit limits are documented; large supported captures receive a capacity diagnostic rather than a visual-failure verdict. + +Canonical marker/state writers hold one nonblocking lock from read through validation/persistence. Concurrent contenders can both receive busy and retry. Unique PID entries allow the next writer to recover from a killed process without deleting a new owner's lock. Dedicated regressions cover stale writers, simultaneous claims, explicit exits, SIGTERM/SIGKILL recovery, malformed images, zero-placeholder measurements and source-path confinement. Existing Cursor projection and canonical D2C tests remain required. + +Mutation command entry observes allowlisted registered native tools and session-move API availability, blocking known missing read/shell before prompt admission. Unavailable metadata remains unknown; Status/Config do not depend on the lookup. Registration does not establish permissions or actual execution. Effective nesting depth remains unknown because the SDK has no direct accessor; native delegation admission and independent review remain mandatory. Skill result/mention identity binding changes only complete owned bodies, preserving surrounding literals and unrelated Skills. + +OpenCode 2.2.2, 2.3.0 and 2.3.2 each passed 136 Bun tests, including 23 scripted native tests. OpenCode 2.3.2 + DeepSeek used its real native identity for a fresh owner claim and accepted a controlled completed synthetic checkpoint; missing screenshot and another native owner were rejected. A real mutation entry observed the catalogue and unknown depth, then stopped at the actual Router prerequisite blocker without creating business artifacts. These are real-model checks using synthetic evidence, not a complete design-to-code or TUI/desktop acceptance. At that checkpoint, support remained Preview. + +## D2C 显式证据门禁与入口预检(2026-11-23) + +OpenCode 适配器新增 [D2C 显式门禁](../../hosts/opencode/runtime.md),复用 canonical checkpoint/guard。新请求先进入 phase 0,再用实际原生会话身份立即认领;完成检查校验同一 owner、本次调用、健康的源码/截图指纹、有效 PNG、canonical 测量和 Markdown 报告中的 fenced JSON。它是主动调用的审计,不是原生 Stop 拦截,也不能证明截图来自已认证浏览器/MasterGo。容量边界见运行说明;超大截图返回容量诊断,不作视觉失败结论。 + +canonical marker/state 写入从读取、校验到落盘使用同一非阻塞锁,并发竞争可双方均返回 busy 后重试。唯一 PID 条目支持后续写入恢复已终止进程的遗留,不删除新 owner 的锁。专项回归覆盖旧写入、并发认领、显式退出、SIGTERM/SIGKILL 恢复、损坏图片、空占位测量和源码路径边界;仍须运行原有 Cursor projection 与 canonical D2C 测试。 + +写入型命令入口只观察允许名单中的原生工具登记和会话移动 API;已知缺少 read/shell 时在 prompt 准入前阻断。元数据不可用保持未知,Status/Config 不依赖此查询。登记不等于权限或执行成功;SDK 无直接查询有效嵌套深度的接口,因此深度保持未知,继续保留原生委派准入和独立评审要求。Skill 结果/mention 仅绑定完整的本插件正文,不改外围字面值和其他 Skill。 + +OpenCode 2.2.2、2.3.0、2.3.2 各通过 136 项 Bun 测试,其中包含 23 项脚本原生测试。OpenCode 2.3.2 + DeepSeek 用真实原生身份完成新 owner 认领,并接受受控的合成完成检查点;缺失截图和另一原生 owner 均被拒绝。真实写入型入口取得工具登记和未知深度后,按 Router 的实际前置条件阻断,未创建业务工件。这些是真实模型消费合成证据的检查,不构成完整设计稿还原或 TUI/桌面验收;当次验收时,支持等级保持 Preview。 + + +## Targeted terminal UI acceptance (2026-11-23) + +OpenCode 2.3.2 loaded an independent plugin copy without installing development dependencies. A controlled standalone Git-root package passed native install, update, uniquely pinned rollback and removal, with business sentinel files preserved. Its Git transport used isolated rewrites to a local synthetic repository; this does not establish public GitHub transport or monorepo subdirectory installation. For this repository's nested plugin, use a checkout and configure its absolute package directory as described in the [installer](../../hosts/opencode/installer.md). The native CLI does not accept an absolute directory as `plugin add` input in this tested version. + +A real OpenCode PTY terminal client with DeepSeek exercised native question selection, permission rejection, double-Escape interruption of a running shell command, reattachment with the same native session/history, the nine-command menu and readonly Status. Permission refusal left the target file absent; cancellation recorded native `interrupted=true`; Status preserved project file hashes. Terminal byte streams and reconstructed text states are interaction evidence, not desktop GUI or pixel-layout acceptance. Setup attempts that allowed a probe or let a command finish are retained separately and are not counted as refusal/cancellation passes. + +The first empty Status receipt was correct, but its model response appended a filter suggestion absent from the receipt. The canonical command now separates empty and nonempty presentation: empty responses end after scope, no requirements and the no-rerun note. Three fresh isolated Git-root real-model cases (default query, completed query, and a terminal default query) followed that branch; a nonempty fixture retained its actual `next_command`. This is a prompt-contract mitigation, not deterministic final-output interception. At that checkpoint, support remained Preview; production projects, unattended reliability, complete terminal coverage and desktop GUI remain unverified. + +OpenCode 2.3.2 在未安装开发依赖的情况下加载了独立插件副本。受控的独立 Git 根包通过原生安装、更新、唯一版本固定后的回退和卸载,业务哨兵文件保持不变。Git 传输使用隔离规则改写到本地合成仓库,不代表公开 GitHub 链路或本仓子目录安装通过。本仓嵌套插件采用 checkout 后配置绝对包目录的方式,见[安装说明](../../hosts/opencode/installer.md);该已测版本的 native `plugin add` 不接受绝对目录。 + +真实 OpenCode PTY 终端客户端与 DeepSeek 验证了原生问答选择、权限拒绝、双 Escape 中断运行中 shell、同原生会话及历史重连、九命令菜单和只读 Status。拒绝后目标文件不存在,中断产生原生 `interrupted=true`,Status 项目文件哈希不变。终端字节流和重建文本只证明交互,不构成图形桌面或像素布局验收;准备阶段曾允许探针或正常结束命令,已单列保留,不计入拒绝/取消通过。 + +首次空 Status 回执正确,模型却追加了回执中没有的筛选建议。公共合同已拆分空/非空展示分支,空结果在查询范围、没有需求、未重跑说明后结束。三个全新独立 Git 根目录真实模型场景(默认查询、completed 查询、终端默认查询)均遵守该分支;非空样本仍保留真实 `next_command`。这属于指令合同缓解,不是确定性最终输出拦截。当次验收时支持等级保持 Preview,生产项目、无人干预可靠性、完整终端覆盖和图形桌面仍未验收。 + + +## Existing Java project acceptance (2026-11-23) + +A synthetic existing Java17/Maven library began with one business class and four sentinel tests. Real-model Init/Propose completed. Its deliberately unborn Git fixture correctly blocked review when the implementation overlapped the dirty baseline; that case remains a blocker, not an Apply pass. A fresh controlled copy restored all 34 original baseline files byte-for-byte and received an operator-created initial test commit and the same approved ready planning inputs, without old private Apply/Review state. Real-model Apply then passed seven tests and two independent native reviewer axes (both APPROVE); an external Java probe passed 65 assertions. Existing tests and pom.xml remained byte-identical. Archive confirmed and authorized five exact knowledge paths, archived without model commits/pushes, and the readonly completed gate returned archived with archive_check=passed. The reviewed code seal and initial fixture HEAD stayed unchanged through Archive. + +This is a synthetic, multi-session controlled acceptance with normal product, Advisory and knowledge-scope choices. The clean copy's planning inputs and initial test history were fixture preparation, not a claim of an uninterrupted unattended production lifecycle. Production services, real Kotlin/Groovy/multi-module compilation, Windows and naturally elapsed one-hour timeouts remain outside this run. + +合成 Java17/Maven 存量类库初始包含一个业务类和四个哨兵测试,真实模型完成 Init/Propose。刻意无 Git 初始历史的夹具因实现与脏基线重叠而正确阻断评审,该场景不计 Apply 通过。随后在全新受控副本中逐字节恢复 34 个原基线文件,由操作者建立仅限测试的初始提交并预置同一已确认 ready 规划输入,不复制旧 private Apply/Review 状态。真实 Apply 通过七个测试和两个独立原生评审轴(均 APPROVE),外部 Java 探针通过 65 个断言;原测试与 pom.xml 字节不变。Archive 按确认的五个精确知识路径先授权后更新,模型不提交/推送;只读 completed 门禁返回 archived、archive_check=passed,代码封存哈希与初始夹具 HEAD 保持不变。 + +这是含正常产品、Advisory、知识范围选择的多会话合成受控验收。clean 副本的规划输入与初始测试历史属于夹具准备,不代表连续无人干预生产流程。生产服务、真实 Kotlin/Groovy/多模块编译、Windows 及自然经过一小时的超时仍未覆盖。 + + +## Helix-owned capability adapters (2026-11-23) + +The [capability guide](../../hosts/opencode/capabilities.md) documents the new adapters: consented stage facts/workflow traces without native transcript collection, atomic progress updates over canonical tasks.md, bounded post-edit project linters, and confirmation-gated pinned fast-forward source updates. Project settings hooks and equivalent Stop/failure/session-end business hooks remain unsupported; idle does not finish a stage. Uncollected usage/execution remains unavailable, including after Archive. + +Python regression coverage includes synthetic source updates through the entire check/prepare/decide/install authorization chain, stale/dirty/divergent/detached/no-upstream/version-mismatch rejection, disabled Git hooks, idempotent installation-step retry, task receipts/dependencies/path confinement, consent/session isolation, stage-only supplements and archive seals. The complete suite runs 910 tests: 903 pass and 7 skip. OpenCode 2.2.2, 2.3.0 and 2.3.2 each pass 146 Bun tests (515 assertions), including actual native edit feedback and consent-off → synthetic grant → stage start/finish; typecheck passes. The two older clients retain automated-compatibility status only. + +A fresh OpenCode 2.3.2 + DeepSeek synthetic acceptance used the same native session to update task progress, observe an intentionally failing project check, repair the code and finish both tasks. Disabled telemetry created no ledger. After a harness-supplied synthetic consent grant, a new stage started and finished with the correct native session hash; the model did not modify consent. An unmanaged source copy returned a real update warning and was not changed. The session was archived and its isolated server stopped. This is targeted adapter acceptance, not a new full Init → Archive or production acceptance run, and it does not establish unattended model reliability. Actual source installation is covered by the synthetic Git authorization tests, not by updating the user's checkout. + +本次补齐阶段统计、canonical 任务进度、编辑后巡检和确认后锁定 commit 的源码快进更新。全量 Python 910 项中 7 项跳过;三个 OpenCode 版本各通过 146 项 Bun 测试,类型检查通过。真实模型定向验收验证了任务更新、巡检失败修复、关闭统计时不建账本、合成授权后的同会话阶段收口,以及更新拒绝修改不受管理的副本。该授权仅属于隔离测试,不修改用户授权;未重新宣称完整工作流或生产验收。 diff --git a/helixharness/opencode/tests/core.test.ts b/helixharness/opencode/tests/core.test.ts index de640ee..0962e33 100644 --- a/helixharness/opencode/tests/core.test.ts +++ b/helixharness/opencode/tests/core.test.ts @@ -89,8 +89,8 @@ describe("plugin resources", () => { ); 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"); + expect(plugin.capabilities.telemetry).toBe("emulated"); + expect(plugin.capabilities.plugin_update).toBe("emulated"); }); test("maps disable-model-invocation to OpenCode autoinvoke=false", () => { @@ -122,7 +122,7 @@ describe("rendering", () => { 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("`update_plan` is emulated by `scripts/task_plan.py"); expect(text).toContain("HelixHarness 公共命令唯一契约"); expect(text).toContain("--arguments='--feature demo'"); }); diff --git a/helixharness/opencode/tests/e2e.test.ts b/helixharness/opencode/tests/e2e.test.ts index 8471558..dee98e3 100644 --- a/helixharness/opencode/tests/e2e.test.ts +++ b/helixharness/opencode/tests/e2e.test.ts @@ -1,10 +1,56 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test"; import fs from "node:fs"; import path from "node:path"; +import { createHash } from "node:crypto"; +import { REPO_ROOT_TOKEN } from "../core.ts"; import { eventually, startNativeFixture } from "./native-fixture.ts"; const PLUGIN_ROOT = path.resolve(import.meta.dir, "../.."); const ENABLED = process.env.HELIXHARNESS_OPENCODE_E2E === "1"; + +describe.skipIf(!ENABLED)("native optional project checks and stage identity", () => { + let native: Awaited>; + beforeAll(async () => { native = await startNativeFixture(PLUGIN_ROOT, 2, undefined, true); }, 30_000); + afterAll(async () => { await native?.stop(); }); + + test("real edit completes and returns generated linter failure to the model", async () => { + const folder = path.join(native.directory, "docs/harness/linters"); + fs.mkdirSync(folder, { recursive: true }); + fs.writeFileSync(path.join(folder, "invariant-check.py"), "print('synthetic invariant finding');raise SystemExit(1)\n"); + fs.writeFileSync(path.join(folder, "spec-sync-check.py"), "print('synthetic spec passed')\n"); + const session = await native.session("Synthetic project checks"); + await native.prompt(session.id, "HELIX_E2E_PROJECT_CHECK"); + const row = await eventually(async () => native.observations.find(item => item.tag === "HELIX_E2E_PROJECT_CHECK" && item.results.includes("project_check_failed")), Boolean); + expect(row!.results).toContain("synthetic invariant finding"); + expect(fs.readFileSync(path.join(native.directory, "synthetic-edited.txt"), "utf8")).toBe("synthetic edit"); + }, 30_000); + + test("real shell hook supplies only its requesting native session and directory", async () => { + const session = await native.session("Synthetic telemetry identity"); + await native.prompt(session.id, "HELIX_E2E_TELEMETRY_BINDING"); + const row = await eventually(async () => native.observations.find(item => item.tag === "HELIX_E2E_TELEMETRY_BINDING" && item.results.includes("HELIXHARNESS_SESSION_CWD")), Boolean); + expect(row!.results).toContain(session.id); + expect(row!.results).toContain(fs.realpathSync(native.directory)); + expect(row!.results).toContain(path.join(native.directory, "synthetic-host-state")); + }, 30_000); + + test("real native shell rechecks consent and records only the authorized stage", async () => { + expect(Bun.spawnSync(["git", "-c", "core.hooksPath=/dev/null", "init", "-q", native.directory]).exitCode).toBe(0); + const home = path.join(native.directory, "synthetic-telemetry"); + fs.mkdirSync(home, { recursive: true }); + fs.writeFileSync(path.join(home, "config.json"), JSON.stringify({ endpoint: "disabled-for-synthetic-test" })); + const session = await native.session("Synthetic stage lifecycle"); + await native.prompt(session.id, "HELIX_E2E_TELEMETRY_LIFECYCLE"); + const row = await eventually(async () => native.observations.find(item => item.tag === "HELIX_E2E_TELEMETRY_LIFECYCLE" && item.results !== "[]"), Boolean); + expect(row!.results).toContain("recorded"); + expect(row!.results).toContain("telemetry_disabled"); + expect(row!.results).toContain("started"); + const ledger = JSON.parse(fs.readFileSync(path.join(native.directory, "docs/eval/native-telemetry/eval-log.json"), "utf8")); + expect(ledger.entries).toHaveLength(1); + expect(ledger.entries[0].status).toBe("completed"); + expect(ledger.entries[0].session_hash).toBe("session-" + createHash("sha256").update(session.id).digest("hex").slice(0, 32)); + }, 30_000); +}); let fixture: Awaited>; async function request(_port: number, route: string, init: RequestInit = {}): Promise { @@ -149,6 +195,7 @@ describe.skipIf(!ENABLED)("installed OpenCode plugin", () => { await fixture.prompt(session.id, "HELIX_E2E_SKILL"); const observation = await eventually(async () => fixture.observations.find((x) => x.tag === "HELIX_E2E_SKILL" && x.results !== "[]"), Boolean); expect(observation!.results).toContain("HelixHarness Host Context"); + expect(observation!.results).toContain(`native_session_id: \`${session.id}\``); expect(observation!.results).toContain(fs.realpathSync(target)); expect(observation!.results).not.toContain("@@HELIXHARNESS_REPO_ROOT@@"); }, 20_000); @@ -210,3 +257,186 @@ describe.skipIf(!ENABLED)("OpenCode default nesting limit", () => { } finally { await limited.stop(); } }, 30_000); }); + + +describe.skipIf(!ENABLED)("native Skill mention binding", () => { + let native: Awaited>; + beforeAll(async () => { native = await startNativeFixture(PLUGIN_ROOT); }, 30_000); + afterAll(async () => { await native?.stop(); }); + + async function observed(tag: string) { + const deadline = Date.now() + 15_000; + while (Date.now() < deadline) { + const result = native.observations.find(row => row.tag === tag); + if (result) return result; + await Bun.sleep(50); + } + throw new Error(`Synthetic model did not receive ${tag}`); + } + + test("direct mentions bind each requesting session instead of the plugin location", async () => { + const other = fs.mkdirSync(path.join(native.directory, "mention other $&"), { recursive: true })!; + const a = await native.session("Synthetic mention A"); + const b = await native.session("Synthetic mention B", other); + for (const [session, tag, expected] of [ + [a, "HELIX_E2E_MENTION_ALPHA", native.directory], + [b, "HELIX_E2E_MENTION_BETA", other], + ] as const) { + await native.data(`/api/session/${session.id}/prompt`, { text: tag, skills: [{ id: "helix-tdd" }] }); + const row = await observed(tag); + expect(row.messages.includes(REPO_ROOT_TOKEN)).toBe(false); + expect(row.messages.includes(`repo_root: \`${fs.realpathSync(expected)}\``)).toBe(true); + expect(row.results).toBe("[]"); + } + }, 30_000); + + test("mention binding preserves literal markers in the user input", async () => { + const session = await native.session("Synthetic literal mention"); + const tag = "HELIX_E2E_MENTION_LITERAL"; + await native.data(`/api/session/${session.id}/prompt`, { + text: `${tag} User literal ${REPO_ROOT_TOKEN}`, skills: [{ id: "helix-tdd" }], + }); + const row = await observed(tag); + expect(row.messages.split(REPO_ROOT_TOKEN)).toHaveLength(2); + expect(row.messages.includes(`repo_root: \`${fs.realpathSync(native.directory)}\``)).toBe(true); + }, 20_000); + + test("command Skill attachments are bound before the model request", async () => { + const session = await native.session("Synthetic command mention"); + const response = await native.request(`/api/session/${session.id}/command`, { name: "helix:status", text: "HELIX_E2E_MENTION_COMMAND", skills: [{ id: "helix-tdd" }] }); + expect(response.ok).toBe(true); + const row = await observed("HELIX_E2E_MENTION_COMMAND"); + expect(row.messages.includes(REPO_ROOT_TOKEN)).toBe(false); + expect(row.messages.includes(`repo_root: \`${fs.realpathSync(native.directory)}\``)).toBe(true); + }, 20_000); + + test("native skill activation is bound without invoking the skill tool", async () => { + const session = await native.session("Synthetic native activation"); + await native.data(`/api/session/${session.id}/prompt`, { text: "HELIX_E2E_MENTION_ACTIVATION", resume: false }); + const response = await native.request(`/api/experimental/session/${session.id}/skill`, { id: "helix-tdd" }); + expect(response.ok).toBe(true); + const row = await observed("HELIX_E2E_MENTION_ACTIVATION"); + expect(row.messages.includes(REPO_ROOT_TOKEN)).toBe(false); + expect(row.messages.includes(`repo_root: \`${fs.realpathSync(native.directory)}\``)).toBe(true); + expect(row.results).toBe("[]"); + }, 20_000); +}); + + +for (const fault of ["lookup", "invalid"] as const) { + describe.skipIf(!ENABLED)(`native mention ${fault} failure`, () => { + let native: Awaited>; + beforeAll(async () => { native = await startNativeFixture(PLUGIN_ROOT, 2, fault); }, 30_000); + afterAll(async () => { await native?.stop(); }); + + test("binding failure aborts before the model receives the Skill", async () => { + const session = await native.session("Synthetic mention lookup failure"); + await native.data(`/api/session/${session.id}/prompt`, { + text: "HELIX_E2E_MENTION_FAILURE", skills: [{ id: "helix-tdd" }], + }); + const deadline = Date.now() + 10_000; + let info: any; + while (Date.now() < deadline) { + info = await native.data(`/api/session/${session.id}`); + if (info.time.idle || native.observations.length) break; + await Bun.sleep(50); + } + expect(info.outcome).toBe("failed"); + expect(native.observations).toHaveLength(0); + }, 15_000); + }); +} + + +describe.skipIf(!ENABLED)("native UT atomic publication", () => { + let stateFixture: Awaited>; + beforeAll(async () => { stateFixture = await startNativeFixture(PLUGIN_ROOT, 2, undefined, true); }, 30_000); + afterAll(async () => { await stateFixture?.stop(); }); + test("blocks first native direct write before it changes the target", async () => { + const dir = path.join(stateFixture.directory, "docs/specs/active/acceptance"); + fs.mkdirSync(dir, {recursive:true}); + const target = path.join(dir, "unittest-summary.md"); + fs.writeFileSync(target, "previous complete report"); + const session = await stateFixture.session("Synthetic direct UT write"); + await stateFixture.request(`/api/session/${session.id}/prompt`, {text:"HELIX_E2E_UT_DIRECT_WRITE"}); + await eventually(async () => stateFixture.observations.some(x=>x.tag==="HELIX_E2E_UT_DIRECT_WRITE" && x.results!=="[]"), Boolean); + expect(fs.readFileSync(target,"utf8")).toBe("previous complete report"); + expect(stateFixture.observations.some(x=>x.results.includes("ut_atomic_write_required"))).toBe(true); + }); + test("blocks a native write through a file-link alias", async () => { + const target = path.join(stateFixture.directory,"docs/specs/active/acceptance/unittest-summary.md"); + fs.writeFileSync(target,"complete alias target"); + fs.symlinkSync(target,path.join(stateFixture.directory,"ut-report-link.md")); + const session=await stateFixture.session("Synthetic aliased UT write"); + await stateFixture.request(`/api/session/${session.id}/command`,{name:"helix:ut",text:"HELIX_E2E_UT_ALIAS_WRITE"}); + await eventually(async()=>stateFixture.observations.some(x=>x.tag==="HELIX_E2E_UT_ALIAS_WRITE" && x.results.includes("ut_atomic_write_required")),Boolean); + expect(fs.readFileSync(target,"utf8")).toBe("complete alias target"); + }); + test("publishes staged content through the real helper", async () => { + const session = await stateFixture.session("Synthetic atomic UT write"); + await stateFixture.request(`/api/session/${session.id}/prompt`, {text:"HELIX_E2E_UT_STAGED_WRITE"}); + await eventually(async () => stateFixture.observations.some(x=>x.tag==="HELIX_E2E_UT_STAGED_WRITE" && x.results.includes("atomic")), Boolean); + const target = path.join(stateFixture.directory,"docs/specs/active/acceptance/unittest-summary.md"); + expect(fs.readFileSync(target,"utf8")).toBe("Synthetic UTF-8 report 验证\n"); + expect(fs.existsSync(target+".tmp")).toBe(false); + }); +}); + +// Actual filesystem transport regression: casing must never evade the reserved namespace. +describe.skipIf(!ENABLED)('native UT casing regression',()=>{ + let fixture:Awaited>; + beforeAll(async()=>{fixture=await startNativeFixture(PLUGIN_ROOT,2,undefined,true);},30_000); + afterAll(async()=>{await fixture?.stop();}); + test('blocks casing variants before write on the host filesystem',async()=>{ + const dir=path.join(fixture.directory,'docs/specs/active/acceptance');fs.mkdirSync(dir,{recursive:true}); + const target=path.join(dir,'unittest-summary.md');fs.writeFileSync(target,'private complete report',{mode:0o600}); + const caseAlias=path.join(fixture.directory,'DOCS/SPECS/ACTIVE/acceptance/UNITTEST-SUMMARY.MD'); + const caseInsensitive=fs.existsSync(caseAlias); + const session=await fixture.session('Synthetic casing write'); + await fixture.request(`/api/session/${session.id}/prompt`,{text:'HELIX_E2E_UT_CASE_WRITE'}); + await eventually(async()=>fixture.observations.some(x=>x.tag==='HELIX_E2E_UT_CASE_WRITE' && x.results.includes('ut_atomic_write_required')),Boolean); + expect(fs.readFileSync(target,'utf8')).toBe('private complete report'); + expect(fs.statSync(target).mode & 0o777).toBe(0o600); + if(caseInsensitive)expect(fs.readFileSync(caseAlias,'utf8')).toBe('private complete report'); + }); +}); + +for(const fault of ['lookup','invalid'] as const)describe.skipIf(!ENABLED)(`ordinary native write with ${fault} session API`,()=>{ + let fixture:Awaited>; + beforeAll(async()=>{fixture=await startNativeFixture(PLUGIN_ROOT,2,fault,true);},30_000); + afterAll(async()=>{await fixture?.stop();}); + test('keeps ordinary editor usable despite plugin directory lookup failure',async()=>{ + const session=await fixture.session('Synthetic ordinary editor'); + await fixture.request(`/api/session/${session.id}/prompt`,{text:'HELIX_E2E_ORDINARY_WRITE'}); + await eventually(async()=>fs.existsSync(path.join(fixture.directory,'ordinary.txt')),Boolean); + expect(fs.readFileSync(path.join(fixture.directory,'ordinary.txt'),'utf8')).toBe('Synthetic UTF-8 report 验证\n'); + }); +}); + + +describe.skipIf(!ENABLED)("native entry preflight metadata", () => { + test("mutation prompt has actual session identity and native catalogue observations", async () => { + const native=await startNativeFixture(PLUGIN_ROOT,2,undefined,true); + try { + const session=await native.session("Synthetic preflight observation"); + const response=await native.request(`/api/session/${session.id}/command`,{name:"helix:apply",text:"synthetic"}); + expect(response.ok).toBe(true); + const ctx=JSON.stringify(await native.context(session.id)); + expect(ctx).toContain(`native_session_id: \`${session.id}\``); + expect(ctx).toContain("native_tool_catalog: `available`"); + expect(ctx).toContain("native_delegation_depth: `unknown`"); + expect(ctx).not.toContain("@@HELIXHARNESS_SESSION_ID@@"); + } finally {await native.stop();} + },30000); + test("missing required native tools prevent command admission and model delivery", async () => { + const native=await startNativeFixture(PLUGIN_ROOT,2,undefined,true,"missing-shell"); + try { + const session=await native.session("Synthetic unavailable shell"); + const response=await native.request(`/api/session/${session.id}/command`,{name:"helix:apply",text:"must-not-admit"}); + expect(response.ok).toBe(false); + expect(await response.text()).toContain("opencode_preflight_tools_unavailable: shell"); + expect(JSON.stringify(await native.context(session.id))).not.toContain("must-not-admit"); + expect(native.observations).toHaveLength(0); + } finally {await native.stop();} + },30000); +}); diff --git a/helixharness/opencode/tests/managed-bundle-probe.ts b/helixharness/opencode/tests/managed-bundle-probe.ts new file mode 100644 index 0000000..3cf80e0 --- /dev/null +++ b/helixharness/opencode/tests/managed-bundle-probe.ts @@ -0,0 +1,69 @@ +/** Test-only probe: import a real managed installation, never the checkout's runtime. */ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; +import { eventually, startNativeFixture } from "./native-fixture.ts"; + +const [root, workspace, mode] = process.argv.slice(2); +assert(root && workspace && ["setup", "native"].includes(mode!)); +assert(!fs.existsSync(path.join(root, "node_modules"))); +assert(!fs.existsSync(path.join(root, "opencode/tests"))); + +if (mode === "setup") { + const manifest = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8")); + assert.equal(manifest.exports["."], "./opencode/index.ts"); + const plugin = (await import(pathToFileURL(path.join(root, manifest.exports["."])).href)).default; + const commands: any[] = [], skills: any[] = [], agents: string[] = []; + const before: any[] = [], after: any[] = [], hooks: string[] = [], prompts: any[] = []; + await plugin.setup({ + location: { directory: workspace }, + command: { async transform(callback: any) { callback({ add: (item: any) => commands.push(item) }); } }, + skill: { async transform(callback: any) { callback({ add: (item: any) => skills.push(item) }); } }, + agent: { async transform(callback: any) { + callback({ update(id: string, update: any) { + update({ name: id, mode: "primary", hidden: false, permissions: [] }); agents.push(id); + } }); + } }, + tool: { async hook(name: string, callback: any) { (name === "execute.before" ? before : after).push(callback); } }, + session: { + async hook(name: string) { hooks.push(name); }, + async get() { return { location: { directory: workspace } }; }, + async prompt(input: any) { prompts.push(input); }, + }, + }); + assert.equal(commands.length, 9); assert.equal(skills.length, 8); assert.equal(agents.length, 17); + assert(agents.includes("helix-worker")); assert(hooks.includes("experimental.idle")); + await commands.find(command => command.name === "helix:status").execute({ sessionID: "ses_bundle", prompt: { text: "--help" } }); + assert(prompts[0].text.includes(`plugin_root: \`${fs.realpathSync(root)}\``)); + let guarded = false; + try { + await before[0]({ tool: "write", sessionID: "ses_bundle", input: { path: "docs/specs/active/synthetic/unittest-summary.md" } }); + } catch (error) { guarded = String(error).includes("ut_atomic_write_required"); } + assert(guarded); + await after[0]({ tool: "write", sessionID: "ses_bundle", status: "completed", input: { path: "ordinary.txt" }, result: { content: "synthetic saved" } }); + console.log(JSON.stringify({ mode, commands: commands.length, skills: skills.length, agents: agents.length, ut_guard: true })); +} else { + const native = await startNativeFixture(root, 2, undefined, true); + try { + const commands = await native.data("/api/command"); + const skills = await native.data("/api/skill"); + const agents = await native.data("/api/agent"); + assert.equal(commands.filter((item: any) => item.name.startsWith("helix:")).length, 9); + assert.equal(skills.filter((item: any) => item.id.startsWith("helix-")).length, 8); + assert(agents.some((item: any) => item.id === "helix-worker")); + const folder = path.join(native.directory, "docs/harness/linters"); + fs.mkdirSync(folder, { recursive: true }); + fs.writeFileSync(path.join(folder, "invariant-check.py"), "print('synthetic bundle invariant');raise SystemExit(1)\n"); + fs.writeFileSync(path.join(folder, "spec-sync-check.py"), "print('synthetic bundle spec passed')\n"); + const project = await native.session("Synthetic managed bundle project check"); + await native.prompt(project.id, "HELIX_E2E_PROJECT_CHECK"); + const result = await eventually(async () => native.observations.find(item => item.tag === "HELIX_E2E_PROJECT_CHECK" && item.results.includes("project_check_failed")), Boolean); + assert(result!.results.includes("synthetic bundle invariant")); + const ut = await native.session("Synthetic managed bundle UT guard"); + await native.prompt(ut.id, "HELIX_E2E_UT_DIRECT_WRITE"); + await eventually(async () => native.observations.find(item => item.tag === "HELIX_E2E_UT_DIRECT_WRITE" && item.results.includes("ut_atomic_write_required")), Boolean); + assert(!fs.existsSync(path.join(native.directory, "docs/specs/active/acceptance/unittest-summary.md"))); + console.log(JSON.stringify({ mode, native_registration: true, project_check: true, ut_guard: true })); + } finally { await native.stop(); } +} diff --git a/helixharness/opencode/tests/native-fixture.ts b/helixharness/opencode/tests/native-fixture.ts index 2b4407c..4a17fe2 100644 --- a/helixharness/opencode/tests/native-fixture.ts +++ b/helixharness/opencode/tests/native-fixture.ts @@ -2,11 +2,13 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import { pathToFileURL } from "node:url"; export interface ModelObservation { tag: string; tools: string[]; results: string; + messages: string; } export async function eventually(read: () => Promise, ready: (value: T) => boolean): Promise { @@ -19,7 +21,7 @@ export async function eventually(read: () => Promise, ready: (value: T) => } } -export async function startNativeFixture(pluginRoot: string, depth = 2) { +export async function startNativeFixture(pluginRoot: string, depth = 2, lookupFault?: "lookup" | "invalid", allowStateWrite = false, catalogueFault?: "missing-shell") { const executable = Bun.which(process.env.HELIXHARNESS_OPENCODE_BIN ?? "opencode"); if (!executable) throw new Error("OpenCode E2E requires opencode or HELIXHARNESS_OPENCODE_BIN"); const directory = fs.mkdtempSync(path.join(os.tmpdir(), "helix-opencode-e2e-")); @@ -34,13 +36,34 @@ export async function startNativeFixture(pluginRoot: string, depth = 2) { .match(/HELIX_E2E_[A-Z_]+/)?.[0] ?? "command"; const tools = (body.tools ?? []).map((tool: any) => tool.function.name) as string[]; const results = JSON.stringify(body.messages.filter((m: any) => m.role === "tool")); - observations.push({ tag, tools, results }); + observations.push({ tag, tools, results, messages: JSON.stringify(body.messages) }); const calls: Array<{ name: string; arguments: Record }> = []; let text = results.includes("Subagent depth limit reached") ? "BLOCKED: native_depth_unavailable" : "Synthetic transport completed"; if (/denied|not allowed|No tool named/i.test(results)) text = "BLOCKED: leaf_delegation_denied"; + if (tag === "HELIX_E2E_UT_STAGED_WRITE" && results !== "[]" && !results.includes("atomic")) { + const quote = (value: string) => "'" + value.replaceAll("'", "'\\''") + "'"; + const target = path.join(directory, "docs/specs/active/acceptance/unittest-summary.md"); + calls.push({ name: "shell", arguments: { command: + `python3 ${quote(path.join(pluginRoot, "scripts/ut_artifacts.py"))} --repo-root ${quote(directory)} --feature acceptance write --name unittest-summary.md --source ${quote(target + ".tmp")}` } }); + } if (results === "[]") { - if (tag === "HELIX_E2E_SKILL" || tag === "HELIX_E2E_MISSING_ROOT") { + if (tag === "HELIX_E2E_PROJECT_CHECK") { + calls.push({ name: "write", arguments: { path: "synthetic-edited.txt", content: "synthetic edit" } }); + } else if (tag === "HELIX_E2E_TELEMETRY_LIFECYCLE") { + const quote = (value: string) => "'" + value.replaceAll("'", "'\\''") + "'"; + const metrics = `python3 ${quote(path.join(pluginRoot, "scripts/metrics.py"))} --repo-root ${quote(directory)} --platform opencode`; + const grant = `import sys;from pathlib import Path;sys.path.insert(0,${JSON.stringify(path.join(pluginRoot, "scripts"))});import telemetry_consent;from telemetry_hosts.opencode import OpenCodeAdapter;r=Path(${JSON.stringify(directory)}).resolve();telemetry_consent.set_mode(r,"opencode",OpenCodeAdapter().consent_cache_path(),"project","enabled",consent_source="explicit-command",user_confirmed=True)`; + calls.push({ name: "shell", arguments: { command: `${metrics} start --feature native-telemetry --stage propose --trigger user_command\npython3 -c ${quote(grant)}\n${metrics} start --feature native-telemetry --stage propose --trigger user_command\n${metrics} finish --feature native-telemetry --stage propose --status completed` } }); + } else if (tag === "HELIX_E2E_TELEMETRY_BINDING") { + const quote = (value: string) => "'" + value.replaceAll("'", "'\\''") + "'"; + calls.push({ name: "shell", arguments: { command: `python3 ${quote(path.join(pluginRoot, "scripts/metrics.py"))} --help >/dev/null\npython3 -c 'import os,json;print(json.dumps({k:os.environ.get(k) for k in ("HELIXHARNESS_SESSION_ID","HELIXHARNESS_SESSION_CWD","HELIXHARNESS_OPENCODE_HOME")}))'` } }); + } else if (tag === "HELIX_E2E_ORDINARY_WRITE" || tag === "HELIX_E2E_UT_CASE_WRITE" || tag === "HELIX_E2E_UT_DIRECT_WRITE" || tag === "HELIX_E2E_UT_STAGED_WRITE" || tag === "HELIX_E2E_UT_ALIAS_WRITE") { + calls.push({ name: "write", arguments: { + path: tag === "HELIX_E2E_ORDINARY_WRITE" ? "ordinary.txt" : tag === "HELIX_E2E_UT_CASE_WRITE" ? "DOCS/SPECS/ACTIVE/acceptance/UNITTEST-SUMMARY.MD" : tag === "HELIX_E2E_UT_ALIAS_WRITE" ? "ut-report-link.md" : "docs/specs/active/acceptance/unittest-summary.md" + (tag === "HELIX_E2E_UT_STAGED_WRITE" ? ".tmp" : ""), + content: "Synthetic UTF-8 report 验证\n", + } }); + } else if (tag === "HELIX_E2E_SKILL" || tag === "HELIX_E2E_MISSING_ROOT") { if (removeBeforeSkill) { fs.rmSync(removeBeforeSkill, { recursive: true, force: true }); removeBeforeSkill = undefined; @@ -83,8 +106,35 @@ export async function startNativeFixture(pluginRoot: string, depth = 2) { }); }, }); + let installation = pluginRoot; + if (lookupFault || catalogueFault) { + installation = path.join(directory, "fault-plugin"); + fs.mkdirSync(installation); + fs.writeFileSync(path.join(installation, "package.json"), JSON.stringify({ + name: "helix-synthetic-fault", version: "1.0.0", type: "module", exports: "./index.ts", + })); + const core = JSON.stringify(pathToFileURL(path.join(pluginRoot, "opencode/core.ts")).href); + const fault = lookupFault === "lookup" + ? 'throw new Error("synthetic lookup failure details");' + : lookupFault === "invalid" ? 'return { location: { directory: "relative" } };' : 'return ctx.session.get({ sessionID });'; + fs.writeFileSync(path.join(installation, "index.ts"), ` + import { registerHelixHarness } from ${core}; + export default { id: "helix-synthetic-fault", async setup(ctx) { + await registerHelixHarness({ + location: ctx.location, command: ctx.command, skill: ctx.skill, + agent: ctx.agent, tool: ${catalogueFault ? '{ hook: (name, callback) => ctx.tool.hook(name, callback), list: async () => [{id:"read"}] }' : 'ctx.tool'}, + session: { + get: async ({sessionID}) => { ${fault} }, + move: ctx.session.move, + prompt: input => ctx.session.prompt(input), + hook: (name, callback) => ctx.session.hook(name, callback), + }, + }, { pluginRoot: ${JSON.stringify(pluginRoot)} }); + } }; + `); + } fs.writeFileSync(path.join(directory, "opencode.json"), JSON.stringify({ - plugins: [pluginRoot], model: "helix-test/scripted", + plugins: [installation], model: "helix-test/scripted", providers: { "helix-test": { name: "Synthetic transport fixture", package: "@opencode/ai/providers/openai-compatible", settings: { baseURL: `http://127.0.0.1:${model.port}/v1`, apiKey: "synthetic" }, @@ -93,6 +143,10 @@ export async function startNativeFixture(pluginRoot: string, depth = 2) { permissions: [ { action: "execute", resource: "*", effect: "deny" }, { action: "skill", resource: "*", effect: "allow" }, + ...(allowStateWrite ? [ + { action: "edit", resource: "*", effect: "allow" }, + { action: "shell", resource: "*", effect: "allow" }, + ] : []), ], experimental: { subagent_depth: depth }, })); @@ -109,6 +163,9 @@ export async function startNativeFixture(pluginRoot: string, depth = 2) { OPENCODE_TEST_HOME: path.join(directory, "home"), XDG_CONFIG_HOME: path.join(directory, "config"), XDG_DATA_HOME: path.join(directory, "data"), XDG_CACHE_HOME: path.join(directory, "cache"), XDG_STATE_HOME: path.join(directory, "state"), + HELIXHARNESS_OPENCODE_HOME: path.join(directory, "synthetic-host-state"), + HELIXHARNESS_TELEMETRY_HOME: path.join(directory, "synthetic-telemetry"), + HELIXHARNESS_TELEMETRY_DISABLE_SCHEDULER: "1", OPENCODE_PASSWORD: "synthetic-e2e-password", }, stdout: "ignore", stderr: "ignore", diff --git a/helixharness/opencode/tests/plugin.test.ts b/helixharness/opencode/tests/plugin.test.ts index 5778c60..2230557 100644 --- a/helixharness/opencode/tests/plugin.test.ts +++ b/helixharness/opencode/tests/plugin.test.ts @@ -6,6 +6,7 @@ import path from "node:path"; import { REPO_ROOT_TOKEN, type PluginContext, + type SessionBindingEvent, registerHelixHarness, } from "../core.ts"; @@ -15,13 +16,36 @@ const SESSION_ROOT = fs.mkdirSync(path.join(FIXTURE_ROOT, "session repo's direct const LOCATION_ROOT = fs.mkdirSync(path.join(FIXTURE_ROOT, "plugin-location"), { recursive: true })!; afterAll(() => fs.rmSync(FIXTURE_ROOT, { recursive: true, force: true })); +test("owned telemetry shell calls receive per-call native identity without global environment mutation", async () => { + const { ctx, captured } = createContext(); + await registerHelixHarness(ctx, { pluginRoot: PLUGIN_ROOT }); + const input = { command: `python3 '${PLUGIN_ROOT}/scripts/metrics.py' --help` }; + const before = process.env.HELIXHARNESS_SESSION_ID; + await captured.beforeHooks[0]({ tool: "shell", sessionID: "ses_boundA", input }); + expect(input.command).toContain("HELIXHARNESS_SESSION_ID='ses_boundA'"); + expect(input.command).toContain("HELIXHARNESS_SESSION_CWD="); + expect(input.command).toContain("'\\''"); + expect(process.env.HELIXHARNESS_SESSION_ID).toBe(before); +}); + +test("ordinary shell calls are unchanged and telemetry identity lookup fails closed", async () => { + const { ctx, captured } = createContext({ getSession: async () => { throw new Error("synthetic unavailable"); } }); + await registerHelixHarness(ctx, { pluginRoot: PLUGIN_ROOT }); + const ordinary = { command: "git status --short" }; + await captured.beforeHooks[0]({ tool: "shell", sessionID: "ses_A", input: ordinary }); + expect(ordinary.command).toBe("git status --short"); + await expect(captured.beforeHooks[0]({ tool: "shell", sessionID: "ses_A", input: { command: `python3 '${PLUGIN_ROOT}/scripts/metrics.py' --help` } })).rejects.toThrow("repo_root_lookup_failed"); +}); + interface Captured { commands: Array>; skills: Array>; agents: Array<{ id: string; draft: Record }>; prompts: Array>; + beforeHooks: Array<(event: any) => Promise | void>; toolHooks: Array<(event: any) => Promise | void>; sessionGets: string[]; + sessionHooks: Array<{ name: string; callback: (event: any) => Promise | void }>; registrationOrder: string[]; } @@ -30,6 +54,7 @@ function createContext(options: { sessionDirectory?: string; getSession?: (sessionID: string) => Promise; hookError?: Error; + sessionHookError?: string; } = {}): { ctx: PluginContext; captured: Captured } { const captured: Captured = { commands: [], @@ -37,7 +62,9 @@ function createContext(options: { agents: [], prompts: [], toolHooks: [], + beforeHooks: [], sessionGets: [], + sessionHooks: [], registrationOrder: [], }; const ctx = { @@ -72,13 +99,18 @@ function createContext(options: { }, }, tool: { - async hook(_name: string, callback: (event: any) => Promise | void) { - captured.registrationOrder.push("hook"); + async hook(name: string, callback: (event: any) => Promise | void) { + captured.registrationOrder.push(name === "execute.before" ? "before-hook" : "hook"); if (options.hookError) throw options.hookError; - captured.toolHooks.push(callback); + (name === "execute.before" ? captured.beforeHooks : captured.toolHooks).push(callback); }, }, session: { + async hook(name: string, callback: (event: any) => Promise | void) { + captured.registrationOrder.push(`session-hook:${name}`); + if (options.sessionHookError === name) throw new Error("Synthetic request hook unavailable"); + captured.sessionHooks.push({ name, callback }); + }, async get({ sessionID }: { sessionID: string }) { captured.sessionGets.push(sessionID); if (options.getSession) return options.getSession(sessionID); @@ -171,19 +203,18 @@ describe("OpenCode registration", () => { const { ctx, captured } = createContext(); await registerHelixHarness(ctx, { pluginRoot: PLUGIN_ROOT }); - const result = { - content: `repo_root: \`${REPO_ROOT_TOKEN}\``, - }; + const body = captured.skills.find(s => s.id === "helix-d-d2c")!.content; + const result = { content: body }; await captured.toolHooks[0]({ tool: "skill", sessionID: "ses_test", status: "completed", result, }); - expect(result.content).toBe(`repo_root: \`${fs.realpathSync(SESSION_ROOT)}\``); + expect(result.content).toContain(`repo_root: \`${fs.realpathSync(SESSION_ROOT)}\``); const arrayResult = { - content: [{ type: "text" as const, text: `x ${REPO_ROOT_TOKEN}` }], + content: [{ type: "text" as const, text: body }], }; await captured.toolHooks[0]({ tool: "skill", @@ -191,7 +222,7 @@ describe("OpenCode registration", () => { status: "completed", result: arrayResult, }); - expect(arrayResult.content[0].text).toBe(`x ${fs.realpathSync(SESSION_ROOT)}`); + expect(arrayResult.content[0].text).toContain(`repo_root: \`${fs.realpathSync(SESSION_ROOT)}\``); const untouched = { content: "no marker" }; await captured.toolHooks[0]({ @@ -257,7 +288,7 @@ describe("session directory binding fails closed", () => { }, }); await registerHelixHarness(ctx, { pluginRoot: PLUGIN_ROOT }); - const original = `unsafe original ${REPO_ROOT_TOKEN}`; + const original = `unsafe original ${captured.skills.find(s => s.id === "helix-d-d2c")!.content}`; const event = { tool: "skill", sessionID: "failed", status: "completed", result: { @@ -314,12 +345,13 @@ describe("session directory binding fails closed", () => { const init = captured.commands.find((command) => command.name === "helix:init")!; const commandA = init.execute({ sessionID: "A", prompt: { text: "A" } }); const fileBlock = { type: "file", uri: "file:///synthetic-attachment" }; - const resultB = { content: [fileBlock, { type: "text", text: `B ${REPO_ROOT_TOKEN}` }] }; + const body = captured.skills.find(s => s.id === "helix-d-d2c")!.content; + const resultB = { content: [fileBlock, { type: "text", text: body }] }; await captured.toolHooks[0]({ tool: "skill", sessionID: "B", status: "completed", result: resultB }); releaseA(); await commandA; expect(captured.prompts[0].text).toContain(`repo_root: \`${fs.realpathSync(SESSION_ROOT)}\``); - expect(resultB.content[1]).toEqual({ type: "text", text: `B ${fs.realpathSync(repoB)}` }); + expect((resultB.content[1] as any).text).toContain(`repo_root: \`${fs.realpathSync(repoB)}\``); expect(resultB.content[0]).toBe(fileBlock); currentA = repoB; await init.execute({ sessionID: "A", prompt: { text: "A moved" } }); @@ -331,16 +363,17 @@ describe("session directory binding fails closed", () => { const directory = fs.mkdirSync(path.join(FIXTURE_ROOT, "repo $& $$ $` $'"), { recursive: true })!; const { ctx, captured } = createContext({ sessionDirectory: directory }); await registerHelixHarness(ctx, { pluginRoot: PLUGIN_ROOT }); - const result = { content: `before ${REPO_ROOT_TOKEN} after` }; + const body = captured.skills.find(s => s.id === "helix-d-d2c")!.content; + const result = { content: body }; await captured.toolHooks[0]({ tool: "skill", sessionID: "literal", status: "completed", result }); - expect(result.content).toBe(`before ${fs.realpathSync(directory)} after`); + expect(result.content).toContain(`repo_root: \`${fs.realpathSync(directory)}\``); expect(result.content).not.toContain(REPO_ROOT_TOKEN); }); test("required hook is registered before command, skill or agent surfaces", async () => { const { ctx, captured } = createContext(); await registerHelixHarness(ctx, { pluginRoot: PLUGIN_ROOT }); - expect(captured.registrationOrder).toEqual(["hook", "command", "skill", "agent"]); + expect(captured.registrationOrder).toEqual(["hook", "before-hook", "session-hook:context", "session-hook:compaction", "session-hook:generate", "session-hook:title", "session-hook:experimental.idle", "command", "skill", "agent"]); }); for (const missing of [true, false]) { @@ -354,3 +387,262 @@ describe("session directory binding fails closed", () => { }); } }); + + +describe("native Skill mention request binding", () => { + const hookNames = ["context", "compaction", "generate", "title"] as const; + async function context(options: Parameters[0] = {}) { + const result = createContext(options); + await registerHelixHarness(result.ctx, { pluginRoot: PLUGIN_ROOT }); + expect(result.captured.sessionHooks.map(h => h.name)).toEqual([...hookNames, "experimental.idle"]); + return result; + } + + for (const name of hookNames) { + test(`binds owned skill text in ${name} requests without changing source messages`, async () => { + const { captured } = await context(); + const skill = captured.skills.find(s => s.id === "helix-tdd")!; + const source = { role: "user", content: `\n${skill.content.trimEnd()}\n` }; + const system = { type: "text", text: skill.content, metadata: { synthetic: true } }; + const sourceText = source.content; + const event = { sessionID: "mention", messages: [source], system: [system] }; + await captured.sessionHooks.find(h => h.name === name)!.callback(event); + expect(event.messages[0].content).toContain(`repo_root: \`${fs.realpathSync(SESSION_ROOT)}\``); + expect(event.messages[0].content).not.toContain(REPO_ROOT_TOKEN); + expect(event.system[0].text).not.toContain(REPO_ROOT_TOKEN); + expect(event.system[0].metadata).toBe(system.metadata); + expect(source.content).toBe(sourceText); + expect(system.text).toContain(REPO_ROOT_TOKEN); + expect(captured.sessionGets).toEqual(["mention"]); + }); + } + + test("preserves user literals, unrelated skills, media and metadata", async () => { + const { captured } = await context(); + const skill = captured.skills.find(s => s.id === "helix-feedback")!; + const media = { type: "media", media: { synthetic: true } }; + const userLiteral = `User literal: ${REPO_ROOT_TOKEN} $ARGUMENTS`; + const textPart = { type: "text", text: `${userLiteral}\n${skill.content}` }; + const source = { role: "user", content: [textPart, media], metadata: { synthetic: true } }; + const unrelated = { role: "user", content: `Unrelated skill: ${REPO_ROOT_TOKEN}` }; + const event: SessionBindingEvent = { sessionID: "mention", messages: [source, unrelated], system: [] }; + await captured.sessionHooks.find(h => h.name === "context")!.callback(event); + const parts = event.messages[0].content as ReadonlyArray<{ type: string; text?: string }>; + expect(parts[0].text).toContain(userLiteral); + expect(parts[0].text).toContain(`repo_root: \`${fs.realpathSync(SESSION_ROOT)}\``); + expect(parts[1]).toBe(media); + expect(event.messages[0].metadata).toBe(source.metadata); + expect(event.messages[1]).toBe(unrelated); + expect(textPart.text).toContain(skill.content); + }); + + test("re-resolves moved and interleaved sessions without caching", async () => { + const b = fs.mkdirSync(path.join(FIXTURE_ROOT, "mention B $& $$ $` $'"), { recursive: true })!; + let a = SESSION_ROOT; + const { captured } = await context({ getSession: async id => ({ location: { directory: id === "A" ? a : b } }) }); + const text = captured.skills.find(s => s.id === "helix-tdd")!.content; + const hook = captured.sessionHooks.find(h => h.name === "context")!.callback; + for (const [id, expected] of [["A", SESSION_ROOT], ["B", b], ["A", b]]) { + if (id === "A" && expected === b) a = b; + const event = { sessionID: id, messages: [{ role: "user", content: text }], system: [] }; + await hook(event); + expect(event.messages[0].content).toContain(`repo_root: \`${fs.realpathSync(expected)}\``); + } + expect(captured.sessionGets).toEqual(["A", "B", "A"]); + }); + + for (const failure of ["lookup", "invalid"] as const) { + test(`${failure} failure aborts the model request without mutating it`, async () => { + const { captured } = await context({ getSession: async () => { + if (failure === "lookup") throw new Error("private synthetic detail"); + return { location: { directory: "relative" } }; + } }); + const event = { sessionID: "failed", messages: [{ role: "user", content: captured.skills[0].content }], system: [] }; + const before = JSON.stringify(event); + const hook = captured.sessionHooks.find(h => h.name === "context")!.callback; + let error: unknown; + try { await hook(event); } catch (caught) { error = caught; } + expect(error).toBeInstanceOf(Error); + expect((error as Error).message).toContain(failure === "lookup" ? "repo_root_lookup_failed" : "repo_root_invalid"); + expect((error as Error).message).not.toContain("private synthetic"); + expect(JSON.stringify(event)).toBe(before); + }); + } + + test("unrelated model text does not query the session", async () => { + const { captured } = await context({ getSession: async () => { throw new Error("must not query"); } }); + const event = { sessionID: "unrelated", messages: [{ role: "user", content: REPO_ROOT_TOKEN }], system: [] }; + const before = JSON.stringify(event); + await captured.sessionHooks.find(h => h.name === "context")!.callback(event); + expect(JSON.stringify(event)).toBe(before); + expect(captured.sessionGets).toEqual([]); + }); + + for (const name of hookNames) { + test(`rejecting ${name} hook prevents all surface registration`, async () => { + const { ctx, captured } = createContext({ sessionHookError: name }); + await expect(registerHelixHarness(ctx, { pluginRoot: PLUGIN_ROOT })).rejects.toThrow(); + expect(captured.commands).toEqual([]); + expect(captured.skills).toEqual([]); + expect(captured.agents).toEqual([]); + }); + } + + test("missing request hook prevents all surface registration", async () => { + const { ctx, captured } = createContext(); + delete (ctx.session as any).hook; + await expect(registerHelixHarness(ctx, { pluginRoot: PLUGIN_ROOT })).rejects.toThrow("repo_root_hook_unavailable"); + expect(captured.commands).toEqual([]); + expect(captured.skills).toEqual([]); + expect(captured.agents).toEqual([]); + }); +}); + + +test("registers UT direct-write guard before public entry points", async () => { + const {ctx,captured}=createContext(); + await registerHelixHarness(ctx,{pluginRoot:PLUGIN_ROOT}); + expect(captured.beforeHooks).toHaveLength(1); + await expect(Promise.resolve(captured.beforeHooks[0]({tool:"write",sessionID:"synthetic",input:{path:"docs/specs/active/sample/unittest-session.md"}}))).rejects.toThrow("ut_atomic_write_required"); + expect(captured.registrationOrder.indexOf("before-hook")).toBeLessThan(captured.registrationOrder.indexOf("command")); +}); + +test('UT scope protects aliases without making ordinary editing depend on session lookup',async()=>{ + let broken=false; + const {ctx,captured}=createContext({getSession:async()=>{if(broken)throw Error('synthetic API failure');return {location:{directory:SESSION_ROOT}};}}); + await registerHelixHarness(ctx,{pluginRoot:PLUGIN_ROOT}); + const event={tool:'write',sessionID:'active-ut',input:{path:'ordinary.txt'}}; + broken=true;await captured.beforeHooks[0](event);expect(captured.sessionGets).toEqual([]); + broken=false;await captured.commands.find(c=>c.name==='helix:ut')!.execute({sessionID:'active-ut',prompt:{text:''}}); + broken=true;await expect(Promise.resolve(captured.beforeHooks[0](event))).rejects.toThrow('repo_root'); + const idle=captured.sessionHooks.find(h=>h.name==='experimental.idle')!;expect(idle).toBeDefined(); + await idle.callback({sessionID:'active-ut',background:[{kind:'subagent'}]}); + await expect(Promise.resolve(captured.beforeHooks[0](event))).rejects.toThrow('repo_root'); + await idle.callback({sessionID:'another',background:[]}); + await expect(Promise.resolve(captured.beforeHooks[0](event))).rejects.toThrow('repo_root'); + await idle.callback({sessionID:'active-ut',background:[]});await captured.beforeHooks[0](event); + await expect(Promise.resolve(captured.beforeHooks[0]({...event,agent:'helix-unit-test-worker'}))).rejects.toThrow('repo_root'); + broken=false;await captured.commands.find(c=>c.name==='helix:ut')!.execute({sessionID:'active-ut',prompt:{text:''}}); + await captured.commands.find(c=>c.name==='helix:status')!.execute({sessionID:'active-ut',prompt:{text:''}}); + broken=true;await captured.beforeHooks[0](event); +}); + +describe("native session identity binding", () => { + test("commands expose their actual requesting identity while preserving literal arguments", async () => { + const { ctx, captured } = createContext(); + await registerHelixHarness(ctx, { pluginRoot: PLUGIN_ROOT }); + await captured.commands.find(c => c.name === "helix:status")!.execute({ + sessionID: "native-owner-alpha", prompt: { text: "literal @@HELIXHARNESS_SESSION_ID@@" }, + }); + expect(captured.prompts[0].text).toContain("native_session_id: `native-owner-alpha`"); + expect(captured.prompts[0].text).toContain("literal @@HELIXHARNESS_SESSION_ID@@"); + }); + + test("native skill results bind each request's identity without caching", async () => { + const { ctx, captured } = createContext(); + await registerHelixHarness(ctx, { pluginRoot: PLUGIN_ROOT }); + const body = captured.skills.find(s => s.id === "helix-d-d2c")!.content; + for (const sessionID of ["native-owner-alpha", "native-owner-beta"]) { + const event: any = { tool: "skill", sessionID, status: "completed", result: { content: body } }; + for (const hook of captured.toolHooks) await hook(event); + expect(event.result.content).toContain(`native_session_id: \`${sessionID}\``); + expect(event.result.content).not.toContain("@@HELIXHARNESS_SESSION_ID@@"); + } + expect(body).toContain("@@HELIXHARNESS_SESSION_ID@@"); + }); + + for (const shape of ["string", "blocks"] as const) { + test(`native skill ${shape} binds only complete owned bodies and preserves surrounding literals`, async () => { + const { ctx, captured } = createContext(); + await registerHelixHarness(ctx, { pluginRoot: PLUGIN_ROOT }); + const body = captured.skills.find(s => s.id === "helix-d-d2c")!.content; + const literal = `literal ${REPO_ROOT_TOKEN} @@HELIXHARNESS_SESSION_ID@@`; + const text = `${literal}\n${body}\n${literal}`; + const event: any = {tool:"skill",sessionID:"owned-native",status:"completed", + result:{content:shape === "string" ? text : [{type:"text",text},{type:"text",text:literal}]}}; + await captured.toolHooks[0](event); + const bound = shape === "string" ? event.result.content : event.result.content[0].text; + expect(bound).toContain("native_session_id: `owned-native`"); + expect(bound.startsWith(literal)).toBe(true); + expect(bound.endsWith(literal)).toBe(true); + if (shape === "blocks") expect(event.result.content[1].text).toBe(literal); + }); + test(`unrelated skill ${shape} token literals do not trigger lookup or mutation`, async () => { + const { ctx, captured } = createContext({getSession:async()=>{throw new Error("must not resolve");}}); + await registerHelixHarness(ctx, {pluginRoot:PLUGIN_ROOT}); + const literal = `other skill ${REPO_ROOT_TOKEN} @@HELIXHARNESS_SESSION_ID@@`; + const event:any={tool:"skill",sessionID:"unrelated",status:"completed", + result:{content:shape === "string" ? literal : [{type:"text",text:literal}]}}; + const before=JSON.stringify(event); + await captured.toolHooks[0](event); + expect(JSON.stringify(event)).toBe(before); + expect(captured.sessionGets).toEqual([]); + }); + } + + test("mention binding changes only owned bodies and keeps source messages intact", async () => { + const { ctx, captured } = createContext(); + await registerHelixHarness(ctx, { pluginRoot: PLUGIN_ROOT }); + const body = captured.skills.find(s => s.id === "helix-d-d2c")!.content; + const source = { role: "user", content: body + "\nliteral @@HELIXHARNESS_SESSION_ID@@" }; + for (const sessionID of ["native-mention-alpha", "native-mention-beta"]) { + const event: any = { sessionID, system: [], messages: [source] }; + await captured.sessionHooks.find(h => h.name === "context")!.callback(event); + expect(event.messages[0].content).toContain(`native_session_id: \`${sessionID}\``); + expect(event.messages[0].content).toContain("literal @@HELIXHARNESS_SESSION_ID@@"); + } + expect(source.content).toBe(body + "\nliteral @@HELIXHARNESS_SESSION_ID@@"); + }); +}); + +describe("allowlisted native preflight observations", () => { + test("mutating commands observe actual tool metadata without exposing unrelated configuration", async () => { + const { ctx, captured } = createContext(); + const queries: unknown[] = []; + (ctx.tool as any).list = async (input: unknown) => { + queries.push(input); + return [{ id: "shell", headers: { token: "synthetic-do-not-expose" } }, { id: "read" }, { id: "subagent" }, { id: "unrelated_private_tool" }]; + }; + (ctx.session as any).move = async () => { throw new Error("preflight must not move a session"); }; + await registerHelixHarness(ctx, { pluginRoot: PLUGIN_ROOT }); + await captured.commands.find(c => c.name === "helix:apply")!.execute({sessionID:"preflight-current",prompt:{text:"demo"}}); + expect(queries).toEqual([{sessionID:"preflight-current"}]); + const prompt = captured.prompts[0].text; + expect(prompt).toContain('registered_native_tools: `["read","shell","subagent"]`'); + expect(prompt).toContain('native_session_move_api: `available`'); + expect(prompt).toContain('native_delegation_depth: `unknown`'); + expect(prompt).not.toContain("synthetic-do-not-expose"); + expect(prompt).not.toContain("unrelated_private_tool"); + }); + test("an unavailable catalogue stays unknown and does not leak native error details", async () => { + const {ctx,captured}=createContext(); + (ctx.tool as any).list=async()=>{throw new Error("synthetic-do-not-expose");}; + await registerHelixHarness(ctx,{pluginRoot:PLUGIN_ROOT}); + await captured.commands.find(c=>c.name==="helix:ut")!.execute({sessionID:"preflight-current",prompt:{text:""}}); + expect(captured.prompts[0].text).toContain('native_tool_catalog: `unavailable`'); + expect(captured.prompts[0].text).not.toContain("synthetic-do-not-expose"); + }); + test("Status and config do not depend on the capability lookup", async () => { + const {ctx,captured}=createContext();let calls=0; + (ctx.tool as any).list=async()=>{calls++;throw new Error("must not query");}; + await registerHelixHarness(ctx,{pluginRoot:PLUGIN_ROOT}); + for(const name of ["status","config"])await captured.commands.find(c=>c.name==="helix:"+name)!.execute({sessionID:"read-only",prompt:{text:""}}); + expect(calls).toBe(0);expect(captured.prompts).toHaveLength(2); + }); +}); + +test("known missing mandatory execution tools reject mutation commands before prompt admission", async () => { + const {ctx,captured}=createContext(); + (ctx.tool as any).list=async()=>[{id:"read"}]; + await registerHelixHarness(ctx,{pluginRoot:PLUGIN_ROOT}); + await expect(captured.commands.find(c=>c.name==="helix:apply")!.execute({sessionID:"missing-shell",prompt:{text:"demo"}})).rejects.toThrow("opencode_preflight_tools_unavailable: shell"); + expect(captured.prompts).toHaveLength(0); +}); + +test("unrecognized native catalogue shapes are unknown rather than falsely missing tools", async () => { + const {ctx,captured}=createContext(); + (ctx.tool as any).list=async()=>[{displayName:"future-tool-shape"}]; + await registerHelixHarness(ctx,{pluginRoot:PLUGIN_ROOT}); + await captured.commands.find(c=>c.name==="helix:apply")!.execute({sessionID:"future-catalogue",prompt:{text:"demo"}}); + expect(captured.prompts[0].text).toContain('native_tool_catalog: `unavailable`'); +}); diff --git a/helixharness/opencode/tests/project-checks.test.ts b/helixharness/opencode/tests/project-checks.test.ts new file mode 100644 index 0000000..e38a821 --- /dev/null +++ b/helixharness/opencode/tests/project-checks.test.ts @@ -0,0 +1,72 @@ +import { afterEach, expect, test } from "bun:test"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { runProjectChecks, runBounded } from "../project-checks.ts"; + +const roots: string[] = []; +afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); }); +function fixture() { + const root = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), "helix-project-check-")); + roots.push(root); + const linters = path.join(root, "docs/harness/linters"); + fs.mkdirSync(linters, { recursive: true }); + for (const name of ["invariant-check", "spec-sync-check"]) fs.writeFileSync(path.join(linters, `${name}.py`), "print('synthetic')"); + return root; +} +const pluginRoot = path.resolve(import.meta.dir, "../.."); + +test("successful edit runs both linters against the requesting session root", async () => { + const root = fixture(); + const commands: string[][] = []; + const event: any = { tool: "edit", status: "completed", sessionID: "ses_A", input: { path: "src/a.ts" }, result: { content: "edited" } }; + await runProjectChecks(event, pluginRoot, async () => root, async command => { + commands.push(command); return { code: 0, output: "synthetic passed" }; + }); + expect(commands).toHaveLength(2); + expect(commands.every(command => command.includes(root))).toBe(true); + expect(event.result.content).toBe("edited"); +}); + +test("failed tools, non-edits and repositories without linters do not launch checks", async () => { + let launches = 0; + const root = fs.mkdtempSync(path.join(os.tmpdir(), "helix-no-linters-")); roots.push(root); + for (const event of [ + { tool: "edit", status: "error", sessionID: "ses_A" }, + { tool: "read", status: "completed", sessionID: "ses_A" }, + { tool: "write", status: "completed", sessionID: "ses_A", input: { path: "a.ts" } }, + ]) await runProjectChecks(event as any, pluginRoot, async () => root, async () => { launches++; return { code: 0, output: "" }; }); + expect(launches).toBe(0); +}); + +test("linter failure is attached without undoing the edit or completing a stage", async () => { + const root = fixture(); + const event: any = { tool: "write", status: "completed", sessionID: "ses_A", input: { path: "a.ts" }, result: { content: [{ type: "text", text: "saved" }] } }; + await runProjectChecks(event, pluginRoot, async () => root, async () => ({ code: 1, output: "synthetic invariant violated" })); + expect(event.status).toBe("completed"); + expect(event.result.content[0].text).toBe("saved"); + expect(event.result.content.at(-1).text).toContain("project_check_failed"); +}); + +test("foreign file and external linter symlinks never execute", async () => { + const root = fixture(); const foreign = fixture(); + for (const name of ["invariant-check", "spec-sync-check"]) { + const target = path.join(root, `docs/harness/linters/${name}.py`); + fs.unlinkSync(target); fs.symlinkSync(path.join(foreign, `docs/harness/linters/${name}.py`), target); + } + let launches = 0; + for (const file of ["a.ts", path.join(foreign, "a.ts")]) { + await runProjectChecks({ tool: "write", status: "completed", sessionID: "ses_A", input: { path: file }, result: { content: "saved" } } as any, + pluginRoot, async () => root, async () => { launches++; return { code: 0, output: "" }; }); + } + expect(launches).toBe(0); +}); + +test("bounded runner preserves nonzero exit, bounds output and terminates timeouts", async () => { + const failed = await runBounded([process.execPath, "-e", "process.stdout.write('synthetic');process.exit(7)"], { timeoutMs: 3000 }); + expect(failed.code).toBe(7); expect(failed.output).toContain("synthetic"); + const oversized = await runBounded([process.execPath, "-e", "process.stdout.write('x'.repeat(50000))"], { maxBytes: 500, timeoutMs: 3000 }); + expect(oversized.code).not.toBe(0); expect(oversized.output.length).toBeLessThan(800); + const slow = await runBounded([process.execPath, "-e", "setTimeout(()=>{}, 100000)"], { timeoutMs: 60 }); + expect(slow.code).not.toBe(0); expect(slow.output).toContain("timeout"); +}); diff --git a/helixharness/opencode/tests/resource-boundaries.test.ts b/helixharness/opencode/tests/resource-boundaries.test.ts new file mode 100644 index 0000000..fcc5656 --- /dev/null +++ b/helixharness/opencode/tests/resource-boundaries.test.ts @@ -0,0 +1,105 @@ +import { afterAll, describe, expect, test } from "bun:test"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { COMMAND_NAMES, loadPluginResources } from "../core.ts"; + +const PACKAGE = path.resolve(import.meta.dir, "../.."); +const TEMP = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "helix-resource-boundaries-"))); +afterAll(() => fs.rmSync(TEMP, { recursive: true, force: true })); +let sequence = 0; + +function fixture() { + const parent = path.join(TEMP, String(++sequence)); + const root = path.join(parent, "plugin"); + const outside = path.join(parent, "plugin-sidecar"); + fs.mkdirSync(root, { recursive: true }); + fs.mkdirSync(outside); + const manifest = JSON.parse(fs.readFileSync(path.join(PACKAGE, "hosts/opencode/host.json"), "utf8")); + function write(relative: string, text: string) { + const target = path.join(root, relative); + fs.mkdirSync(path.dirname(target), { recursive: true }); + fs.writeFileSync(target, text); + } + write("hosts/opencode/host.json", JSON.stringify(manifest)); + for (const ref of Object.values(manifest.adapters) as string[]) { + if (ref.startsWith("resource:")) write(ref.slice("resource:".length), "Synthetic resource\n"); + } + for (const command of COMMAND_NAMES) write(`commands/${command}.md`, "---\ndescription: Synthetic command\n---\nSynthetic body\n"); + write("skills/demo/SKILL.md", "---\nname: demo\n---\nSynthetic skill\n"); + write("agents/demo.md", "---\ndescription: Synthetic agent\n---\nSynthetic agent body\n"); + return { root, outside }; +} + +function moveToLink(root: string, relative: string, destination: string) { + const source = path.join(root, relative); + fs.mkdirSync(path.dirname(destination), { recursive: true }); + const directory = fs.statSync(source).isDirectory(); + fs.renameSync(source, destination); + fs.symlinkSync(destination, source, directory ? "dir" : "file"); +} + +describe("canonical plugin resource containment", () => { + for (const relative of [ + "hosts/opencode/host.json", "hosts/opencode/runtime.md", "commands/init.md", + "skills/demo/SKILL.md", "agents/demo.md", "commands", "skills", "skills/demo", "agents", + ]) { + test(`rejects external links at ${relative} before loading resources`, () => { + const { root, outside } = fixture(); + moveToLink(root, relative, path.join(outside, "target")); + expect(() => loadPluginResources(root)).toThrow("escapes the plugin root"); + }); + } + + for (const relative of ["hosts/opencode/runtime.md", "commands/init.md", "skills/demo/SKILL.md", "agents/demo.md"]) { + test(`allows an internal file link at ${relative}`, () => { + const { root } = fixture(); + moveToLink(root, relative, path.join(root, "internal/target.md")); + const plugin = loadPluginResources(root); + expect(plugin.commands).toHaveLength(9); + expect(plugin.skills.map(s => s.id)).toEqual(["helix-demo"]); + expect(plugin.agents.map(a => a.id)).toEqual(["helix-demo"]); + }); + } + + for (const relative of ["commands", "skills", "skills/demo", "agents"]) { + test(`allows internal directory links at ${relative}`, () => { + const { root } = fixture(); + moveToLink(root, relative, path.join(root, "internal/target")); + const plugin = loadPluginResources(root); + expect(plugin.commands).toHaveLength(9); + expect(plugin.skills).toHaveLength(1); + expect(plugin.agents).toHaveLength(1); + }); + } + + for (const relative of ["hosts/opencode/runtime.md", "skills/demo/SKILL.md", "agents/demo.md"]) { + test(`rejects a dangling link at ${relative}`, () => { + const { root } = fixture(); + const file = path.join(root, relative); + fs.unlinkSync(file); + fs.symlinkSync(path.join(root, "missing.md"), file); + expect(() => loadPluginResources(root)).toThrow(); + }); + } + + test("rejects link cycles", () => { + const { root } = fixture(); + const first = path.join(root, "hosts/opencode/runtime.md"); + const second = path.join(root, "cycle.md"); + fs.unlinkSync(first); + fs.symlinkSync(second, first); + fs.symlinkSync(first, second); + expect(() => loadPluginResources(root)).toThrow(); + }); + + test("rejects a lexical traversal even when it resolves back inside", () => { + const { root } = fixture(); + const manifestPath = path.join(root, "hosts/opencode/host.json"); + const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8")); + fs.symlinkSync(root, path.join(path.dirname(root), "back"), "dir"); + manifest.adapters.runtime = "resource:../back/hosts/opencode/runtime.md"; + fs.writeFileSync(manifestPath, JSON.stringify(manifest)); + expect(() => loadPluginResources(root)).toThrow("escapes the plugin root"); + }); +}); diff --git a/helixharness/opencode/tests/ut-state.test.ts b/helixharness/opencode/tests/ut-state.test.ts new file mode 100644 index 0000000..60116f2 --- /dev/null +++ b/helixharness/opencode/tests/ut-state.test.ts @@ -0,0 +1,58 @@ +import {afterAll,expect,test} from 'bun:test'; +import fs from 'node:fs';import os from 'node:os';import path from 'node:path'; +import {guardUtStateWrite, isProtectedUtStatePath} from '../ut-state.ts'; +const root=fs.mkdtempSync(path.join(os.tmpdir(),'helix-ut-guard-')); +const directory=path.join(root,'docs/specs/active/example');fs.mkdirSync(directory,{recursive:true}); +afterAll(()=>fs.rmSync(root,{recursive:true,force:true})); +const bind=async()=>root; +for(const name of ['unittest-queue.md','unittest-session.md','unittest-results.md','unittest-summary.md','unittest-defects.md','unittest-experience.md','worker-1-result.md','worker-2-defects.md','worker-3-findings.json']){ + for(const tool of ['write','edit'])test(`blocks ${tool} to protected ${name} before first write`,async()=>{ + await expect(guardUtStateWrite({tool,sessionID:'synthetic',input:{path:`docs/specs/active/example/${name}`}},bind)).rejects.toThrow('ut_atomic_write_required'); + expect(fs.existsSync(path.join(directory,name))).toBe(false); + }); +} +test('allows staging and ordinary business files without changing their input',async()=>{ + for(const p of ['docs/specs/active/example/unittest-results.md.tmp','src/main/Rules.java','docs/specs/active/example/spec.md','docs/notes/unittest-results.md']){ + const e={tool:'write',sessionID:'synthetic',input:{path:p,content:'literal'}};await guardUtStateWrite(e,bind);expect(e.input.content).toBe('literal'); + } +}); +test('protects an absolute path and an alias to a protected directory',async()=>{ + const alias=path.join(root,'alias');fs.symlinkSync(directory,alias,'dir'); + for(const p of [path.join(directory,'unittest-results.md'),path.join(alias,'unittest-results.md')])await expect(guardUtStateWrite({tool:'write',sessionID:'synthetic',input:{path:p}},bind)).rejects.toThrow('ut_atomic_write_required'); +}); +test('ignores read and shell calls; never parses or rewrites arbitrary shell code',async()=>{ + for(const tool of ['read','shell'])await guardUtStateWrite({tool,sessionID:'synthetic',input:{path:path.join(directory,'unittest-results.md')}},async()=>{throw Error('must not look up session')}); +}); +test('relative writes use the requesting session directory, not plugin cwd',async()=>{ + const other=path.join(root,'other');fs.mkdirSync(other); + await expect(guardUtStateWrite({tool:'write',sessionID:'B',input:{path:'../docs/specs/active/example/worker-1-result.md'}},async()=>other)).rejects.toThrow('ut_atomic_write_required'); +}); + +test('recognizes platform-normalized Windows UT paths',()=>{ + expect(isProtectedUtStatePath(String.raw`C:\repo\docs\specs\active\sample\unittest-summary.md`)).toBe(true); + expect(isProtectedUtStatePath(String.raw`C:\repo\src\Rules.java`)).toBe(false); +}); +test('protects existing, dangling and chained leaf file aliases',async()=>{ + const target=path.join(directory,'unittest-summary.md');fs.writeFileSync(target,'complete'); + const alias=path.join(root,'report-alias.md');fs.symlinkSync(target,alias); + const dangling=path.join(root,'dangling-alias.md');fs.symlinkSync(path.join(directory,'unittest-session.md'),dangling); + const chained=path.join(root,'chain-alias.md');fs.symlinkSync(alias,chained); + for(const p of [alias,dangling,chained])await expect(guardUtStateWrite({tool:'write',sessionID:'synthetic',input:{path:p}},bind)).rejects.toThrow('ut_atomic_write_required'); + expect(fs.readFileSync(target,'utf8')).toBe('complete'); +}); +test('allows ordinary file symlinks without rewriting tool input',async()=>{ + const target=path.join(root,'ordinary.txt');fs.writeFileSync(target,'original');const alias=path.join(root,'ordinary-link.txt');fs.symlinkSync(target,alias); + await guardUtStateWrite({tool:'write',sessionID:'synthetic',input:{path:alias}},bind); + expect(fs.readFileSync(target,'utf8')).toBe('original'); +}); + +test('protects casing variants of reserved paths while allowing ordinary names',async()=>{ + for(const p of ['DOCS/SPECS/ACTIVE/Example/UNITTEST-SUMMARY.MD','docs/specs/active/example/Worker-1-Findings.JSON'])await expect(guardUtStateWrite({tool:'write',sessionID:'s',input:{path:p}},bind)).rejects.toThrow('ut_atomic_write_required'); + expect(isProtectedUtStatePath('docs/notes/UNITTEST-SUMMARY.MD')).toBe(false); +}); +test('ordinary relative editing outside UT never depends on session API',async()=>{ + for(const tool of ['write','edit'])await guardUtStateWrite({tool,sessionID:'ordinary',input:{path:'src/Rules.java'}},async()=>{throw Error('session unavailable')},false); +}); +test('UT relative aliases still fail closed when session directory is unavailable',async()=>{ + await expect(guardUtStateWrite({tool:'write',sessionID:'ut',input:{path:'report-link.md'}},async()=>{throw Error('session unavailable')},true)).rejects.toThrow('session unavailable'); +}); diff --git a/helixharness/opencode/ut-state.ts b/helixharness/opencode/ut-state.ts new file mode 100644 index 0000000..e2073bb --- /dev/null +++ b/helixharness/opencode/ut-state.ts @@ -0,0 +1,30 @@ +/** Guard the native direct-write surface; actual publication uses ut_artifacts.py. */ +import fs from 'node:fs'; +import path from 'node:path'; +export interface UtWriteEvent {tool: string; sessionID: string; agent?: string; input: unknown;} +const PROTECTED = /(?:^|\/)docs\/specs\/active\/[^/]+\/(?:unittest-(?:queue|session|results|defects|summary|experience)\.md|worker-[1-9]\d*-(?:(?:result|defects)\.md|findings\.json))$/i; +export function isProtectedUtStatePath(value: string): boolean { return PROTECTED.test(value.replaceAll("\\", "/")); } +export async function guardUtStateWrite(event: UtWriteEvent, resolveRoot: () => Promise, inspectRelativeAliases = true): Promise { + if (!['write', 'edit'].includes(event.tool) || !event.input || typeof event.input !== 'object') return; + const input = event.input as {path?: unknown}; + if (typeof input.path !== 'string') return; + // Lexical reserved paths require no session API. Resolve relative aliases only + // in active UT orchestration/worker scope, so ordinary editing stays independent. + if (isProtectedUtStatePath(path.normalize(input.path))) throw new Error('ut_atomic_write_required: Use scripts/ut_artifacts.py with same-directory .tmp staging. Direct write/edit blocked.'); + if (!path.isAbsolute(input.path) && !inspectRelativeAliases) return; + const target = path.isAbsolute(input.path) ? path.normalize(input.path) : path.resolve(await resolveRoot(), input.path); + const candidates = new Set(); + let cursor = target; + for (let depth = 0; depth < 40 && !candidates.has(cursor); depth++) { + candidates.add(cursor); + try { + cursor = path.join(fs.realpathSync(path.dirname(cursor)), path.basename(cursor)); + candidates.add(cursor); + if (!fs.lstatSync(cursor).isSymbolicLink()) break; + cursor = path.resolve(path.dirname(cursor), fs.readlinkSync(cursor)); + } catch { break; } // Missing final files are covered by their lexical target. + } + if ([...candidates].some(isProtectedUtStatePath)) { + throw new Error('ut_atomic_write_required: Write the complete content to .tmp, then run the bound plugin scripts/ut_artifacts.py with --repo-root, --feature and write --name --source. Findings JSON uses findings --worker --source; aggregate generates the parent defects report. Direct write/edit was blocked before execution.'); + } +} diff --git a/helixharness/reference/eval-protocol.md b/helixharness/reference/eval-protocol.md index ce742cc..7a3a9a6 100644 --- a/helixharness/reference/eval-protocol.md +++ b/helixharness/reference/eval-protocol.md @@ -26,7 +26,7 @@ Codex: ${CODEX_HOME:-$HOME/.codex}/helixharness/telemetry-consent-cache.json Cursor: ${HELIXHARNESS_CURSOR_HOME:-$HOME/.cursor}/helixharness/telemetry-consent-cache.json ``` -OpenCode 声明 `telemetry=unsupported`,没有 consent 缓存路径;统计脚本返回 `unsupported_host` 后继续业务,不读写上述缓存或借用其他宿主授权。 +OpenCode 使用自己的 consent 缓存:`HELIXHARNESS_OPENCODE_HOME`(否则 `$XDG_STATE_HOME/opencode` 或 `~/.local/state/opencode`)下的 `helixharness/telemetry-consent-cache.json`。明确授权后仅记录阶段事实和工作流轨迹;不读取原始会话日志,不借用其他宿主授权,token 和工具调用信息保持未知。 用户主动查询和修改配置使用 `/helix:config`,通过 `scripts/user_config.py` 复用本协议 API;默认查看不触发 CLI resolve 的清理副作用,显式修改仍由既有授权 API 管理 scope、epoch 和清理。 diff --git a/helixharness/reference/eval-supplement-protocol.md b/helixharness/reference/eval-supplement-protocol.md index 8ca4957..689323b 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 与 Cursor 均注册 Adapter。OpenCode 声明 `telemetry=unsupported`,按 `unsupported_host` 跳过本次统计并继续业务,不借用其他宿主授权或事件源。CLI 输入仅做大小写规范化,并接受已安装 manifest 明确声明的 aliases;不能根据模型名、包装标签或包含 `claude` / `codex` 的子串猜测宿主。公开 Ledger 与 Supplement 始终只落 canonical ID。Cursor 通过授权后的原生 hooks 维护自有事件源,不读取私有数据库或 transcript。会话身份和 workspace roots 必须来自当前 sessionStart,显式绑定每次命令;缺失时按 `cursor_session_context_unavailable` 跳过本次统计,业务继续。新增统计能力在 `scripts/telemetry_hosts/` 实现 `HostAdapter`(含统一 Supplement 窗口),由 Host Kit manifest 绑定;不得修改业务正文,也不得在 Ledger、Collector 或 Schema 中增加平台分支。 +业务合同与统计支持集相互独立:业务正文和三工件不记录宿主,同一需求可以跨宿主继续;`current_platform` 只用于本次 Telemetry Adapter 选择。当前 Claude Code、Codex、Cursor 与 OpenCode 均注册 Adapter。OpenCode 的 `stage_facts_only` 适配只提交授权后的阶段事实和 canonical workflow trace,不采集原始会话。Supplement 的 usage/execution 保持空对象、evidence 明确 unavailable;缺失数据不补零。其归档 seal 使用 stage_facts 边界,不能借此放宽其他 Adapter 的 transcript 边界校验。CLI 输入仅做大小写规范化,并接受已安装 manifest 明确声明的 aliases;不能根据模型名、包装标签或包含 `claude` / `codex` 的子串猜测宿主。公开 Ledger 与 Supplement 始终只落 canonical ID。Cursor 通过授权后的原生 hooks 维护自有事件源,不读取私有数据库或 transcript。会话身份和 workspace roots 必须来自当前 sessionStart,显式绑定每次命令;缺失时按 `cursor_session_context_unavailable` 跳过本次统计,业务继续。新增统计能力在 `scripts/telemetry_hosts/` 实现 `HostAdapter`(含统一 Supplement 窗口),由 Host Kit manifest 绑定;不得修改业务正文,也不得在 Ledger、Collector 或 Schema 中增加平台分支。 Cursor 的输入/输出 Token 只使用原生 hook 中实际存在的非负整数,同一 conversation/generation 的 afterAgentResponse 与 stop 快照去重。只有完整落在阶段内的轮次才数值归属;正常单轮命令的 prompt 可能早于 start、终值晚于 finish,不能伪造阶段差值。用量保留 `collection_status=collected|partial|unavailable`、`unavailable_reason`、`scope=parent_only`、`attribution=complete_generations_within_stage`、`input_tokens_include_cache=true` 与 `generations`。缓存是 input 的明细,total=input+output;不把缺失计数填成 0,也不把父代理数值称为子代理总量。基础阶段/工具统计仍可用,平台部分采集显示小计并保留范围与原因。 diff --git a/helixharness/reference/host-api.md b/helixharness/reference/host-api.md index 2f267e1..761acfd 100644 --- a/helixharness/reference/host-api.md +++ b/helixharness/reference/host-api.md @@ -15,11 +15,11 @@ HelixHarness 提供 Claude Code、Codex、Cursor 和 OpenCode Host Kit。公共 - `claude-code`:原生命令、Hook 生命周期、原生 Agent、Claude marketplace; - `codex`:Skill 命令投影、独立启动/结束 Hook 与命令驱动阶段生命周期、Codex subagent、Codex marketplace; - `cursor`:独立 Skill 投影、Cursor 原生 hooks、Task 子代理与 Cursor plugin 分发;Stable(桌面范围); -- `opencode`:插件注册原生命令/Skill/Agent、绑定当前仓库与会话 Host Context、原生 subagent 和 OpenCode plugin 分发;Host API 1.1 / Preview(v2.2.2+)。 +- `opencode`:插件注册原生命令/Skill/Agent、命令、原生 `skill` 工具、Skill mention 与原生 Skill 激活的会话目录绑定、原生 subagent 和 OpenCode plugin 分发;Host API 1.1 / Stable(macOS、OpenCode 2.3.2;详见[支持矩阵](../../docs/opencode-testing.md))。 Claude Code 与 Codex 保持 Host API 1.1 / Stable;Cursor 使用向后兼容的 1.2 / Stable。 Cursor 的会话统计和插件更新为 `emulated`:原生 hook 提供有边界的事件/用量证据,登记的托管本地安装通过批准后的原子交换升级。本次正式支持范围为桌面研发工作流;原生自动升级等限制与已接受的验证缺口见 Cursor 安装说明。 -OpenCode 的 `telemetry`、`plugin_update` 和 `project_hooks` 为 `unsupported`,完整真实模型工作流尚未验收。Workspace Apply 的 `may_delegate` RepoJob 使用 `helix-worker` 且需要 `experimental.subagent_depth >= 2`,reviewer 仍为只读 leaf;深度不足阻塞,不绕过评审。 +OpenCode 的统计、源码更新和任务跟踪为 `emulated`;原生项目设置 Hook 仍为 `unsupported`,插件级 `project_checks` 已接入编辑后巡检。详细边界见 [OpenCode 能力适配](../hosts/opencode/capabilities.md)。2026-11-20 已在 OpenCode 2.3.2 + DeepSeek 上完成一次合成单仓真实模型闭环(含操作者确认与受控合同修订);2026-11-23 又完成合成双仓 Workspace 与独立 UT 的操作者辅助验证;后续分类校验与原子发布保护已修复并通过无纠正提醒的真实模型 UT 复验。[合成 Workspace 的专项真实模型验证](../opencode/tests/README.md#recovery-and-auxiliary-workflow-acceptance-2026-11-23)还覆盖了 Apply 与部分 Archive 原生取消后新会话恢复,以及注入原生 context hook 故障后阻断依赖派发。完整生产业务项目、无人干预时的协议遵守与完整 TUI/桌面 UI 验收仍未完成;已覆盖范围见[定向终端 UI 验收](../opencode/tests/README.md#targeted-terminal-ui-acceptance-2026-11-23)。Skill mention 仓库绑定与插件资源符号链接越界检查已于 2026-11-23 修复并经原生宿主回归;当前 Stable 仅覆盖上述支持矩阵;OpenCode 2.2.2、2.3.0 仅有自动化兼容覆盖。Workspace Apply 的 `may_delegate` RepoJob 使用 `helix-worker` 且需要 `experimental.subagent_depth >= 2`,reviewer 仍为只读 leaf;深度不足阻塞,不绕过评审。 未知宿主必须关闭失败,不能回退到 Claude Code 或借用 Codex 资源。 ## 共享核心与 Host Kit diff --git a/helixharness/reference/host-runtime-protocol.md b/helixharness/reference/host-runtime-protocol.md index d29473c..cc6c287 100644 --- a/helixharness/reference/host-runtime-protocol.md +++ b/helixharness/reference/host-runtime-protocol.md @@ -89,7 +89,7 @@ command 中的 `Read`、`Write`、`Edit`、`Bash`、`AskUserQuestion`、`TodoWri `commands/{command}.md` 唯一契约入口;宿主资源不进入公共命令面。 - `project_hooks=native|emulated`:读取 `resources.project_hooks`,按 owner、目标、合并策略和去重键 执行;为 `unsupported` 时不创建替代 settings 文件。 -- `task_tracking=native|emulated`:使用宿主计划工具;为 `unsupported` 时回退到当前 Feature +- `task_tracking=native`:使用宿主计划工具;`emulated` 使用 Host Kit 明确的计划适配器(可直接操作 canonical tasks.md);为 `unsupported` 时回退到当前 Feature 的 `tasks.md`,不得另造宿主专属状态文件。 - telemetry 命令必须读取 `reference/telemetry-command-protocol.md` 与 `resources.telemetry_protocol`,只按 `hook|command|disabled` 生命周期模式执行;不得按宿主 ID、 @@ -103,7 +103,7 @@ command 中的 `Read`、`Write`、`Edit`、`Bash`、`AskUserQuestion`、`TodoWri ## 5. 未来宿主扩展契约 -当前仓库提供 Claude Code、Codex、Cursor 与 OpenCode(Preview)。OpenCode 的 `telemetry`、`plugin_update` 和 `project_hooks` 为 `unsupported`。未来接入新宿主时,正常改动范围应限制为: +当前仓库提供 Claude Code、Codex、Cursor 与 [OpenCode(macOS Stable)](../../docs/opencode-testing.md)。OpenCode 的统计、源码更新和任务跟踪为 `emulated`;原生项目设置 Hook 仍为 `unsupported`,插件级 `project_checks` 已接入编辑后巡检。详细边界见 [OpenCode 能力适配](../hosts/opencode/capabilities.md)。未来接入新宿主时,正常改动范围应限制为: - `hosts/{host-id}/host.json`; - 该 Host Kit 引用的分发、安装、入口投影、启动、工具映射、生命周期、项目配置、遥测或更新适配器; diff --git a/helixharness/reference/ut-artifact-protocol.md b/helixharness/reference/ut-artifact-protocol.md new file mode 100644 index 0000000..38a1e72 --- /dev/null +++ b/helixharness/reference/ut-artifact-protocol.md @@ -0,0 +1,99 @@ +# UT 分类与工件发布协议 + +本资源由公共 `commands/ut.md` 与 `agents/unit-test-worker.md` 共同消费,不替代扫描、6 Loop、 +真实 worker 终态、重试、源外构建或主项目统一验证。首次 UT 工件写入前必须完整读取。 + +## 原子发布入口 + +UT 的 queue、session、results、summary、experience 和 worker result 的**每次创建/更新**, +包括空表初始化、失败结果、最终完成状态,都使用绑定插件的 `scripts/ut_artifacts.py`: + +1. 用当前宿主 Write 将完整内容写入目标同目录的 `.tmp`(不是目标文件)。 +2. 在原项目目录执行(示例 name 可替换为允许的 UT 状态名): + +```bash +{helix_python} "{plugin_root}/scripts/ut_artifacts.py" --repo-root "{repo_root}" --feature "{feature}" write --name unittest-session.md --source "{repo_root}/docs/specs/active/{feature}/unittest-session.md.tmp" +``` + +脚本只接受 UT 状态白名单、当前 feature 目录和同名 `.tmp` 源;拒绝越界/符号链接, +用独立同目录临时文件、flush/fsync、原子 replace 发布,再清除输入 staging。失败时旧目标 +保持完整、输入 staging 保留。替换已有普通文件保留其 POSIX mode,新文件默认 0644;不承诺 ACL/xattr 等其他元数据。成功输出 `atomic:true`;失败不得假称已写入。 + +不得直接 Write/Edit 最终状态,也不得用 `cat > target`、`echo > target`、`tee target` 或 Python +直接覆盖目标来绕过入口。rename 归档已有 worker 工件不属于内容发布,可保持原协议执行。 +`worker-*-defects.md`、`worker-*-findings.json` 和 `unittest-defects.md` 由以下分类入口生成, +不接受普通 write 子命令,也不由模型手写覆盖。业务测试文件仍按原 Loop 4 同步。 + +## 分类依据与计数 + +每条观察必须区分: + +- `confirmed_defect`:违反已确认要求,或有可复现的机械失败,且有实际反例证据。 +- `unconfirmed_risk`:风险依赖尚未确认的产品期望、边界或没有足够证据。 +- `optional_improvement`:兼容的 API/诊断/风格/文档改进建议。 + +只有第一类计入缺陷总数与 High/Medium/Low。风险和建议分别统计、完整保留,不混入缺陷, +不能因“发现缺陷数为 0”隐藏观察。没有相关需求时,不自行发明 Unicode 空白处理、舍入方式、 +null 必须抛 NPE、错误消息粒度或 Javadoc 要求。现有代码仅证明当前行为,不自动成为规范性 +来源;测试按某个猜测失败也不能把猜测升级成已确认要求。 + +### Worker 结构化记录 + +每个 worker 在最后写 result 前,准备自己的 `worker-{ID}-findings.json.tmp`: + +```json +{ + "worker_id": 1, + "class_name": "example.SomeClass", + "observations": [ + { + "id": "O-01", + "classification": "optional_improvement", + "title": "可进一步细化诊断信息", + "actual_behavior": "非法入参已正确拒绝,但共用一条异常消息" + } + ] +} +``` + +无观察使用 `observations:[]`,不省略文件。ID 在当前 worker 内唯一。已证实缺陷还必须提供: + +- `severity`:`High|Medium|Low`;`actual_behavior` 和具体影响应说明真实错误。 +- `basis=contract`:`normative_ref={path,quote}`,path 是当前 repo README/AGENTS 或 docs 下 + Markdown 的规范性来源,quote 必须逐字存在;明确指出它如何约束当前方法,不能引用实现正文 + 充当未确认需求,也不能引用本协议作为具体产品规则。 +- 或 `basis=mechanical`:用于无法作为合法预期解释的机械失败,给出 `code_ref={path,quote}` + 与 `mechanical_kind`:`inevitable_exception|nontermination|data_corruption|control_flow_failure|security_violation|misleading_success`。 + 异常类还需 `observed_exception`(例如 ClassCastException、ZeroDivisionError 或 Go panic),必须逐字出现在反例日志;不使用异常名称白名单。 + 源码引用支持 Java/Kotlin/Groovy、Python、JS/TS(含 JSX/TSX/MJS/CJS)、Go,不接受配置文件充当源码依据。不能把正常的参数拒绝、异常类型偏好、舍入政策或风格归为机械失败。 +- `reproducer={command,expected,actual,evidence_path,evidence_quote}`:真实执行过的反例, + expected/actual 必须不同;日志路径在本 repo 或本 worker 的系统临时目录内,quote 逐字存在。 + 不得构造/改写日志来证明猜测。该 command 只作记录,脚本不会执行它。 + +```bash +{helix_python} "{plugin_root}/scripts/ut_artifacts.py" --repo-root "{repo_root}" --feature "{feature}" findings --worker {ID} --source "{repo_root}/docs/specs/active/{feature}/worker-{ID}-findings.json.tmp" +``` + +脚本校验当前 worker 身份、引用和反例结构,原子生成规范化 JSON 与 `worker-{ID}-defects.md`。 +缺少支持的 confirmed 提议自动降为 risk,保留原提议、proposed_severity 和原因;不得以原提议继续计数、提前高危退出 +或禁用测试。worker result 的缺陷/风险/建议数以脚本返回的 counts 为准,随后最后原子发布 result。 +对已证实 High 保持原高危退出协议,仍先输出 findings 和分类报告,再发布失败 result。 + +脚本校验的是来源与证据存在性,不是对所有业务语义的机械证明。父流程仍须对照实际合同复核; +不能仅凭 JSON 通过就把不合理的推理当成事实。 + +## 父流程汇总 + +先等待原生终态并校验 result、6 Loop、测试/覆盖率和写域。按原重试去重规则选择每个类的最终 +Worker ID,然后执行(优先在清理临时证据前)(下面 ID 为示例): + +```bash +{helix_python} "{plugin_root}/scripts/ut_artifacts.py" --repo-root "{repo_root}" --feature "{feature}" aggregate --workers 1,2 +``` + +只聚合显式选择的最终 workers,支持当前或 archived-worker 文件,单个 ID 只选同一组;存在当前工件时不混用旧归档,归档中断须先按恢复协议还原整组。新发布的 schema_version=2 记录保存发布时已校验的分类与完整性摘要;聚合检查身份、结构、counts 和摘要,不因临时日志已清理而重新降级。摘要仅检查完整性,不是签名或业务正确性证明;这些是发布时的观察,不能冒充当前源码的重新验收。损坏/非法 JSON 仍阻断。 +旧会话只有 result/defects,或 schema_version=1 尚未重新核验时,保留原件和状态并输出 legacy_workers;分类总数 `counts` 为 null、`classification_complete=false`,`known_counts` 只含已核验部分。超时代写 result 同样处理,不能编造空 findings 或把未知算零;缺少 result 且无有效新分类仍阻断。正常新 worker 仍必须先发布 findings 再 result。 +命令原子生成 `unittest-defects.md`;results/summary/最终回复数字须一致,分类不全时显示“未核验”,列出原报告,不宣称全量零缺陷或分类验收通过。 +不得重新把风险/建议数称为缺陷数。其余状态和结果报告通过 write 子命令发布。 +归档 worker 文件时包含 `.md` 与 `-findings.json`,保留 ID/扩展名与重试关联;共享经验写入所有权 +仍服从宿主 adapter,worker 不得借此写共享汇总或经验文件。 diff --git a/helixharness/reference/version-update-protocol.md b/helixharness/reference/version-update-protocol.md index 4c0c5e0..3b90161 100644 --- a/helixharness/reference/version-update-protocol.md +++ b/helixharness/reference/version-update-protocol.md @@ -18,7 +18,7 @@ update 与 eval 分别使用动态 Host Registry,并保持独立 capability、cache 和生命周期。update 是否 可用只看当前 Host Kit 的 `plugin_update=native|emulated|unsupported`;公共协议不维护宿主白名单。 Claude Code/Codex adapter 提供原生更新能力。Cursor 的 `plugin_update=emulated`,仅更新通过 Helix installer 登记的 macOS/Linux 本地安装;未登记副本或原生市场缓存不被接管。 -OpenCode 明确声明 `plugin_update=unsupported`,`/helix:update` 的 check 返回 `continue_silently`;通过 OpenCode 插件管理手动更新,不创建 Helix 更新授权或接管其他宿主安装。 +OpenCode 的 `plugin_update=emulated` 仅适配有明确 Git upstream 的干净源码分支,复用同一 check/prepare/decide/install 授权链路,锁定批准 commit 并只允许快进;有本地改动、游离版本或不受管理副本时保留手动更新,不接管其他宿主安装。安装步骤见 [OpenCode 安装说明](../hosts/opencode/installer.md),适配边界见文末 OpenCode source checkout adapter。 任何未注册宿主或未启用更新能力的宿主执行 update `check` 时固定返回 `state=unsupported, reason=unsupported_host, next_action=continue_silently`,不读取或写入 版本缓存、不提示更新、不创建 authorization,也不执行任何 plugin 命令。 @@ -306,3 +306,8 @@ Cursor: ${HELIXHARNESS_CURSOR_HOME:-$HOME/.cursor}/helixharness/version-check-ca ## Cursor native update boundary 仅 Cursor 原生安装:`check` 返回 `reason=installation_update_not_supported`、`next_action=continue_with_warning` 时,展示当前安装及手动更新步骤后结束更新流程;业务继续。不得进入 prepare/decide/install,不得改用旧 Local 缓存或授权,不把 unknown 当作已是最新。显式后续更新操作退出码为 2。此限制不改变 managed-local、Claude Code 或 Codex 的原协议。 + + +## OpenCode source checkout adapter + +OpenCode 的 `checkout` 范围由 `update_hosts.opencode.OpenCodeUpdateAdapter` 实现。检查通过临时 Git ref 和隔离快照读取正式 policy;已有本地改动、无 upstream、游离版本或分叉不进入安装。prepare/decide/install 保持原确认协议,绑定 checkout、分支、原 HEAD 和批准 target commit;安装禁用 Git hooks,仅允许快进并核验版本与 HEAD。不强制重置、不 stash、不 commit/push。当前会话仍需在更新后重启。包管理缓存不借用本适配或其他宿主授权,详见 [OpenCode 能力适配](../hosts/opencode/capabilities.md)。 diff --git a/helixharness/reference/workspace-repo-dispatch.md b/helixharness/reference/workspace-repo-dispatch.md index 2281150..21ab702 100644 --- a/helixharness/reference/workspace-repo-dispatch.md +++ b/helixharness/reference/workspace-repo-dispatch.md @@ -93,9 +93,16 @@ identity、上下文继承、结果编码、容量准入、等待和生命周期 Reviewer 必须继承同一读取上限。额外跨仓输入缺失时返回父 Coordinator, 由其执行聚合验收或按已确认合同提供明确输入,子任务不自行扩大范围。 - `read` job 不得修改业务代码;`write` job 也不得越过自己的 repo 根。 + `read` 表示业务代码只读;各阶段仍由该 repo 的 Single 命令维护本 feature 的工件和私有状态, + 不等于整个 repo 文件系统不可写。 - 父 Coordinator 不与仍在运行的子任务并发写同一 repo。子任务原生失败后不自动重试, 也不以内联执行覆盖失败事实。 - 任一 job 失败或 `needs_input` 时,停止它的依赖后继;不回滚、不重跑不相关的已完成 job。 +- `failed|cancelled` 按原生失败收口,本轮不得自动再次派发或转成内联执行。 + `in_progress` 继续等待本轮原生 job;重新生成 plan 不代表可以启动第二个 owner。 + 跨会话重新读取根合同和各仓工件,使用逻辑 `job_id`、输入收据及工件恢复, + 不把旧 child/session ID 当作可续用的 handle,也不写入恢复状态。 + 未确认旧 owner 已终止时,不得仅因新 plan 仍有该 repo 就并发启动新 owner。 ## 5. 父级完成校验 @@ -110,3 +117,12 @@ identity、上下文继承、结果编码、容量准入、等待和生命周期 所有调用同时传入 `--repo-root "{ownership_root}" --feature "{feature}"`。只有子任务原生 终态成功、Router identity 匹配且确定性完成校验通过,RepoJob 才记为 completed。父流程 随后重新运行 Workspace plan/聚合门禁,以本地工件事实决定下一批,而不是信任内存状态。 + +新 plan 的 `jobs` 和 `batches` 只包含尚需执行的 repo;`repo_results` 保留已校验的完成事实。 +Apply 的 `implemented|completed` 子仓必须先通过严格 `archive-preflight` 才跳过; +Archive 已移动的子仓必须通过 completed preflight 才跳过。收据、证据或 Review Scope 无效时 +不得当作已完成。Apply 在身份、Tasks 和首次基线校验通过后,若 Evidence 缺失、无效或 Review Scope +变化,仍派发完整 Single Apply 的 Evidence 恢复分支,保留已完成任务并重新验证、Review 和生成报告; +身份、Tasks 或首次基线无效仍阻断,不重建基线。Archive 的 preflight 失败继续阻断。 +待执行 job 的 `depends_on` 仍引用原合同的 repo key, +已跳过的依赖通过 `repo_results` 中的校验事实满足。plan 不保存宿主运行状态,也不授权重试。 diff --git a/helixharness/scripts/task_plan.py b/helixharness/scripts/task_plan.py new file mode 100644 index 0000000..600cc7b --- /dev/null +++ b/helixharness/scripts/task_plan.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""Inspect or atomically update the canonical Feature task table, without a second plan store.""" +from __future__ import annotations + +import argparse +import hashlib +import json +import re +from pathlib import Path + +from atomic_files import atomic_write_text +from workflow import (WorkflowError, TASK_STATUSES, _repair_lock, feature_dir, + frontmatter, markdown_cells, task_rows, validate_task_graph) + + +def _cell_spans(line: str) -> list[tuple[int, int]]: + """Locate raw cells using the canonical parser's escaped-pipe semantics.""" + end = len(line.rstrip("\r\n")) + spans = [] + start = index = 0 + while index < end: + if line[index] == "\\" and index + 1 < end and line[index + 1] == "|": + index += 2 + continue + if line[index] == "|": + spans.append((start, index)) + start = index + 1 + index += 1 + spans.append((start, end)) + if spans and not line[slice(*spans[0])].strip(): + spans.pop(0) + if spans and not line[slice(*spans[-1])].strip(): + spans.pop() + return spans + + +def _load(repo: Path, feature: str): + root = repo.resolve(strict=True) + target = feature_dir(root, feature) / "tasks.md" + if any(parent.is_symlink() for parent in (target, *target.parents) if parent != root and root in parent.parents): + raise WorkflowError("tasks.md path is unsafe") + if not target.resolve().is_relative_to(root) or not target.is_file() or target.stat().st_size > 8 * 1024 * 1024: + raise WorkflowError("tasks.md is missing or unsafe") + raw = target.read_bytes() + text = raw.decode("utf-8") + values, _, _ = frontmatter(text, "tasks.md") + if values.get("feature") != feature: + raise WorkflowError("tasks.md feature identity mismatch") + rows = task_rows(text) + try: + next_task, active = validate_task_graph(rows) + except WorkflowError as exc: + if str(exc) != "tasks.md has unfinished work but no executable task": + raise + next_task, active = None, [] + return target, text, values, rows, {"feature": feature, "status": values.get("status"), + "tasks": rows, "next_task": next_task, "in_progress_tasks": active, + "receipt_sha256": hashlib.sha256(raw).hexdigest()} + + +def inspect_plan(repo: Path, feature: str) -> dict: + return _load(repo, feature)[-1] + + +def update_task(repo: Path, feature: str, task: str, status: str, expected_receipt: str) -> dict: + # Reuse the workflow mutation lock so repair and plan updates cannot race. + _load(repo, feature) + with _repair_lock(repo.resolve(), feature): + target, text, values, rows, result = _load(repo, feature) + if result["receipt_sha256"] != expected_receipt: + raise WorkflowError("tasks.md changed; inspect the plan again") + if values.get("status") not in {"ready", "applying"}: + raise WorkflowError("plan is not open for progress updates") + if status not in TASK_STATUSES: + raise WorkflowError("invalid task status") + by_id = {row["id"]: row for row in rows} + if task not in by_id: + raise WorkflowError("unknown task") + row = by_id[task] + if status in {"in_progress", "completed"} and any(by_id[key]["status"] != "completed" for key in row["blocked_by"]): + raise WorkflowError("task dependencies are incomplete") + if status != "completed" and any(task in item["blocked_by"] and item["status"] in {"in_progress", "completed"} for item in rows): + raise WorkflowError("cannot reopen a dependency of started work") + lines = text.splitlines(keepends=True) + columns = None + changed = 0 + for index, line in enumerate(lines): + cells = markdown_cells(line) + normalized = [cell.strip().lower() for cell in cells] + if "id" in normalized and "status" in normalized: + columns = {cell: position for position, cell in enumerate(normalized)} + elif columns and len(cells) > max(columns.values()) and cells[columns["id"]].strip() == task: + # Preserve all unrelated prose, columns, whitespace and line endings. + spans = _cell_spans(line) + if len(spans) != len(cells): + raise WorkflowError("task cell boundaries are ambiguous") + start, end = spans[columns["status"]] + replacement = re.sub(r"\S+", status, line[start:end], count=1) + lines[index] = line[:start] + replacement + line[end:] + changed += 1 + if changed != 1: + raise WorkflowError("task row is ambiguous") + updated = "".join(lines) + expected = [{**item, "status": status} if item["id"] == task else item for item in rows] + if task_rows(updated) != expected: + raise WorkflowError("plan update changed an unrelated task field") + if hashlib.sha256(target.read_bytes()).hexdigest() != expected_receipt: + raise WorkflowError("tasks.md changed before publication") + atomic_write_text(target, updated, mode=target.stat().st_mode & 0o777) + return inspect_plan(repo, feature) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--repo-root", required=True, type=Path) + parser.add_argument("--feature", required=True) + sub = parser.add_subparsers(dest="command", required=True) + sub.add_parser("show") + update = sub.add_parser("update") + update.add_argument("--task", required=True) + update.add_argument("--status", choices=sorted(TASK_STATUSES), required=True) + update.add_argument("--expected-receipt", required=True) + args = parser.parse_args() + try: + result = (inspect_plan(args.repo_root, args.feature) if args.command == "show" else + update_task(args.repo_root, args.feature, args.task, args.status, args.expected_receipt)) + except (WorkflowError, OSError, UnicodeError) as exc: + print(json.dumps({"status": "blocked", "reason": str(exc)})) + return 2 + print(json.dumps(result, ensure_ascii=False)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/helixharness/scripts/telemetry_collector.py b/helixharness/scripts/telemetry_collector.py index 58866ea..42378e5 100644 --- a/helixharness/scripts/telemetry_collector.py +++ b/helixharness/scripts/telemetry_collector.py @@ -150,11 +150,13 @@ def _sealed_boundary( ) if boundary is None: raise ValueError("Lite collection seal does not contain stage entry") - return _validate_sealed_boundary(boundary) + entry = next(item for item in ledger.get("entries", []) if item.get("entry_id") == entry_id) + adapter = get_host_adapter(str(entry.get("platform") or "")) + return _validate_sealed_boundary(boundary, allow_stage_facts=getattr(adapter, "stage_facts_only", False) is True) -def _validate_sealed_boundary(boundary: dict[str, Any]) -> dict[str, Any]: - if boundary.get("source_status") != "recorded": +def _validate_sealed_boundary(boundary: dict[str, Any], *, allow_stage_facts: bool = False) -> dict[str, Any]: + if boundary.get("source_status") != "recorded" and not (allow_stage_facts and boundary.get("source_status") == "stage_facts"): raise ValueError("session source was unavailable when requirement was archived") limit = boundary.get("source_limit_bytes") fingerprint = boundary.get("source_fingerprint") @@ -207,7 +209,7 @@ def _collection_context( boundary = frozen.get("sealed_boundary") try: validated_boundary = ( - _validate_sealed_boundary(boundary) + _validate_sealed_boundary(boundary, allow_stage_facts=getattr(get_host_adapter(str(locator.get("platform") or "")), "stage_facts_only", False) is True) if isinstance(boundary, dict) else None ) @@ -264,36 +266,46 @@ def _collect_entry( adapter = get_host_adapter(platform) if adapter is None: raise UnrecoverableCollectionError("unsupported_telemetry_host") - validated_source = adapter.validate_session_source(session_path, repo) if adapter is not None else None - if validated_source is None or Path(validated_source).resolve() != session_path.expanduser().resolve(): - raise UnrecoverableCollectionError("session_source_unavailable") - transcript_fingerprint = transcript_fingerprint or _source_fingerprint(session_path) - source_fingerprint = ( - hashlib.sha256( - f"{transcript_fingerprint}\0{trace_fingerprint}".encode("utf-8") - ).hexdigest() - if transcript_fingerprint - else None - ) - if previous and source_fingerprint and previous.get("source_fingerprint") == source_fingerprint: - return previous, False, str(previous.get("content_id") or ""), source_fingerprint, boundary is not None - started_at = str( - boundary["started_at"] if boundary is not None else locator["started_at"] - ) - ended_at = str( - boundary["ended_at"] if boundary is not None else locator["ended_at"] - ) - try: - window = adapter.collect_supplement_window( - session_path, - started_at=started_at, - ended_at=ended_at, - max_bytes=source_limit_bytes, + stage_only = getattr(adapter, "stage_facts_only", False) is True + if stage_only: + # The canonical workflow trace is available; host conversation and + # usage are not. Missing observations must never become zero counts. + source_fingerprint = hashlib.sha256(f"stage-facts\0{trace_fingerprint}\0{entry_id}".encode()).hexdigest() + started_at = str(boundary["started_at"] if boundary is not None else locator["started_at"]) + ended_at = str(boundary["ended_at"] if boundary is not None else locator["ended_at"]) + events, usage = [], {} + evidence = {"status": "unavailable", "reason_code": "host_transcript_not_collected"} + else: + validated_source = adapter.validate_session_source(session_path, repo) if adapter is not None else None + if validated_source is None or Path(validated_source).resolve() != session_path.expanduser().resolve(): + raise UnrecoverableCollectionError("session_source_unavailable") + transcript_fingerprint = transcript_fingerprint or _source_fingerprint(session_path) + source_fingerprint = ( + hashlib.sha256( + f"{transcript_fingerprint}\0{trace_fingerprint}".encode("utf-8") + ).hexdigest() + if transcript_fingerprint + else None ) - except FileNotFoundError as exc: - raise UnrecoverableCollectionError("session_source_unavailable") from exc - events, usage = window.events, window.usage - evidence = telemetry_protocol.build_evolution_evidence(events, started_at=started_at, ended_at=ended_at) + if previous and source_fingerprint and previous.get("source_fingerprint") == source_fingerprint: + return previous, False, str(previous.get("content_id") or ""), source_fingerprint, boundary is not None + started_at = str( + boundary["started_at"] if boundary is not None else locator["started_at"] + ) + ended_at = str( + boundary["ended_at"] if boundary is not None else locator["ended_at"] + ) + try: + window = adapter.collect_supplement_window( + session_path, + started_at=started_at, + ended_at=ended_at, + max_bytes=source_limit_bytes, + ) + except FileNotFoundError as exc: + raise UnrecoverableCollectionError("session_source_unavailable") from exc + events, usage = window.events, window.usage + evidence = telemetry_protocol.build_evolution_evidence(events, started_at=started_at, ended_at=ended_at) fixed = { "entry_id": entry_id, "requirement_id": ledger["requirement"]["id"], @@ -306,7 +318,7 @@ def _collect_entry( else str(locator["raw_session_id"]) ), } - execution = _execution_summary(events) + execution = {} if stage_only else _execution_summary(events) candidate = telemetry_protocol.build_stage_supplement( fixed, session_hash=str(entry.get("session_hash") or "session-unknown"), diff --git a/helixharness/scripts/telemetry_hosts/opencode.py b/helixharness/scripts/telemetry_hosts/opencode.py new file mode 100644 index 0000000..f642aec --- /dev/null +++ b/helixharness/scripts/telemetry_hosts/opencode.py @@ -0,0 +1,51 @@ +"""Consent-gated stage facts for OpenCode; no native transcript collection.""" +from __future__ import annotations + +import os +import re +from pathlib import Path +from typing import Any + +from telemetry_session import SessionContextUnavailable + + +class OpenCodeAdapter: + host_id = "opencode" + parser_version = "lite-opencode-stage/1.0" + strict_private_cleanup = True + stage_facts_only = True + + def consent_cache_path(self, override: str | None = None) -> Path: + if override: + return Path(override).expanduser().resolve() + home = Path(os.environ.get("HELIXHARNESS_OPENCODE_HOME") or + Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local/state") / "opencode") + return home.expanduser() / "helixharness/telemetry-consent-cache.json" + + def current_session_context(self, repo: Path) -> dict[str, str]: + identity = os.environ.get("HELIXHARNESS_SESSION_ID", "") + directory = os.environ.get("HELIXHARNESS_SESSION_CWD", "") + if not re.fullmatch(r"ses_[A-Za-z0-9_-]{1,160}", identity) or not Path(directory).is_absolute(): + raise SessionContextUnavailable("opencode_session_identity_unavailable") + try: + root = repo.resolve(strict=True) + if not root.is_dir() or Path(directory).resolve(strict=True) != root: + raise ValueError() + except (OSError, ValueError): + raise SessionContextUnavailable("opencode_session_identity_unavailable") from None + return {"session_id": identity, "session_cwd": str(root)} + + def prepare_session_source(self, repo: Path, context: dict[str, Any], consent_epoch: str) -> dict[str, str]: + del consent_epoch + bound = self.current_session_context(repo) + if context.get("session_id") != bound["session_id"]: + raise SessionContextUnavailable("opencode_session_identity_unavailable") + # Explicitly strip any other host's inherited source environment. + return bound + + def validate_session_source(self, value: Any, repo: Path | None = None) -> None: + return None + + def collect_supplement_window(self, source: Path, *, started_at: str, ended_at: str, + max_bytes: int | None = None): + raise SessionContextUnavailable("opencode_transcript_collection_unsupported") diff --git a/helixharness/scripts/telemetry_ledger.py b/helixharness/scripts/telemetry_ledger.py index d415ee9..7e1d778 100644 --- a/helixharness/scripts/telemetry_ledger.py +++ b/helixharness/scripts/telemetry_ledger.py @@ -792,6 +792,11 @@ def _source_boundary( } if not locator: return boundary + if getattr(get_host_adapter(str(entry.get("platform") or "")), "stage_facts_only", False) is True: + snapshot = json.dumps(entry, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + boundary.update({"source_status": "stage_facts", "source_limit_bytes": 0, + "source_fingerprint": "sealed-" + hashlib.sha256(snapshot.encode("utf-8")).hexdigest()}) + return boundary try: path = Path(str(locator.get("session_log_path") or "")).expanduser() if path.is_symlink() or not path.is_file(): diff --git a/helixharness/scripts/tests/test_cursor_bundle_update.py b/helixharness/scripts/tests/test_cursor_bundle_update.py index 0c554e5..6d57f16 100644 --- a/helixharness/scripts/tests/test_cursor_bundle_update.py +++ b/helixharness/scripts/tests/test_cursor_bundle_update.py @@ -16,21 +16,45 @@ REPOSITORY = Path(__file__).resolve().parents[3] PLUGIN = REPOSITORY / "helixharness" +BUN = shutil.which("bun") +OPENCODE_NATIVE = os.environ.get("HELIXHARNESS_OPENCODE_E2E") == "1" and shutil.which(os.environ.get("HELIXHARNESS_OPENCODE_BIN", "opencode")) @unittest.skipUnless(shutil.which("git") and sys.platform in {"darwin", "linux"}, "Git and atomic directory exchange required") class CursorFullBundleUpdateTests(unittest.TestCase): def test_native_opencode_distribution_includes_runtime_without_dependencies_or_private_files(self): - for name in ("package.json", "opencode/index.ts", "opencode/core.ts"): + for name in ("package.json", "opencode/index.ts", "opencode/core.ts", "opencode/project-checks.ts", "opencode/ut-state.ts"): with self.subTest(name=name): self.assertTrue(_distributed(PurePosixPath(name))) for name in ("bun.lock", "node_modules/dependency/index.ts", "opencode/node_modules/dependency/index.ts", "opencode/.bun/cache/index.ts", "opencode/.env.local", "opencode/credentials.json", - "opencode/output/session.json", "opencode/tests/native-fixture.ts", "opencode/runtime/session.json"): + "opencode/output/session.json", "opencode/tests/native-fixture.ts", "opencode/tests/managed-bundle-probe.ts", + "opencode/runtime/session.json", "opencode/unreviewed-helper.ts"): with self.subTest(name=name): self.assertFalse(_distributed(PurePosixPath(name))) def test_installed_bundle_runs_without_checkout_pythonpath_and_updates_itself(self): + self._installed_bundle_scenario() + + @unittest.skipUnless(BUN, "Bun is required to import the installed OpenCode runtime") + def test_installed_and_updated_bundle_loads_opencode_without_checkout_dependencies(self): + self._installed_bundle_scenario(probe="setup") + + @unittest.skipUnless(BUN and OPENCODE_NATIVE, "Enable OpenCode E2E with Bun and a native client") + def test_installed_and_updated_bundle_runs_native_opencode_hooks(self): + self._installed_bundle_scenario(probe="native") + + def _probe(self, plugin, workspace, mode): + environment = {key: os.environ[key] for key in ("PATH", "TMPDIR", "LANG", "SystemRoot", "HELIXHARNESS_OPENCODE_BIN") if key in os.environ} + environment.update({"HOME": str(workspace), "NODE_PATH": ""}) + result = subprocess.run([BUN, str(PLUGIN / "opencode/tests/managed-bundle-probe.ts"), str(plugin), str(workspace), mode], + cwd=workspace, env=environment, capture_output=True, text=True, timeout=60) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + value = json.loads(result.stdout) + self.assertTrue(value["ut_guard"]) + return environment + + def _installed_bundle_scenario(self, *, probe=None): with tempfile.TemporaryDirectory(prefix="helix-cursor-bundle-") as temporary: root = Path(temporary).resolve() source = root / "synthetic public distribution" @@ -58,8 +82,8 @@ def test_installed_bundle_runs_without_checkout_pythonpath_and_updates_itself(se selected.add(relative.as_posix()) self.assertIn("scripts/update_hosts/cursor.py", selected) self.assertIn("hosts/cursor/hooks.json", selected) - native_files = ("package.json", "opencode/index.ts", "opencode/core.ts") - for name in native_files: + native_files = ("package.json", "opencode/index.ts", "opencode/core.ts", "opencode/project-checks.ts", "opencode/ut-state.ts") + for name in native_files[:3]: self.assertIn(name, selected) native_contents = {name: (PLUGIN / name).read_bytes() for name in native_files} root_manifest = source / ".cursor-plugin/marketplace.json" @@ -106,6 +130,19 @@ def release(version): release("1.0.0") installed = run(source / "helixharness/scripts/cursor_managed_install.py", "install", "--source", str(source), "--ref", "main", "--user-confirmed") plugin = Path(installed["plugin_root"]) + if probe: + self._probe(plugin, workspace, probe) + if probe == "setup": + for missing in ("project-checks.ts", "ut-state.ts"): + with self.subTest(missing=missing): + damaged = root / ("damaged-" + missing) + shutil.copytree(plugin, damaged) + (damaged / "opencode" / missing).unlink() + process = subprocess.run([BUN, str(PLUGIN / "opencode/tests/managed-bundle-probe.ts"), str(damaged), str(workspace), "setup"], + cwd=workspace, env={"PATH": os.environ.get("PATH", ""), "HOME": str(workspace), "NODE_PATH": ""}, + capture_output=True, text=True, timeout=15) + self.assertNotEqual(process.returncode, 0) + self.assertIn(missing, process.stderr) for name, content in native_contents.items(): self.assertEqual((plugin / name).read_bytes(), content) for name in excluded_native_files: @@ -149,6 +186,8 @@ def release(version): self.assertEqual(updated["verified_commit"], approved_commit) self.assertEqual(updated["verified_version"], "1.0.1") self.assertEqual((plugin / "reference/cursor-synthetic-release.txt").read_text(), "1.0.1") + if probe: + self._probe(plugin, workspace, probe) for name, content in native_contents.items(): self.assertEqual((plugin / name).read_bytes(), content) for directory in ("node_modules", ".bun", "opencode/tests", "opencode/runtime"): diff --git a/helixharness/scripts/tests/test_cursor_telemetry.py b/helixharness/scripts/tests/test_cursor_telemetry.py index d7a729d..32c2472 100644 --- a/helixharness/scripts/tests/test_cursor_telemetry.py +++ b/helixharness/scripts/tests/test_cursor_telemetry.py @@ -216,7 +216,7 @@ def test_clean_installed_runtime_uses_snapshot_for_all_hosts_without_checkout_im self.assertEqual(set(HostRegistry.discover(ROOT / "hosts").supported_ids()), {"claude-code", "codex", "cursor", "opencode"}) snapshot = build_runtime_snapshot(ROOT) - self.assertEqual({host["host_id"] for host in snapshot["hosts"]}, {"claude-code", "codex", "cursor"}) + self.assertEqual({host["host_id"] for host in snapshot["hosts"]}, {"claude-code", "codex", "cursor", "opencode"}) telemetry_async.install_runtime(ROOT, self.home) runtime = self.home / "runtime" self.assertEqual(json.loads((runtime / RUNTIME_SNAPSHOT_NAME).read_text()), snapshot) @@ -230,7 +230,7 @@ def test_clean_installed_runtime_uses_snapshot_for_all_hosts_without_checkout_im clean = {**self.env, "PYTHONPATH": ""} result = subprocess.run([sys.executable, "-I", "-c", code, str(runtime)], cwd=self.root, env=clean, text=True, capture_output=True, check=True) output = json.loads(result.stdout) - self.assertEqual(set(output["hosts"]), {"claude-code", "codex", "cursor"}) + self.assertEqual(set(output["hosts"]), {"claude-code", "codex", "cursor", "opencode"}) self.assertEqual(output["hosts"], output["ids"]) self.assertTrue(output["unknown"]) self.assertFalse(output["source_imported"]) diff --git a/helixharness/scripts/tests/test_feedback_submit.py b/helixharness/scripts/tests/test_feedback_submit.py index 8aa290e..0a73586 100644 --- a/helixharness/scripts/tests/test_feedback_submit.py +++ b/helixharness/scripts/tests/test_feedback_submit.py @@ -86,8 +86,10 @@ def test_registered_future_host_can_prepare_feedback(self): self.assertEqual("future-host", draft["item"]["document"]["host"]) def test_registered_host_without_telemetry_preserves_feedback_identity(self): - self.assertIsNone(feedback.get_host_adapter("opencode")) - draft = self.prepare(platform="opencode") + # Simulate a registered host with telemetry disabled; OpenCode now has + # a stage-facts adapter, so its real installed manifest is not this case. + with mock.patch.object(feedback, "get_host_adapter", return_value=None): + draft = self.prepare(platform="opencode") self.assertEqual("opencode", draft["item"]["document"]["host"]) self.assertEqual("unknown", draft["item"]["document"]["session"]) self.assertEqual("unknown", self.prepare(platform="unregistered-host")["item"]["document"]["host"]) diff --git a/helixharness/scripts/tests/test_opencode_d2c_gate.py b/helixharness/scripts/tests/test_opencode_d2c_gate.py new file mode 100644 index 0000000..a122d94 --- /dev/null +++ b/helixharness/scripts/tests/test_opencode_d2c_gate.py @@ -0,0 +1,597 @@ +"""Explicit OpenCode D2C checks against synthetic filesystem evidence only.""" +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import struct +import tempfile +import time +import unittest +import zlib +from datetime import datetime, timedelta, timezone + + +PLUGIN = Path(__file__).resolve().parents[2] +GATE = PLUGIN / "hosts/opencode/d2c_gate.cjs" + + +@unittest.skipUnless(shutil.which("node"), "Node.js required") +class OpenCodeD2CGateTests(unittest.TestCase): + @staticmethod + def png(width=1, height=1, raw=None, compressed=None): + def chunk(kind, data): + return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data)) + if raw is None: + raw = (b"\0" + b"\xff\xff\xff\xff" * width) * height + if compressed is None: + compressed = zlib.compress(raw) + return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0)) + + chunk(b"IDAT", compressed) + chunk(b"IEND", b"")) + + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name).resolve() / "synthetic project" + self.page = "synthetic-page" + self.page_dir = self.root / "d-d2c/temp" / self.page + self.round_dir = self.page_dir / "r1" + self.round_dir.mkdir(parents=True) + self.started = (datetime.now(timezone.utc) - timedelta(seconds=2)).isoformat() + self.state_file = self.page_dir / "workflow-state.json" + self.marker_file = self.page_dir.parent / ".active-workflow.json" + self.state = {"currentPhase": 0, "round": 1, "phases": { + "0": {"status": "in_progress", "enteredAt": self.started}, + }} + self.marker = {"pageDir": self.page, "workflowStartedAt": self.started, + "stateFile": str(self.state_file), "status": "active"} + self.save() + + def save(self): + self.state_file.write_text(json.dumps(self.state), encoding="utf-8") + self.marker_file.write_text(json.dumps(self.marker), encoding="utf-8") + + def run_gate(self, action="stop", session="synthetic-native-session", *extra): + args = [shutil.which("node"), str(GATE), "--repo-root", str(self.root), + "--page-dir", self.page, "--started-at", self.started, "--action", action] + if session is not None: + args += ["--session-id", session] + result = subprocess.run(args + list(extra), cwd=self.root, capture_output=True, + text=True, timeout=10, env={"PATH": os.environ.get("PATH", "")}) + self.assertEqual(result.stderr, "", result.stderr) + return result.returncode, json.loads(result.stdout) + + def owned(self): + self.marker["ownerSessionId"] = "synthetic-native-session" + self.marker["ownerClaimedAt"] = self.started + self.save() + + def completed(self, visual=True, current=6): + self.owned() + self.state["phases"] = {str(n): {"status": "completed", "enteredAt": self.started, + "completedAt": self.started} for n in (0, 1, 2, 3, 4, 6)} + self.state["phases"]["4"]["decision"] = "cancel" + self.state["currentPhase"] = current + if current == 4: + self.state["phases"]["4"] = {"status": "in_progress", "enteredAt": self.started} + del self.state["phases"]["6"] + report = self.root / "d2c/temp/d2c-fidelity-evaluator-report/d2c-fidelity-evaluator-r1.md" + self.state["phases"]["3"].update(report=str(report), score=94) + self.save() + if visual: + report.parent.mkdir(parents=True, exist_ok=True) + self.evaluation = {"version": "1.0", "round": 1, "reportFile": str(report), "overallScore": 94, + "scoreUnit": "percent", "summary": "Synthetic fixture evaluation; no real browser acceptance.", + "dimensions": {key: {"weight": weight, "score": 94, "deduction": 6, "notes": "Synthetic fixture"} + for key, weight in (("layoutStructure", .4), ("visualStyle", .25), + ("contentAssets", .15), ("perceptualSimilarity", .2))}, + "optimizationPlan": [], "findings": [], "unresolvedQuestions": []} + self.write_report() + # A real tiny PNG fixture, not browser or visual acceptance evidence. + actual = self.round_dir / "synthetic-actual.png" + actual.write_bytes(self.png()) + self.meta = {"outPath": str(actual), "actualSha256": hashlib.sha256(actual.read_bytes()).hexdigest(), + "captureMode": "full-page", "materialStatus": "valid", + "runtimeHealth": {"status": "passed", "askUser": False}, + "sourceFingerprint": {"digest": hashlib.sha256(b"d2c-runtime-source-v1\0").hexdigest(), + "files": [], "explicitFiles": [], "excludedFiles": []}} + self.write_meta() + for name in ("geometry", "vertical", "render"): + measured = {"wDesign": 1, "leftDesign": 0} if name == "geometry" else ( + {"top": 0, "height": 1, "bottom": 1} if name == "vertical" else { + "matched": True, "layoutMark": "synthetic-scope", + "style": {"rectWidth": 1, "rectHeight": 1, "backgroundColor": "rgb(255,255,255)", "opacity": "1"}}) + measurement = {"version": "1.0", "pageDir": str(self.page_dir), "url": "http://localhost/synthetic", + "captureMode": "full-page", "designFrameWidth": 1, "effectiveCssWidth": 1, + "scaleCssToDesign": 1, "checkedCount": 1, "matchedCount": 1, + "items": [{"layoutMark": "synthetic-scope", "matched": True, + "expected": {"w": 1, "absX": 0, "top": 0, "height": 1}, "measured": measured}], + "violations": [], "violationCount": 0} + if name == "vertical": + measurement.update(tool="d2c-vertical-check", mode="page-flow", primaryCount=0, derivedCount=0) + if name == "render": + measurement.update(gate="render-integrity", hardViolationCount=0) + measurement["items"][0]["expected"] = {"visualFill": "rgba(255,255,255,1)", "textSpans": [], "assets": [], "opacity": 1} + (self.round_dir / f"{name}-diff.json").write_text(json.dumps(measurement), encoding="utf-8") + + def write_report(self): + Path(self.state["phases"]["3"]["report"]).write_text( + "# Synthetic fidelity report\n**Fidelity Score**: 94%\n```json\n" + json.dumps(self.evaluation) + "\n```\n", encoding="utf-8") + + def write_meta(self): + (self.round_dir / "capture-meta.json").write_text(json.dumps(self.meta), encoding="utf-8") + + def test_claim_binds_fresh_phase0_then_checks_are_read_only(self): + code, result = self.run_gate("claim") + self.assertEqual(code, 0) + self.assertEqual(result["action"]["kind"], "claimed") + self.assertEqual(json.loads(self.marker_file.read_text())["ownerSessionId"], "synthetic-native-session") + before = self.marker_file.read_bytes(), self.state_file.read_bytes() + self.assertEqual(self.run_gate()[0], 2) + self.assertEqual(before, (self.marker_file.read_bytes(), self.state_file.read_bytes())) + + def test_missing_session_and_unowned_completion_are_rejected(self): + self.completed() + self.assertEqual(self.run_gate(session=None)[0], 2) + del self.marker["ownerSessionId"] + self.save() + self.assertEqual(self.run_gate()[0], 2) + self.assertEqual(self.run_gate("claim")[0], 2) + + def test_other_session_cannot_claim_or_complete(self): + self.completed() + for action in ("claim", "stop", "ask"): + with self.subTest(action=action): + self.assertEqual(self.run_gate(action, "another-native-session")[0], 2) + + def test_stale_unowned_phase0_cannot_be_claimed(self): + self.started = (datetime.now(timezone.utc) - timedelta(hours=1)).isoformat() + self.state["phases"]["0"]["enteredAt"] = self.started + self.marker["workflowStartedAt"] = self.started + self.save() + self.assertEqual(self.run_gate("claim")[0], 2) + + def test_claim_cannot_reclaim_owned_state(self): + self.owned() + self.assertEqual(self.run_gate("claim")[0], 2) + + def test_ownership_claim_must_belong_to_this_invocation(self): + self.completed() + for claimed in (None, "2000-01-01T00:00:00Z"): + self.marker["ownerClaimedAt"] = claimed + self.save() + with self.subTest(claimed=claimed): + self.assertEqual(self.run_gate()[0], 2) + + def test_complete_status_without_actual_evidence_is_rejected(self): + self.completed(visual=False) + code, result = self.run_gate() + self.assertEqual(code, 2) + self.assertFalse(result["allow"]) + + def test_present_evidence_allows_completion_not_spurious_ask(self): + self.completed() + code, result = self.run_gate() + self.assertEqual(code, 0, result) + self.assertEqual(result["action"]["kind"], "done") + self.assertEqual(self.run_gate("ask")[0], 2) + + def test_missing_each_visual_artifact_is_rejected(self): + self.completed() + paths = [self.round_dir / name for name in ("capture-meta.json", "synthetic-actual.png", + "geometry-diff.json", "vertical-diff.json", "render-diff.json")] + paths += [Path(self.state["phases"]["3"]["report"])] + for file in paths: + with self.subTest(file=file.name): + saved = file.read_bytes() + file.unlink() + self.assertEqual(self.run_gate()[0], 2) + file.write_bytes(saved) + + def test_stale_files_rejected_even_when_status_timestamps_are_current(self): + self.completed() + for file in (self.round_dir / "synthetic-actual.png", self.round_dir / "render-diff.json", + Path(self.state["phases"]["3"]["report"])): + with self.subTest(file=file.name): + stat = file.stat() + os.utime(file, (1, 1)) + self.assertEqual(self.run_gate()[0], 2) + os.utime(file, ns=(stat.st_atime_ns, stat.st_mtime_ns)) + + def test_modified_capture_bytes_and_invalid_material_are_rejected(self): + self.completed() + actual = self.round_dir / "synthetic-actual.png" + original = actual.read_bytes() + actual.write_bytes(original + b"changed") + self.assertEqual(self.run_gate()[0], 2) + actual.write_bytes(original) + self.meta["materialStatus"] = "invalid" + self.write_meta() + self.assertEqual(self.run_gate()[0], 2) + + def test_empty_measurements_and_malformed_json_are_rejected(self): + self.completed() + for content in ("{}", "[]", "invalid", ""): + with self.subTest(content=content): + (self.round_dir / "geometry-diff.json").write_text(content) + self.assertEqual(self.run_gate()[0], 2) + + def test_phase4_needs_evidence_and_headless_cannot_ask(self): + self.completed(current=4) + self.assertEqual(self.run_gate("ask")[0], 0) + self.assertEqual(self.run_gate("ask", "synthetic-native-session", "--headless")[0], 2) + (self.round_dir / "synthetic-actual.png").unlink() + self.assertEqual(self.run_gate("ask")[0], 2) + + def test_external_input_and_cancel_preserve_distinct_legal_outcomes(self): + self.owned() + for kind, expected in (("external-input", "wait-external-input"), ("user-cancelled", "aborted")): + self.state["workflowPause"] = {"kind": kind, "reason": "synthetic", "detail": "Synthetic reason", "createdAt": self.started} + self.save() + code, result = self.run_gate() + self.assertEqual(code, 0, result) + self.assertEqual(result["action"]["kind"], expected) + + def test_file_and_directory_symlink_escapes_are_rejected(self): + self.completed() + evidence = self.round_dir / "render-diff.json" + outside = Path(self.temp.name) / "outside.json" + outside.write_bytes(evidence.read_bytes()) + evidence.unlink() + evidence.symlink_to(outside) + self.assertEqual(self.run_gate()[0], 2) + + def test_old_completed_phase6_cannot_mask_fresh_restart(self): + self.completed() + self.state["currentPhase"] = 0 + self.state["phases"]["0"]["status"] = "in_progress" + self.save() + self.assertEqual(self.run_gate()[0], 2) + + def test_missing_failed_and_stale_runtime_health_are_rejected(self): + self.completed() + healthy = self.meta["runtimeHealth"] + for health in (None, {"status": "failed"}, {"status": "passed", "askUser": True}): + self.meta["runtimeHealth"] = health + self.write_meta() + with self.subTest(health=health): + self.assertEqual(self.run_gate()[0], 2) + self.meta["runtimeHealth"] = healthy + self.meta["sourceFingerprint"]["digest"] = "0" * 64 + self.write_meta() + self.assertEqual(self.run_gate()[0], 2) + + def test_source_edit_after_capture_invalidates_runtime_evidence(self): + self.completed() + source = self.root / "synthetic.vue" + source.write_text("") + digest = hashlib.sha256(b"d2c-runtime-source-v1\0synthetic.vue\0" + source.read_bytes() + b"\0").hexdigest() + self.meta["sourceFingerprint"].update(digest=digest, files=["synthetic.vue"], explicitFiles=["synthetic.vue"]) + self.write_meta() + self.assertEqual(self.run_gate()[0], 0) + source.write_text("") + self.assertEqual(self.run_gate()[0], 2) + + def test_region_evidence_needs_design_scope_and_fresh_design_source(self): + self.completed() + self.meta.update(captureMode="region", designScope="synthetic-scope") + self.write_meta() + for name in ("geometry", "vertical", "render"): + path = self.round_dir / f"{name}-diff.json" + report = json.loads(path.read_text()) + report.update(captureMode="region", scope={"layoutMarks": ["synthetic-scope"]}) + path.write_text(json.dumps(report)) + self.assertEqual(self.run_gate()[0], 2) + design = self.round_dir / "synthetic-design-source.png" + design.write_bytes((self.round_dir / "synthetic-actual.png").read_bytes()) + self.assertEqual(self.run_gate()[0], 0) + os.utime(design, (1, 1)) + self.assertEqual(self.run_gate()[0], 2) + + def test_stale_handoff_does_not_authorize_current_stop(self): + self.owned() + (self.page_dir / "browser-handoff.json").write_text(json.dumps({ + "active": True, "status": "awaiting-user", "updatedAt": "2000-01-01T00:00:00Z", + "browserReadyAt": "2000-01-01T00:00:00Z"})) + self.assertEqual(self.run_gate()[0], 2) + + def test_real_checkpoint_restart_claims_new_native_session(self): + self.completed() + checkpoint = PLUGIN / "skills/d-d2c/scripts/d2c-workflow-checkpoint.cjs" + result = subprocess.run([shutil.which("node"), str(checkpoint), "--enter", "0", "--page-dir", self.page], + cwd=self.root, capture_output=True, text=True, timeout=10) + self.assertEqual(result.returncode, 0, result.stderr) + self.state = json.loads(self.state_file.read_text()) + self.marker = json.loads(self.marker_file.read_text()) + self.started = self.state["phases"]["0"]["enteredAt"] + self.assertIsNone(self.marker["ownerSessionId"]) + self.assertIn("6", self.state["phases"]) + self.assertEqual(self.run_gate("claim", "second-native-session")[0], 0) + self.assertEqual(self.run_gate("stop", "second-native-session")[0], 2) + + def test_unknown_duplicate_and_invalid_arguments_are_rejected(self): + for action, extra in (("invalid", ()), ("stop", ("--unknown", "x")), + ("stop", ("--session-id", "duplicate"))): + with self.subTest(action=action, extra=extra): + self.assertEqual(self.run_gate(action, "synthetic-native-session", *extra)[0], 2) + + def test_git_discovered_source_symlink_rejected_before_external_read(self): + self.completed() + subprocess.run(["git", "init", "-q", str(self.root)], check=True) + outside = Path(self.temp.name) / "outside-synthetic.vue" + outside.write_bytes(b"synthetic outside repository") + (self.root / "link.vue").symlink_to(outside) + self.meta["sourceFingerprint"]["digest"] = hashlib.sha256( + b"d2c-runtime-source-v1\0link.vue\0" + outside.read_bytes() + b"\0").hexdigest() + self.write_meta() + self.assertEqual(self.run_gate()[0], 2) + # An exit code alone would not prove the external target was never read. + observed = Path(self.temp.name) / "external-read-observed" + preload = Path(self.temp.name) / "observe-read.cjs" + preload.write_text("const fs=require('fs'); const read=fs.readFileSync; fs.readFileSync=function(file,...args){" + "try{if(fs.realpathSync(file)===process.env.TEST_OUTSIDE){fs.writeFileSync(process.env.TEST_OBSERVED,'read')}}catch{}" + "return read.call(fs,file,...args)}") + result = subprocess.run([shutil.which("node"), "--require", str(preload), str(GATE), + "--repo-root", str(self.root), "--page-dir", self.page, "--started-at", self.started, + "--session-id", "synthetic-native-session", "--action", "stop"], + cwd=self.root, capture_output=True, text=True, timeout=10, + env={"PATH": os.environ.get("PATH", ""), "TEST_OUTSIDE": str(outside), "TEST_OBSERVED": str(observed)}) + self.assertEqual(result.returncode, 2, result.stdout) + self.assertFalse(observed.exists(), "external source was read before the rejection") + + def test_invalid_png_structure_crc_deflate_and_scanline_are_rejected(self): + self.completed() + original = self.png() + invalid_chunk_type = bytearray(original) + invalid_chunk_type[12] |= 0x80 + invalid_chunk_type[29:33] = struct.pack(">I", zlib.crc32(invalid_chunk_type[12:29])) + # Include a header-only fake and damaged IDAT/CRC, not just bad magic. + candidates = [bytes.fromhex("89504e470d0a1a0a") + b"NOT_PNG!" + struct.pack(">II", 1, 1), + original[:-12], original[:45] + bytes([original[45] ^ 1]) + original[46:], + self.png(compressed=b"not-deflate"), self.png(raw=b"\x05\xff\xff\xff\xff"), + self.png(raw=b"\0\xff"), self.png(raw=b"\0\xff\xff\xff\xffextra"), invalid_chunk_type] + for image in candidates: + (self.round_dir / "synthetic-actual.png").write_bytes(image) + self.meta["actualSha256"] = hashlib.sha256(image).hexdigest() + self.write_meta() + with self.subTest(length=len(image)): + self.assertEqual(self.run_gate()[0], 2) + + def test_representative_long_png_valid_and_explicit_size_limit(self): + self.completed() + # DPR 2 captures of long pages must remain supported within the audit bound. + image = self.png(width=1356, height=10000) + (self.round_dir / "synthetic-actual.png").write_bytes(image) + self.meta["actualSha256"] = hashlib.sha256(image).hexdigest() + self.write_meta() + self.assertEqual(self.run_gate()[0], 0) + oversize = bytearray(self.png()) + oversize[16:20] = struct.pack(">I", 4000) + oversize[20:24] = struct.pack(">I", 1000000) + oversize[29:33] = struct.pack(">I", zlib.crc32(oversize[12:29])) + (self.round_dir / "synthetic-actual.png").write_bytes(oversize) + self.meta["actualSha256"] = hashlib.sha256(oversize).hexdigest() + self.write_meta() + code, result = self.run_gate() + self.assertEqual(code, 2) + self.assertIn("audit limit", result["detail"]) + + def test_zero_reports_and_positive_counts_without_measurements_are_rejected(self): + self.completed() + path = self.round_dir / "render-diff.json" + original = json.loads(path.read_text()) + for change in ({"checkedCount": 0, "matchedCount": 0, "items": []}, + {"items": [{"matched": True}]}, {"checkedCount": 2}): + path.write_text(json.dumps({**original, **change})) + with self.subTest(change=change): + self.assertEqual(self.run_gate()[0], 2) + + def test_canonical_vertical_with_no_applicable_anchor_remains_legal(self): + self.completed() + path = self.round_dir / "vertical-diff.json" + report = json.loads(path.read_text()) + report.update(checkedCount=0, matchedCount=0, items=[]) + path.write_text(json.dumps(report)) + self.assertEqual(self.run_gate()[0], 0) + + def test_canonical_vertical_producer_unresolved_warning_is_preserved(self): + self.completed() + # Execute the canonical producer unchanged. Only its browser boundary is + # synthetic; DSL traversal and the emitted report are real producer code. + (self.page_dir / "dsl_layout_marked.json").write_text(json.dumps({"nodes": [{ + "_layoutMark": "synthetic-scope", "type": "GROUP", "name": "Synthetic anchor", + "layoutStyle": {"relativeX": 0, "relativeY": 0, "width": 1, "height": 1}, "children": []}]})) + (self.page_dir / "layout-h5.json").write_text(json.dumps({ + "designFrameSize": {"width": 1}, "hostLayoutPolicy": "none"})) + core = PLUGIN / "skills/d-d2c/scripts/lib/d2c-dom-measure-core.cjs" + preload = Path(self.temp.name) / "synthetic-browser-boundary.cjs" + preload.write_text("const core=require(" + json.dumps(str(core)) + ");" + "core.loadPuppeteer=()=>({chrome:null,puppeteer:{}});" + "core.openBrowserSession=async()=>({sessionId:'synthetic-browser',targetId:'synthetic-target',attached:false," + "page:{evaluate:async(fn,payload)=>({viewportCssWidth:1,effectiveCssWidth:1," + "results:payload.targets.map(target=>({layoutMark:target.layoutMark,matched:false}))})}});" + "core.closeBrowserSession=async()=>{}") + producer = PLUGIN / "skills/d-d2c/scripts/d2c-vertical-check.cjs" + result = subprocess.run([shutil.which("node"), "--require", str(preload), str(producer), + "--url", "http://localhost/synthetic", "--page-dir", str(self.page_dir), + "--out", str(self.round_dir), "--scope", "synthetic-scope", "--wait", "0"], + cwd=self.root, capture_output=True, text=True, timeout=10, + env={"PATH": os.environ.get("PATH", "")}) + self.assertEqual(result.returncode, 0, (result.stdout, result.stderr)) + path = self.round_dir / "vertical-diff.json" + original = path.read_bytes() + report = json.loads(original) + self.assertEqual((report["checkedCount"], report["matchedCount"], report["violationCount"]), (1, 0, 0)) + self.assertEqual(report["warnings"][0]["kind"], "mark-unresolved") + self.assertIsNone(report["items"][0]["measured"]) + code, decision = self.run_gate() + self.assertEqual(code, 0, decision) + self.assertEqual(decision["evidenceAudit"]["unresolvedVerticalAnchors"], 1) + self.assertEqual(decision["evidenceAudit"]["warnings"][0]["kind"], "mark-unresolved") + self.assertEqual(path.read_bytes(), original, "the gate must preserve canonical warning evidence") + # Missing, unrelated, or wrong-anchor warnings cannot excuse placeholders. + for warnings in ([], [{"kind": "text-fallback", "layoutMark": "synthetic-scope", "note": "Synthetic"}], + [{"kind": "mark-unresolved", "layoutMark": "another-anchor", "note": "Synthetic"}]): + report["warnings"] = warnings + path.write_text(json.dumps(report)) + with self.subTest(warnings=warnings): + self.assertEqual(self.run_gate()[0], 2) + + def test_unrelated_and_foreign_round_or_score_report_is_rejected(self): + self.completed() + path = Path(self.state["phases"]["3"]["report"]) + path.write_text("Unrelated report") + self.assertEqual(self.run_gate()[0], 2) + for key, bad in (("round", 2), ("overallScore", 12), ("reportFile", str(self.root / "foreign.md"))): + original = self.evaluation[key] + self.evaluation[key] = bad + self.write_report() + with self.subTest(key=key): + self.assertEqual(self.run_gate()[0], 2) + self.evaluation[key] = original + + def test_render_unknown_payload_is_not_a_canonical_measurement(self): + self.completed() + path = self.round_dir / "render-diff.json" + report = json.loads(path.read_text()) + report["items"][0].update(expected={"unrelated": "payload"}, measured={"unrelated": 123}) + path.write_text(json.dumps(report)) + self.assertEqual(self.run_gate()[0], 2) + + def test_canonical_decimal_score_and_custom_report_path_are_supported(self): + self.completed() + custom = self.root / "custom-evidence/evaluation.md" + custom.parent.mkdir() + self.state["phases"]["3"].update(report=str(custom), score=94.2) + self.evaluation.update(reportFile=str(custom), overallScore=94.2) + for dimension in self.evaluation["dimensions"].values(): + dimension.update(score=94.2, deduction=5.8) + self.save() + self.write_report() + code, result = self.run_gate() + self.assertEqual(code, 0, result) + + def test_concurrent_claim_is_exclusive_and_restart_cannot_be_overwritten(self): + preload = Path(self.temp.name) / "claim-barrier.cjs" + arrived = Path(self.temp.name) / "arrived" + release = Path(self.temp.name) / "release" + preload.write_text("const fs=require('fs'); const rename=fs.renameSync; fs.renameSync=function(a,b){" + "if(String(b).endsWith('.active-workflow.json')){fs.writeFileSync(process.env.TEST_ARRIVED,'ready');" + "while(!fs.existsSync(process.env.TEST_RELEASE)){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10)}}" + "return rename.call(fs,a,b)}") + args = [shutil.which("node"), "--require", str(preload), str(GATE), "--repo-root", str(self.root), + "--page-dir", self.page, "--started-at", self.started, "--action", "claim", "--session-id", "first-native-session"] + first = subprocess.Popen(args, cwd=self.root, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + env={"PATH": os.environ.get("PATH", ""), "TEST_ARRIVED": str(arrived), "TEST_RELEASE": str(release)}) + try: + deadline = time.monotonic() + 5 + while not arrived.exists() and time.monotonic() < deadline: + time.sleep(.01) + self.assertTrue(arrived.exists()) + self.assertEqual(self.run_gate("claim", "second-native-session")[0], 2) + before = self.marker_file.read_bytes(), self.state_file.read_bytes() + checkpoint = PLUGIN / "skills/d-d2c/scripts/d2c-workflow-checkpoint.cjs" + restart = subprocess.run([shutil.which("node"), str(checkpoint), "--enter", "0", "--page-dir", self.page], + cwd=self.root, capture_output=True, text=True, timeout=10) + self.assertNotEqual(restart.returncode, 0) + self.assertEqual(before, (self.marker_file.read_bytes(), self.state_file.read_bytes())) + finally: + release.touch() + out, err = first.communicate(timeout=10) + self.assertEqual(first.returncode, 0, (out, err)) + self.assertEqual(json.loads(self.marker_file.read_text())["ownerSessionId"], "first-native-session") + # Retrying the restart after the lock is released succeeds normally. + restart = subprocess.run([shutil.which("node"), str(checkpoint), "--enter", "0", "--page-dir", self.page], + cwd=self.root, capture_output=True, text=True, timeout=10) + self.assertEqual(restart.returncode, 0, restart.stderr) + self.assertIsNone(json.loads(self.marker_file.read_text())["ownerSessionId"]) + + def test_lock_cleanup_on_explicit_process_exit_and_rejected_checkpoint(self): + guard = PLUGIN / "skills/d-d2c/scripts/lib/d2c-workflow-guard-core.cjs" + script = "require(process.argv[1]).withWorkflowLock(process.argv[2],()=>process.exit(7))" + result = subprocess.run([shutil.which("node"), "-e", script, str(guard), str(self.page_dir.parent)], + capture_output=True, text=True, timeout=10) + self.assertEqual(result.returncode, 7) + self.assertFalse(list(self.page_dir.parent.glob(".workflow-state.lock*"))) + self.assertEqual(self.run_gate("claim")[0], 0) + + def test_stale_marker_sync_cannot_replace_restarted_workflow(self): + old_state = self.root / "old-state.json" + old_state.write_bytes(self.state_file.read_bytes()) + checkpoint = PLUGIN / "skills/d-d2c/scripts/d2c-workflow-checkpoint.cjs" + restart = subprocess.run([shutil.which("node"), str(checkpoint), "--enter", "0", "--page-dir", self.page], + cwd=self.root, capture_output=True, text=True, timeout=10) + self.assertEqual(restart.returncode, 0, restart.stderr) + before = self.marker_file.read_bytes() + guard = PLUGIN / "skills/d-d2c/scripts/lib/d2c-workflow-guard-core.cjs" + script = ("const fs=require('fs'); try{require(process.argv[1]).syncActiveWorkflow({stateDir:process.argv[2]," + "pageDir:process.argv[3],state:JSON.parse(fs.readFileSync(process.argv[4])),stateFile:process.argv[5]})}" + "catch(e){process.stdout.write(e.message);process.exitCode=2}") + stale = subprocess.run([shutil.which("node"), "-e", script, str(guard), str(self.page_dir.parent), + self.page, str(old_state), str(self.state_file)], capture_output=True, text=True, timeout=10) + self.assertEqual(stale.returncode, 2, stale.stdout) + self.assertEqual(before, self.marker_file.read_bytes()) + + def test_mutating_checkpoint_locks_before_reading_its_state(self): + checkpoint = PLUGIN / "skills/d-d2c/scripts/d2c-workflow-checkpoint.cjs" + preload = Path(self.temp.name) / "state-read-barrier.cjs" + arrived, release = Path(self.temp.name) / "arrived", Path(self.temp.name) / "release" + preload.write_text("const fs=require('fs'); const read=fs.readFileSync; let paused=false;" + "fs.readFileSync=function(file,...args){const result=read.call(fs,file,...args);" + "if(!paused&&String(file).endsWith('workflow-state.json')){paused=true;fs.writeFileSync(process.env.TEST_ARRIVED,'ready');" + "while(!fs.existsSync(process.env.TEST_RELEASE)){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10)}}return result}") + first = subprocess.Popen([shutil.which("node"), "--require", str(preload), str(checkpoint), + "--page-dir", self.page, "--pause", "user-cancelled", "--reason", "synthetic-first-operation"], + cwd=self.root, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + env={"PATH": os.environ.get("PATH", ""), "TEST_ARRIVED": str(arrived), "TEST_RELEASE": str(release)}) + try: + deadline = time.monotonic() + 5 + while not arrived.exists() and time.monotonic() < deadline: + time.sleep(.01) + self.assertTrue(arrived.exists()) + before = self.marker_file.read_bytes(), self.state_file.read_bytes() + restart = subprocess.run([shutil.which("node"), str(checkpoint), "--enter", "0", "--page-dir", self.page], + cwd=self.root, capture_output=True, text=True, timeout=10) + self.assertNotEqual(restart.returncode, 0) + self.assertEqual(before, (self.marker_file.read_bytes(), self.state_file.read_bytes())) + finally: + release.touch() + out, err = first.communicate(timeout=10) + self.assertEqual(first.returncode, 0, (out, err)) + + def test_killed_lock_owner_does_not_block_later_checkpoint_or_claim(self): + guard = PLUGIN / "skills/d-d2c/scripts/lib/d2c-workflow-guard-core.cjs" + checkpoint = PLUGIN / "skills/d-d2c/scripts/d2c-workflow-checkpoint.cjs" + for signal in ("SIGKILL", "SIGTERM"): + ready = Path(self.temp.name) / f"ready-{signal}" + script = ("const fs=require('fs');require(process.argv[1]).withWorkflowLock(process.argv[2],()=>{" + "fs.writeFileSync(process.argv[3],'ready');while(true)Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10000)})") + owner = subprocess.Popen([shutil.which("node"), "-e", script, str(guard), str(self.page_dir.parent), str(ready)], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + try: + deadline = time.monotonic() + 5 + while not ready.exists() and time.monotonic() < deadline: + time.sleep(.01) + self.assertTrue(ready.exists()) + if signal == "SIGKILL": + owner.kill() + else: + owner.terminate() + owner.communicate(timeout=5) + restart = subprocess.run([shutil.which("node"), str(checkpoint), "--enter", "0", "--page-dir", self.page], + cwd=self.root, capture_output=True, text=True, timeout=10) + self.assertEqual(restart.returncode, 0, restart.stderr) + self.state = json.loads(self.state_file.read_text()) + self.marker = json.loads(self.marker_file.read_text()) + self.started = self.state["phases"]["0"]["enteredAt"] + self.assertEqual(self.run_gate("claim")[0], 0) + self.assertFalse(list(self.page_dir.parent.glob(".workflow-state.lock*"))) + finally: + if owner.poll() is None: + owner.kill() + owner.communicate(timeout=5) + + +if __name__ == "__main__": + unittest.main() diff --git a/helixharness/scripts/tests/test_opencode_host.py b/helixharness/scripts/tests/test_opencode_host.py index 8b0c123..cc9ef48 100644 --- a/helixharness/scripts/tests/test_opencode_host.py +++ b/helixharness/scripts/tests/test_opencode_host.py @@ -40,7 +40,7 @@ def setUp(self) -> None: 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.support_level, "stable") self.assertEqual(self.manifest.display_name, "OpenCode") expected = { @@ -53,12 +53,13 @@ def test_manifest_is_discovered_with_expected_capabilities(self) -> None: "workflow_transition": "emulated", "subagents": "native", "unit_test_workflow": "native", - "task_tracking": "unsupported", + "task_tracking": "emulated", "project_hooks": "unsupported", + "project_checks": "emulated", "session_events": "unsupported", - "telemetry": "unsupported", + "telemetry": "emulated", "plugin_install": "native", - "plugin_update": "unsupported", + "plugin_update": "emulated", "session_end": "unsupported", } self.assertEqual(self.manifest.capabilities, expected) @@ -147,31 +148,21 @@ def test_detector_requires_explicit_opencode_markers(self) -> None: self.assertIsNone(detect_host({})) self.assertIsNone(detect_host({"CODEX_THREAD_ID": "thread"})) - def test_telemetry_and_update_are_declared_unsupported(self) -> None: + def test_telemetry_is_registered_and_update_refuses_unmanaged_copy(self) -> None: self.assertEqual(normalize_host_id("opencode"), "opencode") - self.assertIsNone(get_host_adapter("opencode")) + self.assertEqual(get_host_adapter("opencode").host_id, "opencode") + from version_update import check_for_update + + # Never depend on the developer checkout being dirty or fetch its remote. 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") + root = Path(directory).resolve() + plugin = root / "unmanaged-plugin" + plugin.mkdir() + payload = check_for_update("opencode", root, root / "state/cache.json", plugin_root=plugin) + self.assertFalse((root / "state").exists()) + self.assertEqual(payload["state"], "unavailable") + self.assertEqual(payload["next_action"], "continue_with_warning") def test_host_context_cli_resolves_the_installed_plugin(self) -> None: result = subprocess.run( @@ -194,7 +185,7 @@ def test_host_context_cli_resolves_the_installed_plugin(self) -> None: 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["capabilities"]["telemetry"], "emulated") self.assertEqual( payload["resources"]["runtime"], "hosts/opencode/runtime.md" ) diff --git a/helixharness/scripts/tests/test_opencode_telemetry.py b/helixharness/scripts/tests/test_opencode_telemetry.py new file mode 100644 index 0000000..ee2f825 --- /dev/null +++ b/helixharness/scripts/tests/test_opencode_telemetry.py @@ -0,0 +1,105 @@ +"""Synthetic OpenCode stage telemetry: explicit identity, consent, no transcripts.""" +import os +import subprocess +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +import metrics +import telemetry_consent +import telemetry_collector +from telemetry_hosts import get_host_adapter +from telemetry_hosts.opencode import OpenCodeAdapter +from telemetry_session import SessionContextUnavailable + + +class OpenCodeTelemetryTest(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name).resolve() + self.repo = self.root / "synthetic repo" + self.repo.mkdir() + subprocess.run(["git", "init", "-q", str(self.repo)], check=True) + env = patch.dict(os.environ, { + "HELIXHARNESS_OPENCODE_HOME": str(self.root / "host"), + "HELIXHARNESS_TELEMETRY_HOME": str(self.root / "telemetry"), + "HELIXHARNESS_SESSION_ID": "ses_synthetic1", + "HELIXHARNESS_SESSION_CWD": str(self.repo), + "HELIXHARNESS_TELEMETRY_DISABLE_SCHEDULER": "1", + }) + env.start() + self.addCleanup(env.stop) + self.adapter = OpenCodeAdapter() + for name, result in (("ensure_runtime_ready", {}), ("wake_detached", False)): + stub = patch.object(metrics.telemetry_async, name, return_value=result) + stub.start() + self.addCleanup(stub.stop) + + def enable(self): + telemetry_consent.set_mode(self.repo, "opencode", self.adapter.consent_cache_path(), + "project", "enabled", consent_source="explicit-command", user_confirmed=True) + + def test_registry_and_explicit_session_binding(self): + self.assertIsInstance(get_host_adapter("opencode"), OpenCodeAdapter) + self.assertEqual(self.adapter.current_session_context(self.repo), + {"session_id": "ses_synthetic1", "session_cwd": str(self.repo)}) + + def test_missing_foreign_or_other_host_identity_fails_closed(self): + for values in ({"HELIXHARNESS_SESSION_ID": ""}, + {"HELIXHARNESS_SESSION_CWD": str(self.root)}, + {"HELIXHARNESS_SESSION_ID": "thread_other_host"}, + {"HELIXHARNESS_SESSION_CWD": "."}): + with self.subTest(values=values), patch.dict(os.environ, values): + with self.assertRaises(SessionContextUnavailable): + self.adapter.current_session_context(self.repo) + + def test_disabled_does_not_create_ledger(self): + # Revocation/disabled cleanup must not touch another host's private state. + other = self.repo / ".helixharness/telemetry-v2/lite-active/demo/propose.json" + other.parent.mkdir(parents=True) + original = '{"version":2,"active":{"foreign":{"platform":"cursor","entry_id":"synthetic_foreign"}}}' + other.write_text(original) + result = metrics.start(self.repo, "opencode", "demo", "propose", "user_command") + self.assertEqual(result["reason"], "telemetry_disabled") + self.assertFalse((self.repo / "docs/eval").exists()) + self.assertEqual(other.read_text(), original) + + def test_enabled_records_and_finishes_without_session_source(self): + self.enable() + started = metrics.start(self.repo, "opencode", "demo", "propose", "user_command") + self.assertEqual(started["status"], "started", started) + finished = metrics.finish(self.repo, "opencode", "demo", "propose", "completed", None, {}) + self.assertEqual(finished["status"], "recorded", finished) + for path in self.repo.rglob("*.json"): + self.assertNotIn('"session_log_path": "', path.read_text()) + + def test_invalid_identity_skips_even_after_consent(self): + self.enable() + with patch.dict(os.environ, {"HELIXHARNESS_SESSION_ID": ""}): + result = metrics.start(self.repo, "opencode", "demo", "apply", "user_command") + self.assertEqual(result["status"], "skipped", result) + self.assertFalse((self.repo / "docs/eval").exists()) + + def test_arbitrary_sources_never_read(self): + self.assertIsNone(self.adapter.validate_session_source(self.root / "anything.jsonl", self.repo)) + with self.assertRaises(SessionContextUnavailable): + self.adapter.collect_supplement_window(self.root / "missing", started_at="", ended_at="") + + def test_stage_only_supplement_and_archived_seal_keep_unknown_usage_unavailable(self): + self.enable() + started = metrics.start(self.repo, "opencode", "demo", "propose", "user_command") + metrics.finish(self.repo, "opencode", "demo", "propose", "completed", None, {}) + home = self.root / "telemetry" + supplement = telemetry_collector.collect_entry(self.repo, started["entry_id"], home=home, + endpoint="http://127.0.0.1:9/synthetic") + self.assertEqual(supplement["usage"], {}) + self.assertEqual(supplement["execution"], {}) + self.assertEqual(supplement["evidence"]["status"], "unavailable") + archived = metrics.start(self.repo, "opencode", "demo", "archive", "user_command") + metrics.finish(self.repo, "opencode", "demo", "archive", "completed", None, {}) + final = telemetry_collector.collect_entry(self.repo, archived["entry_id"], home=home, + endpoint="http://127.0.0.1:9/synthetic") + self.assertEqual(final["usage"], {}) + self.assertEqual(final["platform"], "opencode") diff --git a/helixharness/scripts/tests/test_opencode_update.py b/helixharness/scripts/tests/test_opencode_update.py new file mode 100644 index 0000000..46b5602 --- /dev/null +++ b/helixharness/scripts/tests/test_opencode_update.py @@ -0,0 +1,161 @@ +"""Pinned, consent-driven checkout updates, using synthetic local Git sources.""" +import json +import os +import subprocess +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +from update_hosts.base import BoundedCommandRunner, UpdateHostError +from update_hosts.opencode import OpenCodeUpdateAdapter, plugin_version +import version_update as updates + + +class OpenCodeUpdateTest(unittest.TestCase): + def git(self, root, *args): + return subprocess.check_output(["git", "-c", "core.hooksPath=/dev/null", "-C", str(root), *args], text=True).strip() + + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name).resolve() + self.source = self.root / "source" + self.source.mkdir() + self.git(self.source, "init", "-q", "-b", "main") + self.git(self.source, "config", "user.name", "Synthetic") + self.git(self.source, "config", "user.email", "synthetic@example.invalid") + plugin = self.source / "helixharness" + plugin.mkdir() + def release(version): + marketplace = {"name": "helixharness-marketplace", "plugins": [{"name": "helix", "source": "./helixharness", "version": version}]} + policy = {"schema_version": "1.0", "plugin": "helix", "marketplace": "helixharness-marketplace", "latest_version": version, + "minimum_supported_version": "1.0.0", "force_update_below": None, "force_update_message": None, + "releases": [{"version": value, "date": "2026-11-23", "update_type": "recommended", "title": "Synthetic", "changes": ["Synthetic"], "restart_required": True} + for value in ([version, "1.0.0"] if version != "1.0.0" else [version])]} + (self.source / ".claude-plugin").mkdir(exist_ok=True) + (self.source / ".claude-plugin/marketplace.json").write_text(json.dumps(marketplace)) + (plugin / "reference").mkdir(exist_ok=True) + (plugin / "reference/version-policy.json").write_text(json.dumps(policy)) + release("1.0.0") + (plugin / "package.json").write_text(json.dumps({"name": "helixharness-opencode", "version": "1.0.0", "exports": {".": "./opencode/index.ts"}})) + (plugin / "opencode").mkdir() + (plugin / "opencode/index.ts").write_text("export default {}") + self.git(self.source, "add", ".") + self.git(self.source, "commit", "-qm", "synthetic A") + self.checkout = self.root / "installed checkout" + subprocess.run(["git", "-c", "core.hooksPath=/dev/null", "clone", "-q", str(self.source), str(self.checkout)], check=True) + self.plugin = self.checkout / "helixharness" + self.old = self.git(self.checkout, "rev-parse", "HEAD") + (plugin / "package.json").write_text(json.dumps({"name": "helixharness-opencode", "version": "1.0.1", "exports": {".": "./opencode/index.ts"}})) + release("1.0.1") + self.git(self.source, "add", ".") + self.git(self.source, "commit", "-qm", "synthetic B") + self.new = self.git(self.source, "rev-parse", "HEAD") + self.adapter = OpenCodeUpdateAdapter(str, lambda p: json.loads(p.read_text()), home=self.root / "state") + self.runner = BoundedCommandRunner() + + def test_entire_authorization_chain_and_single_consumption(self): + cache = self.root / "state/cache.json" + authorization = self.root / "state/authorization.json" + with patch.dict(updates._HOST_ADAPTERS, {"opencode": self.adapter}): + checked = updates.check_for_update("opencode", self.root, cache, plugin_root=self.plugin, runner=self.runner, force_refresh=True) + self.assertEqual(checked["update_status"], "recommended", checked) + prepared = updates.prepare_authorization("opencode", "checkout", cache, authorization) + challenge = prepared["challenge_id"] + with self.assertRaises(updates.UpdateError): + updates.install("opencode", cache, authorization, challenge, plugin_root=self.plugin, runner=self.runner) + self.assertEqual(self.git(self.checkout, "rev-parse", "HEAD"), self.old) + with self.assertRaises(updates.UpdateError): + updates.apply_update_choice(cache, authorization, challenge, "upgrade_now", False) + updates.apply_update_choice(cache, authorization, challenge, "upgrade_now", True) + installed = updates.install("opencode", cache, authorization, challenge, plugin_root=self.plugin, runner=self.runner) + self.assertTrue(installed["authorization_consumed"]) + self.assertEqual(self.git(self.checkout, "rev-parse", "HEAD"), self.new) + with self.assertRaises(updates.UpdateError): + updates.install("opencode", cache, authorization, challenge, plugin_root=self.plugin, runner=self.runner) + + def test_target_version_mismatch_is_rejected_before_mutation(self): + binding = self.binding() + with self.assertRaises(UpdateHostError): + self.adapter.execute_install_step(self.adapter.install_steps("checkout", self.runner)[0], self.runner, + authorization={"state": "installing", "update_binding": binding, "target_version": "9.0.0"}, plugin_root=self.plugin) + self.assertEqual(self.git(self.checkout, "rev-parse", "HEAD"), self.old) + + def binding(self): + installation = self.adapter.inspect_installation(self.root, self.plugin, self.runner) + with self.adapter.refresh_marketplace(self.runner) as snapshot: + self.assertEqual(plugin_version(snapshot / "helixharness"), "1.0.1") + return self.adapter.update_binding(snapshot, installation, self.runner) + + def test_check_does_not_change_head_or_worktree(self): + binding = self.binding() + self.assertEqual(binding["target_commit"], self.new) + self.assertEqual(self.git(self.checkout, "rev-parse", "HEAD"), self.old) + self.assertEqual(plugin_version(self.plugin), "1.0.0") + + def test_authorized_target_is_pinned_even_if_source_advances(self): + binding = self.binding() + (self.source / "later.txt").write_text("synthetic later") + self.git(self.source, "add", ".") + self.git(self.source, "commit", "-qm", "synthetic C") + auth = {"state": "installing", "scope": "checkout", "update_binding": binding, "target_version": "1.0.1"} + step = self.adapter.install_steps("checkout", self.runner)[0] + self.adapter.execute_install_step(step, self.runner, authorization=auth, plugin_root=self.plugin) + self.adapter.execute_install_step(step, self.runner, authorization=auth, plugin_root=self.plugin) + self.assertEqual(self.git(self.checkout, "rev-parse", "HEAD"), self.new) + self.assertFalse((self.checkout / "later.txt").exists()) + self.assertEqual(self.adapter.verify_installation(auth, self.runner, plugin_root=self.plugin)["target_commit"], self.new) + + def test_dirty_checkout_blocks_without_overwriting(self): + binding = self.binding() + (self.checkout / "local.txt").write_text("keep") + with self.assertRaises(UpdateHostError): + self.adapter.execute_install_step(self.adapter.install_steps("checkout", self.runner)[0], self.runner, + authorization={"state": "installing", "update_binding": binding}, plugin_root=self.plugin) + self.assertEqual((self.checkout / "local.txt").read_text(), "keep") + self.assertEqual(self.git(self.checkout, "rev-parse", "HEAD"), self.old) + + def test_detached_and_no_upstream_are_rejected(self): + self.git(self.checkout, "checkout", "--detach", "-q") + with self.assertRaises(UpdateHostError): + self.adapter.inspect_installation(self.root, self.plugin, self.runner) + self.git(self.checkout, "checkout", "-q", "main") + self.git(self.checkout, "branch", "--unset-upstream") + with self.assertRaises(UpdateHostError): + self.adapter.inspect_installation(self.root, self.plugin, self.runner) + + def test_divergence_is_rejected_and_git_hooks_never_run(self): + marker = self.root / "hook-must-not-run" + hook = self.checkout / ".git/hooks/post-merge" + hook.write_text(f"#!/bin/sh\ntouch '{marker}'\n") + hook.chmod(0o755) + binding = self.binding() + self.adapter.execute_install_step(self.adapter.install_steps("checkout", self.runner)[0], self.runner, + authorization={"state": "installing", "update_binding": binding, "target_version": "1.0.1"}, plugin_root=self.plugin) + self.assertFalse(marker.exists()) + # Two descendants of B now diverge; all commits stay inside this fixture. + (self.checkout / "local-branch.txt").write_text("synthetic local commit") + self.git(self.checkout, "add", ".") + self.git(self.checkout, "-c", "user.name=Synthetic", "-c", "user.email=synthetic@example.invalid", "commit", "-qm", "synthetic local") + head = self.git(self.checkout, "rev-parse", "HEAD") + (self.source / "upstream-branch.txt").write_text("synthetic upstream commit") + self.git(self.source, "add", ".") + self.git(self.source, "commit", "-qm", "synthetic upstream") + with self.assertRaises(UpdateHostError): + self.binding() + self.assertEqual(self.git(self.checkout, "rev-parse", "HEAD"), head) + + def test_malformed_binding_and_unconfirmed_execution_are_rejected(self): + binding = self.binding() + for changed in ({"plugin_relative": "../foreign"}, {"target_commit": "main"}, {"checkout_root": "relative"}): + with self.subTest(changed=changed), self.assertRaises(UpdateHostError): + self.adapter.validate_update_binding({**binding, **changed}) + with self.assertRaises(UpdateHostError): + self.adapter.execute_install_step(self.adapter.install_steps("checkout", self.runner)[0], self.runner, + authorization={"state": "prepared", "update_binding": binding}, plugin_root=self.plugin) + + def test_dirty_inspection_is_rejected(self): + (self.plugin / "package.json").write_text("local edits") + with self.assertRaises(UpdateHostError): + self.adapter.inspect_installation(self.root, self.plugin, self.runner) diff --git a/helixharness/scripts/tests/test_project_status_regressions.py b/helixharness/scripts/tests/test_project_status_regressions.py new file mode 100644 index 0000000..274f941 --- /dev/null +++ b/helixharness/scripts/tests/test_project_status_regressions.py @@ -0,0 +1,123 @@ +"""Status remains observational across active, blocked and archived workflows.""" +from __future__ import annotations + +import hashlib +import os +from pathlib import Path +import subprocess +import tempfile +import unittest +from unittest import mock + +import project_status +import test_workflow as workflow_fixture + + +class StatusObservationTest(unittest.TestCase): + def setUp(self): + # The shared fixture creates only a temporary synthetic Git history. + # Never invoke a developer's global commit hooks from this regression. + count = int(os.environ.get('GIT_CONFIG_COUNT', '0')) + git_env = mock.patch.dict(os.environ, { + 'GIT_CONFIG_COUNT': str(count + 1), + f'GIT_CONFIG_KEY_{count}': 'core.hooksPath', + f'GIT_CONFIG_VALUE_{count}': os.devnull, + }) + git_env.start() + self.addCleanup(git_env.stop) + self.fixture = workflow_fixture.LiteWorkflowCliTest() + self.fixture.tempdir = tempfile.TemporaryDirectory() + self.fixture.repo = Path(self.fixture.tempdir.name) / 'repo' + self.fixture.repo.mkdir() + subprocess.run(['git', 'init', '-q', str(self.fixture.repo)], check=True) + subprocess.run([ + 'git', '-C', str(self.fixture.repo), '-c', f'core.hooksPath={os.devnull}', + '-c', 'user.email=test@example.invalid', '-c', 'user.name=Synthetic test', + 'commit', '--allow-empty', '-qm', 'synthetic baseline', + ], check=True) + self.fixture.feature = 'checkout' + self.addCleanup(self.fixture.tearDown) + self.repo = self.fixture.repo + + def files(self): + return { + str(p.relative_to(self.repo)): hashlib.sha256(p.read_bytes()).hexdigest() + for p in self.repo.rglob('*') if p.is_file() + } + + def observe(self, *args, **kwargs): + before = self.files() + result = project_status.snapshot(self.repo, *args, **kwargs) + self.assertEqual(before, self.files(), 'Status changed repository or private state') + self.assertTrue(result['read_only']) + self.assertIn('not rerun', result['note']) + return result + + def test_empty_repository_has_no_feature_or_invented_next_action(self): + result = self.observe() + self.assertTrue(result['empty']) + self.assertEqual(result['features'], []) + self.assertFalse((self.repo / '.helixharness').exists()) + + def test_ready_status_does_not_bind_apply_or_start_execution(self): + self.fixture.write_spec(status='ready') + self.fixture.write_tasks(status='ready') + item = self.observe()['features'][0] + self.assertEqual(item['status'], 'ready') + self.assertEqual(item['next_command'], '/helix:apply checkout') + self.assertEqual(item['tasks']['pending'], 1) + self.assertFalse((self.repo / '.helixharness').exists()) + + def test_blocked_task_is_reported_without_repair_or_reset(self): + self.fixture.write_spec(status='ready') + self.fixture.write_tasks(status='ready', rows='| T-01 | Waiting for input | AC-01 | — | blocked |') + item = self.observe()['features'][0] + self.assertEqual(item['tasks']['blocked'], 1) + self.assertEqual(item['blocked_tasks'][0]['id'], 'T-01') + self.assertTrue(item['issues']) + self.assertIn('unfinished work', ' '.join(item['issues'])) + + def test_in_progress_task_is_not_reset_by_status(self): + self.fixture.write_spec(status='applying') + self.fixture.write_tasks(status='applying', rows='| T-01 | Partial implementation | AC-01 | — | in_progress |') + self.fixture.write_apply_state() + item = self.observe('checkout')['features'][0] + self.assertEqual(item['tasks']['in_progress'], 1) + self.assertEqual(len(item['in_progress_tasks']), 1) + + def test_missing_evidence_does_not_claim_archive_passed(self): + self.fixture.write_spec(status='implemented') + self.fixture.write_tasks(status='completed', rows='| T-01 | Completed implementation | AC-01 | — | completed |') + self.fixture.write_apply_state() + item = self.observe()['features'][0] + self.assertEqual(item['archive_check'], 'failed') + self.assertIsNone(item['next_command']) + self.assertTrue(item['issues']) + + def test_completed_directory_requires_valid_evidence_and_review_seal(self): + self.fixture.write_spec(status='implemented') + self.fixture.write_tasks(status='completed', rows='| T-01 | Completed implementation | AC-01 | — | completed |') + self.fixture.write_apply_state() + workflow_fixture.write(self.repo / 'delivery.py', 'def value():\n return 1\n') + self.fixture.write_evidence() + self.fixture.run_cli('authorize-knowledge', '--feature', 'checkout', '--paths-json', '[]') + directory = self.fixture.feature_dir + for name, before, after in ( + ('spec.md', 'status: implemented', 'status: completed'), + ('verify-report.md', 'archive: pending', 'archive: completed'), + ): + p = directory / name + p.write_text(p.read_text().replace(before, after)) + self.fixture.run_cli('finalize-preflight', '--feature', 'checkout') + completed = self.repo / 'docs/specs/completed/checkout' + completed.parent.mkdir(parents=True) + directory.rename(completed) + item = self.observe('checkout')['features'][0] + self.assertEqual(item['status'], 'archived') + self.assertEqual(item['archive_check'], 'passed') + self.assertIsNone(item['next_command']) + (completed / 'verify-report.md').unlink() + item = self.observe(completed=True)['features'][0] + self.assertNotEqual(item['status'], 'archived') + self.assertEqual(item['archive_check'], 'failed') + self.assertIsNone(item['next_command']) diff --git a/helixharness/scripts/tests/test_task_plan.py b/helixharness/scripts/tests/test_task_plan.py new file mode 100644 index 0000000..c3dcefa --- /dev/null +++ b/helixharness/scripts/tests/test_task_plan.py @@ -0,0 +1,87 @@ +"""One canonical plan store, optimistic receipts and dependency-safe edits.""" +import hashlib +import os +import tempfile +import unittest +from pathlib import Path + +from task_plan import inspect_plan, update_task +from workflow import WorkflowError + +TEXT = """--- +feature: demo +status: applying +--- +# Keep this description +| ID | Task | Covers | Blocked By | Status | +|---|---|---|---|---| +| T-01 | First | AC-01 | — | pending | +| T-02 | Second | AC-02 | T-01 | pending | +""" + + +class TaskPlanTest(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.repo = Path(temporary.name).resolve() + self.file = self.repo / "docs/specs/active/demo/tasks.md" + self.file.parent.mkdir(parents=True) + self.file.write_text(TEXT) + + def receipt(self): + return hashlib.sha256(self.file.read_bytes()).hexdigest() + + def test_view_has_no_side_effect_and_returns_next_task(self): + before = sorted(self.repo.rglob("*")) + result = inspect_plan(self.repo, "demo") + self.assertEqual(result["next_task"], "T-01") + self.assertEqual(result["receipt_sha256"], self.receipt()) + self.assertEqual(sorted(self.repo.rglob("*")), before) + + def test_update_preserves_document_and_mode(self): + os.chmod(self.file, 0o640) + update_task(self.repo, "demo", "T-01", "in_progress", self.receipt()) + self.assertEqual(self.file.read_text(), TEXT.replace("— | pending", "— | in_progress")) + self.assertEqual(self.file.stat().st_mode & 0o777, 0o640) + update_task(self.repo, "demo", "T-01", "completed", self.receipt()) + self.assertEqual(inspect_plan(self.repo, "demo")["next_task"], "T-02") + + def test_stale_receipt_dependency_and_unknown_task_do_not_write(self): + for task, state, receipt in (("T-01", "completed", "0" * 64), + ("T-02", "in_progress", self.receipt()), + ("T-02", "completed", self.receipt()), + ("T-99", "completed", self.receipt())): + with self.subTest(task=task, state=state), self.assertRaises(WorkflowError): + update_task(self.repo, "demo", task, state, receipt) + self.assertEqual(self.file.read_text(), TEXT) + + def test_closed_or_mismatched_plan_is_not_mutated(self): + for text in (TEXT.replace("status: applying", "status: completed"), + TEXT.replace("feature: demo", "feature: foreign")): + self.file.write_text(text) + with self.assertRaises(WorkflowError): + update_task(self.repo, "demo", "T-01", "completed", self.receipt()) + self.assertEqual(self.file.read_text(), text) + + def test_parent_symlink_escape_is_rejected(self): + with tempfile.TemporaryDirectory() as other: + self.file.unlink() + self.file.parent.rmdir() + self.file.parent.symlink_to(other, target_is_directory=True) + Path(other, "tasks.md").write_text(TEXT) + with self.assertRaises(WorkflowError): + inspect_plan(self.repo, "demo") + + def test_escaped_pipes_reordered_columns_and_crlf_preserve_all_but_status(self): + for text in ( + TEXT.replace("First", r"Preserve A\|B"), + "---\nfeature: demo\nstatus: applying\n---\n| ID | Task | Status |\n|---|---|---|\n| T-01 | Preserve A\\|B | pending |\n", + "---\r\nfeature: demo\r\nstatus: applying\r\n---\r\n | Status | Task | ID |\r\n |---|---|---|\r\n | pending | Preserve A\\|B | T-01 |\r\n", + ): + with self.subTest(text=text): + self.file.write_bytes(text.encode()) + result = update_task(self.repo, "demo", "T-01", "in_progress", self.receipt()) + self.assertEqual(self.file.read_bytes(), text.replace("pending", "in_progress", 1).encode()) + self.assertEqual(result["tasks"][0]["status"], "in_progress") + self.assertIn("A|B", result["tasks"][0]["description"]) diff --git a/helixharness/scripts/tests/test_ut_artifacts.py b/helixharness/scripts/tests/test_ut_artifacts.py new file mode 100644 index 0000000..5c42aef --- /dev/null +++ b/helixharness/scripts/tests/test_ut_artifacts.py @@ -0,0 +1,189 @@ +from __future__ import annotations +import json +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch + +try: + import ut_artifacts as ut +except ModuleNotFoundError: + ut = None + +class UtArtifactsTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.repo = Path(self.tmp.name) / 'repo' + self.directory = self.repo / 'docs/specs/active/sample' + self.directory.mkdir(parents=True) + (self.repo/'README.md').write_text('Invalid percentages must be rejected.\n',encoding='utf-8') + (self.repo/'evidence.log').write_text('FAIL: expected rejection; returned -1\n',encoding='utf-8') + self.assertIsNotNone(ut, 'UT artifacts implementation is required') + def stage(self, name, text): + p=self.directory/(name+'.tmp');p.write_text(text,encoding='utf-8');return p + def observation(self, category='confirmed_defect', **kwargs): + d=dict(id='D1',classification=category,title='Percentage is not rejected',actual_behavior='Returns -1',severity='Low',basis='contract',normative_ref={'path':'README.md','quote':'Invalid percentages must be rejected.'},reproducer={'command':'synthetic test','expected':'rejection','actual':'returned -1','evidence_path':'evidence.log','evidence_quote':'FAIL: expected rejection; returned -1'}) + d.update(kwargs);return d + def findings(self, worker, observations): + src=self.stage(f'worker-{worker}-findings.json',json.dumps({'worker_id':worker,'class_name':'synthetic.Rules','observations':observations})) + return ut.publish_findings(self.repo,'sample',worker,src) + def test_supported_contract_violation_counts(self): + result=self.findings(1,[self.observation()]);self.assertEqual(result['counts']['confirmed_defect'],1) + self.assertIn('已证实缺陷', (self.directory/'worker-1-defects.md').read_text()) + def test_unsupported_expectations_are_preserved_as_risks(self): + obs=[self.observation(id=f'D{i}',title=title,normative_ref=None) for i,title in enumerate(('Unicode whitespace','Different messages','NPE instead of IAE','Different rounding','Javadoc'),1)] + result=self.findings(1,obs);self.assertEqual(result['counts']['confirmed_defect'],0);self.assertEqual(result['counts']['unconfirmed_risk'],5) + doc=json.loads((self.directory/'worker-1-findings.json').read_text());self.assertEqual(len(doc['observations']),5) + self.assertTrue(all(x['classification_reason'] for x in doc['observations'])) + def test_misquoted_or_outside_contract_cannot_confirm(self): + for ref in ({'path':'README.md','quote':'Must throw NPE'}, {'path':'../outside.md','quote':'x'}): + with self.subTest(ref=ref):self.assertEqual(self.findings(1,[self.observation(normative_ref=ref)])['counts']['confirmed_defect'],0) + def test_missing_or_identical_counterexample_cannot_confirm(self): + for value in (None, {'expected':'x','actual':'x'}, {'expected':'x','actual':'y','evidence_path':'evidence.log','evidence_quote':'not in the log'}): + with self.subTest(value=value):self.assertEqual(self.findings(1,[self.observation(reproducer=value)])['counts']['confirmed_defect'],0) + def test_optional_improvement_never_counts_as_defect(self): + r=self.findings(1,[self.observation('optional_improvement',normative_ref=None,reproducer=None)]);self.assertEqual(r['counts']['optional_improvement'],1);self.assertEqual(r['counts']['confirmed_defect'],0) + def test_mechanical_failure_requires_reproduced_evidence(self): + (self.repo/'Rules.java').write_text('return 1 / 0;') + (self.repo/'exception.log').write_text('java.lang.ArithmeticException: / by zero') + r=self.findings(1,[self.observation(basis='mechanical',mechanical_kind='inevitable_exception',observed_exception='ArithmeticException',code_ref={'path':'Rules.java','quote':'return 1 / 0;'},normative_ref=None,reproducer={'command':'synthetic runtime test','expected':'returns a result','actual':'ArithmeticException','evidence_path':'exception.log','evidence_quote':'java.lang.ArithmeticException: / by zero'})]) + self.assertEqual(r['counts']['confirmed_defect'],1) + r=self.findings(1,[self.observation(basis='mechanical',mechanical_kind='style',normative_ref=None)]) + self.assertEqual(r['counts']['confirmed_defect'],0) + def test_sanitized_project_name_can_supply_temp_evidence(self): + renamed=self.repo.parent/'My App';self.repo.rename(renamed);self.repo=renamed;self.directory=self.repo/'docs/specs/active/sample' + base=Path(self.tmp.name)/'os-temp';worker=base/'my-app/worker-1';worker.mkdir(parents=True) + log=worker/'evidence.log';log.write_text('FAIL: expected rejection; returned -1') + repro={'command':'test','expected':'rejection','actual':'returned -1','evidence_path':str(log.resolve()),'evidence_quote':'FAIL: expected rejection; returned -1'} + with patch('ut_artifacts.tempfile.gettempdir',return_value=str(base)): + self.assertEqual(self.findings(1,[self.observation(reproducer=repro)])['counts']['confirmed_defect'],1) + def test_symlink_worker_evidence_root_cannot_escape(self): + outside=Path(self.tmp.name)/'outside';outside.mkdir();(outside/'evidence.log').write_text('FAIL: expected rejection; returned -1') + base=Path(self.tmp.name)/'os-temp';project=base/self.repo.name;project.mkdir(parents=True) + (project/'worker-1').symlink_to(outside,target_is_directory=True) + repro={'command':'test','expected':'rejection','actual':'returned -1','evidence_path':str((outside/'evidence.log').resolve()),'evidence_quote':'FAIL: expected rejection; returned -1'} + with patch('ut_artifacts.tempfile.gettempdir',return_value=str(base)): + self.assertEqual(self.findings(1,[self.observation(reproducer=repro)])['counts']['confirmed_defect'],0) + def test_generated_classification_reports_cannot_be_overwritten_by_write(self): + for name in ('unittest-defects.md','worker-1-defects.md'): + with self.subTest(name=name),self.assertRaises(ValueError):ut.publish_state(self.repo,'sample',name,self.stage(name,'invented counts')) + def test_atomic_write_publishes_unicode_and_consumes_staging(self): + target=self.directory/'unittest-summary.md';target.write_text('old') + src=self.stage(target.name,'新的报告\n');ut.publish_state(self.repo,'sample',target.name,src) + self.assertEqual(target.read_text(),'新的报告\n');self.assertFalse(src.exists()) + def test_failed_replace_keeps_previous_file_and_staging(self): + target=self.directory/'unittest-session.md';target.write_text('previous');src=self.stage(target.name,'next') + with patch('atomic_files.os.replace',side_effect=OSError('synthetic failure')): + with self.assertRaises(OSError):ut.publish_state(self.repo,'sample',target.name,src) + self.assertEqual(target.read_text(),'previous');self.assertTrue(src.exists()) + self.assertEqual(sorted(p.name for p in self.directory.iterdir()),sorted([target.name,src.name])) + def test_rejects_path_traversal_arbitrary_source_and_symlink(self): + src=self.stage('unittest-results.md','safe') + for feature,name,source in (('../escape','unittest-results.md',src),('sample','spec.md',src),('sample','unittest-results.md',self.repo/'README.md')): + with self.subTest(feature=feature,name=name),self.assertRaises(ValueError):ut.publish_state(self.repo,feature,name,source) + outside=self.repo/'outside';outside.write_text('untouched');target=self.directory/'unittest-results.md';target.symlink_to(outside) + with self.assertRaises((ValueError,OSError)):ut.publish_state(self.repo,'sample',target.name,src) + self.assertEqual(outside.read_text(),'untouched') + def test_rejects_symlink_ancestor_before_reading_staging(self): + outside=Path(self.tmp.name)/'outside';outside.mkdir();(outside/'unittest-results.md.tmp').write_text('not authorized') + (self.repo/'docs/specs/active/alias').symlink_to(outside,target_is_directory=True) + with self.assertRaises(ValueError):ut.publish_state(self.repo,'alias','unittest-results.md',outside/'unittest-results.md.tmp') + def test_aggregation_uses_only_explicit_terminal_workers(self): + self.findings(1,[self.observation('optional_improvement')]);self.findings(2,[self.observation()]);self.findings(3,[self.observation()]) + result=ut.aggregate_findings(self.repo,'sample',[1,2]);self.assertEqual(result['counts']['confirmed_defect'],1);self.assertEqual(result['counts']['optional_improvement'],1) + self.assertEqual(result['worker_ids'],[1,2]);self.assertNotIn('worker-3', (self.directory/'unittest-defects.md').read_text()) + with self.assertRaises(ValueError):ut.aggregate_findings(self.repo,'sample',[4]) + def test_rejects_duplicate_observations_and_worker_mismatch(self): + with self.assertRaises(ValueError):self.findings(1,[self.observation(),self.observation()]) + src=self.stage('worker-1-findings.json',json.dumps({'worker_id':2,'class_name':'a','observations':[]})) + with self.assertRaises(ValueError):ut.publish_findings(self.repo,'sample',1,src) + def test_legacy_timeout_and_archived_workers_keep_unknown_totals(self): + for worker,status,prefix in ((1,'成功',''),(2,'超时终止',''),(3,'失败','archived-')): + result=self.directory/f'{prefix}worker-{worker}-result.md' + result.write_text(f'状态: {status}\nlegacy High defect: preserve this report\n') + defects=self.directory/f'{prefix}worker-{worker}-defects.md';defects.write_text('old detailed evidence') + before={p:p.read_bytes() for p in (result,defects)} + r=ut.aggregate_findings(self.repo,'sample',[worker]) + self.assertFalse(r['classification_complete']);self.assertIsNone(r['counts']['confirmed_defect']) + self.assertEqual(r['legacy_workers'][0]['status'],status) + self.assertIn(result.name,(self.directory/'unittest-defects.md').read_text()) + self.assertTrue(all(p.read_bytes()==v for p,v in before.items())) + def test_mixed_legacy_and_current_does_not_claim_zero(self): + self.findings(1,[self.observation()]) + (self.directory/'worker-2-result.md').write_text('状态: 超时终止\n') + r=ut.aggregate_findings(self.repo,'sample',[1,2]) + self.assertFalse(r['classification_complete']);self.assertIsNone(r['counts']['confirmed_defect']) + self.assertEqual(r['known_counts']['confirmed_defect'],1) + self.assertIn('未核验',(self.directory/'unittest-defects.md').read_text()) + def test_published_findings_survive_evidence_cleanup_but_corruption_blocks(self): + self.findings(1,[self.observation()]);(self.repo/'evidence.log').unlink() + r=ut.aggregate_findings(self.repo,'sample',[1]);self.assertTrue(r['classification_complete']) + self.assertEqual(r['counts']['confirmed_defect'],1) + file=self.directory/'worker-1-findings.json';doc=json.loads(file.read_text());doc['counts']['confirmed_defect']=99;file.write_text(json.dumps(doc)) + with self.assertRaises(ValueError):ut.aggregate_findings(self.repo,'sample',[1]) + def test_class_cast_and_non_jvm_runtime_failures_remain_confirmed_high(self): + for suffix,exception in (('.java','ClassCastException'),('.py','ZeroDivisionError'),('.ts','RangeError'),('.js','TypeError'),('.go','panic: runtime error')): + with self.subTest(suffix=suffix): + name='Rules'+suffix;(self.repo/name).write_text('synthetic failing expression') + (self.repo/'exception.log').write_text(exception) + obs=self.observation(basis='mechanical',severity='High',mechanical_kind='inevitable_exception',observed_exception=exception,normative_ref=None,code_ref={'path':name,'quote':'synthetic failing expression'},reproducer={'command':'runtime reproducer','expected':'returns safely','actual':exception,'evidence_path':'exception.log','evidence_quote':exception}) + self.assertEqual(self.findings(1,[obs])['counts']['confirmed_defect'],1) + self.assertEqual(json.loads((self.directory/'worker-1-findings.json').read_text())['observations'][0]['severity'],'High') + def test_other_reproduced_mechanical_failures_and_invalid_marker(self): + (self.repo/'Rules.java').write_text('synthetic failing expression') + for kind in ('nontermination','data_corruption','control_flow_failure','security_violation','misleading_success'): + self.assertEqual(self.findings(1,[self.observation(basis='mechanical',mechanical_kind=kind,code_ref={'path':'Rules.java','quote':'synthetic failing expression'})])['counts']['confirmed_defect'],1) + for marker in ([],None,''): + self.assertEqual(self.findings(1,[self.observation(basis='mechanical',mechanical_kind='inevitable_exception',observed_exception=marker)])['counts']['confirmed_defect'],0) + doc=json.loads((self.directory/'worker-1-findings.json').read_text()) + self.assertEqual(doc['observations'][0]['proposed_severity'],'Low') + def test_configuration_is_not_a_mechanical_code_reference(self): + (self.repo/'settings.json').write_text('synthetic setting') + self.assertEqual(self.findings(1,[self.observation(basis='mechanical',mechanical_kind='data_corruption',code_ref={'path':'settings.json','quote':'synthetic setting'})])['counts']['confirmed_defect'],0) + def test_existing_posix_modes_survive_all_publication_paths(self): + import stat + for mode in (0o600,0o640,0o750): + target=self.directory/'unittest-summary.md';target.write_text('old');target.chmod(mode) + ut.publish_state(self.repo,'sample',target.name,self.stage(target.name,'new')) + self.assertEqual(stat.S_IMODE(target.stat().st_mode),mode) + self.findings(1,[self.observation()]) + for name in ('worker-1-findings.json','worker-1-defects.md'):(self.directory/name).chmod(0o600) + self.findings(1,[self.observation()]) + for name in ('worker-1-findings.json','worker-1-defects.md'):self.assertEqual(stat.S_IMODE((self.directory/name).stat().st_mode),0o600) + def test_host_worker_contracts_allow_generated_json_and_staging(self): + plugin=Path(__file__).resolve().parents[2] + for host in ('codex','cursor','opencode'): + text=(plugin/f'hosts/{host}/ut.md').read_text() + self.assertIn('findings',text);self.assertIn('.tmp',text) + def test_v1_snapshot_is_unverified_and_corrupt_json_cannot_fallback(self): + result=self.directory/'worker-1-result.md';result.write_text('状态: 成功\n') + findings=self.directory/'worker-1-findings.json' + findings.write_text(json.dumps({'schema_version':1,'worker_id':1,'class_name':'Rules','observations':[],'counts':{k:0 for k in ut.KINDS}})) + self.assertFalse(ut.aggregate_findings(self.repo,'sample',[1])['classification_complete']) + for text in (json.dumps({'schema_version':True,'worker_id':1,'observations':[]}),json.dumps({'schema_version':1,'worker_id':1,'class_name':'Rules','observations':[None],'counts':{'confirmed_defect':999}}),'{broken',json.dumps({'schema_version':2,'worker_id':1}),json.dumps({'schema_version':1,'worker_id':2,'observations':[]})): + findings.write_text(text) + with self.assertRaises(ValueError):ut.aggregate_findings(self.repo,'sample',[1]) + def test_archived_valid_snapshot_keeps_counts_after_cleanup(self): + self.findings(1,[self.observation()]);(self.repo/'evidence.log').unlink() + for suffix in ('findings.json','defects.md'): + file=self.directory/f'worker-1-{suffix}';file.rename(self.directory/('archived-'+file.name)) + self.assertEqual(ut.aggregate_findings(self.repo,'sample',[1])['counts']['confirmed_defect'],1) + def test_replace_failure_preserves_private_mode_and_new_file_default(self): + import stat + target=self.directory/'unittest-session.md';target.write_text('private');target.chmod(0o600) + with patch('atomic_files.os.replace',side_effect=OSError('synthetic failure')): + with self.assertRaises(OSError):ut.publish_state(self.repo,'sample',target.name,self.stage(target.name,'replacement')) + self.assertEqual(target.read_text(),'private');self.assertEqual(stat.S_IMODE(target.stat().st_mode),0o600) + name='unittest-summary.md';ut.publish_state(self.repo,'sample',name,self.stage(name,'new')) + self.assertEqual(stat.S_IMODE((self.directory/name).stat().st_mode),0o644) + def test_active_timeout_never_inherits_archived_worker_generation(self): + self.findings(1,[]) + for suffix in ('findings.json','defects.md'): + p=self.directory/f'worker-1-{suffix}';p.rename(self.directory/('archived-'+p.name)) + (self.directory/'archived-worker-1-result.md').write_text('状态: 成功\nold class') + current=self.directory/'worker-1-result.md';current.write_text('状态: 超时终止\nnew class') + r=ut.aggregate_findings(self.repo,'sample',[1]) + self.assertFalse(r['classification_complete']);self.assertIsNone(r['counts']['confirmed_defect']) + self.assertEqual(r['legacy_workers'][0]['paths'],['worker-1-result.md']) +if __name__=='__main__':unittest.main() diff --git a/helixharness/scripts/tests/test_ut_precompile.py b/helixharness/scripts/tests/test_ut_precompile.py new file mode 100644 index 0000000..78660fa --- /dev/null +++ b/helixharness/scripts/tests/test_ut_precompile.py @@ -0,0 +1,250 @@ +"""UT precompile freshness guards, using isolated Java sources and real wrappers.""" +from __future__ import annotations + +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +try: + import ut_precompile +except ModuleNotFoundError: + ut_precompile = None + +PLUGIN_ROOT = Path(__file__).resolve().parents[2] + + +@unittest.skipIf(os.name == "nt", "Synthetic executable wrappers use POSIX shebangs") +class UtPrecompileTest(unittest.TestCase): + def setUp(self): + self.assertIsNotNone(ut_precompile, "The UT precompile gate is required") + self.javac = shutil.which("javac") + if self.javac is None: + self.skipTest("Java compiler is required for real-source compilation regressions") + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.repo = Path(temporary.name).resolve() / "synthetic-project" + self.repo.mkdir() + self.source = self.repo / "src/main/java/Value.java" + self.source.parent.mkdir(parents=True) + self.source.write_text("public class Value { public static int value() { return 1; } }\n") + self.test_file = self.repo / "src/test/java/ExistingTest.java" + self.test_file.parent.mkdir(parents=True) + self.test_file.write_text("// Synthetic existing test; preserve these exact bytes.\n") + + def project(self, tool, *, nested=False, language="java"): + build_file = self.repo / ("build.gradle" if tool == "gradle" else "pom.xml") + build_file.write_text("// synthetic build marker\n" if tool == "gradle" else "\n") + output = self.repo / ("module" if nested else "") / ( + f"build/classes/{language}/main" if tool == "gradle" else "target/classes") + wrapper = self.repo / ("gradlew" if tool == "gradle" else "mvnw") + wrapper.write_text( + f"#!{sys.executable}\n" + "from pathlib import Path\nimport json, subprocess, sys\n" + "root = Path.cwd()\n" + "with (root / 'build-invocations.jsonl').open('a') as log:\n" + " log.write(json.dumps(sys.argv[1:]) + '\\n')\n" + f"output = Path({str(output)!r})\n" + "output.mkdir(parents=True, exist_ok=True)\n" + "sources = sorted(str(p) for p in (root / 'src/main/java').rglob('*.java'))\n" + f"result = subprocess.run([{self.javac!r}, '-d', str(output), *sources])\n" + "raise SystemExit(result.returncode)\n" + ) + wrapper.chmod(0o755) + return wrapper, output + + def test_changed_source_and_new_package_compile_again_in_both_build_tools(self): + for tool in ("gradle", "maven"): + with self.subTest(tool=tool): + for marker in ("build.gradle", "pom.xml"): + (self.repo / marker).unlink(missing_ok=True) + wrapper, classes = self.project(tool) + self.assertTrue(ut_precompile.precompile(self.repo)["ready"]) + old_class = (classes / "Value.class").read_bytes() + self.source.write_text("public class Value { public static int value() { return 2; } }\n") + added = self.source.parent / "newpackage/Added.java" + added.parent.mkdir(exist_ok=True) + added.write_text("package newpackage; public class Added {}\n") + before = {p: p.read_bytes() for p in (self.source, added, self.test_file)} + + result = ut_precompile.precompile(self.repo) + + self.assertEqual("compile_ready", result["status"]) + self.assertTrue(result["ready"]) + self.assertFalse(result["tests_run"]) + self.assertEqual(str(wrapper), result["command"][0]) + self.assertIn("classes" if tool == "gradle" else "compile", result["command"]) + self.assertNotIn("clean", result["command"]) + self.assertNotEqual(old_class, (classes / "Value.class").read_bytes()) + self.assertTrue((classes / "newpackage/Added.class").is_file()) + self.assertTrue(all(p.read_bytes() == content for p, content in before.items())) + self.source.write_text("public class Value { public static int value() { return 1; } }\n") + + def test_failed_compile_is_not_ready_even_when_old_class_directory_exists(self): + for tool in ("gradle", "maven"): + with self.subTest(tool=tool): + for marker in ("build.gradle", "pom.xml"): + (self.repo / marker).unlink(missing_ok=True) + self.source.write_text("public class Value {}\n") + _, classes = self.project(tool) + self.assertTrue(ut_precompile.precompile(self.repo)["ready"]) + self.source.write_text("public class Value { invalid Java source }\n") + + result = ut_precompile.precompile(self.repo) + + self.assertTrue(classes.is_dir()) + self.assertEqual("blocked", result["status"]) + self.assertFalse(result["ready"]) + self.assertEqual("precompile_failed", result["reason"]) + self.assertNotEqual(0, result["exit_code"]) + self.assertTrue(result["stdout"] or result["stderr"]) + self.assertFalse(result["tests_run"]) + self.assertIn("preserve these exact bytes", self.test_file.read_text()) + + def test_zero_exit_without_expected_class_output_is_not_ready(self): + wrapper, _ = self.project("gradle") + wrapper.write_text(f"#!{sys.executable}\nraise SystemExit(0)\n") + result = ut_precompile.precompile(self.repo) + self.assertEqual(0, result["exit_code"]) + self.assertFalse(result["ready"]) + self.assertEqual("class_output_missing", result["reason"]) + + def test_multimodule_expected_output_is_detected(self): + for tool in ("gradle", "maven"): + with self.subTest(tool=tool): + for marker in ("build.gradle", "pom.xml"): + (self.repo / marker).unlink(missing_ok=True) + _, classes = self.project(tool, nested=True) + result = ut_precompile.precompile(self.repo) + self.assertFalse(result["ready"], "Nested modules require verified explicit directories") + result = ut_precompile.precompile(self.repo, class_directories=[classes]) + self.assertTrue(result["ready"], result) + self.assertIn(str(classes), result["class_directories"]) + + def test_unrelated_nested_stale_output_cannot_grant_readiness(self): + for tool in ("gradle", "maven"): + with self.subTest(tool=tool): + for marker in ("build.gradle", "pom.xml"): + (self.repo / marker).unlink(missing_ok=True) + wrapper, _ = self.project(tool) + wrapper.write_text(f"#!{sys.executable}\nraise SystemExit(0)\n") + stale = self.repo / "examples/archived" / ( + "build/classes/java/main" if tool == "gradle" else "target/classes") + stale.mkdir(parents=True) + (stale / "Old.class").write_bytes(b"synthetic stale output") + + result = ut_precompile.precompile(self.repo) + + self.assertEqual(0, result["exit_code"]) + self.assertFalse(result["ready"], result) + self.assertEqual("class_output_missing", result["reason"]) + self.assertEqual([], result["class_directories"]) + + def test_explicit_outputs_all_must_exist_and_stay_under_root_without_symlinks(self): + self.project("gradle") + external = self.repo.parent / "outside-classes" + external.mkdir() + (self.repo / "alias").symlink_to(external, target_is_directory=True) + for requested in ([external], [self.repo / "alias"], [Path("../outside-classes")], + [Path("build/classes/java/main"), Path("missing-module/classes")]): + with self.subTest(requested=requested): + result = ut_precompile.precompile(self.repo, class_directories=requested) + self.assertFalse(result["ready"], result) + self.assertIn(result["reason"], ("class_directory_invalid", "class_output_missing")) + + def test_cli_explicit_verified_module_output_is_supported(self): + self.project("maven", nested=True) + result = subprocess.run([ + sys.executable, str(PLUGIN_ROOT / "scripts/ut_precompile.py"), + "--repo-root", str(self.repo), "--class-directory", "module/target/classes", + ], text=True, capture_output=True) + self.assertEqual(0, result.returncode, result.stdout + result.stderr) + payload = json.loads(result.stdout) + self.assertTrue(payload["ready"]) + self.assertEqual([str(self.repo / "module/target/classes")], payload["class_directories"]) + + def test_gradle_kotlin_and_groovy_only_output_paths_are_preserved(self): + # Path-discovery contract only; the wrapper still executes synthetic javac. + for language in ("kotlin", "groovy"): + with self.subTest(language=language): + _, classes = self.project("gradle", language=language) + result = ut_precompile.precompile(self.repo) + self.assertTrue(result["ready"], result) + self.assertIn(str(classes), result["class_directories"]) + + def test_gradle_mixed_jvm_output_paths_are_all_passed_to_workers(self): + _, java = self.project("gradle") + other_outputs = [self.repo / f"build/classes/{language}/main" for language in ("kotlin", "groovy")] + for directory in other_outputs: + directory.mkdir(parents=True) + result = ut_precompile.precompile(self.repo) + self.assertTrue(result["ready"]) + self.assertEqual(sorted(str(p) for p in (java, *other_outputs)), result["class_directories"]) + + def test_system_tool_is_used_only_without_project_wrapper(self): + wrapper, _ = self.project("gradle") + binaries = self.repo / "synthetic-bin" + binaries.mkdir() + system_tool = binaries / "gradle" + wrapper.rename(system_tool) + with patch.dict(os.environ, {"PATH": str(binaries)}): + result = ut_precompile.precompile(self.repo) + self.assertTrue(result["ready"]) + self.assertEqual(str(system_tool), result["command"][0]) + + def test_relative_path_system_tool_keeps_discovered_location_when_cwd_changes(self): + wrapper, _ = self.project("gradle") + binaries = self.repo / "synthetic-bin" + binaries.mkdir() + system_tool = binaries / "gradle" + wrapper.rename(system_tool) + previous_cwd = Path.cwd() + try: + os.chdir(self.repo.parent) + with patch.dict(os.environ, {"PATH": str(binaries.relative_to(self.repo.parent))}): + result = ut_precompile.precompile(self.repo) + finally: + os.chdir(previous_cwd) + self.assertTrue(result["ready"], result) + self.assertEqual(str(system_tool), result["command"][0]) + + def test_cli_returns_nonzero_and_diagnostics_before_dispatch_on_compile_failure(self): + self.project("maven") + self.source.write_text("public class Value { invalid Java source }\n") + result = subprocess.run([ + sys.executable, str(PLUGIN_ROOT / "scripts/ut_precompile.py"), + "--repo-root", str(self.repo), + ], text=True, capture_output=True) + self.assertNotEqual(0, result.returncode) + payload = json.loads(result.stdout) + self.assertFalse(payload["ready"]) + self.assertEqual("precompile_failed", payload["reason"]) + self.assertTrue(payload["stderr"]) + + def test_unknown_or_ambiguous_project_is_blocked_without_running_builds(self): + self.assertFalse(ut_precompile.precompile(self.repo)["ready"]) + self.project("gradle") + (self.repo / "pom.xml").write_text("\n") + self.assertFalse(ut_precompile.precompile(self.repo)["ready"]) + self.assertFalse((self.repo / "build-invocations.jsonl").exists()) + + +class UtPrecompileCommandContractTest(unittest.TestCase): + def test_every_mode_requires_current_precompile_gate_before_workers(self): + text = (PLUGIN_ROOT / "commands/ut.md").read_text() + section = text.split("#### 4.1.6", 1)[1].split("### 4.2", 1)[0] + self.assertIn("scripts/ut_precompile.py", section) + self.assertIn("compile_ready", section) + self.assertIn("ready=false", section) + self.assertNotIn("存在则跳过", section) + self.assertIn("不得启动", section) + self.assertIn("不是测试通过", section) + + +if __name__ == "__main__": + unittest.main() diff --git a/helixharness/scripts/tests/test_workflow.py b/helixharness/scripts/tests/test_workflow.py index d93deee..32ce965 100644 --- a/helixharness/scripts/tests/test_workflow.py +++ b/helixharness/scripts/tests/test_workflow.py @@ -42,7 +42,8 @@ def setUp(self) -> None: check=True, ) subprocess.run( - ["git", "-C", str(self.repo), "commit", "--allow-empty", "-qm", "initial"], + ["git", "-C", str(self.repo), "-c", "core.hooksPath=/dev/null", + "commit", "--allow-empty", "-qm", "initial"], check=True, ) self.feature = "checkout" @@ -1113,6 +1114,92 @@ def test_begin_repair_is_idempotent_for_the_same_repair_key(self) -> None: self.assertTrue(second["resumed"]) self.assertEqual(first["repair_revision"], second["repair_revision"]) + def test_bug_fix_fresh_process_resume_preserves_baseline_and_invalidates_old_approve(self) -> None: + self.write_spec(status="ready") + self.write_tasks(status="ready", rows="| T-01 | First | AC-01 | — | pending |") + preexisting = self.repo / "user-notes.txt" + preexisting.write_text("Synthetic user-owned preexisting work.\n") + self.run_cli("bind-apply", "--feature", self.feature) + spec_path = self.feature_dir / "spec.md" + tasks_path = self.feature_dir / "tasks.md" + spec_path.write_text(spec_path.read_text().replace("status: ready", "status: implemented")) + tasks_path.write_text(tasks_path.read_text().replace("status: ready", "status: completed") + .replace("| pending |", "| completed |")) + self.write_evidence() + evidence = self.feature_dir / "verify-report.md" + original_evidence = evidence.read_bytes() + state_dir = self.repo / ".helixharness/workflow" / self.feature + baseline_before = json.loads((state_dir / "apply-state.json").read_text()) + old_review = (state_dir / "review-state.json").read_bytes() + self.assertTrue(baseline_before["apply_baseline_manifest"]) + begin_args = ( + "begin-repair", "--feature", self.feature, "--repair-key", "a" * 64, + "--source-sha256", "b" * 64, "--repair-kind", "implementation_regression", + "--expected-spec-receipt", workflow.spec_receipt(spec_path.read_text()), + "--expected-tasks-receipt", workflow.artifact_receipt(tasks_path.read_text()), + ) + begun = json.loads(self.run_cli(*begin_args).stdout) + resumed = json.loads(self.run_cli(*begin_args).stdout) + self.assertFalse(begun["resumed"]) + self.assertTrue(resumed["resumed"]) + self.assertEqual(1, resumed["repair_revision"]) + editing = json.loads(self.run_cli("repair-preflight", "--feature", self.feature).stdout) + self.assertEqual("in_progress", editing["repair_state"]["status"]) + spec_path.write_text( + spec_path.read_text().replace("status: implemented\n", "status: implemented\nrepair_revision: 1\n") + + "\n## Repair Revisions\n\n" + + "| Revision | Repair Key | Kind | Source SHA-256 | Summary |\n" + + "|---|---|---|---|---|\n" + + f"| R-01 | {'a' * 64} | implementation_regression | {'b' * 64} | Repair original behavior |\n" + ) + tasks_path.write_text( + tasks_path.read_text().replace("| ID | Task |", "| ID | Revision | Task |") + .replace("|---|---|---|---|---|", "|---|---|---|---|---|---|") + .replace("| T-01 | First |", "| T-01 | R-00 | First |") + + "| T-02 | R-01 | Repair behavior | AC-01 | T-01 | pending |\n" + ) + facts = json.loads(self.run_cli( + "validate-tasks", "--feature", self.feature, "--stage", "propose", "--repair-key", "a" * 64 + ).stdout) + rebind_args = ( + "repair-rebind", "--feature", self.feature, "--repair-key", "a" * 64, + "--expected-spec-receipt", facts["spec_receipt_sha256"], + "--expected-tasks-receipt", facts["tasks_receipt_sha256"], + ) + first_rebind = json.loads(self.run_cli(*rebind_args).stdout) + before_resume = {p: p.read_bytes() for p in self.repo.rglob("*") if p.is_file()} + for _ in range(2): + # Each Router/preflight/rebind call runs in a new Python process. + route = subprocess.run([ + sys.executable, str(PLUGIN_ROOT / "scripts/workflow_router.py"), + "--repo-root", str(self.repo), "route", "--command", "bug-fix", + "--arguments=" + self.feature, "--arguments-mode", "auto", + ], check=True, capture_output=True, text=True) + routed = json.loads(route.stdout) + self.assertEqual("repair_feature", routed["action"]) + self.assertEqual(self.feature, routed["workflow_arguments"]) + bound = json.loads(self.run_cli("repair-preflight", "--feature", self.feature).stdout) + self.assertEqual("bound", bound["repair_state"]["status"]) + self.assertEqual(1, bound["repair_state"]["repair_revision"]) + self.assertEqual("a" * 64, bound["repair_state"]["repair_key"]) + self.assertEqual(first_rebind, json.loads(self.run_cli(*rebind_args).stdout)) + self.assertEqual(before_resume, {p: p.read_bytes() for p in self.repo.rglob("*") if p.is_file()}) + baseline_after = json.loads((state_dir / "apply-state.json").read_text()) + for key in ("apply_baseline_head", "apply_baseline_manifest", "apply_baseline_sha256"): + self.assertEqual(baseline_before[key], baseline_after[key], key) + self.assertFalse((state_dir / "review-state.json").exists()) + self.assertEqual(old_review, (state_dir / "review-state.r1.invalidated.json").read_bytes()) + self.assertEqual(original_evidence, evidence.read_bytes()) + self.assertEqual(1, len(workflow.repair_rows(spec_path.read_text()))) + self.assertEqual(["completed", "pending"], [row["status"] for row in workflow.task_rows(tasks_path.read_text())]) + self.assertEqual("T-02", json.loads(self.validate("apply").stdout)["next_task"]) + spec_path.write_text(spec_path.read_text().replace("status: applying", "status: implemented")) + tasks_path.write_text(tasks_path.read_text().replace("status: applying", "status: completed") + .replace("| pending |", "| completed |")) + stale_approve = self.run_cli("archive-preflight", "--feature", self.feature, check=False) + self.assertNotEqual(0, stale_approve.returncode) + self.assertIn("invalid spec_receipt_sha256", stale_approve.stderr) + def test_repair_revision_is_a_critical_frontmatter_field(self) -> None: self.write_spec(status="applying") self.write_tasks(status="applying") diff --git a/helixharness/scripts/tests/test_workspace.py b/helixharness/scripts/tests/test_workspace.py index c16402b..89e211f 100644 --- a/helixharness/scripts/tests/test_workspace.py +++ b/helixharness/scripts/tests/test_workspace.py @@ -3,6 +3,7 @@ import json import re import subprocess +import sys import tempfile import unittest from pathlib import Path @@ -969,6 +970,160 @@ def test_archive_recovery_rejects_completed_repo_from_an_old_workspace_contract( self.workspace, "cross-repo" ) + def test_apply_recovery_skips_verified_implemented_repo(self) -> None: + self._write_overview(status="applying") + self._make_repo_archive_ready("api") + self._write_repo_feature("web") + + result = workspace.workspace_execution_plan(self.workspace, "cross-repo", "apply") + + self.assertEqual(["web"], [job["repo"] for job in result["jobs"]]) + self.assertEqual([["web"]], result["batches"]) + self.assertEqual("ready", result["repo_results"]["api"]["archive_state"]) + self.assertEqual(["api"], result["jobs"][0]["depends_on"]) + + def test_apply_recovery_dispatches_invalid_evidence_for_single_apply_repair(self) -> None: + self._write_overview(status="applying") + self._make_repo_archive_ready("api") + self._write_repo_feature("web") + evidence = self.workspace / "api/docs/specs/active/cross-repo/verify-report.md" + evidence.write_text(evidence.read_text().replace("spec_verdict: APPROVE", "spec_verdict: REJECT")) + + result = workspace.workspace_execution_plan(self.workspace, "cross-repo", "apply") + self.assertEqual(["api", "web"], [job["repo"] for job in result["jobs"]]) + self.assertEqual("workflows/single/apply.md", result["jobs"][0]["expected_workflow"]) + + def test_apply_recovery_dispatches_missing_evidence_without_resetting_tasks(self) -> None: + self._write_overview(status="applying") + self._make_repo_archive_ready("api") + self._write_repo_feature("web") + directory = self.workspace / "api/docs/specs/active/cross-repo" + (directory / "verify-report.md").unlink() + before = (directory / "tasks.md").read_bytes() + + result = workspace.workspace_execution_plan(self.workspace, "cross-repo", "apply") + + self.assertEqual(["api", "web"], [job["repo"] for job in result["jobs"]]) + self.assertEqual(before, (directory / "tasks.md").read_bytes()) + self.assertEqual(None, result["repo_results"]["api"]["next_task"]) + + def test_apply_recovery_cannot_rebuild_missing_original_baseline(self) -> None: + self._write_overview(status="applying") + self._make_repo_archive_ready("api") + self._write_repo_feature("web") + state = self.workspace / "api/.helixharness/workflow/cross-repo/apply-state.json" + state.unlink() + + with self.assertRaisesRegex(workspace.WorkspaceError, "Apply state"): + workspace.workspace_execution_plan(self.workspace, "cross-repo", "apply") + self.assertFalse(state.exists()) + + def test_archive_recovery_skips_validated_completed_repo(self) -> None: + self._write_overview(status="implemented") + self._make_repo_archive_ready("api") + self._move_repo_to_completed("web") + + result = workspace.workspace_execution_plan(self.workspace, "cross-repo", "archive") + + self.assertEqual(["api"], [job["repo"] for job in result["jobs"]]) + self.assertEqual([["api"]], result["batches"]) + self.assertEqual("completed", result["repo_results"]["web"]["archive_state"]) + + def test_archive_recovery_with_all_children_completed_has_no_jobs(self) -> None: + self._write_overview(status="implemented") + self._move_repo_to_completed("api") + self._move_repo_to_completed("web") + + result = workspace.workspace_archive_preflight(self.workspace, "cross-repo") + + self.assertTrue(result["ready"]) + self.assertEqual([], result["jobs"]) + self.assertEqual([], result["batches"]) + + def _plan_in_fresh_process(self, command: str) -> dict: + result = subprocess.run([ + sys.executable, str(PLUGIN_ROOT / "scripts/workspace.py"), + "--workspace-root", str(self.workspace), "workspace-plan", + "--feature", "cross-repo", "--command", command, + ], check=True, capture_output=True, text=True) + return json.loads(result.stdout) + + def test_new_process_recovers_only_pending_work_without_rewriting_state(self) -> None: + self._write_overview(status="applying") + self._make_repo_archive_ready("api") + self._make_repo_archive_ready("web") + spec = self.workspace / "web/docs/specs/active/cross-repo/spec.md" + spec.write_text(spec.read_text().replace("status: implemented", "status: applying")) + tasks = spec.with_name("tasks.md") + original_tasks = tasks.read_text().replace("status: completed", "status: applying") + + for unfinished_status in ("pending", "in_progress"): + with self.subTest(unfinished_status=unfinished_status): + tasks.write_text(original_tasks + f"| T-02 | Resume local slice | {unfinished_status} |\n") + before = {str(p.relative_to(self.workspace)): p.read_bytes() + for p in self.workspace.rglob("*") if p.is_file()} + first = self._plan_in_fresh_process("apply") + second = self._plan_in_fresh_process("apply") + + self.assertEqual(first, second) + self.assertEqual(["web"], [job["repo"] for job in second["jobs"]]) + self.assertEqual([["web"]], second["batches"]) + self.assertEqual("T-02", second["repo_results"]["web"]["next_task"]) + self.assertEqual(["T-02"] if unfinished_status == "in_progress" else [], + second["repo_results"]["web"]["in_progress_tasks"]) + self.assertEqual(before, {str(p.relative_to(self.workspace)): p.read_bytes() + for p in self.workspace.rglob("*") if p.is_file()}) + self.assertEqual(["completed", unfinished_status], + [row["status"] for row in workflow.task_rows(tasks.read_text())]) + serialized = json.dumps(second) + for native_field in ("child_id", "session_id", "agent_id", "handle"): + self.assertNotIn(f'"{native_field}"', serialized) + + def test_read_repo_replanning_preserves_business_files_and_local_artifacts(self) -> None: + self._write_overview() + overview = self.workspace / "docs/specs/active/cross-repo/spec.md" + overview.write_text(overview.read_text().replace("| web | write |", "| web | read |")) + self._write_repo_feature("api") + self._write_repo_feature("web") + business_file = self.workspace / "web/consumer.py" + business_file.write_text("# Synthetic existing consumer\nVALUE = 1\n") + before = {str(p.relative_to(self.workspace)): p.read_bytes() + for p in self.workspace.rglob("*") if p.is_file()} + + plan = self._plan_in_fresh_process("apply") + + read_job = next(job for job in plan["jobs"] if job["repo"] == "web") + self.assertEqual("read", read_job["mode"]) + self.assertEqual(before, {str(p.relative_to(self.workspace)): p.read_bytes() + for p in self.workspace.rglob("*") if p.is_file()}) + + def test_read_repo_recovery_dispatches_drift_for_single_apply_review(self) -> None: + self._write_overview(status="applying") + overview = self.workspace / "docs/specs/active/cross-repo/spec.md" + overview.write_text(overview.read_text().replace("| web | write |", "| web | read |")) + self._make_repo_archive_ready("api") + self._make_repo_archive_ready("web") + business_file = self.workspace / "web/consumer.py" + business_file.write_text("# Synthetic unexpected business change\nVALUE = 2\n") + before = business_file.read_bytes() + + result = workspace.workspace_execution_plan(self.workspace, "cross-repo", "apply") + + self.assertEqual(["web"], [job["repo"] for job in result["jobs"]]) + self.assertEqual("read", result["jobs"][0]["mode"]) + self.assertEqual("workflows/single/apply.md", result["jobs"][0]["expected_workflow"]) + self.assertEqual(before, business_file.read_bytes()) + + def test_propose_recovery_removes_skipped_repos_from_batches(self) -> None: + self._write_overview() + self._write_repo_feature("api") + + plan = self._plan_in_fresh_process("propose") + + self.assertEqual(["web"], [job["repo"] for job in plan["jobs"]]) + self.assertEqual([["web"]], plan["batches"]) + self.assertIn("api", plan["repo_results"]) + if __name__ == "__main__": unittest.main() diff --git a/helixharness/scripts/update_hosts/cursor.py b/helixharness/scripts/update_hosts/cursor.py index 1350cdb..b5740ef 100644 --- a/helixharness/scripts/update_hosts/cursor.py +++ b/helixharness/scripts/update_hosts/cursor.py @@ -34,7 +34,10 @@ RECEIPT_KEYS = {"schema_version", "install_id", "registration_sha256", "version", "commit", "tree_sha256"} DISTRIBUTION_DIRS = {".claude-plugin", ".codex-plugin", ".cursor-plugin", "agents", "commands", "hosts", "opencode", "reference", "scripts", "skills", "templates", "workflows"} DISTRIBUTION_FILES = {"AGENTS.md", "CLAUDE.md", "LICENSE", "NOTICE", "PLUGIN_USAGE.md", "README.md", "README.zh-CN.md", "SKILL.md", "THIRD_PARTY_NOTICES.md", ".gitignore", "package.json"} -OPENCODE_RUNTIME_FILES = {"opencode/index.ts", "opencode/core.ts"} +OPENCODE_RUNTIME_FILES = { + "opencode/index.ts", "opencode/core.ts", + "opencode/project-checks.ts", "opencode/ut-state.ts", +} EXCLUDED_PARTS = {".git", ".env", ".cursor", ".claude", ".codex", ".agents", ".aws", "output", "temp", "node_modules", "__pycache__", ".pytest_cache", ".venv", "venv"} MAX_ARCHIVE_BYTES = 256 * 1024 * 1024 MAX_FILE_BYTES = 32 * 1024 * 1024 diff --git a/helixharness/scripts/update_hosts/opencode.py b/helixharness/scripts/update_hosts/opencode.py index f46359c..6218b29 100644 --- a/helixharness/scripts/update_hosts/opencode.py +++ b/helixharness/scripts/update_hosts/opencode.py @@ -1,15 +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. -""" +"""OpenCode source-checkout updates, pinned to the exact consented Git commit.""" from __future__ import annotations +import json +import os +import re +import tempfile +import uuid +from contextlib import contextmanager +from pathlib import Path from typing import Any +from .base import (MARKETPLACE, PLUGIN_ID, BoundedCommandRunner, InstallStep, + UpdateHostAdapter, UpdateHostError) + def detect_host(environment: Any) -> int | None: """Return a confidence score only for explicit OpenCode runtime markers.""" @@ -17,3 +21,180 @@ def detect_host(environment: Any) -> int | None: if environment.get("OPENCODE_SESSION_ID"): return 100 return 80 if environment.get("OPENCODE") else None + + +def plugin_version(plugin_root: Path) -> str: + try: + if (plugin_root / "package.json").is_symlink(): + raise ValueError() + package = json.loads((plugin_root / "package.json").read_text(encoding="utf-8")) + version = package.get("version") + if (package.get("name") != "helixharness-opencode" or package.get("exports", {}).get(".") != "./opencode/index.ts" or + not isinstance(version, str) or not re.fullmatch(r"\d+\.\d+\.\d+", version)): + raise ValueError() + return version + except (OSError, ValueError, AttributeError): + raise UpdateHostError("OpenCode package version is unavailable") from None + + +class OpenCodeUpdateAdapter(UpdateHostAdapter): + """Only clean, attached checkouts with an explicit upstream can be updated. + + Package-manager caches and detached pins are never guessed or rewritten. + Checks fetch an isolated ref and inspect a disposable clone; installation + performs one hook-free fast-forward to the commit in the authorization. + """ + host_id = "opencode" + supported_scopes = frozenset({"checkout"}) + manifest_directory = ".claude-plugin" + marketplace_manifest_directory = ".claude-plugin" + + def __init__(self, normalize_version, read_json, *, home: Path | None = None): + self._normalize_version = normalize_version + self._read_json = read_json + self._home = home or Path(os.environ.get("HELIXHARNESS_OPENCODE_HOME") or + Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local/state") / "opencode") + self._live: dict[str, Any] | None = None + self._target: str | None = None + + def state_home(self) -> Path: + return self._home.expanduser().resolve() + + def declared_version(self, plugin_root: Path) -> str: + return plugin_version(plugin_root) + + @staticmethod + def _git(runner, root, *args, timeout=8): + return runner.run(("git", "-c", "core.hooksPath=/dev/null", "-c", "submodule.recurse=false", + "-C", str(root), *args), timeout=timeout).stdout.strip() + + def inspect_installation(self, repo_root, plugin_root, runner, plugin_list_data=None): + del repo_root, plugin_list_data + plugin = plugin_root.expanduser().absolute() + if any(item.is_symlink() for item in (plugin, *plugin.parents)): + raise UpdateHostError("OpenCode checkout path must not use symlinks") + root = Path(self._git(runner, plugin, "rev-parse", "--show-toplevel")).resolve() + if not plugin.is_relative_to(root): + raise UpdateHostError("OpenCode plugin is outside its checkout") + if self._git(runner, root, "status", "--porcelain=v1", "--untracked-files=all"): + raise UpdateHostError("OpenCode checkout has local changes; update refused") + branch = self._git(runner, root, "symbolic-ref", "--quiet", "--short", "HEAD") + upstream = self._git(runner, root, "for-each-ref", "--format=%(upstream:remotename)%00%(upstream:remoteref)", f"refs/heads/{branch}").split("\0") + if len(upstream) != 2 or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", upstream[0]) or not upstream[1].startswith("refs/heads/"): + raise UpdateHostError("OpenCode checkout requires an explicit remote branch upstream") + version = self._normalize_version(plugin_version(plugin)) + live = {"platform": self.host_id, "plugin_id": PLUGIN_ID, "current_version": version, + "current_scope": "checkout", "current_source": MARKETPLACE, + "available_scopes": ["checkout"], "plugin_root": str(plugin), + "checkout_root": str(root), "plugin_relative": plugin.relative_to(root).as_posix(), + "source_commit": self._git(runner, root, "rev-parse", "HEAD"), + "branch": branch, "remote": upstream[0], "remote_ref": upstream[1]} + self._live = live + return live + + def marketplace_root(self, runner, marketplace_list_data=None): + raise UpdateHostError("OpenCode updates require a fresh pinned source snapshot") + + @contextmanager + def refresh_marketplace(self, runner): + if self._live is None: + raise UpdateHostError("OpenCode installation must be inspected first") + live = self._live + root = Path(live["checkout_root"]) + ref = "refs/helixharness-check/" + uuid.uuid4().hex + try: + self._git(runner, root, "fetch", "--no-tags", "--no-recurse-submodules", "--no-write-fetch-head", + live["remote"], f"{live['remote_ref']}:{ref}", timeout=20) + target = self._git(runner, root, "rev-parse", "--verify", f"{ref}^{{commit}}") + self._git(runner, root, "merge-base", "--is-ancestor", live["source_commit"], target) + with tempfile.TemporaryDirectory(prefix="helix-opencode-policy-") as directory: + snapshot = Path(directory) / "snapshot" + runner.run(("git", "-c", "core.hooksPath=/dev/null", "clone", "--no-checkout", "--shared", "--quiet", "--", str(root), str(snapshot)), timeout=20) + snapshot = snapshot.resolve() + self._git(runner, snapshot, "checkout", "--quiet", "--detach", target, timeout=20) + self._target = target + yield snapshot + finally: + self._git(runner, root, "update-ref", "-d", ref) + self._target = None + + def update_binding(self, snapshot_root, installation, runner): + if self._target is None or snapshot_root is None: + raise UpdateHostError("OpenCode target snapshot is missing") + binding = {key: installation[key] for key in + ("checkout_root", "plugin_relative", "source_commit", "branch", "remote", "remote_ref")} + binding.update({"kind": "opencode-checkout/1.0", "target_commit": self._target}) + self.validate_update_binding(binding) + plugin = snapshot_root / binding["plugin_relative"] + if plugin.is_symlink() or not plugin.resolve().is_relative_to(snapshot_root.resolve()): + raise UpdateHostError("OpenCode target package escapes its checkout") + plugin_version(plugin) + entry = plugin / "opencode/index.ts" + if not entry.is_file() or not entry.resolve().is_relative_to(plugin.resolve()): + raise UpdateHostError("OpenCode target package entry is missing") + return binding + + def validate_update_binding(self, binding): + keys = {"kind", "checkout_root", "plugin_relative", "source_commit", "target_commit", "branch", "remote", "remote_ref"} + if not isinstance(binding, dict) or set(binding) != keys or binding.get("kind") != "opencode-checkout/1.0": + raise UpdateHostError("invalid OpenCode update binding") + if any(not isinstance(value, str) or not value or any(ord(c) < 32 for c in value) for value in binding.values()): + raise UpdateHostError("invalid OpenCode update binding values") + relative = Path(binding["plugin_relative"]) + if not Path(binding["checkout_root"]).is_absolute() or relative.is_absolute() or ".." in relative.parts: + raise UpdateHostError("unsafe OpenCode update paths") + for key in ("source_commit", "target_commit"): + if not re.fullmatch(r"[0-9a-f]{40}", binding[key]): + raise UpdateHostError("OpenCode update requires immutable commit IDs") + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", binding["remote"]) or not binding["remote_ref"].startswith("refs/heads/"): + raise UpdateHostError("invalid OpenCode update upstream") + + def prepare_update_binding(self, binding): + self.validate_update_binding(binding) + return f"OpenCode source target: {binding['target_commit']}. Only a clean fast-forward is allowed; restart OpenCode afterwards." + + def cache_binding_matches_installation(self, binding, installation): + try: + self.validate_update_binding(binding) + except UpdateHostError: + return False + return all(binding[key] == installation.get(key) for key in + ("checkout_root", "plugin_relative", "source_commit", "branch", "remote", "remote_ref")) + + def install_steps(self, scope, runner): + self.validate_scope(scope) + return (InstallStep("opencode-checkout-fast-forward", ()),) + + def execute_install_step(self, step, runner, *, authorization, plugin_root): + if step.step_id != "opencode-checkout-fast-forward" or authorization.get("state") != "installing": + raise UpdateHostError("OpenCode update requires an authorized installation transaction") + binding = authorization.get("update_binding") + self.validate_update_binding(binding) + live = self.inspect_installation(plugin_root, plugin_root, runner) + if live["source_commit"] == binding["target_commit"]: + # A crash between the fast-forward and its receipt can be retried. + self.verify_installation(authorization, runner, plugin_root=plugin_root) + return + if not self.cache_binding_matches_installation(binding, live): + raise UpdateHostError("OpenCode checkout changed after authorization") + root = Path(binding["checkout_root"]) + target = binding["target_commit"] + prefix = "" if binding["plugin_relative"] == "." else binding["plugin_relative"] + "/" + try: + package = json.loads(self._git(runner, root, "show", f"{target}:{prefix}package.json")) + if (package.get("name") != "helixharness-opencode" or package.get("version") != authorization.get("target_version") or + package.get("exports", {}).get(".") != "./opencode/index.ts"): + raise ValueError() + except (ValueError, AttributeError): + raise UpdateHostError("OpenCode target version/package differs from authorization") from None + self._git(runner, root, "merge-base", "--is-ancestor", binding["source_commit"], target) + self._git(runner, root, "merge", "--ff-only", "--no-edit", "--no-overwrite-ignore", target, timeout=60) + + def verify_installation(self, authorization, runner, *, plugin_root): + binding = authorization.get("update_binding") + self.validate_update_binding(binding) + live = self.inspect_installation(plugin_root, plugin_root, runner) + if (any(live[key] != binding[key] for key in ("checkout_root", "plugin_relative", "branch", "remote", "remote_ref")) or + live["source_commit"] != binding["target_commit"] or live["current_version"] != authorization["target_version"]): + raise UpdateHostError("OpenCode installed revision/version verification failed") + return {"target_commit": live["source_commit"], "current_version": live["current_version"], "restart_required": True} diff --git a/helixharness/scripts/ut_artifacts.py b/helixharness/scripts/ut_artifacts.py new file mode 100644 index 0000000..40158e6 --- /dev/null +++ b/helixharness/scripts/ut_artifacts.py @@ -0,0 +1,280 @@ +#!/usr/bin/env python3 +"""Ground UT observation counts and publish bounded UT artifacts atomically. + +Reference checks establish provenance, not a proof of business semantics. Commands +in reproducer records are data only and are never executed by this module. +""" +from __future__ import annotations +import argparse +import hashlib +import stat +import json +import os +from pathlib import Path +import re +import tempfile +from typing import Any +from atomic_files import atomic_write_text + +STATE_NAME = re.compile(r'(?:unittest-(?:queue|session|results|summary|experience)\.md|worker-[1-9][0-9]*-result\.md)\Z') +KINDS = ('confirmed_defect', 'unconfirmed_risk', 'optional_improvement') +LABELS = dict(zip(KINDS, ('已证实缺陷', '待确认风险', '可选改进'))) + +def _safe_file(root: Path, path: Path) -> Path: + if not path.is_absolute(): + path = root / path + if '..' in path.parts: + raise ValueError('UT artifact reference cannot traverse parents') + try: + relative = path.relative_to(root) + except ValueError: + raise ValueError('UT artifact reference is outside its authorized root') from None + current = root + for part in relative.parts: + current = current / part + if current.is_symlink(): + raise ValueError('UT artifact/reference cannot follow a symbolic link') + if not path.is_file(): + raise ValueError('UT artifact/reference must be a regular file') + return path + + +def _directory(repo: Path, feature: str) -> Path: + repo = repo.resolve(strict=True) + if not repo.is_dir() or not feature or feature in ('.', '..') or any(c in feature for c in ('/', '\\', '\0')): + raise ValueError('Invalid UT repository or feature') + current = repo + for part in ('docs', 'specs', 'active', feature): + current = current / part + if current.is_symlink() or (current.exists() and not current.is_dir()): + raise ValueError('Unsafe UT state directory') + current.mkdir(exist_ok=True) + return current + + +def _publish(target: Path, text: str) -> None: + if os.path.lexists(target) and (target.is_symlink() or not target.is_file()): + raise ValueError('Unsafe UT artifact target') + atomic_write_text(target, text, mode=stat.S_IMODE(target.stat().st_mode) if target.exists() else 0o644) + + +def _staged(directory: Path, name: str, source: Path) -> Path: + expected = directory / (name + '.tmp') + if source.name != expected.name or source.parent.resolve() != directory: + raise ValueError('Use the target same-directory .tmp staging file') + return _safe_file(directory, expected) + + +def publish_state(repo: Path, feature: str, name: str, source: Path) -> dict[str, Any]: + if not STATE_NAME.fullmatch(name): + raise ValueError('Unsupported UT state filename') + directory = _directory(repo, feature) + staged = _staged(directory, name, source) + _publish(directory / name, staged.read_text(encoding='utf-8')) + staged.unlink() + return {'status': 'written', 'atomic': True, 'path': str(directory / name)} + + +def _reference(repo: Path, ref: Any, *, normative: bool = False) -> bool: + if not isinstance(ref, dict) or not isinstance(ref.get('path'), str) or not isinstance(ref.get('quote'), str) or not ref['quote'].strip(): + return False + try: + file = _safe_file(repo, Path(ref['path'])) + relative = file.relative_to(repo) + if not normative and file.suffix.lower() not in ('.java', '.kt', '.groovy', '.py', '.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.go'): + return False + if normative and (file.suffix.lower() != '.md' or not (relative.parts[0] in ('docs',) or relative.name in ('README.md', 'AGENTS.md'))): + return False + return ref['quote'] in file.read_text(encoding='utf-8') + except (ValueError, OSError, UnicodeError): + return False + + +def _reproducer(repo: Path, worker: int, value: Any) -> bool: + if not isinstance(value, dict) or not all(isinstance(value.get(k), str) and value[k].strip() for k in ('command', 'expected', 'actual', 'evidence_path', 'evidence_quote')): + return False + if value['expected'].strip() == value['actual'].strip(): + return False + path = Path(value['evidence_path']) + temporary_project = Path(tempfile.gettempdir()) / re.sub(r'[^a-z0-9._-]', '-', repo.name.lower()) + temporary_worker = temporary_project / f'worker-{worker}' + roots = [repo] + # Resolve the platform /var alias only after rejecting links in owned suffixes. + if not temporary_project.is_symlink() and not temporary_worker.is_symlink() and temporary_worker.is_dir(): + roots.extend((temporary_worker, temporary_worker.resolve())) + if path.suffix.lower() not in ('.log', '.txt', '.xml'): + return False + for root in roots: + try: + file = _safe_file(root, path) + if value['evidence_quote'] in file.read_text(encoding='utf-8'): + return True + except (ValueError, OSError, UnicodeError): + pass + return False + + +def normalize_findings(repo: Path, worker: int, document: Any) -> dict[str, Any]: + repo = repo.resolve(strict=True) + if not isinstance(document, dict) or type(document.get('worker_id')) is not int or document.get('worker_id') != worker or not isinstance(document.get('class_name'), str) or not document['class_name'].strip() or not isinstance(document.get('observations'), list): + raise ValueError('Invalid worker observation document') + observations = [] + ids: set[str] = set() + for item in document['observations']: + if not isinstance(item, dict) or not all(isinstance(item.get(k), str) and item[k].strip() for k in ('id', 'title', 'actual_behavior')) or item.get('classification') not in KINDS or item['id'] in ids: + raise ValueError('Invalid or duplicate UT observation') + ids.add(item['id']) + item = dict(item) + category = item['classification'] + if category == 'confirmed_defect': + supported = _reproducer(repo, worker, item.get('reproducer')) + basis = item.get('basis') + if basis == 'contract': + supported = supported and _reference(repo, item.get('normative_ref'), normative=True) + elif basis == 'mechanical': + exception = item.get('observed_exception') + kind = item.get('mechanical_kind') + supported = supported and _reference(repo, item.get('code_ref')) and kind in ('inevitable_exception', 'nontermination', 'data_corruption', 'control_flow_failure', 'security_violation', 'misleading_success') + if kind == 'inevitable_exception': + supported = supported and isinstance(exception, str) and bool(exception.strip()) and exception in str(item.get('reproducer', {}).get('evidence_quote', '')) + else: + supported = False + if not supported: + item['proposed_classification'] = category + item['proposed_severity'] = item.get('severity') + item['classification'] = 'unconfirmed_risk' + item['classification_reason'] = '缺少可核验的规范来源或实际反例;保留观察,不计入已证实缺陷' + item['severity'] = None + elif item.get('severity') not in ('High', 'Medium', 'Low'): + raise ValueError('Confirmed defect needs High/Medium/Low severity') + else: + item['classification_reason'] = '规范/机械失败依据与反例引用校验通过;语义仍由评审负责' + else: + item['severity'] = None + item['classification_reason'] = item.get('classification_reason') or '未确认为违反已确认要求,不计入缺陷' + observations.append(item) + return _seal({'schema_version': 2, 'worker_id': worker, 'class_name': document['class_name'], 'observations': observations, 'counts': {k: sum(x['classification'] == k for x in observations) for k in KINDS}}) + + +def _digest(document: dict[str, Any]) -> str: + # Integrity checksum only, not authentication or a semantic correctness proof. + payload = {k: v for k, v in document.items() if k != 'integrity_sha256'} + return hashlib.sha256(json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode('utf-8')).hexdigest() + + +def _seal(document: dict[str, Any]) -> dict[str, Any]: + document['integrity_sha256'] = _digest(document) + return document + + +def _snapshot(file: Path, worker: int, *, legacy: bool = False) -> dict[str, Any]: + document = json.loads(file.read_text(encoding='utf-8')) + if not isinstance(document, dict) or type(document.get('worker_id')) is not int or document['worker_id'] != worker or not isinstance(document.get('class_name'), str) or not document['class_name'].strip() or not isinstance(document.get('observations'), list): + raise ValueError('Invalid saved worker classification') + if not legacy and (document.get('schema_version') != 2 or document.get('integrity_sha256') != _digest(document)): + raise ValueError('Saved classification version/integrity is invalid; keep original evidence and revalidate explicitly') + ids = set() + for item in document['observations']: + if not isinstance(item, dict) or not all(isinstance(item.get(k), str) and item[k].strip() for k in ('id', 'title', 'actual_behavior', 'classification_reason')) or item['id'] in ids or item.get('classification') not in KINDS: + raise ValueError('Invalid saved observation') + ids.add(item['id']) + if item['classification'] == 'confirmed_defect' and item.get('severity') not in ('High', 'Medium', 'Low'): + raise ValueError('Invalid saved severity') + counts = {k: sum(x['classification'] == k for x in document['observations']) for k in KINDS} + if document.get('counts') != counts or any(type(v) is not int for v in document['counts'].values()): + raise ValueError('Saved classification counts disagree with observations') + return document + + +def _worker_file(directory: Path, worker: int, suffix: str, prefix: str) -> Path | None: + file = directory / f'{prefix}worker-{worker}-{suffix}' + return _safe_file(directory, file) if os.path.lexists(file) else None + + +def _cell(value: Any) -> str: + return str(value).replace('|', '\\|').replace('\n', '
') + + +def _render(documents: list[dict[str, Any]], legacy: list[dict[str, Any]] | None = None) -> str: + counts = {k: sum(d['counts'][k] for d in documents) for k in KINDS} + lines = ['# UT 观察分类报告', '', '> 统计由 ut_artifacts.py 生成;规范引用存在不等于机械证明全部业务语义。', '', '| 已证实缺陷 | 待确认风险 | 可选改进 |', '|---|---|---|', '| ' + ' | '.join(('未核验' if legacy else str(counts[k])) for k in KINDS) + ' |', ''] + for kind in KINDS: + lines += [f'## {LABELS[kind]}', '', '| Worker / Class | ID | 观察 | 实际行为 | 严重程度 | 依据/反例 | 分级依据 |', '|---|---|---|---|---|---|---|'] + for doc in documents: + for item in doc['observations']: + if item['classification'] == kind: + lines.append('| ' + ' | '.join(_cell(x) for x in (f"worker-{doc['worker_id']} / {doc['class_name']}", item['id'], item['title'], item['actual_behavior'], item.get('severity') or '—', json.dumps({'normative':item.get('normative_ref'),'code':item.get('code_ref'),'reproducer':item.get('reproducer')},ensure_ascii=False), item['classification_reason'])) + ' |') + lines.append('') + if legacy: + lines += ['## 分类未核验的历史/未完成 Worker', '', '以下原记录保持不变;全量分类总数未知。上方明细只包含已校验记录,不能将缺失分类算作零。', ''] + for entry in legacy: + lines.append(f"- worker-{entry['worker_id']}:{entry['status']};原记录:" + ', '.join(entry['paths'])) + return '\n'.join(lines) + '\n' + + +def publish_findings(repo: Path, feature: str, worker: int, source: Path) -> dict[str, Any]: + if type(worker) is not int or worker < 1: + raise ValueError('Invalid worker ID') + directory = _directory(repo, feature) + name = f'worker-{worker}-findings.json' + staged = _staged(directory, name, source) + document = normalize_findings(repo, worker, json.loads(staged.read_text(encoding='utf-8'))) + _publish(directory / name, json.dumps(document, ensure_ascii=False, indent=2) + '\n') + _publish(directory / f'worker-{worker}-defects.md', _render([document])) + staged.unlink() + return {'status': 'validated', 'worker_id': worker, 'counts': document['counts'], 'atomic': True} + + +def aggregate_findings(repo: Path, feature: str, workers: list[int]) -> dict[str, Any]: + if not workers or len(set(workers)) != len(workers) or any(type(w) is not int or w < 1 for w in workers): + raise ValueError('Select explicit unique final worker IDs') + directory = _directory(repo, feature) + documents = [] + legacy = [] + for worker in workers: + # Never splice archived evidence into a newly reused active Worker ID. + prefix = '' if any(os.path.lexists(directory / f'worker-{worker}-{suffix}') for suffix in ('result.md', 'findings.json', 'defects.md')) else 'archived-' + file = _worker_file(directory, worker, 'findings.json', prefix) + if file: + raw = json.loads(file.read_text(encoding='utf-8')) + if not isinstance(raw, dict) or type(raw.get('schema_version')) is not int or raw['schema_version'] not in (1, 2): + raise ValueError('Invalid saved classification schema') + if raw['schema_version'] == 2: + documents.append(_snapshot(file, worker)) + continue + _snapshot(file, worker, legacy=True) + result = _worker_file(directory, worker, 'result.md', prefix) + if result is None: + raise ValueError('Missing worker result/classification; cannot assume zero findings') + first = result.read_text(encoding='utf-8').splitlines() + if not first or first[0].strip() not in ('状态: 成功', '状态: 失败', '状态: 超时终止'): + raise ValueError('Invalid legacy worker result status') + defects = _worker_file(directory, worker, 'defects.md', prefix) + legacy.append({'worker_id': worker, 'status': first[0].split(':', 1)[1].strip(), 'paths': [p.name for p in (result, defects, file) if p]}) + known = {k: sum(d['counts'][k] for d in documents) for k in KINDS} + _publish(directory / 'unittest-defects.md', _render(documents, legacy)) + return {'status': 'aggregated', 'worker_ids': workers, 'classification_complete': not legacy, 'counts': {k: None for k in KINDS} if legacy else known, 'known_counts': known, 'legacy_workers': legacy, 'atomic': True} + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--repo-root', type=Path, required=True) + parser.add_argument('--feature', required=True) + sub = parser.add_subparsers(dest='action', required=True) + write = sub.add_parser('write');write.add_argument('--name', required=True);write.add_argument('--source', type=Path, required=True) + findings = sub.add_parser('findings');findings.add_argument('--worker', type=int, required=True);findings.add_argument('--source', type=Path, required=True) + aggregate = sub.add_parser('aggregate');aggregate.add_argument('--workers', required=True, help='comma-separated final worker IDs after retry deduplication') + args = parser.parse_args() + try: + if args.action == 'write': + result = publish_state(args.repo_root, args.feature, args.name, args.source) + elif args.action == 'findings': + result = publish_findings(args.repo_root, args.feature, args.worker, args.source) + else: + result = aggregate_findings(args.repo_root, args.feature, [int(x) for x in args.workers.split(',')]) + except (ValueError, OSError, UnicodeError) as exc: + print(json.dumps({'status': 'blocked', 'reason': str(exc)}, ensure_ascii=False));return 2 + print(json.dumps(result, ensure_ascii=False));return 0 + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/helixharness/scripts/ut_precompile.py b/helixharness/scripts/ut_precompile.py new file mode 100644 index 0000000..eb3f6fc --- /dev/null +++ b/helixharness/scripts/ut_precompile.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""Compile current JVM main sources before UT workers consume class outputs.""" +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import shutil +import subprocess +from typing import Any + + +def _output_path(root: Path, value: Path) -> Path: + candidate = value if value.is_absolute() else root / value + if ".." in candidate.parts: + raise ValueError("Class directory cannot traverse parents") + relative = candidate.relative_to(root) + current = root + for part in relative.parts: + current /= part + if current.is_symlink(): + raise ValueError("Class directory cannot traverse a symbolic link") + return candidate + + +def precompile(repo: Path, *, class_directories: list[Path] | None = None) -> dict[str, Any]: + """Run the project's build tool every time; old directories cannot grant readiness.""" + result: dict[str, Any] = { + "status": "blocked", "ready": False, "tests_run": False, + "command": [], "exit_code": None, "stdout": "", "stderr": "", + "class_directories": [], + } + try: + root = repo.expanduser().resolve(strict=True) + except OSError as exc: + return {**result, "reason": "project_root_invalid", "stderr": str(exc)} + if not root.is_dir(): + return {**result, "reason": "project_root_invalid"} + + gradle = any((root / name).is_file() for name in ( + "build.gradle", "build.gradle.kts", "settings.gradle", "settings.gradle.kts", + )) + maven = (root / "pom.xml").is_file() + if gradle == maven: + return {**result, "reason": "build_tool_ambiguous" if gradle else "build_tool_missing"} + tool = "gradle" if gradle else "maven" + requested = class_directories or ( + [Path(f"build/classes/{language}/main") for language in ("java", "kotlin", "groovy")] + if gradle else [Path("target/classes")] + ) + result["class_directory_scope"] = "explicit" if class_directories else "standard_root_only" + try: + outputs = [_output_path(root, Path(value)) for value in requested] + except ValueError as exc: + return {**result, "build_tool": tool, "reason": "class_directory_invalid", "stderr": str(exc)} + wrapper_name = ( + "gradlew.bat" if os.name == "nt" else "gradlew" + ) if gradle else ("mvnw.cmd" if os.name == "nt" else "mvnw") + wrapper = root / wrapper_name + executable = str(wrapper) if wrapper.is_file() else shutil.which("gradle" if gradle else "mvn") + if executable is None: + return {**result, "build_tool": tool, "reason": "build_executable_missing"} + executable = str(Path(executable).absolute()) + arguments = ( + ["classes", "--no-daemon", "--no-parallel", "--no-watch-fs", "-q"] + if gradle else ["compile", "--batch-mode", "-q"] + ) + command = [executable, *arguments] + result.update({"build_tool": tool, "command": command}) + try: + completed = subprocess.run( + command, cwd=root, capture_output=True, text=True, + encoding="utf-8", errors="replace", check=False, + ) + except OSError as exc: + return {**result, "reason": "precompile_start_failed", "stderr": str(exc)} + result.update({ + "exit_code": completed.returncode, + "stdout": completed.stdout, "stderr": completed.stderr, + }) + if completed.returncode != 0: + return {**result, "reason": "precompile_failed"} + + try: + outputs = [_output_path(root, value) for value in outputs] + except ValueError as exc: + return {**result, "reason": "class_directory_invalid", "stderr": str(exc)} + directories = sorted({str(value) for value in outputs if value.is_dir()}) + if not directories or (class_directories and any(not value.is_dir() for value in outputs)): + return {**result, "reason": "class_output_missing"} + result["class_directories"] = directories + return {**result, "status": "compile_ready", "ready": True} + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--repo-root", type=Path, required=True) + parser.add_argument("--class-directory", type=Path, action="append", + help="Repeat for each active module output verified from current build configuration") + args = parser.parse_args(argv) + result = precompile(args.repo_root, class_directories=args.class_directory) + print(json.dumps(result, ensure_ascii=False)) + return 0 if result["ready"] else 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/helixharness/scripts/workspace.py b/helixharness/scripts/workspace.py index 52ab21a..8ba3c1a 100644 --- a/helixharness/scripts/workspace.py +++ b/helixharness/scripts/workspace.py @@ -585,6 +585,22 @@ def workspace_execution_plan( str(overview["spec_receipt_sha256"]), ) repo_results[repo] = validate_tasks(repo_root, feature, "apply") + child_spec = spec_contract(read_regular( + repo_root / "docs/specs/active" / feature_name(feature) / "spec.md", + f"repo {repo} spec.md", + )) + if child_spec.get("status") in {"implemented", "completed"}: + try: + completed_result = archive_preflight( + repo_root, feature, allow_review_acceptance=False + ) + except (WorkflowError, OSError): + # Single Apply owns recovery of invalid/missing Evidence. + # Identity, Tasks and the original baseline passed above. + pass + else: + repo_results[repo] = completed_result + continue except (WorkflowError, OSError) as exc: raise WorkspaceError( f"repo {repo} Single Lite artifacts are invalid: {exc}" @@ -635,6 +651,7 @@ def workspace_execution_plan( repo_results[repo] = completed_archive_preflight( repo_root, feature ) + continue else: raise WorkflowError( "active/completed feature location is ambiguous" @@ -747,6 +764,9 @@ def workspace_execution_plan( batches = _execution_batches(overview["repositories"]) if command == "archive": batches = list(reversed(batches)) + pending_repos = {job["repo"] for job in jobs} + batches = [pending for batch in batches + if (pending := [repo for repo in batch if repo in pending_repos])] return { **overview, "batches": batches, diff --git a/helixharness/skills/d-d2c/scripts/d2c-print-fidelity-report.cjs b/helixharness/skills/d-d2c/scripts/d2c-print-fidelity-report.cjs index abe0ea8..675eb97 100644 --- a/helixharness/skills/d-d2c/scripts/d2c-print-fidelity-report.cjs +++ b/helixharness/skills/d-d2c/scripts/d2c-print-fidelity-report.cjs @@ -147,4 +147,5 @@ function main() { printFallback(markdown, reportPath) } -main() +if (require.main === module) main() +module.exports = { extractJson } diff --git a/helixharness/skills/d-d2c/scripts/d2c-workflow-checkpoint.cjs b/helixharness/skills/d-d2c/scripts/d2c-workflow-checkpoint.cjs index 8d35f98..8771e44 100644 --- a/helixharness/skills/d-d2c/scripts/d2c-workflow-checkpoint.cjs +++ b/helixharness/skills/d-d2c/scripts/d2c-workflow-checkpoint.cjs @@ -45,6 +45,7 @@ const { isHeadlessEnv, signalForAction, syncActiveWorkflow, + withWorkflowLock, } = require('./lib/d2c-workflow-guard-core.cjs') const { validateHealthEvidence, @@ -185,8 +186,10 @@ function syncWorkflowGuard(stateDir, pageDir, state, stateFile, printSignal = fa } function persistWorkflowState(stateFile, stateDir, pageDir, state, printSignal = false) { - writeState(stateFile, state) - syncWorkflowGuard(stateDir, pageDir, state, stateFile, printSignal, true) + return withWorkflowLock(stateDir, () => { + writeState(stateFile, state) + syncWorkflowGuard(stateDir, pageDir, state, stateFile, printSignal, true) + }) } function persistStateSnapshot(stateDir, pageDir, state) { @@ -2991,7 +2994,12 @@ function showStatus(state) { // ─── main ──────────────────────────────────────────── function main() { const args = parseArgs(process.argv) + const mutating = ['enter', 'component-complete', 'complete', 'pause', 'resume'].some((name) => args[name]) + if (mutating) return withWorkflowLock(args['state-dir'] || 'd-d2c/temp', () => runCommand(args)) + return runCommand(args) +} +function runCommand(args) { const stateDir = args['state-dir'] || 'd-d2c/temp' const pageDir = args['page-dir'] || '' @@ -3058,6 +3066,7 @@ function main() { if (require.main === module) main() module.exports = { + collectPhase2GateStatus, resolvePageFlowReportMarks, collectRenderGateViolations, combinePhase2Gate, diff --git a/helixharness/skills/d-d2c/scripts/lib/d2c-explicit-gate-core.cjs b/helixharness/skills/d-d2c/scripts/lib/d2c-explicit-gate-core.cjs new file mode 100644 index 0000000..5d88e8e --- /dev/null +++ b/helixharness/skills/d-d2c/scripts/lib/d2c-explicit-gate-core.cjs @@ -0,0 +1,304 @@ +#!/usr/bin/env node +'use strict' + +// Explicit host gate: check this invocation's checkpoint, never read transcripts. +const fs = require('fs') +const path = require('path') +const crypto = require('crypto') +const { claimActiveWorkflow, decideStop, isHeadlessEnv, withWorkflowLock } = require('./d2c-workflow-guard-core.cjs') +const { validateHealthEvidence } = require('./d2c-runtime-health-core.cjs') +const { validatePngFile } = require('./d2c-png-evidence.cjs') +const { collectPhase2GateStatus } = require('../d2c-workflow-checkpoint.cjs') +const { extractJson } = require('../d2c-print-fidelity-report.cjs') + +function within(root, candidate) { + const relative = path.relative(root, candidate) + return relative !== '' && relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative) +} + +function readInside(root, candidate, optional = false) { + if (optional && !fs.existsSync(candidate)) return null + const real = fs.realpathSync(candidate) + if (!within(root, real)) throw new Error('checkpoint path escapes its state directory') + const value = JSON.parse(fs.readFileSync(real, 'utf8')) + if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('checkpoint must be an object') + return value +} + +function parseArgs(argv, options = {}) { + const args = { headless: false } + const values = new Set(['--repo-root', '--page-dir', '--started-at', '--action', '--session-id']) + for (let index = 0; index < argv.length; index += 1) { + const key = argv[index] + if (key === '--headless' && !args.headless) { + args.headless = true + } else if (values.has(key) && !Object.prototype.hasOwnProperty.call(args, key) && argv[index + 1] && !argv[index + 1].startsWith('--')) { + args[key] = argv[++index] + } else { + throw new Error(`invalid or duplicate argument: ${key}`) + } + } + for (const key of ['--repo-root', '--page-dir', '--started-at', '--action']) { + if (!args[key]) throw new Error(`required argument: ${key}`) + } + const actions = options.allowClaim ? ['stop', 'ask', 'claim'] : ['stop', 'ask'] + if (!actions.includes(args['--action'])) throw new Error(`action must be ${actions.join(' or ')}`) + if (!Number.isFinite(Date.parse(args['--started-at']))) throw new Error('started-at must be a timestamp') + if (options.requireOwnership && !String(args['--session-id'] || '').trim()) throw new Error('required argument: --session-id from native Host Context') + return args +} + +function timestamp(value) { + return typeof value === 'string' ? Date.parse(value) : NaN +} + +function currentInvocationState(state, startedAt) { + const phases = {} + for (const phase of [0, 1, 2, 3, 4, 6]) { + const entry = state.phases[phase] + if (!entry || !Number.isFinite(timestamp(entry.enteredAt)) || timestamp(entry.enteredAt) < startedAt) continue + if (entry.status === 'completed' && (!Number.isFinite(timestamp(entry.completedAt)) || timestamp(entry.completedAt) < timestamp(entry.enteredAt))) continue + // The canonical checkpoint CLI retains previous phases on --enter 0. + // A retained phase 6 must never outrank the new current phase. + if (phase === 6 && Number(state.currentPhase) !== 6) continue + phases[phase] = entry + } + return { ...state, phases } +} + +function currentInvocationHandoff(handoff, startedAt) { + if (!handoff || !Number.isFinite(timestamp(handoff.updatedAt)) || timestamp(handoff.updatedAt) < startedAt) return null + if (handoff.status === 'awaiting-user' && (!Number.isFinite(timestamp(handoff.browserReadyAt)) || timestamp(handoff.browserReadyAt) < startedAt)) return null + // The canonical guard prioritizes handoff over workflowPause. Old handoff + // state must neither authorize this invocation nor hide its explicit pause. + return handoff +} + +function requireFresh(value, startedAt, label) { + const time = timestamp(value) + if (!Number.isFinite(time) || time < startedAt) throw new Error(`${label} is missing or belongs to an earlier invocation`) + return time +} + +function validateCompletedPhases(state, phases, startedAt) { + let previousEnd = startedAt + for (const phase of phases) { + const entry = state.phases[phase] + if (!entry || entry.status !== 'completed') throw new Error(`phase ${phase} has no completed evidence for this invocation`) + const entered = requireFresh(entry.enteredAt, previousEnd, `phase ${phase} entry`) + previousEnd = requireFresh(entry.completedAt, entered, `phase ${phase} completion`) + } + return previousEnd +} + +function validateAllowedDecision(decision, state, handoff, startedAt) { + if (!decision.allow) return + const kind = decision.action && decision.action.kind + if (state.workflowPause) { + const pause = state.workflowPause + requireFresh(pause.createdAt, startedAt, 'workflow pause') + if (!['external-input', 'user-cancelled'].includes(pause.kind) || !pause.reason) throw new Error('invalid workflow pause') + if (pause.kind === 'external-input' && !pause.detail && !pause.evidence) throw new Error('external-input pause needs evidence or detail') + const pauseKind = pause.kind === 'external-input' ? 'wait-external-input' : 'aborted' + if (kind === pauseKind && decision.reason === pause.reason) return + } + if (kind === 'done') { + if (Number(state.currentPhase) !== 6) throw new Error('only the current phase 6 can complete this invocation') + validateCompletedPhases(state, [0, 1, 2, 3, 4, 6], startedAt) + if (state.phases[4].decision !== 'cancel') throw new Error('phase 4 must authorize finalization') + } else if (kind === 'wait-user-decision') { + const previousEnd = validateCompletedPhases(state, [0, 1, 2, 3], startedAt) + const phase = state.phases[4] + if (Number(state.currentPhase) !== 4 || !phase || phase.status !== 'in_progress') throw new Error('no current phase 4 decision') + requireFresh(phase.enteredAt, previousEnd, 'phase 4 entry') + } else if (handoff && ['wait-browser', 'wait-outer-runner', 'wait-external-input', 'aborted'].includes(kind)) { + requireFresh(handoff.updatedAt, startedAt, 'browser handoff') + if (kind === 'wait-browser') requireFresh(handoff.browserReadyAt, startedAt, 'browser readiness') + } else { + throw new Error('no current invocation evidence authorizes this decision') + } +} + +function freshFile(root, candidate, startedAt) { + const real = fs.realpathSync(candidate) + if (!within(root, real)) throw new Error('visual evidence path escapes its evidence directory') + const stat = fs.statSync(real) + if (!stat.isFile() || stat.size === 0) throw new Error(`visual evidence is empty or not a file: ${path.basename(candidate)}`) + if (stat.mtimeMs + 1 < startedAt) throw new Error(`visual evidence belongs to an earlier invocation: ${path.basename(candidate)}`) + return real +} + +function nonemptyObject(value) { + return value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length > 0 +} + +function validateMeasurement(name, report, pageDir, meta) { + const fail = () => { throw new Error(`${name} measurement evidence is incomplete or inconsistent with the current capture`) } + if (report.version !== '1.0' || typeof report.url !== 'string' || !report.url || typeof report.pageDir !== 'string' || path.resolve(report.pageDir) !== pageDir || report.captureMode !== meta.captureMode) fail() + if (!Number.isInteger(report.checkedCount) || report.checkedCount < 0 || !Number.isInteger(report.matchedCount) || report.matchedCount < 0 || report.matchedCount > report.checkedCount || !Array.isArray(report.items) || report.items.length !== report.checkedCount || !Array.isArray(report.violations) || !Number.isInteger(report.violationCount) || report.violationCount < 0) fail() + if (report.items.filter((item) => item && item.matched === true).length !== report.matchedCount) fail() + if (meta.captureMode === 'region' && (!report.scope || !Array.isArray(report.scope.layoutMarks) || report.scope.layoutMarks.length !== 1 || report.scope.layoutMarks[0] !== meta.designScope)) fail() + if (name === 'vertical' && (report.tool !== 'd2c-vertical-check' || !['page', 'page-flow', 'component'].includes(report.mode))) fail() + if (name === 'render' && (report.gate !== 'render-integrity' || report.checkedCount === 0)) fail() + // Zero vertical anchors can be legitimate. It must still be a canonical + // measurement report, not the same four empty placeholder fields. + if (!report.checkedCount && (!Number.isFinite(report.designFrameWidth) || report.designFrameWidth <= 0 || !Number.isFinite(report.effectiveCssWidth) || report.effectiveCssWidth <= 0 || !Number.isFinite(report.scaleCssToDesign) || report.scaleCssToDesign <= 0 || report.violations.length)) fail() + for (const item of report.items) { + if (!item || typeof item.layoutMark !== 'string' || !item.layoutMark || typeof item.matched !== 'boolean' || !nonemptyObject(item.expected)) fail() + if (!item.matched) { + const canonicalUnresolved = name === 'vertical' && item.measured === null && item.method === null && item.expected.top === null && item.expected.bottom === null && Number.isFinite(item.expected.height) && item.expected.height >= 0 && Array.isArray(report.warnings) && report.warnings.some((warning) => warning && warning.kind === 'mark-unresolved' && warning.layoutMark === item.layoutMark && typeof warning.note === 'string' && warning.note.trim()) + if (!report.violations.some((violation) => violation.layoutMark === item.layoutMark) && !canonicalUnresolved) fail() + continue + } + if (!nonemptyObject(item.measured)) fail() + if (name === 'geometry' && (!Number.isFinite(item.expected.w) || !Number.isFinite(item.expected.absX) || !(Number.isFinite(item.measured.wDesign) && Number.isFinite(item.measured.leftDesign)) && !Number.isFinite(item.measured.fontSizeCss))) fail() + if (name === 'vertical' && (!Number.isFinite(item.expected.top) || !Number.isFinite(item.expected.height) || !Number.isFinite(item.measured.top) || !Number.isFinite(item.measured.height))) fail() + if (name === 'render') { + const expected = item.expected + const style = item.measured.style + const hasContract = expected.text || expected.visualFill || expected.stroke || expected.effect || expected.textSpans && expected.textSpans.length || expected.assets && expected.assets.length || Number.isFinite(expected.borderRadius) || Number.isFinite(expected.opacity) + if (!Array.isArray(expected.textSpans) || !Array.isArray(expected.assets) || !hasContract || item.measured.layoutMark !== item.layoutMark || item.measured.matched !== true || !style || !Number.isFinite(style.rectWidth) || style.rectWidth < 0 || !Number.isFinite(style.rectHeight) || style.rectHeight < 0) fail() + } + } +} + +function validateFidelityReport(root, file, evaluation, round) { + if (fs.statSync(file).size > 8 * 1024 * 1024) throw new Error('fidelity report exceeds the 8 MiB audit limit') + const report = extractJson(fs.readFileSync(file, 'utf8')) + if (!report || report.version !== '1.0' || report.round !== round || report.overallScore !== evaluation.score || report.scoreUnit !== 'percent' || typeof report.summary !== 'string' || !report.summary.trim() || typeof report.reportFile !== 'string' || freshFile(root, path.resolve(root, report.reportFile), 0) !== file) { + throw new Error('fidelity report needs canonical JSON matching this file, round and checkpoint score') + } + const weights = { layoutStructure: .4, visualStyle: .25, contentAssets: .15, perceptualSimilarity: .2 } + let weightedScore = 0 + for (const [name, weight] of Object.entries(weights)) { + const dimension = report.dimensions && report.dimensions[name] + if (!dimension || dimension.weight !== weight || !Number.isFinite(dimension.score) || dimension.score < 0 || dimension.score > 100 || !Number.isFinite(dimension.deduction) || Math.abs(dimension.deduction - (100 - dimension.score)) > 1e-6) throw new Error('fidelity report dimension scores are incomplete or inconsistent') + weightedScore += dimension.score * weight + } + if (Math.abs(weightedScore - evaluation.score) > 1 || !Array.isArray(report.findings) || !Array.isArray(report.optimizationPlan) || !Array.isArray(report.unresolvedQuestions)) throw new Error('fidelity report score or structured findings are inconsistent') +} + +function validateVisualEvidence(root, pageDir, state, startedAt) { + const round = Number(state.round) + if (!Number.isSafeInteger(round) || round < 1) throw new Error('invalid material round') + const roundDir = fs.realpathSync(path.join(pageDir, `r${round}`)) + if (!within(pageDir, roundDir)) throw new Error('material round escapes page directory') + const materialStart = Math.max(startedAt, timestamp(state.phases[2].enteredAt)) + const metaPath = freshFile(roundDir, path.join(roundDir, 'capture-meta.json'), materialStart) + const meta = readInside(roundDir, metaPath) + if (meta.materialStatus === 'invalid' || meta.invalidReason) throw new Error('capture metadata marks visual evidence invalid') + if (!meta.runtimeHealth || typeof meta.runtimeHealth !== 'object') throw new Error('capture metadata has no runtime health evidence') + const fingerprint = meta.sourceFingerprint || {} + for (const file of [...(fingerprint.files || []), ...(fingerprint.explicitFiles || [])]) { + if (typeof file !== 'string' || !within(root, path.resolve(root, file))) throw new Error('capture source path escapes repository') + const candidate = path.resolve(root, file) + if (fs.existsSync(candidate) && !within(root, fs.realpathSync(candidate))) throw new Error('capture source path escapes repository') + } + const healthProblems = validateHealthEvidence({ ...meta.runtimeHealth, sourceFingerprint: meta.sourceFingerprint }, { cwd: root, requireWithinRoot: true }) + if (healthProblems.length) throw new Error(`capture runtime health evidence is missing, failed or stale: ${healthProblems.join('; ')}`) + if (!['full-page', 'region'].includes(meta.captureMode)) throw new Error('capture metadata has no valid capture mode') + if (typeof meta.outPath !== 'string' || !meta.outPath) throw new Error('capture metadata has no actual image path') + const actual = freshFile(roundDir, path.resolve(root, meta.outPath), materialStart) + const image = validatePngFile(actual) + const digest = crypto.createHash('sha256').update(image).digest('hex') + if (meta.actualSha256 !== digest) throw new Error('actual screenshot does not match capture metadata actualSha256') + const warnings = [] + let unresolvedVerticalAnchors = 0 + for (const name of ['geometry', 'vertical', 'render']) { + const file = freshFile(roundDir, path.join(roundDir, `${name}-diff.json`), materialStart) + const report = readInside(roundDir, file) + validateMeasurement(name, report, pageDir, meta) + if (name === 'vertical') unresolvedVerticalAnchors = report.items.filter((item) => !item.matched).length + for (const warning of Array.isArray(report.warnings) ? report.warnings : []) { + if (warning && typeof warning === 'object' && !Array.isArray(warning)) warnings.push({ ...warning, source: name }) + } + } + const gate = collectPhase2GateStatus(path.dirname(pageDir), path.basename(pageDir), round) + if (gate.sourceMaterialFailing.length || gate.failing.length && round < gate.maxRounds) throw new Error('canonical geometry/vertical/render gate still requires repair before finalization') + if (meta.captureMode === 'region') { + if (!meta.designScope || !fs.readdirSync(roundDir).some((name) => { + if (!name.endsWith('-design-source.png')) return false + validatePngFile(freshFile(roundDir, path.join(roundDir, name), materialStart)) + return true + })) throw new Error('region capture needs current scoped design-source evidence') + } + const evaluation = state.phases[3] + if (typeof evaluation.report !== 'string' || !evaluation.report || !Number.isFinite(evaluation.score) || evaluation.score < 0 || evaluation.score > 100) throw new Error('fidelity evaluation needs report and valid score') + const reportFile = freshFile(root, path.resolve(root, evaluation.report), Math.max(startedAt, timestamp(evaluation.enteredAt))) + validateFidelityReport(root, reportFile, evaluation, round) + return { warningCount: warnings.length, unresolvedVerticalAnchors, warnings: warnings.slice(0, 20), warningsTruncated: warnings.length > 20 } +} + +function check(args, options = {}) { + const root = fs.realpathSync(args['--repo-root']) + const stateDir = fs.realpathSync(path.join(root, 'd-d2c/temp')) + if (!within(root, stateDir)) throw new Error('state directory escapes repository') + if (options.requireOwnership && args['--action'] === 'claim' && !options.claimLockHeld) { + // Re-read marker AND state while holding the same lock as checkpoint writes. + return withWorkflowLock(stateDir, () => check(args, { ...options, claimLockHeld: true })) + } + const marker = readInside(stateDir, path.join(stateDir, '.active-workflow.json')) + if (marker.pageDir !== args['--page-dir'] || marker.workflowStartedAt !== args['--started-at']) { + throw new Error('checkpoint does not belong to this invocation') + } + if (marker.ownerSessionId && marker.ownerSessionId !== args['--session-id']) { + throw new Error('checkpoint belongs to another or unidentified session') + } + const pageDir = path.resolve(stateDir, marker.pageDir) + if (!within(stateDir, pageDir)) throw new Error('invalid checkpoint page directory') + const stateFile = fs.realpathSync(marker.stateFile || path.join(pageDir, 'workflow-state.json')) + if (stateFile !== fs.realpathSync(path.join(pageDir, 'workflow-state.json'))) { + throw new Error('checkpoint state does not match page directory') + } + const storedState = readInside(stateDir, stateFile) + if (!storedState.phases || !storedState.phases[0] || storedState.phases[0].enteredAt !== args['--started-at']) { + throw new Error('phase 0 does not match this invocation') + } + const startedAt = timestamp(args['--started-at']) + const state = currentInvocationState(storedState, startedAt) + if (options.requireOwnership) { + const sessionId = String(args['--session-id'] || '').trim() + if (!sessionId) throw new Error('native session identity is required') + if (args['--action'] === 'claim') { + const phase0 = state.phases[0] + const age = Date.now() - startedAt + if (marker.ownerSessionId) throw new Error('workflow ownership is already claimed') + // The canonical CLI retains old phases on --enter 0, so its marker may + // still say completed. Only this invocation's filtered phases count. + if (age < 0 || age > 5 * 60 * 1000 || Number(state.currentPhase) !== 0 || !phase0 || phase0.status !== 'in_progress' || Object.keys(state.phases).some((phase) => phase !== '0')) { + throw new Error('claim requires fresh unowned phase 0 before work begins; re-enter phase 0') + } + claimActiveWorkflow(path.join(stateDir, '.active-workflow.json'), marker, sessionId) + return { allow: true, reason: 'workflow-claimed-for-native-session', action: { kind: 'claimed', askUser: false } } + } + if (!marker.ownerSessionId || marker.ownerSessionId !== sessionId) throw new Error('workflow must be claimed by this native session before work begins') + requireFresh(marker.ownerClaimedAt, startedAt, 'workflow ownership claim') + } + const handoff = currentInvocationHandoff(readInside(stateDir, path.join(pageDir, 'browser-handoff.json'), true), startedAt) + const decision = decideStop({ root, stateDir, marker, state, handoff }, { + sessionId: args['--session-id'], + headless: args.headless || isHeadlessEnv(process.env), + scoreThreshold: process.env.D2C_SCORE_THRESHOLD, + }) + validateAllowedDecision(decision, state, handoff, startedAt) + if (options.requireVisualEvidence && decision.allow && decision.action && ['done', 'wait-user-decision'].includes(decision.action.kind)) { + decision.evidenceAudit = validateVisualEvidence(root, fs.realpathSync(pageDir), state, startedAt) + } + if (args['--action'] === 'ask' && !(decision.allow && decision.action && decision.action.askUser)) { + return { ...decision, allow: false, reason: 'user interaction is not permitted at this checkpoint' } + } + return decision +} + +function main(argv = process.argv.slice(2), options = {}) { + let result + try { + result = check(parseArgs(argv, options), options) + } catch (error) { + result = { allow: false, reason: `${options.host || 'cursor'}_d2c_gate_failed`, detail: error.message } + } + process.stdout.write(`${JSON.stringify(result)}\n`) + return result.allow ? 0 : 2 +} + +module.exports = { check, main, parseArgs } diff --git a/helixharness/skills/d-d2c/scripts/lib/d2c-png-evidence.cjs b/helixharness/skills/d-d2c/scripts/lib/d2c-png-evidence.cjs new file mode 100644 index 0000000..69894c9 --- /dev/null +++ b/helixharness/skills/d-d2c/scripts/lib/d2c-png-evidence.cjs @@ -0,0 +1,105 @@ +'use strict' + +const fs = require('fs') +const zlib = require('zlib') + +// An evidence audit must bound decompression. Larger captures get an explicit +// size diagnostic; this does not classify them as corrupt or visually invalid. +const MAX_FILE_BYTES = 32 * 1024 * 1024 +const MAX_DECODED_BYTES = 128 * 1024 * 1024 +const crcTable = Array.from({ length: 256 }, (_, index) => { + let crc = index + for (let bit = 0; bit < 8; bit += 1) crc = (crc & 1) ? 0xedb88320 ^ (crc >>> 1) : crc >>> 1 + return crc >>> 0 +}) + +function crc32(bytes) { + let crc = 0xffffffff + for (const byte of bytes) crc = crcTable[(crc ^ byte) & 255] ^ (crc >>> 8) + return (crc ^ 0xffffffff) >>> 0 +} + +function validatePngFile(file) { + if (fs.statSync(file).size > MAX_FILE_BYTES) throw new Error('PNG evidence exceeds the 32 MiB compressed audit limit; use a smaller supported capture') + const bytes = fs.readFileSync(file) + const invalid = () => { throw new Error('PNG evidence is malformed or cannot be decompressed') } + if (bytes.length < 57 || bytes.subarray(0, 8).toString('hex') !== '89504e470d0a1a0a') invalid() + let offset = 8 + let header = null + let ended = false + let idatEnded = false + let palette = false + let paletteEntries = 0 + const compressed = [] + while (offset < bytes.length) { + if (offset + 12 > bytes.length || ended) invalid() + const length = bytes.readUInt32BE(offset) + const end = offset + 12 + length + if (end > bytes.length) invalid() + const kind = bytes.toString('latin1', offset + 4, offset + 8) + if (!/^[A-Za-z]{4}$/.test(kind) || kind[2] !== kind[2].toUpperCase()) invalid() + const data = bytes.subarray(offset + 8, end - 4) + if (crc32(bytes.subarray(offset + 4, end - 4)) !== bytes.readUInt32BE(end - 4)) invalid() + if (!header && kind !== 'IHDR') invalid() + if (kind === 'IHDR') { + if (header || length !== 13) invalid() + const width = data.readUInt32BE(0) + const height = data.readUInt32BE(4) + const depth = data[8] + const color = data[9] + const channels = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }[color] + const depths = { 0: [1, 2, 4, 8, 16], 2: [8, 16], 3: [1, 2, 4, 8], 4: [8, 16], 6: [8, 16] }[color] + if (!width || !height || width > 0x7fffffff || height > 0x7fffffff || !channels || !depths.includes(depth) || data[10] !== 0 || data[11] !== 0 || data[12] > 1) invalid() + header = { width, height, depth, color, channels, interlace: data[12] } + } else if (kind === 'PLTE') { + if (palette || compressed.length || !length || length % 3 || length > 768 || [0, 4].includes(header.color)) invalid() + palette = true + paletteEntries = length / 3 + if (header.color === 3 && paletteEntries > 2 ** header.depth) invalid() + } else if (kind === 'IDAT') { + if (idatEnded || (header.color === 3 && !palette)) invalid() + compressed.push(data) + } else if (kind === 'IEND') { + if (length || !compressed.length) invalid() + ended = true + } else { + // Unknown critical chunks cannot be decoded by the PNG contract. + if (kind[0] === kind[0].toUpperCase()) invalid() + if (compressed.length) idatEnded = true + } + offset = end + } + if (!ended) invalid() + const passes = header.interlace + ? [[0, 0, 8, 8], [4, 0, 8, 8], [0, 4, 4, 8], [2, 0, 4, 4], [0, 2, 2, 4], [1, 0, 2, 2], [0, 1, 1, 2]] + : [[0, 0, 1, 1]] + const rows = [] + let expectedBytes = 0 + for (const [x, y, dx, dy] of passes) { + const width = Math.max(0, Math.ceil((header.width - x) / dx)) + const height = Math.max(0, Math.ceil((header.height - y) / dy)) + if (!width || !height) continue + const rowBytes = Math.ceil(width * header.channels * header.depth / 8) + expectedBytes += (rowBytes + 1) * height + rows.push({ rowBytes, height }) + } + if (!Number.isSafeInteger(expectedBytes) || expectedBytes > MAX_DECODED_BYTES) throw new Error('PNG evidence exceeds the 128 MiB decoded audit limit; use a smaller supported capture') + const data = Buffer.concat(compressed) + let decoded + try { + const inflated = zlib.inflateSync(data, { maxOutputLength: Math.max(1, expectedBytes), info: true }) + if (inflated.engine.bytesWritten !== data.length) invalid() + decoded = inflated.buffer + } catch { invalid() } + if (decoded.length !== expectedBytes) invalid() + offset = 0 + for (const { rowBytes, height } of rows) { + for (let row = 0; row < height; row += 1) { + if (decoded[offset] > 4) invalid() + offset += rowBytes + 1 + } + } + return bytes +} + +module.exports = { validatePngFile, MAX_FILE_BYTES, MAX_DECODED_BYTES } diff --git a/helixharness/skills/d-d2c/scripts/lib/d2c-runtime-health-core.cjs b/helixharness/skills/d-d2c/scripts/lib/d2c-runtime-health-core.cjs index c4bfa08..fc45824 100644 --- a/helixharness/skills/d-d2c/scripts/lib/d2c-runtime-health-core.cjs +++ b/helixharness/skills/d-d2c/scripts/lib/d2c-runtime-health-core.cjs @@ -422,7 +422,7 @@ function isExcludedPath(file, excludedPaths) { return excludedPaths.some((excluded) => file === excluded || file.startsWith(`${excluded}/`)) } -function sourceFingerprint(cwd = process.cwd(), extraFiles = [], excludeFiles = []) { +function sourceFingerprint(cwd = process.cwd(), extraFiles = [], excludeFiles = [], options = {}) { const root = path.resolve(cwd) const excludedFiles = normalizeRelativeFiles(root, excludeFiles) const explicitFiles = normalizeRelativeFiles(root, extraFiles).filter(isImplementationPath) @@ -432,6 +432,12 @@ function sourceFingerprint(cwd = process.cwd(), extraFiles = [], excludeFiles = hash.update('d2c-runtime-source-v1\0') for (const file of files) { const abs = path.resolve(root, file) + if (options.requireWithinRoot) { + const relative = path.relative(fs.realpathSync(root), fs.existsSync(abs) ? fs.realpathSync(abs) : abs) + if (!relative || relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) { + throw new Error('runtime health source path escapes repository') + } + } hash.update(file) hash.update('\0') if (fs.existsSync(abs) && fs.statSync(abs).isFile()) hash.update(fs.readFileSync(abs)) @@ -461,7 +467,8 @@ function validateHealthEvidence(evidence, options = {}) { const current = sourceFingerprint( options.cwd || process.cwd(), options.extraFiles || evidence.sourceFingerprint.explicitFiles || [], - options.excludeFiles || evidence.sourceFingerprint.excludedFiles || [] + options.excludeFiles || evidence.sourceFingerprint.excludedFiles || [], + { requireWithinRoot: Boolean(options.requireWithinRoot) } ) if (current.digest !== evidence.sourceFingerprint.digest) { problems.push( diff --git a/helixharness/skills/d-d2c/scripts/lib/d2c-workflow-guard-core.cjs b/helixharness/skills/d-d2c/scripts/lib/d2c-workflow-guard-core.cjs index ff3403e..deea9b0 100644 --- a/helixharness/skills/d-d2c/scripts/lib/d2c-workflow-guard-core.cjs +++ b/helixharness/skills/d-d2c/scripts/lib/d2c-workflow-guard-core.cjs @@ -3,10 +3,47 @@ const fs = require('fs') const path = require('path') +const { randomBytes } = require('crypto') const GUARD_VERSION = 1 const ACTIVE_WORKFLOW_FILE = '.active-workflow.json' const ALLOWED_PAUSE_KINDS = new Set(['external-input', 'user-cancelled']) +const heldWorkflowLocks = new Set() + +// All cooperating marker/state writers use the same nonblocking lock. A busy +// invocation fails closed and may retry; no waiting lock survives process.exit. +function withWorkflowLock(stateDir, operation) { + fs.mkdirSync(stateDir, { recursive: true }) + const directory = fs.realpathSync(stateDir) + if (heldWorkflowLocks.has(directory)) return operation() + // Unique entries avoid deleting/replacing a fixed lock while another writer + // is acquiring it. A killed process leaves only its own dead-PID entry. + const lock = path.join(directory, `.workflow-state.lock-${process.pid}-${randomBytes(12).toString('hex')}`) + fs.mkdirSync(lock) + heldWorkflowLocks.add(directory) + const release = () => { + if (!heldWorkflowLocks.has(directory)) return + heldWorkflowLocks.delete(directory) + try { fs.rmdirSync(lock) } catch (error) { if (error.code !== 'ENOENT') throw error } + } + process.once('exit', release) + try { + for (const entry of fs.readdirSync(directory, { withFileTypes: true })) { + const match = entry.name.match(/^\.workflow-state\.lock-([1-9]\d*)-[a-f0-9]{24}$/) + if (!match || !entry.isDirectory() || path.join(directory, entry.name) === lock) continue + const pid = Number(match[1]) + let live = true + try { process.kill(pid, 0) } catch (error) { if (error.code === 'ESRCH') live = false } + if (live) throw new Error('workflow state is busy; retry after its current writer completes') + // This unique directory can never become a new owner's entry (no ABA). + try { fs.rmdirSync(path.join(directory, entry.name)) } catch { /* dead entry need not block a retry */ } + } + return operation() + } finally { + process.removeListener('exit', release) + release() + } +} function nowIso() { return new Date().toISOString() @@ -238,11 +275,19 @@ function markerStatus(action) { } function syncActiveWorkflow(options) { + return withWorkflowLock(options.stateDir || 'd-d2c/temp', () => syncActiveWorkflowLocked(options)) +} + +function syncActiveWorkflowLocked(options) { const stateDir = options.stateDir || 'd-d2c/temp' const pageDir = String(options.pageDir || '').trim() const state = options.state if (!pageDir || !state) return null + const stateFile = path.resolve(options.stateFile || workflowStatePath(stateDir, pageDir)) + const storedState = readJsonIfExists(stateFile) + if (storedState && JSON.stringify(storedState) !== JSON.stringify(state)) throw new Error('workflow state changed before its marker could be synchronized') + const file = activeWorkflowPath(stateDir) const previous = readJsonIfExists(file) const startedAt = workflowStartedAt(state) @@ -258,7 +303,7 @@ function syncActiveWorkflow(options) { const marker = { version: GUARD_VERSION, pageDir, - stateFile: path.resolve(options.stateFile || workflowStatePath(stateDir, pageDir)), + stateFile, mode: state.mode || null, workflowStartedAt: startedAt, ownerSessionId: sameRun ? previous.ownerSessionId || null : null, @@ -275,13 +320,17 @@ function syncActiveWorkflow(options) { function claimActiveWorkflow(filePath, marker, sessionId) { if (!marker || !sessionId || marker.ownerSessionId) return marker - const claimed = { - ...marker, - ownerSessionId: String(sessionId), - ownerClaimedAt: nowIso(), - } - writeJsonAtomic(filePath, claimed) - return claimed + return withWorkflowLock(path.dirname(filePath), () => { + const current = readJsonIfExists(filePath) + if (JSON.stringify(current) !== JSON.stringify(marker)) throw new Error('workflow changed before ownership could be claimed; retry from the current checkpoint') + const claimed = { + ...current, + ownerSessionId: String(sessionId), + ownerClaimedAt: nowIso(), + } + writeJsonAtomic(filePath, claimed) + return claimed + }) } function loadGuardContext(cwd, options = {}) { @@ -422,4 +471,5 @@ module.exports = { syncActiveWorkflow, workflowStatePath, writeJsonAtomic, + withWorkflowLock, } From 527df7fa129049ea18ecac2d66a89c19a14782ef Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Tue, 24 Nov 2026 14:05:34 +0800 Subject: [PATCH 05/37] =?UTF-8?q?feat(qoder):=20=E6=96=B0=E5=A2=9E=20Qoder?= =?UTF-8?q?=20=E5=AE=BF=E4=B8=BB=20Host=20Kit=20=E4=B8=8E=E6=9C=AC?= =?UTF-8?q?=E5=9C=B0=20ZIP=20=E5=88=86=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Qoder 不解析其它宿主的插件清单,也没有把插件 commands/ 注册为可调用斜杠命令的 表面,因此公共入口投影为 hosts/qoder/skills/ 薄入口,唯一业务契约仍只在 commands/*.md 保存一份。分发表面没有等价 marketplace CLI,改为 scripts/package_qoder_plugin.py 产出只含 Qoder 表面的 ZIP,由 App 安装工具落盘。 host.json 的能力面与限制按 Qoder 实测填写,不借用其它宿主的行为推断:会话沿用 启动时绑定的 plugin_root、更新不刷新绑定;项目级 hooks 会话中途写入即生效;hook 非零退出只留静默记录,不进模型上下文;disable-model-invocation 的方法 Skill 不计入 可见列表。plugin_update 与 telemetry 如实记为 unsupported。 telemetry_async.py 去掉 .claude-plugin/.codex-plugin 硬编码,改为读取各 Host Kit 自己 声明的 distribution 资源,新增宿主无需再改该文件;安装与版本判定共用同一解析入口。 --- docs/platform-support.md | 4 +- helixharness/.gitignore | 1 + helixharness/.qoder-plugin/plugin.json | 21 ++ helixharness/PLUGIN_USAGE.md | 2 +- helixharness/README.md | 4 +- .../hosts/qoder/command-projection.json | 42 +++ helixharness/hosts/qoder/hook_entry.py | 34 ++ helixharness/hosts/qoder/hooks.json | 15 + helixharness/hosts/qoder/host.json | 53 +++ helixharness/hosts/qoder/installer.md | 96 ++++++ helixharness/hosts/qoder/lifecycle.md | 15 + helixharness/hosts/qoder/project-hooks.json | 26 ++ helixharness/hosts/qoder/project.json | 6 + helixharness/hosts/qoder/runtime.md | 45 +++ helixharness/hosts/qoder/skill-entry.md | 37 +++ .../hosts/qoder/skills/apply/SKILL.md | 16 + .../hosts/qoder/skills/archive/SKILL.md | 16 + .../hosts/qoder/skills/bug-fix/SKILL.md | 16 + .../hosts/qoder/skills/config/SKILL.md | 16 + helixharness/hosts/qoder/skills/init/SKILL.md | 16 + .../hosts/qoder/skills/propose/SKILL.md | 16 + .../hosts/qoder/skills/status/SKILL.md | 16 + .../hosts/qoder/skills/update/SKILL.md | 16 + helixharness/hosts/qoder/skills/ut/SKILL.md | 16 + helixharness/hosts/qoder/subagent.md | 46 +++ helixharness/hosts/qoder/ut.md | 49 +++ .../hosts/qoder/workflow-transition.md | 14 + helixharness/scripts/package_qoder_plugin.py | 314 ++++++++++++++++++ helixharness/scripts/telemetry_async.py | 46 ++- .../tests/test_public_workflow_router.py | 2 +- .../scripts/tests/test_qoder_host_contract.py | 247 ++++++++++++++ .../scripts/tests/test_reporting_config.py | 3 + 32 files changed, 1254 insertions(+), 12 deletions(-) create mode 100644 helixharness/.qoder-plugin/plugin.json create mode 100644 helixharness/hosts/qoder/command-projection.json create mode 100644 helixharness/hosts/qoder/hook_entry.py create mode 100644 helixharness/hosts/qoder/hooks.json create mode 100644 helixharness/hosts/qoder/host.json create mode 100644 helixharness/hosts/qoder/installer.md create mode 100644 helixharness/hosts/qoder/lifecycle.md create mode 100644 helixharness/hosts/qoder/project-hooks.json create mode 100644 helixharness/hosts/qoder/project.json create mode 100644 helixharness/hosts/qoder/runtime.md create mode 100644 helixharness/hosts/qoder/skill-entry.md create mode 100644 helixharness/hosts/qoder/skills/apply/SKILL.md create mode 100644 helixharness/hosts/qoder/skills/archive/SKILL.md create mode 100644 helixharness/hosts/qoder/skills/bug-fix/SKILL.md create mode 100644 helixharness/hosts/qoder/skills/config/SKILL.md create mode 100644 helixharness/hosts/qoder/skills/init/SKILL.md create mode 100644 helixharness/hosts/qoder/skills/propose/SKILL.md create mode 100644 helixharness/hosts/qoder/skills/status/SKILL.md create mode 100644 helixharness/hosts/qoder/skills/update/SKILL.md create mode 100644 helixharness/hosts/qoder/skills/ut/SKILL.md create mode 100644 helixharness/hosts/qoder/subagent.md create mode 100644 helixharness/hosts/qoder/ut.md create mode 100644 helixharness/hosts/qoder/workflow-transition.md create mode 100644 helixharness/scripts/package_qoder_plugin.py create mode 100644 helixharness/scripts/tests/test_qoder_host_contract.py diff --git a/docs/platform-support.md b/docs/platform-support.md index cda0bcc..f69f7b6 100644 --- a/docs/platform-support.md +++ b/docs/platform-support.md @@ -16,9 +16,9 @@ HelixHarness 面向 macOS、原生 Windows 与 Linux,要求 Python 3.10+、Git | Optional root user isolation / 可选 root 隔离 | Linux `setpriv` only | Leave `HELIXHARNESS_PLATFORM_EVOLUTION_EXECUTION_USER` unset; do not configure Linux user isolation | | D2C browser helpers / 浏览器工具 | Node and Chrome/Edge | Node and Chrome/Edge; native executable discovery | -The host controls hook trust and execution. Codex must support `commandWindows`; Claude Code must support Bash hooks (`shell: "bash"`). Review changed hooks after updating and start a new session. Merely seeing commands in the menu does not verify hooks. +The host controls hook trust and execution. Codex must support `commandWindows`; Claude Code must support Bash hooks (`shell: "bash"`). Review changed hooks after updating and start a new session. Merely seeing commands in the menu does not verify hooks. Generated project hook commands pin the interpreter, the plugin version directory and the resolved repository root, so `project_hooks_cli.py merge` rewrites our own older command only while all of them are unchanged; after a version-directory or path-spelling change it keeps the stale entry and appends a new one, so re-run Init in existing projects and then delete entries that still point at a removed version directory. User-owned hooks are never touched. -宿主负责 Hook 信任与执行。Codex 需要支持 `commandWindows`,Claude Code 需要支持 Bash Hook。升级后审阅变更的 Hook 并新开会话;菜单中可见命令不等于 Hook 已执行。已有业务项目重新运行 `/helix:init`,由 `project_hooks_cli.py merge` 更新本插件的旧检查命令,保留用户的其他 Hook。生成的项目 Hook 绑定当前解释器和插件路径;移动 Python 或更新插件安装路径后重新 Init。 +宿主负责 Hook 信任与执行。Codex 需要支持 `commandWindows`,Claude Code 需要支持 Bash Hook。升级后审阅变更的 Hook 并新开会话;菜单中可见命令不等于 Hook 已执行。生成的项目 Hook 命令钉死了当前解释器、插件版本目录与 resolve 后的仓库根目录,因此 `project_hooks_cli.py merge` 只在这几个字段完全相等时才改写本插件的旧检查命令;换了版本目录或换一种路径写法(macOS 上 `/tmp` 与 `/private/tmp` 即是如此)会保留旧条目并追加新条目,所以已有业务项目重跑 `/helix:init` 之后还要检查 settings,删掉仍指向已删除版本目录的条目;用户自己的其他 Hook 不受影响。 ## Preflight / 预检 diff --git a/helixharness/.gitignore b/helixharness/.gitignore index 2b22ac5..e4fca9f 100644 --- a/helixharness/.gitignore +++ b/helixharness/.gitignore @@ -18,3 +18,4 @@ __pycache__/ /.helixharness/ /output/ /docs/eval/ +/dist/ diff --git a/helixharness/.qoder-plugin/plugin.json b/helixharness/.qoder-plugin/plugin.json new file mode 100644 index 0000000..73f9af6 --- /dev/null +++ b/helixharness/.qoder-plugin/plugin.json @@ -0,0 +1,21 @@ +{ + "name": "helix", + "version": "1.2.9", + "description": "HelixHarness 研发工作流:以项目约束、知识库、Spec 与验证证据驱动 Propose/Apply/Archive 闭环。", + "author": { + "name": "HelixHarness contributors" + }, + "license": "Apache-2.0", + "keywords": [ + "qoder-plugin", + "workflow", + "spec-driven", + "harness", + "knowledge-base" + ], + "category": "Coding", + "skills": [ + "./skills", + "./hosts/qoder/skills" + ] +} diff --git a/helixharness/PLUGIN_USAGE.md b/helixharness/PLUGIN_USAGE.md index ac7f204..4a3add7 100644 --- a/helixharness/PLUGIN_USAGE.md +++ b/helixharness/PLUGIN_USAGE.md @@ -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 或 Qoder。Codex 与 Claude Code 把本目录作为本地 marketplace 添加;Qoder 没有等价 marketplace CLI,需先用 `scripts/package_qoder_plugin.py` 生成 ZIP,再由 App 安装工具安装。宿主具体命令见 `hosts/codex/installer.md`、`hosts/claude-code/installer.md` 或 `hosts/qoder/installer.md`。 ## 项目结构 diff --git a/helixharness/README.md b/helixharness/README.md index 4176733..a35c71b 100644 --- a/helixharness/README.md +++ b/helixharness/README.md @@ -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 或 Qoder。Codex 与 Claude Code 把本目录作为本地 marketplace 添加;Qoder 没有等价 marketplace CLI,需先用 `scripts/package_qoder_plugin.py` 生成 ZIP,再由 App 安装工具安装。宿主具体命令见 `hosts/codex/installer.md`、`hosts/claude-code/installer.md` 或 `hosts/qoder/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 与 Qoder 使用宿主薄入口(`hosts//skills/`),Claude Code 直接发现根 `skills/`;详细示例见[使用指南](../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 和执行上下文,没有独立模式。 diff --git a/helixharness/hosts/qoder/command-projection.json b/helixharness/hosts/qoder/command-projection.json new file mode 100644 index 0000000..8155da5 --- /dev/null +++ b/helixharness/hosts/qoder/command-projection.json @@ -0,0 +1,42 @@ +{ + "projection_version": "1.0", + "surface": "skill", + "entrypoints": { + "apply": [ + "hosts/qoder/skills/apply/SKILL.md", + "commands/apply.md" + ], + "archive": [ + "hosts/qoder/skills/archive/SKILL.md", + "commands/archive.md" + ], + "bug-fix": [ + "hosts/qoder/skills/bug-fix/SKILL.md", + "commands/bug-fix.md" + ], + "config": [ + "hosts/qoder/skills/config/SKILL.md", + "commands/config.md" + ], + "init": [ + "hosts/qoder/skills/init/SKILL.md", + "commands/init.md" + ], + "propose": [ + "hosts/qoder/skills/propose/SKILL.md", + "commands/propose.md" + ], + "status": [ + "hosts/qoder/skills/status/SKILL.md", + "commands/status.md" + ], + "update": [ + "hosts/qoder/skills/update/SKILL.md", + "commands/update.md" + ], + "ut": [ + "hosts/qoder/skills/ut/SKILL.md", + "commands/ut.md" + ] + } +} diff --git a/helixharness/hosts/qoder/hook_entry.py b/helixharness/hosts/qoder/hook_entry.py new file mode 100644 index 0000000..edfb70f --- /dev/null +++ b/helixharness/hosts/qoder/hook_entry.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 +"""Qoder SessionStart adapter: bind the installed plugin root as Host Context. + +Only SessionStart is registered. Qoder telemetry is declared unsupported, so +there is no consent or ledger state that a SessionEnd hook would need to clean, +and stage boundaries stay owned by the public commands. +""" + +import json +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "scripts")) + +from host_runtime import HostRegistry # noqa: E402 +from lifecycle_service import handle_event # noqa: E402 + + +def main() -> int: + try: + payload = json.load(sys.stdin) + if not isinstance(payload, dict): + return 0 + if payload.get("hook_event_name") != "SessionStart": + return 0 + handle_event(HostRegistry.discover(ROOT / "hosts").get("qoder"), payload) + except (OSError, ValueError): + return 0 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/helixharness/hosts/qoder/hooks.json b/helixharness/hosts/qoder/hooks.json new file mode 100644 index 0000000..26dc4c1 --- /dev/null +++ b/helixharness/hosts/qoder/hooks.json @@ -0,0 +1,15 @@ +{ + "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "sh \"${QODER_PLUGIN_ROOT}/scripts/python_hook_bootstrap.sh\" SessionStart \"${QODER_PLUGIN_ROOT}/hosts/qoder/hook_entry.py\"", + "timeout": 5 + } + ] + } + ] + } +} diff --git a/helixharness/hosts/qoder/host.json b/helixharness/hosts/qoder/host.json new file mode 100644 index 0000000..843368a --- /dev/null +++ b/helixharness/hosts/qoder/host.json @@ -0,0 +1,53 @@ +{ + "host_id": "qoder", + "host_api_version": "1.1", + "aliases": [ + "qoder-cn" + ], + "support": { + "level": "preview", + "display_name": "Qoder", + "evidence": null, + "limitations": [ + "分发使用本地 ZIP 与 App 安装工具,宿主没有等价 marketplace CLI,因此 plugin_update 为 unsupported,更新等于构建并安装新版本。", + "实测:已启动的会话沿用会话启动时绑定的 plugin_root,插件更新不会刷新该绑定;旧版本缓存目录被移除后,旧会话里的插件资源路径失效,必须新开会话。", + "子代理可并行派发,但只返回单次终态,没有 job 级写域与显式等待 API;subagents、workflow_transition、unit_test_workflow 记为 emulated,写域隔离由父流程约束并在终态后核查文件系统。", + "telemetry 为 unsupported:不注册 Stop 与 Failure hook(宿主具备这两类事件,本 Kit 只注册 SessionStart),不读写 consent 与 eval-log,不发起异步上报;统计开关不改变工作流完成门禁。", + "实测:9 个 commands/*.md 在盘上,但没有任何注册面区块把它们列为可调用斜杠命令,程序发送 /helix:status 零展开透传(同路径下 /help 会展开);输入框手工提交是否走斜杠解析未排除。投影为 surface=skill,薄入口在 hosts/qoder/skills/ 由清单 skills 声明装载,command_surface 记 emulated。", + "实测:hook 以非零码失败时宿主只记录 hook_non_blocking_error,不注入模型上下文、也不显示在会话界面,因此项目检查静默失败在对话里不可见,验收必须读转录里的 hook 记录。", + "实测:项目级 .qoder/settings.json 的 PostToolUse hook 会被执行且 additionalContext 注入会话,因此 project_hooks 记为 native。配置按事件读取,会话中途写入即在下次同类工具调用生效;注入要求退出码 0 且 stdout 为合法 JSON。", + "Windows 启动器未验证,只提供 POSIX hook 命令。" + ] + }, + "capabilities": { + "command_surface": "emulated", + "skill_discovery": "native", + "session_start": "native", + "session_end": "native", + "stop_hook": "unsupported", + "failure_hook": "unsupported", + "command_lifecycle": "emulated", + "workflow_transition": "emulated", + "subagents": "emulated", + "unit_test_workflow": "emulated", + "task_tracking": "native", + "project_hooks": "native", + "session_events": "native", + "telemetry": "unsupported", + "plugin_install": "native", + "plugin_update": "unsupported" + }, + "adapters": { + "distribution": "resource:.qoder-plugin/plugin.json", + "installer": "resource:hosts/qoder/installer.md", + "command_projection": "resource:hosts/qoder/command-projection.json", + "runtime": "resource:hosts/qoder/runtime.md", + "subagent_protocol": "resource:hosts/qoder/subagent.md", + "workflow_transition": "resource:hosts/qoder/workflow-transition.md", + "project_config": "resource:hosts/qoder/project.json", + "project_hooks": "resource:hosts/qoder/project-hooks.json", + "ut": "resource:hosts/qoder/ut.md", + "lifecycle": "resource:hosts/qoder/lifecycle.md", + "telemetry_protocol": "resource:hosts/shared/telemetry.md" + } +} diff --git a/helixharness/hosts/qoder/installer.md b/helixharness/hosts/qoder/installer.md new file mode 100644 index 0000000..901618f --- /dev/null +++ b/helixharness/hosts/qoder/installer.md @@ -0,0 +1,96 @@ +# Qoder 宿主安装与更新 + +需要 Python 3.10+、Git 与 Qoder Desktop(或 Qoder CLI)。Qoder 不解析其他平台的插件清单,本宿主 +使用 `.qoder-plugin/plugin.json`、约定目录 `agents/`、`skills/`、`hooks/hooks.json`,并在清单里声明 +两个 skill 根:`./skills`(方法 Skill)与 `./hosts/qoder/skills`(9 个公共命令薄入口)。ZIP 根即插件 +根,不生成另一层薄壳分发。 + +## 构建安装物 + +在插件根目录执行,产出只含 Qoder 表面的 ZIP: + +```bash +python3 scripts/package_qoder_plugin.py # 产出 dist/helix-.zip +``` + +脚本排除 `.claude-plugin/`、`.codex-plugin/`、`hosts/claude-code/`、`hosts/codex/`、根 `SKILL.md`、 +`__pycache__` 与本地状态,把 `hosts/qoder/hooks.json` 复制到 ZIP 根 `hooks/hooks.json`,并为每个 +`agents/*.md` 注入与文件名一致的 `name` frontmatter——Qoder 按 `name` 注册子代理角色,这是本宿主的 +分发细节,不写回共享源文件。`commands/*.md` 随包保留:它不进入宿主命令面,但它是薄入口与 Host +Runtime 投影指向的唯一公共契约,缺少它投影就无法解析。 + +## 安装 + +在 Qoder 会话中请求安装本地插件并给出 ZIP 的绝对路径,由 App 安装工具完成校验、版本化缓存落盘与 +用户级启用。不要手工改写 Qoder 配置文件替代安装工具,也不要在调用安装工具后再编辑配置文件。 + +安装后必须开启新会话:插件清单、skills、agents 与插件 hook 在会话启动时装载,当前会话不可见,且实测已启动 +的会话不会随更新刷新绑定——安装 1.2.3 之后,旧会话仍注入已被删除的 1.0.0 安装路径,该路径下的资源调用不可用。 +项目级 `.qoder/settings.json` 的 hook 不在此列:实测同一轮里写入配置后、13 分钟后的第一次 `Write` 就触发了 +handler,没有重启也没有新开会话,所以验收项目 hooks 不必换会话,只要写入位置与该会话的项目根一致。 + +## 更新与卸载 + +宿主未提供等价 marketplace CLI,`plugin_update` 因此声明为 `unsupported`。更新方式是重新构建并安装 +新版本 ZIP;`.qoder-plugin/plugin.json` 的 `version` 是 Qoder 分发版本,与 `hosts/codex`、 +`hosts/claude-code` 清单的版本独立递增,因为 Qoder 按 `/` 目录落盘,同版本覆盖不可靠。 +同名冲突按宿主安装工具提示处理,不得删除其他插件绕过冲突。卸载在 +`扩展 → 已安装 → 该插件 → … → 删除` 完成。插件卸载不删除业务仓库中的 `docs/harness/`、 +`docs/knowledge/`、`docs/specs/` 或业务代码。 + +## 装载验收 + +安装后按客户端流程审阅并信任该插件的 hook 定义,再开启新会话逐项确认: + +1. SessionStart 注入 `canonical_host_id = qoder` 与当前安装路径,且路径指向本次安装版本目录。 +2. 9 个公共入口以 `helix:` 形式出现在 skill 列表:`init`、`propose`、`apply`、`archive`、 + `bug-fix`、`ut`、`update`、`status`、`config`。入口来自 `hosts/qoder/skills/`,不是宿主命令面。 + 注入给模型的 skill 清单受上下文预算影响可能不完整,可见数少于 9 不构成装载失败,以逐个调用成功为准 + (实测 1.2.0 会话 9 个入口齐全,1.2.1 会话漏掉 `config`,两次都只隔了一次安装)。 +3. `helix:*` 子代理角色可被 `Agent` 工具发现,数量与 `agents/*.md` 一致(实测 16 个)。注意 `list_agents` + 里这些条目的 `id` 形如 URL 编码的 `agent-definition:["plugin","helix@local",""]`,`name` 是裸名, + `helix:` 形态只出现在 `Agent` 工具的 `subagent_type` 列表里;按 `helix:` 前缀过滤 `list_agents` 的 + `id` 会得到 0 个,那是判读错误而非装载失败。 +4. 项目 hooks 能实际执行:单仓 Init 写入 `.qoder/settings.json` 后,在同一会话里再写一次文件即可确认 + `project_linter.py` 被触发;重复 Init 保留用户设置且不增加重复命令。 + +实测结论(用于校正上面的期望,不要按其他宿主的行为判断): + +- 插件 `commands/` 没有进入任何注册面:1.1.0 会话里模型上下文只有 skill 清单、agent 清单、MCP 目录和 Memory + 概览四类区块,没有把 9 个公共命令列为可调用斜杠命令的区块;1.2.4 会话同样报告没有命令列表区块,只可见 + `helix:` 与 `helix:`。程序发送 `/helix:status` 零展开透传,同一路径下 `/help` 却被展开为命令 + 消息。因此 `command_surface` 记为 `emulated`,投影使用 `skill` 薄入口。没有排除的是输入框手工提交是否走 + 另一条解析路径——消息形态取证切不开这两种情形,只能由用户在客户端确认。 +- 项目级 `.qoder/settings.json` 的 `PostToolUse` hook 会被执行,`additionalContext` 注入会话,因此 + `project_hooks` 记为 `native`。配置在事件发生时读取:同一会话中途写入后,首次同类工具调用即触发(实测写入 + 与触发之间没有重启、`SessionStart` 或上下文压缩)。hook 只在退出码 0 且 stdout 为合法 JSON 时注入文本—— + 打印裸字符串的探测没有任何注入记录,容易被误读成“会话中途写入不生效”,别据此下结论。 +- 项目 hook 的注入形态要按宿主界面判读:`additionalContext` 不写进工具返回值文本,而是以独立的 + `PostToolUse hook additional context (tool: <工具名>): <文本>` 区块跟在工具结果之后。因此在目标会话里 + “工具结果没有标记”不等于“hook 没跑”,要看它自己的上下文有没有这个区块。 +- 验收项目 hooks 必须在写入 `.qoder/settings.json` 的那个项目根里开启会话:委派新建的会话使用自己的 + 临时目录作为项目根,读不到原目录的 settings,会给出“未装载”的假阴性。 +- `PostToolUse` matcher 的匹配语义(全名或子串)宿主未文档化,因此 `hosts/qoder/project-hooks.json` + 把三个写入类工具名逐一列出(`Write|Edit|NotebookEdit`),不依赖子串命中。 +- hook 以非零码失败时,宿主只留下 `hook_non_blocking_error` 记录:既不注入模型上下文,也不在会话界面显示。 + 实测一份把 linter 路径钉在 `.../helix/1.1.0/` 的配置连续 26 次以 exit 1 失败(`missing project linter + invariant-check; rerun /helix:init`),整个会话里模型一次都没看到这句话。验收 guardrail 必须去读转录里的 + hook 记录,不能以“会话没报错”当作 hook 正常工作的证据。 +- 更新插件后重跑 Init 不会清掉旧 handler(实测):merge 认“自己的旧命令”的条件是 `argv[1:]` 与新命令完全相等, + 而其中同时包含版本目录和 resolve 之后的 repo-root,任一变化就认不出来。把 1.1.0 生成的 handler 交给 1.2.5 + 合并,结果是 4 个 handler:新的两个指向 1.2.5,旧的两个仍指向已删除的 1.1.0 并每次静默失败。macOS 上同一 + 目录写成 `/tmp/...` 会被规范成 `/private/tmp/...`,所以换一种路径写法也会触发同样的重复。结论:更新插件后 + 重新 Init,并检查 `.qoder/settings.json` 里有没有仍指向旧版本目录的条目,动手删掉。 +- 根 `skills/` 中声明 `disable-model-invocation: true` 的方法 Skill 不进入模型可见列表,属预期行为; + 验收按“可见数 ≤ 声明数 − 抑制数”核对,不得据此判定装载失败。实测 1.2.0 会话给出上限那一侧:8 个根方法 + Skill 加 9 个薄入口共 17 个声明,3 个声明抑制,可见 `helix:` 条目 14 个。但同一个验收判据在 1.2.1 会话里 + 只列出 12 个,缺席的是薄入口 `config` 和方法 Skill `d-d2c`——被截掉哪几项不固定,所以 14 是上限而非期望值, + 逐项调用成功才是判据。 +- 首次运行任何插件 Python 脚本会在安装目录里写入字节码:实测一次只读 `host_runtime_cli.py resolve` 就在 + `.../helix/1.2.8/scripts/` 下生成 6 个 `.pyc`(`scripts/__pycache__/` 与 `scripts/host_runtime/__pycache__/`), + 跑过 `helix:status` 的 1.2.4 会话留下 8 个。因此“安装目录 == ZIP”的核对必须双向比并排除 `__pycache__`, + 否则多出的文件会被误读成安装被改动;ZIP 侧本来就不含这些文件,版本目录整体替换也不会跨版本累积。 + +第 2、3 项在只读验收会话里可自证,但输入框 `/` 菜单的实际条目只能由用户在客户端界面确认;未确认前 +不要把 `command_surface` 声称为 `native`。任一项目未通过时保持对应能力为 `emulated` 或 +`unsupported`,不得先声称可用。 diff --git a/helixharness/hosts/qoder/lifecycle.md b/helixharness/hosts/qoder/lifecycle.md new file mode 100644 index 0000000..58a9a7c --- /dev/null +++ b/helixharness/hosts/qoder/lifecycle.md @@ -0,0 +1,15 @@ +# qoder 生命周期适配 + +插件 hook 的源文件是 `hosts/qoder/hooks.json`;打包脚本把它原样复制到 ZIP 根的 +`hooks/hooks.json`,因为 Qoder 只按插件根约定目录装载 hook,不解析插件自定义路径。 +两处内容必须逐字节一致,不得手工维护第二份。 + +- SessionStart 注入当前安装的 Host Context。本宿主 `telemetry=unsupported`,因此不修复遥测 + 运行时、不读写 consent 与账本。 +- 不注册 SessionEnd、Stop 或 Failure 业务钩子:没有授权态需要收尾,阶段开始、完成与失败全部由 + 公共命令显式记账,会话结束不代表阶段完成。 +- 不注册 PreToolUse 守卫。Host Context 已在 SessionStart 绑定并在会话内不可变,命令与 Skill + 复用同一绑定;额外的 Skill 前置注入只会重复同一份上下文。 +- 项目 hooks 由 `project-hooks.json` 独立声明,合并目标 `.qoder/settings.json`。该路径是否被 + 宿主在真实会话中装载尚未验证,Init 后必须单独检查,重复 Init 应保留用户条目且不增加重复命令。 +- 统计关闭不改变工作流完成门禁。 diff --git a/helixharness/hosts/qoder/project-hooks.json b/helixharness/hosts/qoder/project-hooks.json new file mode 100644 index 0000000..ad76299 --- /dev/null +++ b/helixharness/hosts/qoder/project-hooks.json @@ -0,0 +1,26 @@ +{ + "project_hooks_version": "1.0", + "owner": "parent", + "settings_file": ".qoder/settings.json", + "merge_strategy": "json_append_dedup", + "dedupe_key": "hooks.PostToolUse[].matcher=Write|Edit|NotebookEdit", + "payload": { + "hooks": { + "PostToolUse": [ + { + "matcher": "Write|Edit|NotebookEdit", + "hooks": [ + { + "type": "command", + "command": "\"{python}\" -X utf8 \"{plugin_root}/scripts/project_linter.py\" --repo-root \"{repo_root}\" --linter invariant-check" + }, + { + "type": "command", + "command": "\"{python}\" -X utf8 \"{plugin_root}/scripts/project_linter.py\" --repo-root \"{repo_root}\" --linter spec-sync-check" + } + ] + } + ] + } + } +} diff --git a/helixharness/hosts/qoder/project.json b/helixharness/hosts/qoder/project.json new file mode 100644 index 0000000..4325adf --- /dev/null +++ b/helixharness/hosts/qoder/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": ".qoder/settings.json" +} diff --git a/helixharness/hosts/qoder/runtime.md b/helixharness/hosts/qoder/runtime.md new file mode 100644 index 0000000..8cc14e1 --- /dev/null +++ b/helixharness/hosts/qoder/runtime.md @@ -0,0 +1,45 @@ +# Qoder 宿主运行时 + +该宿主保留 Qoder 原生的命令、Skill、子代理、任务与权限语义,不假装存在 Claude Code 或 +Codex 的插件 hook、环境变量与工具名。本资源只映射存在宿主差异的逻辑动作。 + +SessionStart hook 通过 `hookSpecificOutput.additionalContext` 注入当前安装的 +`canonical_host_id`、`plugin_root` 与 `host_manifest`;路径由实际执行的 +`hosts/qoder/hook_entry.py` 定位,不依赖统计开关。入口调用 +`host_runtime_cli.py resolve --platform qoder --expected-plugin-root {plugin_root}`, +只消费校验后的绝对 `resolved_resources`;命令参数不得覆盖已有会话绑定。 +不得把本地源码 checkout 或 marketplace 目录当作安装缓存,也不得搜索其他插件副本。 + +| 逻辑动作 | Qoder 行为 | +|---|---| +| `read_file` | 使用 `Read` 读取确定绝对路径;大文件用 `offset`/`limit`,不扫描 plugin cache 猜资源 | +| `edit_file` | 已有文件使用 `Edit`,新文件使用 `Write`;遵守当前权限模式与单写者约束,不覆盖用户无关改动 | +| `run_command` | 使用 `Bash` 并保留真实退出状态;长任务用 `run_in_background`,超时上限由 `timeout` 参数显式给出 | +| `invoke_skill` | 使用 `Skill` 工具,插件技能传 `:` 全限定名,例如 `helix:code-review`;不得降级为可选建议 | +| `spawn_job` | 使用 `Agent` 工具,`subagent_type` 取注册角色名(插件角色为 `helix:`);遵守 `resources.subagent_protocol` | +| `wait_job` | 宿主无显式等待 API:后台派发的子代理完成时由运行时自动通知。父流程在收到通知前不得假定结果,也不得用 `sleep` 轮询代替 | +| `ask_user` | 使用 `AskUserQuestion`;空结果、取消或未答复不等于选择默认项 | +| `update_plan` | 使用 `TaskCreate`/`TaskUpdate`/`TaskList`;不存在 `TodoWrite`,回退目标仍是当前 Feature 的 `tasks.md` | +| `stage_finish` | `telemetry=unsupported`,不调用宿主记账;阶段终态由公共命令写入仓库证据 | +| `project_entry` | 生成或合并 `AGENTS.md` | +| `project_hooks` | 父流程把 `project-hooks.json` 条目合并到 `.qoder/settings.json`,不覆盖用户条目;子代理不拥有该文件 | + +公共拼写与本宿主真实工具的对应关系固定为:`Read` → `Read`;`Write`/`Edit` → `Write`/`Edit`; +`Bash` → `Bash`;`Skill` → `Skill`;`AskUserQuestion` → `AskUserQuestion`; +`TodoWrite` → `Task*`;`Agent`/`Task` → `Agent`。`MultiEdit` 在本宿主不存在, +多条替换使用 `Edit` 的批量参数完成,不得为此增加第二次写操作。 + +## 用户决策与等待 + +先确认本轮真实暴露的工具与当前权限模式。流程要求的业务决策使用 `AskUserQuestion` 并取得真实 +回答;没有该能力或该能力不被当前步骤允许时,按文本方式展示问题、范围与完整选项,并说明 +“等待你的选择”后交还控制权,不追加完成摘要。已有明确授权时遵守命令合同直接复用,不重复提问。 + +收到新用户消息后先判断它是否回答当前问题;询问进度或讨论其他事项不视为授权。只有真实选择或 +明确取消才能结束该决策。 + +## 写域与权限 + +`mode` 参数只改变子代理的权限提示方式,不作为写域隔离手段。并行派发可能写入同一路径的角色, +由父流程串行化,或改用 `isolation: "worktree"` 让子代理在独立 git worktree 中执行;收到终态后 +必须核查文件系统实际变化,不得把子代理自述当作完成。 diff --git a/helixharness/hosts/qoder/skill-entry.md b/helixharness/hosts/qoder/skill-entry.md new file mode 100644 index 0000000..3ddf05d --- /dev/null +++ b/helixharness/hosts/qoder/skill-entry.md @@ -0,0 +1,37 @@ +# Qoder Skill Entry Protocol + +Qoder 没有任何注册面把插件 `commands/` 列为可调用的斜杠命令(实测:会话上下文只出现 skill、agent、MCP 与 +Memory 区块;程序发送 `/helix:status` 零展开透传,同一路径下 `/help` 却被展开为命令消息。输入框手工提交是否 +走斜杠解析未排除)。因此本宿主的公共入口投影为 `hosts/qoder/skills/{name}/SKILL.md` +薄入口,由 `.qoder-plugin/plugin.json` 的 `skills` 声明把 `./skills` 与 `./hosts/qoder/skills` 一起装载, +Qoder 以 `{plugin}:{name}` 命名空间暴露。薄入口只选择加载机制,不承载业务步骤。 + +`commands/{name}.md` 仍是唯一公共契约,其 Router 选出的 `workflows/single/*.md` 或 +`workflows/workspace/*.md` 是对应阶段正文,canonical 方法 Skill 仍位于 `skills/{name}/SKILL.md`。 + +## 每个薄入口必须完成的顺序 + +1. 确定 plugin root:优先使用会话里 SessionStart 注入的 HelixHarness Host Context 中的 + `plugin_root`;没有注入时,取当前 `SKILL.md` 向上两级目录。禁止搜索其他版本缓存。 +2. 在任何 Python 调用前完整读取 `reference/runtime-preflight.md`,按其 `check` → `exec` 顺序执行 + `scripts/runtime_preflight.sh`。解释器或 Git 不可用时按该协议的语义处理,不得自行猜测路径。 +3. 执行一次 `scripts/host_runtime_cli.py resolve --platform qoder --expected-plugin-root "{plugin_root}"`, + 完整消费 `plugin_root`、`host_manifest`、`resolved_resources`。回执缺失、来源不符或 + `status != resolved` 时报告 `BLOCKED:helixharness_host_contract_invalid` 并停止。 +4. 完整读取 `resolved_resources.command_projection` 指向的投影、`resolved_resources.runtime` + (即 `hosts/qoder/runtime.md`),以及 `reference/workflow-projection-protocol.md` 和 + `reference/host-runtime-protocol.md`。 +5. 完整读取该命令的 `commands/{name}.md`。文件较长时(`init`、`ut`)用同一读取工具按行区间顺序 + 续读直到文件末尾,不得跳段、不得只读开头,也不得用其它宿主的同名文件替代。 +6. 把用户原始参数逐字作为契约的 `$ARGUMENTS`,按契约步骤执行;工具名按 + `reference/tool-semantics.md` 与 `hosts/qoder/runtime.md` 的映射落到 Qoder 真实能力。 + +## 本宿主的差异 + +- 阶段推进:`hosts/qoder/workflow-transition.md` 声明为 `inline`,同一会话内顺序执行下一阶段, + 不依赖宿主自触发命令。 +- 子代理:`hosts/qoder/subagent.md`,派发结果只在终态一次性回传,等待靠运行时通知而非轮询。 +- 统计与遥测:本宿主 `telemetry: unsupported`,不注册 Stop/Failure hook,也不安装统计 runtime; + 阶段终态由契约内的显式记录步骤完成。 +- 插件更新:本宿主 `plugin_update: unsupported`。`/helix:update` 只能按 + `hosts/qoder/installer.md` 的“重新打包并覆盖安装”路径执行,不得伪造 marketplace 更新。 diff --git a/helixharness/hosts/qoder/skills/apply/SKILL.md b/helixharness/hosts/qoder/skills/apply/SKILL.md new file mode 100644 index 0000000..b080ba9 --- /dev/null +++ b/helixharness/hosts/qoder/skills/apply/SKILL.md @@ -0,0 +1,16 @@ +--- +name: apply +description: "执行任务、验证并完成双轴代码评审。" +--- + +> Qoder 薄入口:只绑定 Host Kit 并加载唯一公共契约,不承载业务步骤。 + +1. 确定 plugin root:优先使用 SessionStart 注入的 HelixHarness Host Context 里的 `plugin_root`;没有注入时取当前文件向上两级目录。不得搜索其他版本的插件缓存。 +2. 完整读取并执行 `{plugin_root}/hosts/qoder/skill-entry.md`,命令名固定为 `apply`。 +3. 完整读取 `{plugin_root}/commands/apply.md`,把下方用户输入逐字作为该契约的 `$ARGUMENTS` 执行:不重排参数、不补全需求名、不从历史会话推断。 + +## User Input + +```text +$ARGUMENTS +``` diff --git a/helixharness/hosts/qoder/skills/archive/SKILL.md b/helixharness/hosts/qoder/skills/archive/SKILL.md new file mode 100644 index 0000000..dda65b4 --- /dev/null +++ b/helixharness/hosts/qoder/skills/archive/SKILL.md @@ -0,0 +1,16 @@ +--- +name: archive +description: "校验完成证据,更新知识并归档需求。" +--- + +> Qoder 薄入口:只绑定 Host Kit 并加载唯一公共契约,不承载业务步骤。 + +1. 确定 plugin root:优先使用 SessionStart 注入的 HelixHarness Host Context 里的 `plugin_root`;没有注入时取当前文件向上两级目录。不得搜索其他版本的插件缓存。 +2. 完整读取并执行 `{plugin_root}/hosts/qoder/skill-entry.md`,命令名固定为 `archive`。 +3. 完整读取 `{plugin_root}/commands/archive.md`,把下方用户输入逐字作为该契约的 `$ARGUMENTS` 执行:不重排参数、不补全需求名、不从历史会话推断。 + +## User Input + +```text +$ARGUMENTS +``` diff --git a/helixharness/hosts/qoder/skills/bug-fix/SKILL.md b/helixharness/hosts/qoder/skills/bug-fix/SKILL.md new file mode 100644 index 0000000..fa535ce --- /dev/null +++ b/helixharness/hosts/qoder/skills/bug-fix/SKILL.md @@ -0,0 +1,16 @@ +--- +name: bug-fix +description: "修订未归档需求并复用原 Apply 基线。" +--- + +> Qoder 薄入口:只绑定 Host Kit 并加载唯一公共契约,不承载业务步骤。 + +1. 确定 plugin root:优先使用 SessionStart 注入的 HelixHarness Host Context 里的 `plugin_root`;没有注入时取当前文件向上两级目录。不得搜索其他版本的插件缓存。 +2. 完整读取并执行 `{plugin_root}/hosts/qoder/skill-entry.md`,命令名固定为 `bug-fix`。 +3. 完整读取 `{plugin_root}/commands/bug-fix.md`,把下方用户输入逐字作为该契约的 `$ARGUMENTS` 执行:不重排参数、不补全需求名、不从历史会话推断。 + +## User Input + +```text +$ARGUMENTS +``` diff --git a/helixharness/hosts/qoder/skills/config/SKILL.md b/helixharness/hosts/qoder/skills/config/SKILL.md new file mode 100644 index 0000000..83f5afe --- /dev/null +++ b/helixharness/hosts/qoder/skills/config/SKILL.md @@ -0,0 +1,16 @@ +--- +name: config +description: "查看或修改 HelixHarness 用户配置:统计授权、作用范围、统计与反馈上报地址。" +--- + +> Qoder 薄入口:只绑定 Host Kit 并加载唯一公共契约,不承载业务步骤。 + +1. 确定 plugin root:优先使用 SessionStart 注入的 HelixHarness Host Context 里的 `plugin_root`;没有注入时取当前文件向上两级目录。不得搜索其他版本的插件缓存。 +2. 完整读取并执行 `{plugin_root}/hosts/qoder/skill-entry.md`,命令名固定为 `config`。 +3. 完整读取 `{plugin_root}/commands/config.md`,把下方用户输入逐字作为该契约的 `$ARGUMENTS` 执行:不重排参数、不补全需求名、不从历史会话推断。 + +## User Input + +```text +$ARGUMENTS +``` diff --git a/helixharness/hosts/qoder/skills/init/SKILL.md b/helixharness/hosts/qoder/skills/init/SKILL.md new file mode 100644 index 0000000..58b67ac --- /dev/null +++ b/helixharness/hosts/qoder/skills/init/SKILL.md @@ -0,0 +1,16 @@ +--- +name: init +description: "HelixHarness 初始化入口。默认初始化单服务仓库;传入 --workspace 时初始化多仓 workspace,并生成 workspace registry 与服务关系基线。" +--- + +> Qoder 薄入口:只绑定 Host Kit 并加载唯一公共契约,不承载业务步骤。 + +1. 确定 plugin root:优先使用 SessionStart 注入的 HelixHarness Host Context 里的 `plugin_root`;没有注入时取当前文件向上两级目录。不得搜索其他版本的插件缓存。 +2. 完整读取并执行 `{plugin_root}/hosts/qoder/skill-entry.md`,命令名固定为 `init`。 +3. 完整读取 `{plugin_root}/commands/init.md`,把下方用户输入逐字作为该契约的 `$ARGUMENTS` 执行:不重排参数、不补全需求名、不从历史会话推断。 + +## User Input + +```text +$ARGUMENTS +``` diff --git a/helixharness/hosts/qoder/skills/propose/SKILL.md b/helixharness/hosts/qoder/skills/propose/SKILL.md new file mode 100644 index 0000000..a10ffee --- /dev/null +++ b/helixharness/hosts/qoder/skills/propose/SKILL.md @@ -0,0 +1,16 @@ +--- +name: propose +description: "收敛需求并生成 Spec/Tasks;--loop 自动串联至 Archive。" +--- + +> Qoder 薄入口:只绑定 Host Kit 并加载唯一公共契约,不承载业务步骤。 + +1. 确定 plugin root:优先使用 SessionStart 注入的 HelixHarness Host Context 里的 `plugin_root`;没有注入时取当前文件向上两级目录。不得搜索其他版本的插件缓存。 +2. 完整读取并执行 `{plugin_root}/hosts/qoder/skill-entry.md`,命令名固定为 `propose`。 +3. 完整读取 `{plugin_root}/commands/propose.md`,把下方用户输入逐字作为该契约的 `$ARGUMENTS` 执行:不重排参数、不补全需求名、不从历史会话推断。 + +## User Input + +```text +$ARGUMENTS +``` diff --git a/helixharness/hosts/qoder/skills/status/SKILL.md b/helixharness/hosts/qoder/skills/status/SKILL.md new file mode 100644 index 0000000..ec78666 --- /dev/null +++ b/helixharness/hosts/qoder/skills/status/SKILL.md @@ -0,0 +1,16 @@ +--- +name: status +description: "只读查看需求阶段、任务进度、阻塞原因和下一步命令。" +--- + +> Qoder 薄入口:只绑定 Host Kit 并加载唯一公共契约,不承载业务步骤。 + +1. 确定 plugin root:优先使用 SessionStart 注入的 HelixHarness Host Context 里的 `plugin_root`;没有注入时取当前文件向上两级目录。不得搜索其他版本的插件缓存。 +2. 完整读取并执行 `{plugin_root}/hosts/qoder/skill-entry.md`,命令名固定为 `status`。 +3. 完整读取 `{plugin_root}/commands/status.md`,把下方用户输入逐字作为该契约的 `$ARGUMENTS` 执行:不重排参数、不补全需求名、不从历史会话推断。 + +## User Input + +```text +$ARGUMENTS +``` diff --git a/helixharness/hosts/qoder/skills/update/SKILL.md b/helixharness/hosts/qoder/skills/update/SKILL.md new file mode 100644 index 0000000..8e29b40 --- /dev/null +++ b/helixharness/hosts/qoder/skills/update/SKILL.md @@ -0,0 +1,16 @@ +--- +name: update +description: "检查并升级 HelixHarness plugin。通过 Host Kit 识别安装版本、展示更新内容,并在用户授权后执行当前宿主的更新适配器。" +--- + +> Qoder 薄入口:只绑定 Host Kit 并加载唯一公共契约,不承载业务步骤。 + +1. 确定 plugin root:优先使用 SessionStart 注入的 HelixHarness Host Context 里的 `plugin_root`;没有注入时取当前文件向上两级目录。不得搜索其他版本的插件缓存。 +2. 完整读取并执行 `{plugin_root}/hosts/qoder/skill-entry.md`,命令名固定为 `update`。 +3. 完整读取 `{plugin_root}/commands/update.md`,把下方用户输入逐字作为该契约的 `$ARGUMENTS` 执行:不重排参数、不补全需求名、不从历史会话推断。 + +## User Input + +```text +$ARGUMENTS +``` diff --git a/helixharness/hosts/qoder/skills/ut/SKILL.md b/helixharness/hosts/qoder/skills/ut/SKILL.md new file mode 100644 index 0000000..1efb75f --- /dev/null +++ b/helixharness/hosts/qoder/skills/ut/SKILL.md @@ -0,0 +1,16 @@ +--- +name: ut +description: "单元测试生成与维护命令。基于知识库和活跃需求,逐层扫描代码并生成/维护单测,运行验证并检查逻辑缺陷,确保覆盖率达标。" +--- + +> Qoder 薄入口:只绑定 Host Kit 并加载唯一公共契约,不承载业务步骤。 + +1. 确定 plugin root:优先使用 SessionStart 注入的 HelixHarness Host Context 里的 `plugin_root`;没有注入时取当前文件向上两级目录。不得搜索其他版本的插件缓存。 +2. 完整读取并执行 `{plugin_root}/hosts/qoder/skill-entry.md`,命令名固定为 `ut`。 +3. 完整读取 `{plugin_root}/commands/ut.md`,把下方用户输入逐字作为该契约的 `$ARGUMENTS` 执行:不重排参数、不补全需求名、不从历史会话推断。 + +## User Input + +```text +$ARGUMENTS +``` diff --git a/helixharness/hosts/qoder/subagent.md b/helixharness/hosts/qoder/subagent.md new file mode 100644 index 0000000..9bbb3ad --- /dev/null +++ b/helixharness/hosts/qoder/subagent.md @@ -0,0 +1,46 @@ +# Qoder 子代理运行协议 + +本协议只决定逻辑 job 的物理派发、终态取得、写入者与资源回收,不改变 command-local Dispatch +Contract 的 `job_id`、`prompt_source`、`depends_on`、`read_scope`、`write_scope`、 +`expected_artifacts`、`validation` 与 `unavailable_fallback`。 + +## 派发 + +```text +dispatch_mode: native_job +result_surface: single_terminal_message +wait_api: runtime_notification +write_scope_isolation: parent_enforced +resource_cleanup: not_required +``` + +- 派发使用 `Agent` 工具。`subagent_type` 取注册角色名:插件角色写作 `helix:scan-api`、 + `helix:code-review` 的拥有者形式 `helix:`,通用角色写作 `general-purpose`。 + `subagent_type="general-purpose"` 是本宿主真实支持的原生取值,直接传入,不需要别名映射。 +- `prompt` 必须自包含:子代理看不到当前会话,需显式给出绝对 plugin_root、host_manifest、 + `prompt_source` 路径、写域与期望产物。 +- `description` 给短标签,`name` 在需要稳定引用该 job 时给出可解析的名字。 +- 并行派发即在同一轮发出多个 `Agent` 调用;不得为此重复发起同一角色。 +- `run_in_background: true` 用于与其它工作重叠的长任务。命名子代理始终后台运行。 + +## 等待与终态 + +- 本宿主没有 `wait_job` 原生接口。后台 job 完成时由运行时投递通知;在通知到达之前,父流程对 + 子代理结果一无所知,不得预测或提前汇总。 +- 不得用 `sleep`、轮询目录或反复读取会话记录来代替等待。等待期间没有其它可做的事时,如实报告 + 子代理仍在运行,而不是给出猜测。 +- 需要终止时使用 `TaskStop`;其返回是终止动作的结果,不代替业务终态判定。 +- 子代理返回的单条消息不直接呈现给用户,父流程必须向用户转述结论。 +- 文本自报不等于完成:取得终态后按 `expected_artifacts` 用 `Read`/`Glob`/`Bash` 核查文件系统中 + 的真实产物与 diff,再判定 `validation`。 + +## 写域 + +- 权限模式与 `mode` 参数只控制确认方式,不构成写域隔离;`plan` 不阻止子代理落盘。 +- 写域重叠的角色由父流程串行化。确需并行且仓库受 git 管理时,可使用 `isolation: "worktree"` + 让子代理在独立副本中执行;该副本的改动需要显式核对后才进入主工作树,未改动时由运行时清理。 +- 子代理不得写 `.qoder/settings.json`、`docs/specs/` 状态文件、共享经验库或其它 job 的产物。 +- 单个 job 失败、被取消或越界写入时,停止新任务准入,等待已派发 job 安全收口并输出部分结果。 + +只有确认当前运行时没有暴露子代理能力时才允许 inline fallback,并记录 +`WARN:qoder_subagent_unavailable`;容量暂满、仍在等待、单个 job 失败或取消都不构成能力不可用。 diff --git a/helixharness/hosts/qoder/ut.md b/helixharness/hosts/qoder/ut.md new file mode 100644 index 0000000..48a347c --- /dev/null +++ b/helixharness/hosts/qoder/ut.md @@ -0,0 +1,49 @@ +# Qoder UT 运行适配 + +本资源只把 [公共 UT 命令](../../commands/ut.md) 的 Claude 兼容工具语义映射到 Qoder;不复制参数、 +扫描、6 Loop、重试、统一验证或报告步骤。子代理的通用派发、容量、等待、终态和回退完整服从当前 +`resources.subagent_protocol`。 + +```text +dispatch_mode: native_job +experience_write_mode: parent_finalize +runtime_handle_in_queue: true +permission_prepare: host_approval +permission_cleanup: not_required +``` + +## 权限与工具映射 + +- 不读取、创建或修改其他宿主配置,不自动批准权限,不绕过 sandbox,也不修改 Qoder 全局配置。 +- `Read`/`Write`/`Edit`/`Bash` 使用当前运行时真实工具;不存在 `MultiEdit`,多条替换用 `Edit` 的 + 批量参数完成。 +- 需要额外权限时走宿主确认流程;确认未获得时保存证据并按公共命令标记 blocked/failed, + 不改用其它工具规避。 +- `permission_prepare` 只验证当前工作区、临时目录和必要构建命令是否可用,不写项目配置。 +- `permission_cleanup` 固定返回 `not_required`。 + +## Worker Dispatch Contract + +每个逻辑 Worker ID 建立 `ut_worker_` job: + +| 字段 | 映射 | +|---|---| +| `prompt_source` | `agents/unit-test-worker.md`,worker 首个业务动作前完整读取 | +| `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` 映射为 `Agent` 调用,`subagent_type` 为 `helix:unit-test-worker`;不假定固定 + 并发上限,不预计算 slot,不把容量暂满当不可用。 +- 本宿主没有 job handle 查询接口,`runtime_handle_in_queue` 记为 `true` 表示队列以派发时给出的 + `name`/`task_id` 作为唯一可引用标识;除此之外不伪造句柄。 +- `wait_worker` 依赖运行时完成通知,不按固定频率轮询文件,不因静默自动中断或重试。 +- job 真实终态通过后,父流程再校验 result/defects、目标测试文件和 write scope;文本自报不等于完成。 +- 原生失败、取消、越界写入或非法产物停止新任务准入,等待已派发 job 安全收口并输出部分结果。 +- 重新执行只恢复逻辑队列和已验证产物;旧 `in_progress` 无可验证终态时重置为 `pending`。 +- worker 不写共享经验;在 final 返回有界经验摘要,由父流程验证后串行、原子合并。 + +结构合法的 worker 业务失败(包括高危 Bug)仍按公共 UT 状态机处理,不等同于宿主原生 job 失败。 diff --git a/helixharness/hosts/qoder/workflow-transition.md b/helixharness/hosts/qoder/workflow-transition.md new file mode 100644 index 0000000..f92bbfc --- /dev/null +++ b/helixharness/hosts/qoder/workflow-transition.md @@ -0,0 +1,14 @@ +# Qoder 工作流跳转适配 + +模式:`inline`。本宿主的斜杠命令不暴露为 Agent 可编程入口:宿主 UI 侧的会话提交与命令回注能力 +对 Agent 不可执行。薄入口虽然以 `helix:{command}` 的 Skill 形式存在,阶段推进仍不重新进入入口—— +`propose --loop` 按 Router 返回值,在当前主 Agent 中依次读取并执行 +`workflows/single/` 或 `workflows/workspace/` 下的唯一阶段正文,不尝试触发 `/helix:apply`,也不 +调用 `helix:apply` 技能重跑入口路由。 + +已路由的内部阶段复用保留的 feature、execution_scope 与 trigger,跳过重复入口路由。 + +Apply 的双轴评审完整执行 `skills/code-review/SKILL.md`,按 `resources.subagent_protocol` 派发 +Standards 与 Spec 两个独立只读角色。评审属于同一个 Apply Stage,不创建独立 Review 阶段,也不 +提前 finish coding entry。`telemetry=unsupported` 时不产生阶段记账,统计开关不改变业务完成门禁, +阶段终态仍以仓库中的真实证据为准。 diff --git a/helixharness/scripts/package_qoder_plugin.py b/helixharness/scripts/package_qoder_plugin.py new file mode 100644 index 0000000..8f50a6c --- /dev/null +++ b/helixharness/scripts/package_qoder_plugin.py @@ -0,0 +1,314 @@ +#!/usr/bin/env python3 +"""Build the Qoder plugin archive from this plugin root. + +Qoder loads one manifest (``.qoder-plugin/plugin.json``) and the convention directories +``agents/``, ``skills/`` and ``hooks/hooks.json``. Measured on the host, a plugin's +``commands/`` directory never becomes a slash command, so the public workflows are projected +as thin skill entries under ``hosts/qoder/skills//`` and published through the +manifest's ``skills`` declaration. Everything that belongs to another host stays out of the +archive, and the two host-specific adjustments Qoder needs are applied to the archive only: + +* ``hosts/qoder/hooks.json`` is published as the root ``hooks/hooks.json``, because Qoder only + reads hooks from that fixed path. +* ``agents/*.md`` gain a ``name`` key matching the file stem, which Qoder uses to register the + subagent role. Shared sources are never rewritten for one host. + +Usage:: + + python3 scripts/package_qoder_plugin.py [--output DIR] +""" + +from __future__ import annotations + +import argparse +import hashlib +import io +import json +import stat +import zipfile +from datetime import datetime, timezone +from pathlib import Path, PurePosixPath + +PLUGIN_ROOT = Path(__file__).resolve().parents[1] +MANIFEST_RELATIVE = PurePosixPath(".qoder-plugin/plugin.json") +HOST_RELATIVE = PurePosixPath("hosts/qoder/host.json") +HOOKS_SOURCE_RELATIVE = PurePosixPath("hosts/qoder/hooks.json") +HOOKS_TARGET_RELATIVE = PurePosixPath("hooks/hooks.json") +QODER_SKILL_ENTRY_ROOT = PurePosixPath("hosts/qoder/skills") + +# Owned by other hosts, or not part of the Qoder surface at all. +EXCLUDED_TOP_LEVEL = {".claude-plugin", ".codex-plugin", "SKILL.md", "dist"} +EXCLUDED_PATHS = {PurePosixPath("hosts/claude-code"), PurePosixPath("hosts/codex")} +EXCLUDED_NAMES = {"__pycache__", ".DS_Store", ".git", ".ruff_cache", ".pytest_cache", "output"} +EXCLUDED_SUFFIXES = {".pyc", ".pyo", ".coverage"} + +ZIP_TIMESTAMP = (2026, 1, 1, 0, 0, 0) + + +class PackagingError(RuntimeError): + """Raised when the archive would not be loadable by Qoder.""" + + +def _read_manifest_text(plugin_root: Path, relative: PurePosixPath) -> str: + path = plugin_root / str(relative) + try: + return path.read_text(encoding="utf-8") + except OSError as exc: + raise PackagingError(f"缺少插件文件: {relative}") from exc + + +def plugin_identity(plugin_root: Path) -> tuple[str, str]: + try: + payload = json.loads(_read_manifest_text(plugin_root, MANIFEST_RELATIVE)) + except json.JSONDecodeError as exc: + raise PackagingError(f"清单无法解析: {MANIFEST_RELATIVE}") from exc + if not isinstance(payload, dict): + raise PackagingError("清单必须是 JSON 对象") + name = str(payload.get("name") or "").strip() + version = str(payload.get("version") or "").strip() + if not name or not version: + raise PackagingError("清单必须声明 name 与 version") + return name, version + + +def declared_skill_roots(plugin_root: Path) -> tuple[str, ...]: + """Return the plugin-relative skill directories the Qoder manifest declares.""" + + payload = json.loads(_read_manifest_text(plugin_root, MANIFEST_RELATIVE)) + raw = payload.get("skills") + values = raw if isinstance(raw, list) else [raw] + roots: list[str] = [] + for value in values: + text = str(value or "").strip().removeprefix("./").rstrip("/") + if text and text not in roots: + roots.append(text) + return tuple(roots) + + +def adapter_resource_path(plugin_root: Path, name: str) -> PurePosixPath: + """Return the plugin-relative file a resource adapter points at.""" + + for key, relative in _adapter_entries(plugin_root): + if key == name: + return relative + raise PackagingError(f"宿主清单未声明资源适配器: {name}") + + +def _adapter_entries(plugin_root: Path) -> list[tuple[str, PurePosixPath]]: + try: + payload = json.loads(_read_manifest_text(plugin_root, HOST_RELATIVE)) + except json.JSONDecodeError as exc: + raise PackagingError(f"清单无法解析: {HOST_RELATIVE}") from exc + adapters = payload.get("adapters") + if not isinstance(adapters, dict): + raise PackagingError("宿主清单必须声明 adapters") + entries: list[tuple[str, PurePosixPath]] = [] + for name, raw in sorted(adapters.items()): + reference = str(raw or "") + kind, _, target = reference.partition(":") + if kind != "resource": + # Python adapters are optional for Qoder; a non-resource reference is out of + # scope for this archive and the host contract loader rejects it separately. + continue + relative = PurePosixPath(target) + if relative.is_absolute() or ".." in relative.parts: + raise PackagingError(f"适配器资源越过插件根: {name}") + entries.append((name, relative)) + if not entries: + raise PackagingError("宿主清单没有声明任何资源适配器") + return entries + + +def host_resource_paths(plugin_root: Path) -> list[PurePosixPath]: + """Return every resource file the Qoder host manifest declares.""" + + return [relative for _, relative in _adapter_entries(plugin_root)] + + +def _frontmatter(text: str) -> tuple[list[str], list[str]] | None: + lines = text.splitlines(keepends=True) + if not lines or lines[0].strip() != "---": + return None + for index in range(1, len(lines)): + if lines[index].strip() == "---": + return lines[: index + 1], lines[index + 1 :] + return None + + +def agent_with_name(text: str, agent_name: str) -> str: + """Insert a ``name`` key when the shared agent file does not declare one.""" + + split = _frontmatter(text) + if split is None: + raise PackagingError(f"agent 缺少 YAML frontmatter: {agent_name}") + header, body = split + for line in header[1:-1]: + stripped = line.strip() + if stripped.startswith("name:"): + declared = stripped[len("name:") :].strip().strip("\"'") + if declared != agent_name: + raise PackagingError( + f"agent frontmatter name 与文件名不一致: {declared} != {agent_name}" + ) + return text + header.insert(1, f"name: {agent_name}\n") + return "".join(header) + "".join(body) + + +def skill_directories(plugin_root: Path, relative_root: str = "skills") -> list[Path]: + skills_root = plugin_root / relative_root + if not skills_root.is_dir(): + return [] + return sorted(path for path in skills_root.iterdir() if (path / "SKILL.md").is_file()) + + +def validate_plugin(plugin_root: Path) -> None: + """Run the static checks Qoder itself would apply, before writing anything.""" + + plugin_identity(plugin_root) + for relative in host_resource_paths(plugin_root): + if not (plugin_root / str(relative)).is_file(): + raise PackagingError(f"宿主适配器资源不存在: {relative}") + if not (plugin_root / str(HOOKS_SOURCE_RELATIVE)).is_file(): + raise PackagingError(f"缺少宿主 hook 源: {HOOKS_SOURCE_RELATIVE}") + try: + hooks = json.loads(_read_manifest_text(plugin_root, HOOKS_SOURCE_RELATIVE)) + except json.JSONDecodeError as exc: + raise PackagingError(f"hook 清单无法解析: {HOOKS_SOURCE_RELATIVE}") from exc + if not isinstance(hooks.get("hooks"), dict) or not hooks["hooks"]: + raise PackagingError("hook 清单必须声明非空 hooks 对象") + entry_relative = adapter_resource_path(plugin_root, "command_projection") + payload = json.loads(_read_manifest_text(plugin_root, entry_relative)) + entrypoints = payload.get("entrypoints") or {} + if payload.get("surface") != "skill": + raise PackagingError("Qoder 投影必须使用 skill surface:宿主没有把插件 commands/ 注册为斜杠命令面") + for command, pair in sorted(entrypoints.items()): + entry = PurePosixPath(str(pair[0])) + if entry != QODER_SKILL_ENTRY_ROOT / command / "SKILL.md": + raise PackagingError(f"命令薄入口路径不符合投影约定: {command}") + if str(pair[1]) != f"commands/{command}.md": + raise PackagingError(f"命令契约路径不是唯一公共契约: {command}") + if not (plugin_root / str(entry)).is_file(): + raise PackagingError(f"命令入口不存在: {command}") + # An undeclared skill root ships files Qoder never loads, so the entry would satisfy + # the host contract while staying invisible as a slash command. + if str(QODER_SKILL_ENTRY_ROOT) not in set(declared_skill_roots(plugin_root)): + raise PackagingError(f"清单未声明薄入口目录: {QODER_SKILL_ENTRY_ROOT}") + for skill_root in ("skills", str(QODER_SKILL_ENTRY_ROOT)): + for skill in skill_directories(plugin_root, skill_root): + split = _frontmatter((skill / "SKILL.md").read_text(encoding="utf-8")) + if split is None: + raise PackagingError(f"Skill 缺少 frontmatter: {skill.name}") + header = "".join(split[0]) + if f"name: {skill.name}" not in header: + raise PackagingError(f"Skill frontmatter name 与目录名不一致: {skill.name}") + + +def is_excluded(relative: PurePosixPath) -> bool: + if relative.parts[0] in EXCLUDED_TOP_LEVEL: + return True + for excluded in EXCLUDED_PATHS: + if relative == excluded or relative.parts[: len(excluded.parts)] == excluded.parts: + return True + if any(part in EXCLUDED_NAMES for part in relative.parts): + return True + return relative.suffix in EXCLUDED_SUFFIXES + + +def collect_entries(plugin_root: Path) -> dict[PurePosixPath, bytes]: + archive: dict[PurePosixPath, bytes] = {} + for path in sorted(plugin_root.rglob("*")): + if not path.is_file(): + continue + relative = PurePosixPath(path.relative_to(plugin_root).as_posix()) + if is_excluded(relative): + continue + archive[relative] = path.read_bytes() + + archive[HOOKS_TARGET_RELATIVE] = _read_manifest_text( + plugin_root, HOOKS_SOURCE_RELATIVE + ).encode("utf-8") + + for relative in [item for item in archive if item.match("agents/*.md")]: + agent_name = relative.name[:-len(".md")] + text = archive[relative].decode("utf-8") + archive[relative] = agent_with_name(text, agent_name).encode("utf-8") + + if MANIFEST_RELATIVE not in archive: + raise PackagingError("归档根目录缺少插件清单") + return archive + + +def write_archive(plugin_root: Path, output_dir: Path) -> Path: + validate_plugin(plugin_root) + name, version = plugin_identity(plugin_root) + archive = collect_entries(plugin_root) + output_dir.mkdir(parents=True, exist_ok=True) + target = output_dir / f"{name}-{version}.zip" + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_DEFLATED) as bundle: + for relative in sorted(archive): + info = zipfile.ZipInfo(str(relative), date_time=ZIP_TIMESTAMP) + info.compress_type = zipfile.ZIP_DEFLATED + info.external_attr = stat.S_IMODE(0o644) << 16 + bundle.writestr(info, archive[relative]) + payload = buffer.getvalue() + target.write_bytes(payload) + return target + + +def verify_archive(plugin_root: Path, archive_path: Path) -> dict[str, object]: + with zipfile.ZipFile(archive_path) as bundle: + names = [PurePosixPath(item.filename) for item in bundle.infolist()] + if MANIFEST_RELATIVE not in names: + raise PackagingError("ZIP 根目录缺少 .qoder-plugin/plugin.json") + for relative in names: + if relative.is_absolute() or ".." in relative.parts: + raise PackagingError(f"ZIP 条目路径不安全: {relative}") + if is_excluded(relative) and relative != HOOKS_TARGET_RELATIVE: + raise PackagingError(f"ZIP 混入其他宿主文件: {relative}") + for relative in host_resource_paths(plugin_root): + if relative not in names: + raise PackagingError(f"ZIP 缺少宿主适配器资源: {relative}") + if HOOKS_TARGET_RELATIVE not in names: + raise PackagingError("ZIP 缺少根 hooks/hooks.json") + projection = json.loads( + _read_manifest_text(plugin_root, adapter_resource_path(plugin_root, "command_projection")) + ) + entrypoints = projection.get("entrypoints") or {} + for command, pair in sorted(entrypoints.items()): + for reference in (str(pair[0]), str(pair[1])): + if PurePosixPath(reference) not in names: + raise PackagingError(f"ZIP 缺少命令入口文件: {command} -> {reference}") + agents = [item for item in names if item.match("agents/*.md")] + for relative in agents: + text = bundle.read(str(relative)).decode("utf-8") + if not _frontmatter(text) or not any( + line.strip().startswith("name:") for line in _frontmatter(text)[0] + ): + raise PackagingError(f"ZIP 内 agent 缺少 name: {relative}") + return { + "entries": len(names), + "agents": len(agents), + "bytes": archive_path.stat().st_size, + "sha256": hashlib.sha256(archive_path.read_bytes()).hexdigest(), + "created_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), + } + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Package this plugin for Qoder.") + parser.add_argument( + "--output", + default=str(PLUGIN_ROOT / "dist"), + help="Directory for the generated archive (default: /dist).", + ) + arguments = parser.parse_args(argv) + archive_path = write_archive(PLUGIN_ROOT, Path(arguments.output).expanduser().resolve()) + summary = verify_archive(PLUGIN_ROOT, archive_path) + print(json.dumps({"archive": str(archive_path), **summary}, ensure_ascii=False, indent=2)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/helixharness/scripts/telemetry_async.py b/helixharness/scripts/telemetry_async.py index a9c98f1..bbbd4a8 100644 --- a/helixharness/scripts/telemetry_async.py +++ b/helixharness/scripts/telemetry_async.py @@ -23,7 +23,7 @@ import xml.etree.ElementTree as element_tree from contextlib import ExitStack, contextmanager, nullcontext from datetime import datetime, timezone -from pathlib import Path +from pathlib import Path, PurePosixPath from typing import Any, Callable, Iterator from xml.sax.saxutils import escape @@ -62,14 +62,48 @@ "telemetry_hosts", ) RUNTIME_RESOURCE_DIRECTORIES = ( - ".claude-plugin", - ".codex-plugin", "commands", "hosts", "reference", ) +def _distribution_targets(plugin_root: Path) -> tuple[PurePosixPath, ...]: + """Return every installed Host Kit's declared distribution manifest, plugin-relative. + + Each manifest is read on its own, and only the declared reference is used, so the + runtime snapshot mirrors what the Host Kits point at instead of a per-platform list + while one incomplete kit cannot hide the others. + """ + + targets: list[PurePosixPath] = [] + for manifest_path in sorted((Path(plugin_root) / "hosts").glob("*/host.json")): + try: + payload = json.loads(manifest_path.read_text(encoding="utf-8")) + except (OSError, ValueError): + continue + adapters = payload.get("adapters") if isinstance(payload, dict) else None + reference = adapters.get("distribution") if isinstance(adapters, dict) else None + kind, _, target = str(reference or "").partition(":") + if kind != "resource" or not target: + continue + relative = PurePosixPath(target) + if relative.is_absolute() or ".." in relative.parts or len(relative.parts) < 2: + continue + if relative not in targets: + targets.append(relative) + return tuple(targets) + + +def runtime_resource_directories(plugin_root: Path) -> tuple[str, ...]: + """Static shared resources plus each Host Kit's own distribution directory.""" + + names = set(RUNTIME_RESOURCE_DIRECTORIES) + for target in _distribution_targets(plugin_root): + names.add(target.parts[0]) + return tuple(sorted(names)) + + def _now() -> str: return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z") @@ -77,7 +111,7 @@ def _now() -> str: def _runtime_version(plugin_root: Path) -> str: root = Path(plugin_root).resolve() for path in ( - root / ".codex-plugin" / "plugin.json", + *(root / str(target) for target in _distribution_targets(root)), root / "runtime-manifest.json", ): try: @@ -1272,7 +1306,7 @@ def install_runtime(plugin_root: Path, home: str | Path | None = None) -> Path: target_directory, ignore=shutil.ignore_patterns("__pycache__", "*.pyc"), ) - for directory in RUNTIME_RESOURCE_DIRECTORIES: + for directory in runtime_resource_directories(plugin): source_directory = plugin / directory target_directory = root / directory if source_directory.is_dir(): @@ -1327,7 +1361,7 @@ def trees_match(source_directory: Path, target_directory: Path) -> bool: plugin = source.parent return all( trees_match(plugin / directory, root / directory) - for directory in RUNTIME_RESOURCE_DIRECTORIES + for directory in runtime_resource_directories(plugin) ) except OSError: return False diff --git a/helixharness/scripts/tests/test_public_workflow_router.py b/helixharness/scripts/tests/test_public_workflow_router.py index 607fd97..2220bea 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','qoder'}) diff --git a/helixharness/scripts/tests/test_qoder_host_contract.py b/helixharness/scripts/tests/test_qoder_host_contract.py new file mode 100644 index 0000000..f736ddb --- /dev/null +++ b/helixharness/scripts/tests/test_qoder_host_contract.py @@ -0,0 +1,247 @@ +#!/usr/bin/env python3 + +from __future__ import annotations + +import json +import tempfile +import unittest +import zipfile +from pathlib import Path, PurePosixPath + +import eval_json +import package_qoder_plugin as packager +import telemetry_async +from host_runtime import HostRegistry +from host_runtime.command_projection import WORKFLOW_COMMANDS, load_command_projection +from host_runtime.project_hooks import load_project_hooks + + +PLUGIN_ROOT = Path(__file__).resolve().parents[2] +LOGICAL_ACTIONS = ( + "read_file", + "edit_file", + "run_command", + "invoke_skill", + "spawn_job", + "wait_job", + "ask_user", + "update_plan", + "stage_finish", +) + + +class QoderHostContractTest(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls.manifest = HostRegistry.discover(PLUGIN_ROOT / "hosts").require("qoder") + cls.host_dir = PLUGIN_ROOT / "hosts" / "qoder" + + def test_manifest_declares_preview_support_without_python_adapters(self) -> None: + self.assertEqual(self.manifest.support_level, "preview") + self.assertEqual(self.manifest.display_name, "Qoder") + self.assertTrue(self.manifest.limitations) + for name in sorted(self.manifest.adapters): + reference = self.manifest.adapter_reference(name) + self.assertEqual( + reference.kind, + "resource", + f"qoder.{name} 必须是资源适配器;Python 适配器会把更新与遥测重新引入本宿主", + ) + + def test_unsupported_capabilities_have_no_host_specific_entrypoints(self) -> None: + for capability in ("telemetry", "plugin_update", "stop_hook", "failure_hook"): + self.assertEqual(self.manifest.capability(capability), "unsupported", capability) + + def test_measured_surfaces_match_the_manifest(self) -> None: + # Qoder keeps plugin commands/ on disk but never expands /helix:, while project + # level .qoder/settings.json hooks load and run. The two capabilities record that. + self.assertEqual(self.manifest.capability("command_surface"), "emulated") + self.assertEqual(self.manifest.capability("project_hooks"), "native") + + def test_skill_surface_projects_thin_entries_onto_the_shared_contract(self) -> None: + projection = load_command_projection(self.manifest) + self.assertEqual(projection.surface, "skill") + self.assertEqual(set(projection.entrypoints), set(WORKFLOW_COMMANDS)) + for command, (entry, contract) in projection.entrypoints.items(): + self.assertEqual(entry, f"hosts/qoder/skills/{command}/SKILL.md") + self.assertEqual(contract, f"commands/{command}.md") + self.assertTrue((PLUGIN_ROOT / entry).is_file(), entry) + self.assertTrue((PLUGIN_ROOT / contract).is_file(), contract) + + def test_thin_entries_only_bind_the_host_kit_and_forward_arguments(self) -> None: + for command in sorted(WORKFLOW_COMMANDS): + text = (PLUGIN_ROOT / "hosts" / "qoder" / "skills" / command / "SKILL.md").read_text( + encoding="utf-8" + ) + header = text.split("---")[1] + self.assertIn(f"name: {command}", header, command) + self.assertIn("hosts/qoder/skill-entry.md", text, command) + self.assertIn(f"commands/{command}.md", text, command) + self.assertIn("$ARGUMENTS", text, command) + + def test_manifest_declares_the_skill_roots_it_ships(self) -> None: + payload = json.loads( + (PLUGIN_ROOT / ".qoder-plugin" / "plugin.json").read_text(encoding="utf-8") + ) + self.assertEqual(payload["name"], "helix") + self.assertEqual( + packager.declared_skill_roots(PLUGIN_ROOT), + ("skills", "hosts/qoder/skills"), + ) + self.assertEqual(payload["skills"], ["./skills", "./hosts/qoder/skills"]) + + def test_project_hooks_target_the_qoder_settings_layer_only(self) -> None: + hooks = load_project_hooks(self.manifest) + self.assertEqual(hooks.owner, "parent") + self.assertEqual(hooks.merge_strategy, "json_append_dedup") + self.assertEqual(hooks.settings_file, ".qoder/settings.json") + self.assertEqual(hooks.dedupe_key, "hooks.PostToolUse[].matcher=Write|Edit|NotebookEdit") + payload = json.loads( + (self.host_dir / "project-hooks.json").read_text(encoding="utf-8") + ) + matchers = [item["matcher"] for item in payload["payload"]["hooks"]["PostToolUse"]] + # Qoder 的 matcher 语义未文档化,因此把三个写入类工具名逐一列出而不是依赖子串匹配。 + self.assertEqual(matchers, ["Write|Edit|NotebookEdit"]) + + def test_hook_surface_is_session_start_only(self) -> None: + path = self.host_dir / "hooks.json" + hooks = json.loads(path.read_text(encoding="utf-8"))["hooks"] + self.assertEqual(list(hooks), ["SessionStart"]) + entries = hooks["SessionStart"][0]["hooks"] + self.assertEqual(len(entries), 1) + command = entries[0]["command"] + self.assertIn("${QODER_PLUGIN_ROOT}/scripts/python_hook_bootstrap.sh", command) + self.assertIn("${QODER_PLUGIN_ROOT}/hosts/qoder/hook_entry.py", command) + self.assertNotIn("${CLAUDE_PLUGIN_ROOT}", command) + + def test_hook_entry_uses_two_level_plugin_root_resolution(self) -> None: + source = (self.host_dir / "hook_entry.py").read_text(encoding="utf-8") + compile(source, str(self.host_dir / "hook_entry.py"), "exec") + self.assertIn("parents[2]", source) + self.assertIn("from lifecycle_service import handle_event", source) + self.assertIn('.get("qoder")', source) + + def test_runtime_maps_every_logical_action(self) -> None: + runtime = (self.host_dir / "runtime.md").read_text(encoding="utf-8") + for action in LOGICAL_ACTIONS: + self.assertIn(f"`{action}`", runtime, action) + self.assertIn("`TodoWrite`", runtime) + self.assertIn("`TaskCreate`", runtime) + + def test_workflow_transition_is_inline_for_every_host_read_document(self) -> None: + for name in ("workflow-transition.md", "ut.md", "subagent.md", "lifecycle.md"): + text = (self.host_dir / name).read_text(encoding="utf-8") + self.assertTrue(text.strip(), name) + self.assertNotIn("../claude-code", text, name) + self.assertNotIn("../codex/", text, name) + transition = (self.host_dir / "workflow-transition.md").read_text(encoding="utf-8") + self.assertIn("模式:`inline`", transition) + + def test_host_manifest_resources_all_exist(self) -> None: + for name in sorted(self.manifest.adapters): + resolved = self.manifest.resolve_resource_adapter(name) + self.assertTrue(resolved.is_file(), name) + + def test_runtime_snapshot_covers_the_declared_distribution_manifest(self) -> None: + # The telemetry runtime snapshot copies directories named by each Host Kit, + # so a new distribution surface cannot be left out of an installed snapshot. + distribution = self.manifest.resolve_resource_adapter("distribution") + declared = telemetry_async._distribution_targets(PLUGIN_ROOT) + self.assertIn(PurePosixPath(distribution.relative_to(PLUGIN_ROOT)), declared) + self.assertIn( + distribution.relative_to(PLUGIN_ROOT).parts[0], + telemetry_async.runtime_resource_directories(PLUGIN_ROOT), + ) + + +class QoderPackagingTest(unittest.TestCase): + def test_agent_name_injection_is_idempotent_and_validated(self) -> None: + source = "---\ndescription: \"扫描接口。\"\n---\n\n# 正文\n" + once = packager.agent_with_name(source, "scan-api") + self.assertEqual(once, "---\nname: scan-api\ndescription: \"扫描接口。\"\n---\n\n# 正文\n") + self.assertEqual(packager.agent_with_name(once, "scan-api"), once) + with self.assertRaises(packager.PackagingError): + packager.agent_with_name(once, "scan-db") + + def test_every_shared_agent_file_can_be_injected(self) -> None: + for path in sorted((PLUGIN_ROOT / "agents").glob("*.md")): + packaged = packager.agent_with_name( + path.read_text(encoding="utf-8"), path.stem + ) + header = packaged.split("---")[1] + self.assertIn(f"name: {path.stem}", header, path.name) + + def test_other_host_surfaces_are_excluded(self) -> None: + for relative in ( + PurePosixPath(".claude-plugin/marketplace.json"), + PurePosixPath(".codex-plugin/plugin.json"), + PurePosixPath("SKILL.md"), + PurePosixPath("hosts/codex/host.json"), + PurePosixPath("hosts/claude-code/host.json"), + PurePosixPath("scripts/__pycache__/x.pyc"), + PurePosixPath("dist/helix-1.1.0.zip"), + ): + self.assertTrue(packager.is_excluded(relative), str(relative)) + for relative in ( + PurePosixPath("commands/init.md"), + PurePosixPath("hosts/qoder/host.json"), + PurePosixPath("hosts/qoder/skills/propose/SKILL.md"), + PurePosixPath(".qoder-plugin/plugin.json"), + PurePosixPath("reference/tool-semantics.md"), + ): + self.assertFalse(packager.is_excluded(relative), str(relative)) + + def test_declared_skill_roots_accept_both_manifest_shapes(self) -> None: + self.assertEqual( + packager.declared_skill_roots(PLUGIN_ROOT), + ("skills", "hosts/qoder/skills"), + ) + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / ".qoder-plugin").mkdir() + for skills, expected in ( + ('"./skills/"', ("skills",)), + ('["./skills", "skills"]', ("skills",)), + ('"./hosts/qoder/skills"', ("hosts/qoder/skills",)), + ): + (root / ".qoder-plugin" / "plugin.json").write_text( + f'{{"name":"helix","version":"1.0.0","skills":{skills}}}', + encoding="utf-8", + ) + self.assertEqual(packager.declared_skill_roots(root), expected, skills) + + def test_built_archive_is_loadable_and_self_consistent(self) -> None: + with tempfile.TemporaryDirectory() as directory: + archive = packager.write_archive( + PLUGIN_ROOT, Path(directory) + ) + summary = packager.verify_archive(PLUGIN_ROOT, archive) + self.assertEqual(summary["agents"], len(list((PLUGIN_ROOT / "agents").glob("*.md")))) + with zipfile.ZipFile(archive) as bundle: + names = {PurePosixPath(item.filename) for item in bundle.infolist()} + self.assertIn(PurePosixPath("hooks/hooks.json"), names) + self.assertNotIn(PurePosixPath("SKILL.md"), names) + for command in sorted(WORKFLOW_COMMANDS): + self.assertIn( + PurePosixPath(f"hosts/qoder/skills/{command}/SKILL.md"), names, command + ) + self.assertIn(PurePosixPath(f"commands/{command}.md"), names, command) + root_hooks = json.loads( + bundle.read("hooks/hooks.json").decode("utf-8") + ) + host_hooks = json.loads( + (PLUGIN_ROOT / "hosts" / "qoder" / "hooks.json").read_text( + encoding="utf-8" + ) + ) + self.assertEqual(root_hooks, host_hooks) + payload = eval_json.loads( + bundle.read(".qoder-plugin/plugin.json").decode("utf-8") + ) + self.assertEqual(payload["name"], "helix") + self.assertTrue(payload["version"]) + self.assertIn("./hosts/qoder/skills", payload["skills"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/helixharness/scripts/tests/test_reporting_config.py b/helixharness/scripts/tests/test_reporting_config.py index bb357df..444cb6a 100644 --- a/helixharness/scripts/tests/test_reporting_config.py +++ b/helixharness/scripts/tests/test_reporting_config.py @@ -102,6 +102,9 @@ def test_installed_worker_copies_and_refreshes_published_configuration(self): # The real installer verifies and copies the bundled runtime dependencies. import shutil actual = Path(telemetry_async.__file__).parent + # The installed Host Kits declare which distribution manifest is copied. + shutil.copytree(actual.parent / "hosts", source / "hosts", + ignore=shutil.ignore_patterns("__pycache__")) for name in telemetry_async.RUNTIME_FILES: shutil.copy2(actual / name, source / "scripts" / name) config = source / "scripts/reporting_config.py" From 61593c832c04fb1c4172918c1751f2feb09fdbc3 Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Tue, 24 Nov 2026 18:40:02 +0800 Subject: [PATCH 06/37] =?UTF-8?q?feat(qoder):=20=E5=A3=B0=E6=98=8E?= =?UTF-8?q?=E5=BC=8F=E9=99=88=E6=97=A7=20hook=20=E7=BB=91=E5=AE=9A?= =?UTF-8?q?=E7=AD=96=E7=95=A5=EF=BC=8Cmerge=20=E8=87=AA=E5=8A=A8=E6=94=B6?= =?UTF-8?q?=E6=95=9B=E9=87=8D=E5=A4=8D=20handler?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Qoder 按 / 目录落盘、且 repo-root 会被解析成符号链接真实路径,旧版 project_hooks_cli 用 argv[1:] 全等识别自生成命令,导致插件升级后重新 init 认不出上一版 本的 handler,重复追加并静默失败。现把识别与收敛策略作为 Host Kit 声明数据:Qoder 声明 linter_flag + collapse + warn,共用代码只消费声明、不按宿主 ID 分支。 - project_hooks 契约新增可选 stale_binding_policy 字段,默认 exact_args/append/fail 保持 codex/claude-code 现有行为不变 - merge 按 --linter 加脚本路径尾部的形状识别自生成命令,同形状重复项仅保留首条; check 默认把缺失/重复降级为 warnings,--strict 恢复为失败 - 新增 3 个测试:版本目录收敛、warn 与 --strict 双态、非形状匹配命令不被认领 - Qoder 分发版本 1.2.9 → 1.3.0 --- helixharness/.qoder-plugin/plugin.json | 2 +- helixharness/hosts/qoder/project-hooks.json | 5 + .../scripts/host_runtime/project_hooks.py | 63 +++++- helixharness/scripts/project_hooks_cli.py | 184 +++++++++++++++--- .../scripts/tests/test_project_hooks.py | 104 ++++++++++ 5 files changed, 323 insertions(+), 35 deletions(-) diff --git a/helixharness/.qoder-plugin/plugin.json b/helixharness/.qoder-plugin/plugin.json index 73f9af6..59cc17f 100644 --- a/helixharness/.qoder-plugin/plugin.json +++ b/helixharness/.qoder-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "helix", - "version": "1.2.9", + "version": "1.3.0", "description": "HelixHarness 研发工作流:以项目约束、知识库、Spec 与验证证据驱动 Propose/Apply/Archive 闭环。", "author": { "name": "HelixHarness contributors" diff --git a/helixharness/hosts/qoder/project-hooks.json b/helixharness/hosts/qoder/project-hooks.json index ad76299..007bec5 100644 --- a/helixharness/hosts/qoder/project-hooks.json +++ b/helixharness/hosts/qoder/project-hooks.json @@ -4,6 +4,11 @@ "settings_file": ".qoder/settings.json", "merge_strategy": "json_append_dedup", "dedupe_key": "hooks.PostToolUse[].matcher=Write|Edit|NotebookEdit", + "stale_binding_policy": { + "recognize": "linter_flag", + "merge": "collapse", + "check": "warn" + }, "payload": { "hooks": { "PostToolUse": [ diff --git a/helixharness/scripts/host_runtime/project_hooks.py b/helixharness/scripts/host_runtime/project_hooks.py index 7a77a75..199380d 100644 --- a/helixharness/scripts/host_runtime/project_hooks.py +++ b/helixharness/scripts/host_runtime/project_hooks.py @@ -2,7 +2,7 @@ from __future__ import annotations -from dataclasses import dataclass +from dataclasses import dataclass, field from pathlib import PurePosixPath from typing import Any @@ -14,6 +14,29 @@ HOOK_OWNERS = frozenset({"bootstrap", "parent"}) HOOK_MERGE_STRATEGIES = frozenset({"json_append_dedup", "unsupported"}) +STALE_RECOGNIZE_MODES = frozenset({"exact_args", "linter_flag"}) +STALE_MERGE_MODES = frozenset({"append", "collapse"}) +STALE_CHECK_MODES = frozenset({"fail", "warn"}) + + +@dataclass(frozen=True) +class StaleBindingPolicy: + """How this host handles stale/duplicate linter bindings. + + - recognize: how to identify our own generated command. + * exact_args: argv[1:] must match exactly (current behavior). + * linter_flag: match by --linter + script path tail + absolute interpreter. + - merge: what to do when multiple shape-matched entries exist. + * append: current dedup behavior (keep first, append others). + * collapse: keep first, drop extras. + - check: what check does when stale/duplicate entries are found. + * fail: raise ValueError (current behavior). + * warn: return {"status":"pass","warnings":[...]} listing them. + """ + + recognize: str = "exact_args" + merge: str = "append" + check: str = "fail" def _optional_relative_path(value: Any, label: str) -> str | None: @@ -26,6 +49,26 @@ def _optional_relative_path(value: Any, label: str) -> str | None: return path.as_posix() +def _parse_stale_binding_policy(raw: Any, host_id: str) -> StaleBindingPolicy: + if raw is None: + return StaleBindingPolicy() + if not isinstance(raw, dict): + raise HostContractError(f"stale_binding_policy 必须是对象: {host_id}") + allowed_keys = {"recognize", "merge", "check"} + if set(raw) - allowed_keys: + raise HostContractError(f"stale_binding_policy 字段无效: {host_id}") + recognize = str(raw.get("recognize") or "exact_args").strip() + merge = str(raw.get("merge") or "append").strip() + check = str(raw.get("check") or "fail").strip() + if recognize not in STALE_RECOGNIZE_MODES: + raise HostContractError(f"stale_binding_policy.recognize 无效: {host_id}") + if merge not in STALE_MERGE_MODES: + raise HostContractError(f"stale_binding_policy.merge 无效: {host_id}") + if check not in STALE_CHECK_MODES: + raise HostContractError(f"stale_binding_policy.check 无效: {host_id}") + return StaleBindingPolicy(recognize=recognize, merge=merge, check=check) + + @dataclass(frozen=True) class ProjectHooks: """宿主在 init 时怎样拥有和合并项目级 hooks。""" @@ -35,6 +78,7 @@ class ProjectHooks: merge_strategy: str dedupe_key: str | None payload: dict[str, Any] | None + stale_binding_policy: StaleBindingPolicy = field(default_factory=StaleBindingPolicy) def load_project_hooks(manifest: HostManifest) -> ProjectHooks: @@ -51,7 +95,13 @@ def load_project_hooks(manifest: HostManifest) -> ProjectHooks: "dedupe_key", "payload", } - if not isinstance(payload, dict) or set(payload) != required_fields: + optional_fields = {"stale_binding_policy"} + if not isinstance(payload, dict): + raise HostContractError(f"项目 hooks 字段无效: {manifest.host_id}") + if not required_fields.issubset(set(payload)): + raise HostContractError(f"项目 hooks 缺少必需字段: {manifest.host_id}") + unknown = set(payload) - required_fields - optional_fields + if unknown: raise HostContractError(f"项目 hooks 字段无效: {manifest.host_id}") if payload.get("project_hooks_version") != "1.0": raise HostContractError(f"项目 hooks 版本无效: {manifest.host_id}") @@ -86,12 +136,17 @@ def load_project_hooks(manifest: HostManifest) -> ProjectHooks: raise HostContractError(f"项目 hooks 合并参数无效: {manifest.host_id}") hook_payload = raw_hook_payload + stale_policy = _parse_stale_binding_policy( + payload.get("stale_binding_policy"), manifest.host_id + ) + return ProjectHooks( owner=owner, settings_file=settings_file, merge_strategy=strategy, dedupe_key=dedupe_key, payload=hook_payload, + stale_binding_policy=stale_policy, ) @@ -99,5 +154,9 @@ def load_project_hooks(manifest: HostManifest) -> ProjectHooks: "HOOK_MERGE_STRATEGIES", "HOOK_OWNERS", "ProjectHooks", + "STALE_CHECK_MODES", + "STALE_MERGE_MODES", + "STALE_RECOGNIZE_MODES", + "StaleBindingPolicy", "load_project_hooks", ] diff --git a/helixharness/scripts/project_hooks_cli.py b/helixharness/scripts/project_hooks_cli.py index 2f91d8b..e483632 100755 --- a/helixharness/scripts/project_hooks_cli.py +++ b/helixharness/scripts/project_hooks_cli.py @@ -15,10 +15,12 @@ from pathlib import Path from host_runtime import HostContractError, HostRegistry -from host_runtime.project_hooks import load_project_hooks +from host_runtime.project_hooks import StaleBindingPolicy, load_project_hooks PLUGIN_ROOT = Path(__file__).resolve().parent.parent WINDOWS_COMMAND_PREFIX = "powershell.exe -NoProfile -NonInteractive -EncodedCommand " +KNOWN_LINTERS = ("invariant-check", "spec-sync-check") +LINTER_SCRIPT_SUFFIX = ("scripts", "project_linter.py") def windows_command(argv: list[str]) -> str: @@ -29,22 +31,90 @@ def windows_command(argv: list[str]) -> str: return WINDOWS_COMMAND_PREFIX + encoded +def _parse_windows_command(command: str) -> list[str] | None: + """Decode a Windows powershell-encoded command back to argv.""" + if not command.startswith(WINDOWS_COMMAND_PREFIX): + return None + try: + encoded = command.removeprefix(WINDOWS_COMMAND_PREFIX) + source = base64.b64decode(encoded, validate=True).decode("utf-16-le") + except ValueError: + return None + match = re.match(r"^& ((?:'[^']*'\s*)+);\s*exit\s+\$LASTEXITCODE\s*$", source) + if match is None: + return None + quoted = match[1].strip() + argv = [] + for token in re.findall(r"'((?:[^']|'')*)'", quoted): + argv.append(token.replace("''", "'")) + return argv + + +def _parse_posix_command(command: str) -> list[str] | None: + """Parse a POSIX shell-quoted command into argv.""" + try: + return shlex.split(command) + except ValueError: + return None + + +def _recognize_linter_name(argv: list[str]) -> str | None: + """Return the linter name if argv matches our generator shape, else None.""" + if len(argv) < 4: + return None + if not Path(argv[0]).is_absolute(): + return None + if "-X" not in argv or "utf8" not in argv: + return None + x_index = argv.index("-X") + if argv.index("utf8") != x_index + 1: + return None + script_path = None + for arg in argv: + parts = Path(arg).parts + if len(parts) >= 2 and tuple(parts[-2:]) == LINTER_SCRIPT_SUFFIX: + script_path = arg + break + if script_path is None: + return None + try: + linter_index = argv.index("--linter") + except ValueError: + return None + if linter_index + 1 >= len(argv): + return None + linter_name = argv[linter_index + 1] + if linter_name not in KNOWN_LINTERS: + return None + return linter_name + + +def recognize_linter_command(command: str, policy: StaleBindingPolicy) -> str | None: + """Return the linter name if command is our generated linter, else None. + + Under exact_args policy, returns the linter name only if argv[1:] matches exactly. + Under linter_flag policy, returns the linter name if the shape matches. + """ + if policy.recognize == "exact_args": + # Legacy behavior: caller must pass expected argv[1:] to compare. + # This branch is handled by the caller passing linter_args. + return None + argv = _parse_windows_command(command) or _parse_posix_command(command) + if argv is None: + return None + return _recognize_linter_name(argv) + + def is_bound_linter_command(command: str, linter_args: list[str]) -> bool: - """Recognize our generated command with any absolute interpreter path.""" + """Recognize our generated command with any absolute interpreter path (legacy exact_args).""" if command.startswith(WINDOWS_COMMAND_PREFIX): - try: - encoded = command.removeprefix(WINDOWS_COMMAND_PREFIX) - source = base64.b64decode(encoded, validate=True).decode("utf-16-le") - except ValueError: - return False - match = re.match(r"^& '((?:[^']|'')*)' ", source) - if match is None: + argv = _parse_windows_command(command) + if argv is None: return False - python = match[1].replace("''", "'") + python = argv[0] return Path(python).is_absolute() and command == windows_command([python, *linter_args]) - try: - argv = shlex.split(command) - except ValueError: + argv = _parse_posix_command(command) + if argv is None: return False return ( argv[1:] == linter_args @@ -72,13 +142,23 @@ def validate_events(events: dict) -> None: raise ValueError(f"missing project hook command: {event}") -def merge_payload(current: dict, required: dict, bound_linters: dict[str, tuple[str, list[str]]]) -> dict: +def merge_payload( + current: dict, + required: dict, + bound_linters: dict[str, tuple[str, list[str]]], + policy: StaleBindingPolicy, +) -> tuple[dict, list[str]]: + """Merge required hooks into current settings, returning (merged, warnings). + + Under collapse policy, duplicate shape-matched entries are removed. + """ result = copy.deepcopy(current) events = result.setdefault("hooks", {}) if not isinstance(events, dict): raise ValueError("settings.hooks must be an object") validate_events(events) validate_events(required["hooks"]) + warnings: list[str] = [] for event, expected_groups in required["hooks"].items(): groups = events.setdefault(event, []) for expected in expected_groups: @@ -93,30 +173,60 @@ def merge_payload(current: dict, required: dict, bound_linters: dict[str, tuple[ for handler in expected["hooks"]: command = handler.get("command") legacy, linter_args = bound_linters.get(command, ("", [])) if isinstance(command, str) else ("", []) + handler_linter_name = None + if policy.recognize == "linter_flag" and isinstance(command, str): + handler_linter_name = recognize_linter_command(command, policy) found = False for group in matching: kept = [] for existing in group["hooks"]: old_command = existing.get("command") - if existing.get("type") == handler["type"] and ( - old_command == command - or ( - linter_args and isinstance(old_command, str) - and (old_command == legacy or is_bound_linter_command(old_command, linter_args)) - ) - ): + if not isinstance(old_command, str) or existing.get("type") != handler["type"]: + kept.append(existing) + continue + # Check if this existing entry matches our handler + is_match = False + if policy.recognize == "linter_flag": + # Shape-based recognition + existing_linter_name = recognize_linter_command(old_command, policy) + if existing_linter_name and handler_linter_name and existing_linter_name == handler_linter_name: + is_match = True + # Also check commandWindows under shape match + if not is_match and "commandWindows" in handler: + old_windows = existing.get("commandWindows") + if isinstance(old_windows, str) and recognize_linter_command(old_windows, policy) == handler_linter_name: + is_match = True + else: + # Legacy exact_args recognition + if linter_args: + if old_command == command or old_command == legacy or is_bound_linter_command(old_command, linter_args): + is_match = True + # Also check commandWindows under legacy recognition + if not is_match and "commandWindows" in handler: + old_windows = existing.get("commandWindows") + if isinstance(old_windows, str) and is_bound_linter_command(old_windows, linter_args): + is_match = True + else: + # Exact command match + if old_command == command: + is_match = True + if is_match: if found: + # Duplicate: skip it (original dedup behavior) + # Under collapse policy, also report as warning + if policy.merge == "collapse": + warnings.append(f"Removed duplicate linter handler: {old_command[:80]}") continue found = True + # Update to canonical command if command != old_command: existing["command"] = command old_windows = existing.get("commandWindows") - if ( - "commandWindows" in handler and linter_args - and isinstance(old_windows, str) - and is_bound_linter_command(old_windows, linter_args) - ): - existing["commandWindows"] = handler["commandWindows"] + if "commandWindows" in handler: + if linter_args and isinstance(old_windows, str) and is_bound_linter_command(old_windows, linter_args): + existing["commandWindows"] = handler["commandWindows"] + elif policy.recognize == "linter_flag" and isinstance(old_windows, str) and recognize_linter_command(old_windows, policy): + existing["commandWindows"] = handler["commandWindows"] for key in ("commandWindows", "shell"): if key in handler: existing.setdefault(key, handler[key]) @@ -124,10 +234,10 @@ def merge_payload(current: dict, required: dict, bound_linters: dict[str, tuple[ group["hooks"] = kept if not found: matching[0]["hooks"].append(copy.deepcopy(handler)) - return result + return result, warnings -def project_hooks(repo: Path, platform: str, action: str) -> dict: +def project_hooks(repo: Path, platform: str, action: str, strict: bool = False) -> dict: manifest = HostRegistry.discover(PLUGIN_ROOT / "hosts").get(platform) if manifest is None: raise ValueError("unsupported_host") @@ -172,9 +282,15 @@ def project_hooks(repo: Path, platform: str, action: str) -> dict: handler["command"] = shlex.join(argv) handler["shell"] = "bash" bound_linters[handler["command"]] = (legacy, argv[1:]) - merged = merge_payload(current, required, bound_linters) + merged, merge_warnings = merge_payload(current, required, bound_linters, contract.stale_binding_policy) if action == "check": if not exists or original != merged: + if contract.stale_binding_policy.check == "warn" and not strict: + return { + "status": "pass", + "settings_file": contract.settings_file, + "warnings": merge_warnings if merge_warnings else ["Project hooks missing or duplicated"], + } raise ValueError("project_hooks_missing_or_duplicated") return {"status": "pass", "settings_file": contract.settings_file} changed = not exists or original != merged @@ -191,21 +307,25 @@ def project_hooks(repo: Path, platform: str, action: str) -> dict: os.replace(temporary, target) finally: Path(temporary).unlink(missing_ok=True) - return { + result = { "status": "merged", "changed": changed, "settings_file": contract.settings_file, } + if merge_warnings: + result["warnings"] = merge_warnings + return result def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--repo-root", type=Path, required=True) parser.add_argument("--platform", required=True) + parser.add_argument("--strict", action="store_true", help="Treat warnings as failures in check mode") parser.add_argument("action", choices=("merge", "check")) args = parser.parse_args() try: - result = project_hooks(args.repo_root, args.platform, args.action) + result = project_hooks(args.repo_root, args.platform, args.action, strict=args.strict) except (OSError, ValueError, HostContractError) as exc: print(json.dumps({"status": "blocked", "reason": str(exc)})) return 1 diff --git a/helixharness/scripts/tests/test_project_hooks.py b/helixharness/scripts/tests/test_project_hooks.py index 24ce639..d21665f 100644 --- a/helixharness/scripts/tests/test_project_hooks.py +++ b/helixharness/scripts/tests/test_project_hooks.py @@ -211,6 +211,110 @@ def test_complete_required_hooks_do_not_hide_invalid_user_events(self): project_hooks(repo, "codex", action) self.assertEqual(raw, target.read_text()) + def test_qoder_collapse_removes_version_dir_duplicates(self): + """Under linter_flag policy, entries differing only in --repo-root collapse.""" + from project_hooks_cli import project_hooks + + with tempfile.TemporaryDirectory() as directory: + repo = Path(directory) + target = repo / ".qoder/settings.json" + target.parent.mkdir() + # Simulate stale entries from two different plugin versions + stale = { + "hooks": { + "PostToolUse": [ + { + "matcher": "Write|Edit|NotebookEdit", + "hooks": [ + { + "type": "command", + "command": f"'{sys.executable}' -X utf8 /old/version/1.0.0/scripts/project_linter.py --repo-root /tmp/old --linter invariant-check", + }, + { + "type": "command", + "command": f"'{sys.executable}' -X utf8 /new/version/1.1.0/scripts/project_linter.py --repo-root /tmp/new --linter invariant-check", + }, + { + "type": "command", + "command": f"'{sys.executable}' -X utf8 /old/version/1.0.0/scripts/project_linter.py --repo-root /tmp/old --linter spec-sync-check", + }, + { + "type": "command", + "command": f"'{sys.executable}' -X utf8 /new/version/1.1.0/scripts/project_linter.py --repo-root /tmp/new --linter spec-sync-check", + }, + ], + } + ] + } + } + target.write_text(json.dumps(stale)) + result = project_hooks(repo, "qoder", "merge") + self.assertTrue(result["changed"]) + self.assertIn("warnings", result) + # Should have warnings about removed duplicates + self.assertGreater(len(result["warnings"]), 0) + merged = json.loads(target.read_text()) + handlers = merged["hooks"]["PostToolUse"][0]["hooks"] + # Should collapse to 2 handlers (one per linter) + self.assertEqual(2, len(handlers)) + # Check that both linters are present + linter_names = set() + for handler in handlers: + command = handler["command"] + if "--linter invariant-check" in command: + linter_names.add("invariant-check") + elif "--linter spec-sync-check" in command: + linter_names.add("spec-sync-check") + self.assertEqual({"invariant-check", "spec-sync-check"}, linter_names) + + def test_qoder_check_warns_by_default_fails_with_strict(self): + """Under warn policy, check returns warnings; --strict makes it fail.""" + from project_hooks_cli import project_hooks + + with tempfile.TemporaryDirectory() as directory: + repo = Path(directory) + target = repo / ".qoder/settings.json" + target.parent.mkdir() + # Missing hooks entirely + result = project_hooks(repo, "qoder", "check", strict=False) + self.assertEqual("pass", result["status"]) + self.assertIn("warnings", result) + # With strict, should raise + with self.assertRaisesRegex(ValueError, "project_hooks_missing_or_duplicated"): + project_hooks(repo, "qoder", "check", strict=True) + + def test_qoder_does_not_claim_shape_mismatched_commands(self): + """Commands with project_linter.py but wrong flags are not recognized.""" + from project_hooks_cli import project_hooks + + with tempfile.TemporaryDirectory() as directory: + repo = Path(directory) + target = repo / ".qoder/settings.json" + target.parent.mkdir() + user_hook = { + "type": "command", + "command": f"'{sys.executable}' /some/path/scripts/project_linter.py --unknown-flag", + "timeout": 42, + } + settings = { + "hooks": { + "PostToolUse": [ + { + "matcher": "Write|Edit|NotebookEdit", + "hooks": [user_hook], + } + ] + } + } + target.write_text(json.dumps(settings)) + project_hooks(repo, "qoder", "merge") + merged = json.loads(target.read_text()) + handlers = merged["hooks"]["PostToolUse"][0]["hooks"] + # User hook should be preserved (not recognized as our linter) + self.assertEqual(3, len(handlers)) # user + 2 linters + self.assertEqual(42, handlers[0]["timeout"]) + self.assertEqual(user_hook["command"], handlers[0]["command"]) + if __name__ == "__main__": unittest.main() From 925bcea80329e2135bd690c51e824278ba2e3c91 Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Tue, 24 Nov 2026 19:23:55 +0800 Subject: [PATCH 07/37] =?UTF-8?q?docs(qoder):=20=E6=8A=8A=20Qoder=20?= =?UTF-8?q?=E5=AE=89=E8=A3=85=E8=AF=B4=E6=98=8E=E8=A1=A5=E5=88=B0=E5=85=AC?= =?UTF-8?q?=E5=BC=80=E5=85=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Qoder 适配已经落到特性分支,但根 README 与 docs/installation.md 的宿主 清单一直停留在 Codex / Claude Code / Cursor / OpenCode 四项,新用户 clone 后从 GitHub 首页看不到 Qoder 支持,只有点进 helixharness/ 二级目录才能发 现 hosts/qoder/installer.md。 - 中英 README:宿主清单、Requirements、Quick start 段落、示例分组与 Roadmap 均加入 Qoder;新增一段 Qoder 本地 ZIP 安装说明,并链接 hosts/qoder/installer.md。 - docs/installation.md:Requirements、Install from GitHub 提示加入 Qoder; 在 Cursor 与 Updates 之间插入 `## Qoder` 小节(带 `#qoder` 锚点), 覆盖打包脚本、App / 会话内两种安装入口、hooks 审阅、版本目录与 cache 语义、unsupported 的 plugin_update 及 Host Kit 陈旧绑定收敛行为; Updates、Uninstall 与中文说明同步补齐 Qoder 分支,保持中英对齐。 --- README.md | 20 ++++++++-------- README.zh-CN.md | 20 ++++++++-------- docs/installation.md | 55 ++++++++++++++++++++++++++++++++++++++------ 3 files changed, 70 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index ebfe578..d08e478 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, Claude Code, Cursor and [OpenCode (macOS Stable)](docs/opencode-testing.md).** 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, Cursor, [OpenCode (macOS Stable)](docs/opencode-testing.md) and [Qoder](helixharness/hosts/qoder/installer.md).** 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 / Cursor / [OpenCode (macOS Stable)](docs/opencode-testing.md) · Single repo / multi-repo Workspace · Apache-2.0** +**9 commands · Codex / Claude Code / Cursor / [OpenCode (macOS Stable)](docs/opencode-testing.md) / [Qoder](helixharness/hosts/qoder/installer.md) · 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,11 +63,11 @@ Knowledge accumulates as **reviewable repository documents**. You control what b ### 1. Install the plugin -Requirements: Python 3.10+, Git and a plugin-capable Codex, Claude Code, Cursor or OpenCode installation (macOS, 2.3.2; see the [support matrix](docs/opencode-testing.md)). 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, Cursor, OpenCode installation (macOS, 2.3.2; see the [support matrix](docs/opencode-testing.md)) or Qoder Desktop / CLI. Make sure the host is signed in or has its model configuration set up and is working normally. For macOS and native Windows setup, interpreter detection and host-specific requirements, see [platform support](docs/platform-support.md). Windows Codex uses PowerShell; Windows Claude Code uses Git for Windows Bash. Cursor native acceptance currently covers macOS; Windows Cursor is outside this release's verified scope. -After the repository is public, install Codex and Claude Code plugins with the terminal commands below. Cursor uses the marketplace UI described afterward. These routes do not require a manual source clone: +After the repository is public, install Codex and Claude Code plugins with the terminal commands below. Cursor uses the marketplace UI described afterward. Qoder installs through a locally built ZIP because it has no marketplace CLI. These marketplace routes do not require a manual source clone: ```bash # Codex @@ -85,6 +85,8 @@ Cursor users install `helix` from their Cursor marketplace through **Customize OpenCode installation was verified with 2.3.2: clone this repository and configure the absolute `helixharness/` subdirectory in `opencode.json(c)`. Follow the [local-directory installation steps](docs/installation.md#opencode-local-directory-installation-verified-with-232); this repository is not installed with native `plugin add`. +**Qoder:** Qoder's App install tool only consumes a plugin ZIP, so build one locally and install it. Clone the repository, run `python3 scripts/package_qoder_plugin.py` inside `helixharness/` to produce `dist/helix-.zip`, then pick that ZIP in Qoder's **Extensions → Install local plugin** panel (or ask the assistant to call `qoder-settings.install_extension`). Open a new session afterwards — plugin manifests, skills, agents and hooks load at session start. Qoder has no marketplace CLI, so `/helix:update` is `unsupported`; upgrades reinstall a new ZIP. See the [Qoder installer](helixharness/hosts/qoder/installer.md) for packaging details, capability boundaries and acceptance checks. + **OpenCode Stable support (macOS, 2.3.2):** See the [support matrix](docs/opencode-testing.md) for the current source candidate’s scope and boundaries. OpenCode 2.2.2 and 2.3.0 have automated compatibility coverage only. The plugin registers native `helix:` commands, `helix-` method skills and `helix-` roles. Commands, native `skill` tool results, Skill mentions and native Skill activation bind the requesting session's repository. Unbound Skill content is blocked when session lookup or directory validation fails. On 2026-11-20, OpenCode 2.3.2 with DeepSeek completed one synthetic single-repository Init → Propose → Apply → Archive lifecycle, with operator confirmations and a controlled contract amendment. On 2026-11-23, OpenCode 2.3.2 with DeepSeek also completed assisted synthetic two-repository Workspace and standalone UT runs; UT classification validation and protected atomic publication were subsequently fixed and passed a fresh real-model UT run without corrective operator prompts. [Targeted real-model tests on synthetic Workspaces](helixharness/opencode/tests/README.md#recovery-and-auxiliary-workflow-acceptance-2026-11-23) also verified native Apply and partial Archive cancellation followed by fresh-session recovery, plus dependent-dispatch blocking after an injected native context-hook failure. Full production-project acceptance, unattended protocol compliance and full TUI/desktop UI acceptance remain outstanding; see [targeted terminal UI acceptance](helixharness/opencode/tests/README.md#targeted-terminal-ui-acceptance-2026-11-23) for the tested scope. Workspace Apply uses `helix-worker` for `may_delegate` RepoJobs and requires `experimental.subagent_depth >= 2`; independent reviewers remain read-only leaf jobs. Insufficient depth blocks the RepoJob rather than bypassing review. @@ -99,9 +101,9 @@ The root marketplace installs the `helixharness/` plugin, not the platform. For 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. On Claude Code, Codex and Cursor, review the plugin hooks through the host's native interface; OpenCode registers its surfaces from the plugin package. Then enter the commands for your host in the conversation. +Open a new agent session in the **application repository** you want to develop. On Claude Code, Codex, Cursor and Qoder, review the plugin hooks through the host's native interface; OpenCode registers its surfaces from the plugin package. Then enter the commands for your host in the conversation. -Codex / Claude Code / OpenCode: +Codex / Claude Code / OpenCode / Qoder: ```text /helix:init @@ -115,7 +117,7 @@ Cursor: /helix-propose task-filter ./requirements/task-filter.md --loop ``` -Cursor uses `/helix-` throughout; Codex, Claude Code and OpenCode use `/helix:`. Command arguments and workflows are the same. +Cursor uses `/helix-` throughout; Codex, Claude Code, OpenCode and Qoder use `/helix:`. On Qoder the nine entries come from the plugin's `hosts/qoder/skills/` thin entries rather than a native command surface, but the invocation text and arguments are the same. Use the [self-contained task-filter example](examples/README.md) to get a starter project, requirement and acceptance check. `--loop` runs Propose → Apply → Archive, pausing for decisions or blockers. It does not publish or deploy your code. @@ -222,10 +224,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 to more hosts beyond Codex, Claude Code, Cursor and [OpenCode (macOS Stable)](docs/opencode-testing.md) so teams can use HelixHarness with more of their preferred tools. +- **More coding agents.** Extend support to more hosts beyond Codex, Claude Code, Cursor, [OpenCode (macOS Stable)](docs/opencode-testing.md) and [Qoder](helixharness/hosts/qoder/installer.md) 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 source supports Codex, Claude Code and Cursor, plus [OpenCode within its macOS Stable scope](docs/opencode-testing.md), using the Propose → Apply → Archive workflow. Cursor native-client acceptance is tracked separately from automated contract tests. Share concrete use cases through the [contribution guide](CONTRIBUTING.md) to help shape these directions. +These are planned capabilities. The source supports Codex, Claude Code and Cursor, plus [OpenCode within its macOS Stable scope](docs/opencode-testing.md) and [Qoder through local ZIP installation](helixharness/hosts/qoder/installer.md), using the Propose → Apply → Archive workflow. Cursor native-client acceptance is tracked separately from automated contract tests. 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 c2ebc06..00a382b 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -6,11 +6,11 @@ > > 为适配而生,为进化而设计。让团队的工程 DNA,融入 AI 研发。 -**HelixHarness 帮助团队在 Codex、Claude Code、Cursor 与 [OpenCode(macOS Stable)](docs/opencode-testing.md)上构建专属的 AI Coding Harness。** 将你的业务知识、工程规范与研发工作流带入 Agent 的工作过程,从需求分析、实现、测试、评审到归档,让 AI 按团队的方式开展研发,并将经验证的经验留在项目中,供下一个需求复用。 +**HelixHarness 帮助团队在 Codex、Claude Code、Cursor、[OpenCode(macOS Stable)](docs/opencode-testing.md) 与 [Qoder](helixharness/hosts/qoder/installer.md) 上构建专属的 AI Coding Harness。** 将你的业务知识、工程规范与研发工作流带入 Agent 的工作过程,从需求分析、实现、测试、评审到归档,让 AI 按团队的方式开展研发,并将经验证的经验留在项目中,供下一个需求复用。 从插件开始即可。当你希望改进 Harness 本身时,可选的 **helixharness-platform** 帮助框架维护者观测使用过程、对比框架版本,并在采纳候选改进前验证效果。 -**9 个命令 · Codex / Claude Code / Cursor / [OpenCode(macOS Stable)](docs/opencode-testing.md) · 单仓 / 多仓 Workspace · Apache-2.0** +**9 个命令 · Codex / Claude Code / Cursor / [OpenCode(macOS Stable)](docs/opencode-testing.md) / [Qoder](helixharness/hosts/qoder/installer.md) · 单仓 / 多仓 Workspace · Apache-2.0** [快速开始](#快速开始) · [命名故事](#名字背后的故事) · [框架亮点](#框架亮点) · [框架迭代平台](#围绕-helixharness-框架的迭代平台) · [使用指南](docs/user-guide.zh-CN.md) @@ -63,11 +63,11 @@ Knowledge 与 Harness 通过索引引导上下文加载,Specs 保存每个需 ### 1. 安装插件 -需要 Python 3.10+、Git,以及支持插件的 Codex、Claude Code、Cursor 或 OpenCode(macOS、2.3.2;见[支持矩阵](docs/opencode-testing.md))。先确保宿主已完成登录或模型配置,能够正常使用。 +需要 Python 3.10+、Git,以及支持插件的 Codex、Claude Code、Cursor、OpenCode(macOS、2.3.2;见[支持矩阵](docs/opencode-testing.md))或 Qoder Desktop / CLI。先确保宿主已完成登录或模型配置,能够正常使用。 macOS 与原生 Windows 的依赖、解释器探测及宿主要求见[跨平台说明](docs/platform-support.md)。Windows Codex 使用 PowerShell;Windows Claude Code 使用 Git for Windows Bash。Cursor 实机验收目前覆盖 macOS,Windows Cursor 不在本期已验证范围。 -仓库公开后,Codex 和 Claude Code 使用下方终端命令,Cursor 使用随后说明的市场界面安装;这些方式无需先手动克隆源码: +仓库公开后,Codex 和 Claude Code 使用下方终端命令,Cursor 使用随后说明的市场界面安装,Qoder 使用随后说明的本地 ZIP 安装流程;市场安装方式无需先手动克隆源码: ```bash # Codex @@ -85,6 +85,8 @@ Cursor 用户通过 **Customize → helix → Install** 从市场安装,随后 OpenCode 安装已在 2.3.2 验证:克隆本仓库后,在 `opencode.json(c)` 中配置 `helixharness/` 子目录的绝对路径。详见[本地目录安装步骤](docs/installation.md#opencode-local-directory-installation-verified-with-232);本仓库不使用原生 `plugin add` 安装。 +**Qoder:** Qoder 的安装工具只消费插件 ZIP,需要先本地打包再安装。克隆本仓库后,在 `helixharness/` 内运行 `python3 scripts/package_qoder_plugin.py` 生成 `dist/helix-.zip`,在 Qoder **扩展 → 安装本地插件** 面板选择该 ZIP(或让会话调用 `qoder-settings.install_extension`)。安装完成后须新开会话——插件清单、skills、agents 与 hook 都在会话启动时装载。Qoder 没有等价 marketplace CLI,`/helix:update` 声明为 `unsupported`,升级需重装新版 ZIP。打包细节、能力边界与验收清单见 [Qoder 安装说明](helixharness/hosts/qoder/installer.md)。 + **OpenCode Stable 支持(macOS、2.3.2):** 当前源码候选的支持范围与边界见[支持矩阵](docs/opencode-testing.md)。OpenCode 2.2.2、2.3.0 仅有自动化兼容覆盖。 插件注册原生 `helix:` 命令、`helix-` 方法 Skill 和 `helix-` 角色。命令、原生 `skill` 工具结果、Skill mention 与原生 Skill 激活均按请求会话绑定仓库目录;会话查询或目录校验失败时阻断未绑定的 Skill 正文。2026-11-20 已在 OpenCode 2.3.2 + DeepSeek 上完成一次合成单仓 Init → Propose → Apply → Archive 真实模型闭环,包含操作者确认和一次受控合同修订;2026-11-23 又完成了 OpenCode 2.3.2 + DeepSeek 的操作者辅助合成双仓 Workspace 与独立 UT 验证;后续已修复 UT 分类校验与原子发布保护,并通过无纠正提醒的真实模型复验。[合成 Workspace 的专项真实模型验证](helixharness/opencode/tests/README.md#recovery-and-auxiliary-workflow-acceptance-2026-11-23)还覆盖了 Apply 与部分 Archive 原生取消后新会话恢复,以及注入原生 context hook 故障后阻断依赖派发。完整生产业务项目、无人干预时的协议遵守与完整 TUI/桌面 UI 验收仍未完成;已覆盖范围见[定向终端 UI 验收](helixharness/opencode/tests/README.md#targeted-terminal-ui-acceptance-2026-11-23)。Workspace Apply 的 `may_delegate` RepoJob 使用 `helix-worker`,需要 `experimental.subagent_depth >= 2`;独立 reviewer 保持只读 leaf。深度不足时阻塞该 RepoJob,不得绕过评审。 @@ -97,9 +99,9 @@ OpenCode 适配使用原生工具和会话 Hook,但未提供等价的 SessionS ### 2. 完成一个小需求 -在要开发的**业务仓库**新开 Agent 会话,Claude Code、Codex 和 Cursor 通过宿主原生界面审阅插件 hooks;OpenCode 由插件包注册入口。然后在对话中输入对应宿主的命令。 +在要开发的**业务仓库**新开 Agent 会话,Claude Code、Codex、Cursor 与 Qoder 通过宿主原生界面审阅插件 hooks;OpenCode 由插件包注册入口。然后在对话中输入对应宿主的命令。 -Codex / Claude Code / OpenCode: +Codex / Claude Code / OpenCode / Qoder: ```text /helix:init @@ -113,7 +115,7 @@ Cursor: /helix-propose task-filter ./requirements/task-filter.md --loop ``` -Cursor 全部使用 `/helix-`,Codex、Claude Code 和 OpenCode 使用 `/helix:`;命令参数和工作流相同。 +Cursor 全部使用 `/helix-`,Codex、Claude Code、OpenCode 与 Qoder 使用 `/helix:`;命令参数和工作流相同。Qoder 的九个入口来自插件 `hosts/qoder/skills/` 下的薄入口,而不是宿主原生命令面,但输入形式和参数一致。 [任务筛选示例](examples/README.md)提供起始项目、需求和独立验收脚本,可直接跟着操作。`--loop` 串联 Propose → Apply → Archive,遇到需要决策的问题或阻断时暂停,不包含代码发布或部署。 @@ -220,10 +222,10 @@ python -m web_ui.demo --port 7860 接下来计划围绕两个方向,让更多团队按自己的研发方式使用 HelixHarness: -- **支持更多 Coding Agent**:在 Codex、Claude Code、Cursor 与 [OpenCode(macOS Stable)](docs/opencode-testing.md)的基础上继续扩展宿主适配,让团队能在更多熟悉的工具中使用 HelixHarness。 +- **支持更多 Coding Agent**:在 Codex、Claude Code、Cursor、[OpenCode(macOS Stable)](docs/opencode-testing.md) 与 [Qoder](helixharness/hosts/qoder/installer.md) 的基础上继续扩展宿主适配,让团队能在更多熟悉的工具中使用 HelixHarness。 - **支持工作流配置**:允许团队配置工作流阶段及其顺序,适配自身的研发流程。 -以上为规划方向。当前源码支持 Codex、Claude Code 和 Cursor,另提供 [OpenCode macOS Stable 支持](docs/opencode-testing.md),采用 Propose → Apply → Archive 工作流。Cursor 原生客户端验收与自动化合同测试分别记录。欢迎通过[贡献指南](CONTRIBUTING.md)分享具体使用场景,帮助完善这些方向。 +以上为规划方向。当前源码支持 Codex、Claude Code 和 Cursor,另提供 [OpenCode macOS Stable 支持](docs/opencode-testing.md) 与 [Qoder 本地 ZIP 安装](helixharness/hosts/qoder/installer.md),采用 Propose → Apply → Archive 工作流。Cursor 原生客户端验收与自动化合同测试分别记录。欢迎通过[贡献指南](CONTRIBUTING.md)分享具体使用场景,帮助完善这些方向。 ## 文档与贡献 diff --git a/docs/installation.md b/docs/installation.md index 5d73e39..80b8cd3 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -4,7 +4,7 @@ ## Requirements -Python 3.10+, Git and a plugin-capable Codex, Claude Code, Cursor or OpenCode installation (macOS, 2.3.2; see the [support matrix](opencode-testing.md)) are required. Make sure the host is signed in or has its model configuration set up and is working normally. The platform is optional. Cursor desktop support follows the release scope and limitations below. +Python 3.10+, Git and a plugin-capable Codex, Claude Code, Cursor, OpenCode installation (macOS, 2.3.2; see the [support matrix](opencode-testing.md)) or Qoder Desktop / CLI are required. Make sure the host is signed in or has its model configuration set up and is working normally. The platform is optional. Cursor desktop support follows the release scope and limitations below; Qoder installs through a locally built plugin ZIP because the App has no marketplace CLI. The shared runtime supports macOS, native Windows and Linux; see [platform support and verification](platform-support.md). Windows Codex uses the PowerShell entrypoint, while Claude Code hooks require Git for Windows Bash. Cursor native acceptance currently covers macOS; Windows Cursor is outside this release's verified scope. @@ -14,7 +14,7 @@ This edition uses only the HelixHarness identifiers: `helix@helixharness-marketp ## Install from GitHub after publication -For Codex and Claude Code, run the following terminal commands. For Cursor, use the [marketplace flow](#cursor). These marketplace routes do not require a manual source clone: +For Codex and Claude Code, run the following terminal commands. For Cursor, use the [marketplace flow](#cursor). For Qoder, build a local ZIP and install it through the App — see [Qoder](#qoder). These marketplace routes do not require a manual source clone: ```bash # Codex @@ -118,22 +118,63 @@ Statistics require explicit consent and current-session identity. Missing identi 统计需要明确授权和本次会话身份,缺身份时跳过统计并继续业务,Token 归属可为 partial/unavailable。关闭授权清理当前仓库,关窗及后续启动清理尽力执行。CLI、Cloud、完整 D2C 不在本期完整验收范围,详见[支持与验证边界](cursor-testing.md)。 + + +## Qoder + +Qoder Desktop and Qoder CLI only consume plugin ZIPs through the App install tool, so HelixHarness ships a packaging script instead of a marketplace entry. Clone the repository, then from the plugin directory build the ZIP: + +```bash +cd helixharness +python3 scripts/package_qoder_plugin.py # produces dist/helix-.zip +``` + +The ZIP root is the plugin root and contains only the Qoder-facing surface: `.qoder-plugin/plugin.json`, `agents/`, `skills/`, `hosts/qoder/skills/`, `hosts/qoder/hooks.json` (copied to `hooks/hooks.json` in the package), plus `commands/`, `reference/`, `scripts/`, `templates/` and `workflows/` shared with other hosts. Codex, Claude Code, Cursor and openCode surfaces, `__pycache__` and local state are excluded. Each `agents/*.md` gets a `name` frontmatter matching the file name, because Qoder registers subagents by `name`. + +Install through one of: + +- **Qoder App**: Extensions panel → Install local plugin → pick `dist/helix-.zip`. +- **In-session tool**: ask the assistant to call `qoder-settings.install_extension` with `{source: "local", kind: "plugin", filePath: "/absolute/path/helix-.zip"}`. + +After installation, review and trust the plugin hooks in the App, then open a new session: plugin manifest, skills, agents and hooks load at session start, and a session already started continues using the previously bound plugin root. Qoder's `.qoder-plugin/plugin.json` `version` drives the cache directory `/plugins/cache/local/helix//`, so each release bumps the version and the App replaces the older cache; coexisting versions inside the same session are not supported. Uninstall through Extensions → Installed → the plugin → Delete. + +Because Qoder has no marketplace CLI equivalent, the plugin's `plugin_update` adapter is declared `unsupported`, and `/helix:update` returns a blocked status. Upgrades reinstall a new ZIP built from an updated source copy. The Qoder Host Kit declares a shape-based stale-binding policy so re-running `/helix:init` collapses the linter handlers from earlier version directories in `.qoder/settings.json` and reports residual drift as warnings (`--strict` promotes them to failures); user-owned hooks are never touched. See the [Qoder installer contract](../helixharness/hosts/qoder/installer.md) for the full packaging list, capability boundaries and acceptance checks. + +Qoder Desktop 与 Qoder CLI 只能通过 App 安装工具消费插件 ZIP,因此 HelixHarness 提供本地打包脚本而不是市场条目。克隆仓库后在插件目录内运行: + +```bash +cd helixharness +python3 scripts/package_qoder_plugin.py # 产出 dist/helix-.zip +``` + +ZIP 根即插件根,只包含 Qoder 表面:`.qoder-plugin/plugin.json`、`agents/`、`skills/`、`hosts/qoder/skills/`、`hosts/qoder/hooks.json`(打包时复制为 `hooks/hooks.json`),并保留与其它宿主共享的 `commands/`、`reference/`、`scripts/`、`templates/` 与 `workflows/`。Codex、Claude Code、Cursor、openCode 的表面、`__pycache__` 与本地状态都在排除之列。每个 `agents/*.md` 会被注入与文件名一致的 `name` frontmatter——Qoder 按 `name` 注册子代理角色。 + +安装方式二选一: + +- **Qoder App**:扩展面板 → 安装本地插件 → 选择 `dist/helix-.zip`。 +- **会话内工具**:让助手调用 `qoder-settings.install_extension`,参数 `{source: "local", kind: "plugin", filePath: "/绝对路径/helix-.zip"}`。 + +安装后先在 App 内审阅并信任插件 hooks,然后开新会话:插件清单、skills、agents 与 hook 都在会话启动时装载;已开启的会话仍沿用之前绑定的 `plugin_root`,不会随更新刷新。Qoder 的 `.qoder-plugin/plugin.json` `version` 决定缓存目录 `/plugins/cache/local/helix//`,每次发布递增版本号,App 会替换旧版本缓存,同一会话内不保证多版本共存。卸载在 扩展 → 已安装 → 该插件 → … → 删除 完成。 + +Qoder 没有等价 marketplace CLI,插件的 `plugin_update` 声明为 `unsupported`,`/helix:update` 会返回阻断状态;升级须重新打包并安装新版 ZIP。Qoder Host Kit 声明了基于形状的陈旧绑定策略,重跑 `/helix:init` 时按 `--linter` 参数与脚本路径识别早先写入的检查命令,无论版本目录或路径写法怎么变都会自动收敛重复条目,`check` 默认把残留差异报为 warning,`--strict` 才判失败;用户自己的其他 Hook 不受影响。完整打包列表、能力边界与验收清单见 [Qoder 安装合同](../helixharness/hosts/qoder/installer.md)。 + ## Updates -On Claude Code and Codex, run `/helix:update` in the host conversation. The plugin checks the configured marketplace, shows an available update and uses the host adapter after authorization. Cursor uses `/helix-update` for registered Helix-managed local installations on macOS/Linux, following the same check, confirmation and one-time authorization protocol. Manual copies and Cursor marketplace installations use their original update mechanism. OpenCode's `/helix:update` supports clean source checkouts with an explicit Git upstream through the same confirmation protocol, pins the approved commit and only fast-forwards. Dirty, detached or package-managed copies require their original manual mechanism. Restart or reload OpenCode and open a new session after an update. Rollback remains an explicit source-revision selection, not an automatic reset; see the [OpenCode update and rollback steps](../helixharness/hosts/opencode/installer.md#更新回退与卸载). +On Claude Code and Codex, run `/helix:update` in the host conversation. The plugin checks the configured marketplace, shows an available update and uses the host adapter after authorization. Cursor uses `/helix-update` for registered Helix-managed local installations on macOS/Linux, following the same check, confirmation and one-time authorization protocol. Manual copies and Cursor marketplace installations use their original update mechanism. OpenCode's `/helix:update` supports clean source checkouts with an explicit Git upstream through the same confirmation protocol, pins the approved commit and only fast-forwards. Dirty, detached or package-managed copies require their original manual mechanism. Restart or reload OpenCode and open a new session after an update. Rollback remains an explicit source-revision selection, not an automatic reset; see the [OpenCode update and rollback steps](../helixharness/hosts/opencode/installer.md#更新回退与卸载). Qoder declares `plugin_update` as `unsupported` because the App has no marketplace CLI — upgrade by bumping `.qoder-plugin/plugin.json` `version`, rebuilding the ZIP with `scripts/package_qoder_plugin.py` and installing it through the App; the new version replaces the older cache and any session opened before the install continues using the previously bound plugin root. - **Marketplace Git source (Codex/Claude Code):** the host refreshes the configured repository; use the same marketplace for later versions. OpenCode's clone-based directory configuration follows the local-source steps below. - **Local source:** update the source copy yourself first, then restart or reload the host. 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. +- **Qoder ZIP:** rebuild and reinstall through the App; `/helix:update` returns a blocked status. - 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`; for this repository's OpenCode directory configuration, remove only its entry from the `plugins` array and restart or reload OpenCode. 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 this repository's OpenCode directory configuration, remove only its entry from the `plugins` array and restart or reload OpenCode; for Qoder, uninstall through Extensions → Installed → the plugin → … → Delete. 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、Cursor 或 OpenCode(macOS、2.3.2;见[支持矩阵](opencode-testing.md))。Cursor 使用上面的 [Cursor 独立安装流程](#cursor-preview)。先确保宿主已完成登录或模型配置,能够正常使用。平台不是安装插件的前置条件。共享运行时的 Windows 支持不代表 Windows Cursor 已完成验收;Cursor 实机验收目前覆盖 macOS。 +需要 Python 3.10+、Git,以及支持插件的 Codex、Claude Code、Cursor、OpenCode(macOS、2.3.2;见[支持矩阵](opencode-testing.md))或 Qoder。Cursor 使用上面的 [Cursor 独立安装流程](#cursor-preview),Qoder 使用上面的 [Qoder 本地 ZIP 安装流程](#qoder)。先确保宿主已完成登录或模型配置,能够正常使用。平台不是安装插件的前置条件。共享运行时的 Windows 支持不代表 Windows Cursor 已完成验收;Cursor 实机验收目前覆盖 macOS。 **OpenCode Stable 支持(macOS、2.3.2):** 当前源码候选的支持范围与边界见[支持矩阵](opencode-testing.md)。OpenCode 2.2.2、2.3.0 仅有自动化兼容覆盖。 @@ -141,9 +182,9 @@ Use the host's plugin management to uninstall `helix@helixharness-marketplace`; OpenCode 适配使用原生工具和会话 Hook,但未提供等价的 SessionStart/Stop/失败/会话结束业务保证。任务跟踪通过 `scripts/task_plan.py` 原子更新同一份 `tasks.md`。统计在明确授权后记录阶段事实和工作流轨迹,不采集原始会话,token 和未观察到的工具次数保持未知。`/helix:update` 对有明确 Git upstream 的干净源码安装执行既有确认协议,锁定 commit 并仅快进;有本地修改、游离版本或包管理安装时不自动更新。Init 合并 `AGENTS.md`,不创建 `.opencode/` settings;插件在原生 write/edit/patch 成功后执行已有项目巡检,shell 修改仍需显式检查。d-d2c 的 Claude skill-scoped Stop/PreToolUse guard 不执行,采用无 hook / `--bare` 语义,仍须遵守用户决策、视觉验收和完成门禁。 -正式发布后,Codex 与 Claude Code 使用上面的 GitHub 安装命令,Cursor 使用市场界面流程,这些市场安装方式无需先手动克隆源码。OpenCode 的安装已在 2.3.2 验证:按[本地目录安装步骤](#opencode-local-directory-installation-verified-with-232)先克隆本仓库,再将 `helixharness/` 子目录的绝对路径加入项目或全局 `opencode.json(c)` 的 `plugins`;保留已有配置和其他插件,无需 `bun install`,随后重启或重新加载并新开会话。该版本原生 `plugin add` 不接受绝对本地目录或 Git 子目录后缀;其他版本须另行核验。发布前测试或修改插件时,使用[开发者安装(本地源码)](#developer-installation):先下载或克隆源码;Codex/Claude Code 从**包含两个子项目的根目录**添加本地市场,OpenCode 继续使用上述本地目录配置。根市场指向 `./helixharness`,不会安装平台。独立插件副本仍可添加插件目录本身;同名市场只保留一个来源。 +正式发布后,Codex 与 Claude Code 使用上面的 GitHub 安装命令,Cursor 使用市场界面流程,这些市场安装方式无需先手动克隆源码。Qoder 通过 App 安装本地 ZIP:克隆本仓库,在 `helixharness/` 内运行 `python3 scripts/package_qoder_plugin.py` 生成 `dist/helix-.zip`,再由 Qoder 扩展面板或 `qoder-settings.install_extension` 完成安装,之后在 App 内审阅并信任 hooks、新开一个会话;升级须重新打包并安装新版 ZIP,同一会话不会刷新已绑定的 `plugin_root`。OpenCode 的安装已在 2.3.2 验证:按[本地目录安装步骤](#opencode-local-directory-installation-verified-with-232)先克隆本仓库,再将 `helixharness/` 子目录的绝对路径加入项目或全局 `opencode.json(c)` 的 `plugins`;保留已有配置和其他插件,无需 `bun install`,随后重启或重新加载并新开会话。该版本原生 `plugin add` 不接受绝对本地目录或 Git 子目录后缀;其他版本须另行核验。发布前测试或修改插件时,使用[开发者安装(本地源码)](#developer-installation):先下载或克隆源码;Codex/Claude Code 从**包含两个子项目的根目录**添加本地市场,OpenCode 继续使用上述本地目录配置。根市场指向 `./helixharness`,不会安装平台。独立插件副本仍可添加插件目录本身;同名市场只保留一个来源。 -安装后新开会话,确认九个命令可见;Claude Code/Codex/Cursor 检查插件 hooks 已审阅并实际执行,OpenCode 检查命令展开后的当前仓库/会话 Host Context 绑定,再在业务仓库运行 `/helix:init`(Cursor 为 `/helix-init`)并检查项目文档及宿主支持的项目 hooks(OpenCode 不生成项目 hooks)。单仓 Init 还需检查非空的 `docs/harness/index.md`、`docs/knowledge/index.md`、`docs/knowledge/project-context.md` 及对应项目类型要求的其他产物,不能只看“已完成”回复。若出现 `plugin_source_mismatch`,先核对市场来源与当前安装插件,选定正确来源并新开会话,避免混用其他 checkout 或缓存版本。Claude Code/Codex 更新使用 `/helix:update`;本地来源需先自行更新源码,不能把版本识别成功当作已完成跨版本升级。Cursor 在 macOS/Linux 上使用 `/helix-update` 升级已登记的 Helix 托管本地安装,复用检查、确认与一次性授权协议;手工副本和原生市场安装仍通过原安装方式更新。 +安装后新开会话,确认九个命令可见;Claude Code/Codex/Cursor 检查插件 hooks 已审阅并实际执行,Qoder 在扩展面板审阅插件 hooks,OpenCode 检查命令展开后的当前仓库/会话 Host Context 绑定,再在业务仓库运行 `/helix:init`(Cursor 为 `/helix-init`,Qoder 亦为 `/helix:init`,来源是 `hosts/qoder/skills/` 薄入口)并检查项目文档及宿主支持的项目 hooks(OpenCode 不生成项目 hooks)。单仓 Init 还需检查非空的 `docs/harness/index.md`、`docs/knowledge/index.md`、`docs/knowledge/project-context.md` 及对应项目类型要求的其他产物,不能只看“已完成”回复。若出现 `plugin_source_mismatch`,先核对市场来源与当前安装插件,选定正确来源并新开会话,避免混用其他 checkout 或缓存版本。Claude Code/Codex 更新使用 `/helix:update`;本地来源需先自行更新源码,不能把版本识别成功当作已完成跨版本升级。Cursor 在 macOS/Linux 上使用 `/helix-update` 升级已登记的 Helix 托管本地安装,复用检查、确认与一次性授权协议;手工副本和原生市场安装仍通过原安装方式更新。Qoder 的 `plugin_update` 声明为 `unsupported`,`/helix:update` 返回阻断,升级须重新打包并安装新版 ZIP;重跑 `/helix:init` 时 Qoder 的 Host Kit 会按 `--linter` 参数与脚本路径识别自家 handler,自动收敛旧版本目录与不同路径写法留下的重复条目。 OpenCode 的本仓库安装由用户自行更新源码并重启或重新加载;回退时在源码副本切换到此前批准的版本,不能用原生 `plugin update` 替代。卸载只移除 `plugins` 中本插件的目录条目,不删除业务仓库的知识、需求或代码。固定版本与回退示例见 [OpenCode 安装说明](../helixharness/hosts/opencode/installer.md#更新回退与卸载)。 From da026fc97fc0a80d0d2067dd43d2d4e64cf08932 Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Tue, 24 Nov 2026 19:56:07 +0800 Subject: [PATCH 08/37] =?UTF-8?q?test(qoder):=20=E7=94=A8=20argv=20?= =?UTF-8?q?=E8=A7=A3=E6=9E=90=E6=96=AD=E8=A8=80=20linter=20=E5=90=8D?= =?UTF-8?q?=EF=BC=8C=E9=81=BF=E5=85=8D=20Windows=20=E4=B8=8B=20EncodedComm?= =?UTF-8?q?and=20=E8=AF=AF=E6=8C=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Windows 上 project_hooks_cli 通过 windows_command(argv) 生成 powershell.exe -NoProfile -NonInteractive -EncodedCommand , 直接把 "--linter invariant-check" 作为子串断言会在 CI 上永远失败。 改用 _parse_windows_command/_parse_posix_command 先还原 argv, 再按 --linter 位置读取名称,让 collapse 断言跨平台成立。 --- .../scripts/tests/test_project_hooks.py | 25 +++++++++++-------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/helixharness/scripts/tests/test_project_hooks.py b/helixharness/scripts/tests/test_project_hooks.py index 9e3db9d..53b806e 100644 --- a/helixharness/scripts/tests/test_project_hooks.py +++ b/helixharness/scripts/tests/test_project_hooks.py @@ -216,13 +216,23 @@ def test_complete_required_hooks_do_not_hide_invalid_user_events(self): def test_qoder_collapse_removes_version_dir_duplicates(self): """Under linter_flag policy, entries differing only in --repo-root collapse.""" - from project_hooks_cli import project_hooks + from project_hooks_cli import _parse_posix_command, _parse_windows_command, project_hooks + + def linter_name(command: str) -> str | None: + argv = _parse_windows_command(command) or _parse_posix_command(command) + if not argv or "--linter" not in argv: + return None + idx = argv.index("--linter") + return argv[idx + 1] if idx + 1 < len(argv) else None with tempfile.TemporaryDirectory() as directory: repo = Path(directory) target = repo / ".qoder/settings.json" target.parent.mkdir() - # Simulate stale entries from two different plugin versions + # Simulate stale entries from two different plugin versions. + # Paths use sys.executable (absolute on every OS) and forward-slash + # script/repo paths — shlex.split keeps them literal so the merge + # recognizes the same shape on Windows as on POSIX runners. stale = { "hooks": { "PostToolUse": [ @@ -260,15 +270,8 @@ def test_qoder_collapse_removes_version_dir_duplicates(self): handlers = merged["hooks"]["PostToolUse"][0]["hooks"] # Should collapse to 2 handlers (one per linter) self.assertEqual(2, len(handlers)) - # Check that both linters are present - linter_names = set() - for handler in handlers: - command = handler["command"] - if "--linter invariant-check" in command: - linter_names.add("invariant-check") - elif "--linter spec-sync-check" in command: - linter_names.add("spec-sync-check") - self.assertEqual({"invariant-check", "spec-sync-check"}, linter_names) + self.assertEqual({"invariant-check", "spec-sync-check"}, + {linter_name(handler["command"]) for handler in handlers}) def test_qoder_check_warns_by_default_fails_with_strict(self): """Under warn policy, check returns warnings; --strict makes it fail.""" From 08c82837d05c842a88bc440592d8deb7339a1e40 Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Tue, 24 Nov 2026 20:57:22 +0800 Subject: [PATCH 09/37] =?UTF-8?q?test(status):=20=E5=85=B3=E9=97=AD=20gc.a?= =?UTF-8?q?uto=20=E4=B8=8E=20maintenance.auto=20=E6=B6=88=E9=99=A4=20lockf?= =?UTF-8?q?ile=20race?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit observe() 通过比较 before/after 的 rglob 快照判断 status 是否只读;macOS runner 后台偶尔会写 .git/objects/maintenance.lock 又清掉,让同一份 fixture 前后集合不一致。 在 setUp 的 GIT_CONFIG 里加上 gc.auto=0 与 maintenance.auto=0,让本测试创建的 仓库在窗口期内不再触发 git 自维护。 --- .../scripts/tests/test_project_status_regressions.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/helixharness/scripts/tests/test_project_status_regressions.py b/helixharness/scripts/tests/test_project_status_regressions.py index 274f941..0093b1e 100644 --- a/helixharness/scripts/tests/test_project_status_regressions.py +++ b/helixharness/scripts/tests/test_project_status_regressions.py @@ -16,12 +16,19 @@ class StatusObservationTest(unittest.TestCase): def setUp(self): # The shared fixture creates only a temporary synthetic Git history. - # Never invoke a developer's global commit hooks from this regression. + # Never invoke a developer's global commit hooks from this regression, + # and stop git from writing transient files (objects/maintenance.lock, + # gc.pid) into .git during the observation window — the equality check + # in observe() treats any repo-side delta as a regression. count = int(os.environ.get('GIT_CONFIG_COUNT', '0')) git_env = mock.patch.dict(os.environ, { - 'GIT_CONFIG_COUNT': str(count + 1), + 'GIT_CONFIG_COUNT': str(count + 3), f'GIT_CONFIG_KEY_{count}': 'core.hooksPath', f'GIT_CONFIG_VALUE_{count}': os.devnull, + f'GIT_CONFIG_KEY_{count + 1}': 'gc.auto', + f'GIT_CONFIG_VALUE_{count + 1}': '0', + f'GIT_CONFIG_KEY_{count + 2}': 'maintenance.auto', + f'GIT_CONFIG_VALUE_{count + 2}': '0', }) git_env.start() self.addCleanup(git_env.stop) From c8a733fd0053ecb44122618d7404066c5a33b06f Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Tue, 24 Nov 2026 20:57:25 +0800 Subject: [PATCH 10/37] =?UTF-8?q?ci(windows):=20=E6=8A=8A=20Git\usr\bin=20?= =?UTF-8?q?=E4=B8=80=E5=B9=B6=E5=8A=A0=E5=85=A5=20PATH=20=E8=AE=A9=20sh.ex?= =?UTF-8?q?e=20=E5=8F=AF=E8=A7=A3=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Expose Git Bash 只加了 Git\bin(含 bash.exe / git.exe),但 sh.exe 实际落在 Git\usr\bin\。Cursor / Claude 的 command_scenarios 与 entry_repairs 里 36 条 subprocess.run(["sh", "-c", ...]) 因此一直报 WinError 2 文件未找到。补一行 把 usr\bin 追加进 GITHUB_PATH 即可。 --- .github/workflows/cross-platform.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/cross-platform.yml b/.github/workflows/cross-platform.yml index 1dc6848..da63fb3 100644 --- a/.github/workflows/cross-platform.yml +++ b/.github/workflows/cross-platform.yml @@ -29,7 +29,9 @@ jobs: - name: Expose Git Bash for Claude compatibility fixtures if: runner.os == 'Windows' shell: pwsh - run: '"C:\Program Files\Git\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append' + run: | + "C:\Program Files\Git\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append + "C:\Program Files\Git\usr\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append - name: Install platform test dependencies working-directory: helixharness-platform run: python -m pip install -e ".[server,dev]" From 51bcd49ec45820a0224e2997f5bfe4d7d4735368 Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Tue, 24 Nov 2026 21:25:35 +0800 Subject: [PATCH 11/37] =?UTF-8?q?test(windows):=20=E5=87=80=E5=8C=96?= =?UTF-8?q?=E5=90=8E=E7=9A=84=E5=AD=90=E8=BF=9B=E7=A8=8B=E7=8E=AF=E5=A2=83?= =?UTF-8?q?=E8=A1=A5=20SystemRoot=20=E4=B8=8E=20Git=20=E7=9B=AE=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 宿主场景 fixture 故意清空宿主环境来证明用例不依赖开发者机器上的工具,但 Windows 上这样会连带打死两样东西:子 python.exe 缺 SystemRoot 时停在 _Py_HashRandomization_Init,os.defpath 里没有 Git 安装目录导致 fixture 自己要 跑的 git 与 sh 解析不到。统一走 env_sandbox,Windows 才补、POSIX 结果不变。 --- helixharness/scripts/tests/env_sandbox.py | 59 +++++++++++++++++++ .../tests/test_claude_command_scenarios.py | 4 +- .../tests/test_claude_lifecycle_scenarios.py | 5 +- .../tests/test_codex_command_scenarios.py | 4 +- .../tests/test_codex_lifecycle_scenarios.py | 3 + .../tests/test_codex_update_scenarios.py | 5 +- .../test_cursor_acceptance_regressions.py | 4 +- .../tests/test_cursor_command_scenarios.py | 4 +- .../tests/test_cursor_hook_fastpath.py | 2 + .../tests/test_cursor_lifecycle_scenarios.py | 5 +- 10 files changed, 88 insertions(+), 7 deletions(-) create mode 100644 helixharness/scripts/tests/env_sandbox.py diff --git a/helixharness/scripts/tests/env_sandbox.py b/helixharness/scripts/tests/env_sandbox.py new file mode 100644 index 0000000..74c68f2 --- /dev/null +++ b/helixharness/scripts/tests/env_sandbox.py @@ -0,0 +1,59 @@ +"""Scrubbed subprocess environments that still boot Python on every platform. + +Host scenario fixtures deliberately clear the ambient environment so a developer's +tooling cannot make a case pass. Two facts about Windows break a naive scrub: +a child `python.exe` aborts in `_Py_HashRandomization_Init` unless `SystemRoot` is +present, and `os.defpath` has no Git install directory, so `git` and `sh` — which +the fixtures themselves execute — cannot be resolved. +""" + +from __future__ import annotations + +import os +import shutil +import sys +from pathlib import Path + +# Required by the Windows C runtime to load a freshly started interpreter. +BOOT_VARS = ("SystemRoot", "COMSPEC", "PATHEXT") + + +def boot_vars() -> dict[str, str]: + """Environment entries a Windows child interpreter needs to start at all.""" + return {key: os.environ[key] for key in BOOT_VARS if key in os.environ} + + +def toolchain_dirs() -> list[str]: + """Directories holding the `git`/`sh` binaries the fixtures invoke. + + POSIX resolves both through `os.defpath`; on Windows they live inside the Git + installation, so the layout is discovered from the ambient `git` instead of a + hardcoded path. The Windows `sh` stub in `WindowsApps` starts WSL and is never + usable here, so only Git-provided directories are returned. + """ + if os.name != "nt": + return [] + git = shutil.which("git") + if not git: + return [] + directories, current = [], Path(git).resolve().parent + for _ in range(4): + for candidate in (current, current / "bin", current / "usr" / "bin"): + if (candidate / "git.exe").is_file() or (candidate / "sh.exe").is_file(): + if str(candidate) not in directories: + directories.append(str(candidate)) + if not current.parent or current.parent == current: + break + current = current.parent + return directories + + +def search_path() -> str: + """Minimal PATH: the test interpreter, the fixture binaries, the platform defaults.""" + parts = [str(Path(sys.executable).parent), *toolchain_dirs(), os.defpath] + seen, ordered = set(), [] + for part in parts: + if part and part not in seen: + seen.add(part) + ordered.append(part) + return os.pathsep.join(ordered) diff --git a/helixharness/scripts/tests/test_claude_command_scenarios.py b/helixharness/scripts/tests/test_claude_command_scenarios.py index 1439bbb..6ae768d 100644 --- a/helixharness/scripts/tests/test_claude_command_scenarios.py +++ b/helixharness/scripts/tests/test_claude_command_scenarios.py @@ -18,6 +18,7 @@ from pathlib import Path from unittest.mock import patch +import env_sandbox import test_workflow import validate_init_outputs import workflow @@ -38,7 +39,8 @@ def setUp(self): self.repo = self.root / "synthetic project 中文 空格" self.repo.mkdir() self.env = { - "PATH": str(Path(sys.executable).parent) + os.pathsep + os.defpath, + **env_sandbox.boot_vars(), + "PATH": env_sandbox.search_path(), "TMPDIR": str(self.root), "PYTHONDONTWRITEBYTECODE": "1", "PYTHONIOENCODING": "utf-8", "CODEX_HOME": str(self.root / "codex"), "CLAUDE_CONFIG_DIR": str(self.root / "claude"), "HELIXHARNESS_CURSOR_HOME": str(self.root / "cursor"), diff --git a/helixharness/scripts/tests/test_claude_lifecycle_scenarios.py b/helixharness/scripts/tests/test_claude_lifecycle_scenarios.py index 56b2857..e25cd6b 100644 --- a/helixharness/scripts/tests/test_claude_lifecycle_scenarios.py +++ b/helixharness/scripts/tests/test_claude_lifecycle_scenarios.py @@ -17,6 +17,8 @@ from datetime import datetime, timedelta, timezone from pathlib import Path +import env_sandbox + PLUGIN = Path(__file__).resolve().parents[2] @@ -32,7 +34,8 @@ def setUp(self): (self.telemetry / "config.json").write_text('{"endpoint":""}') self.claude = self.root / "claude" self.env = { - "PATH": str(Path(sys.executable).parent) + os.pathsep + os.defpath, + **env_sandbox.boot_vars(), + "PATH": env_sandbox.search_path(), "PYTHONDONTWRITEBYTECODE": "1", "PYTHONIOENCODING": "utf-8", "CODEX_HOME": str(self.root / "codex"), "CLAUDE_CONFIG_DIR": str(self.claude), "HELIXHARNESS_CURSOR_HOME": str(self.root / "cursor"), diff --git a/helixharness/scripts/tests/test_codex_command_scenarios.py b/helixharness/scripts/tests/test_codex_command_scenarios.py index 3dee2ea..79f2050 100644 --- a/helixharness/scripts/tests/test_codex_command_scenarios.py +++ b/helixharness/scripts/tests/test_codex_command_scenarios.py @@ -18,6 +18,7 @@ from pathlib import Path from unittest.mock import patch +import env_sandbox import test_workflow import validate_init_outputs @@ -34,7 +35,8 @@ def setUp(self) -> None: self.repo.mkdir() self.state = self.root / "entry snapshots" self.env = { - "PATH": f"{Path(sys.executable).parent}{os.pathsep}{os.defpath}", + **env_sandbox.boot_vars(), + "PATH": env_sandbox.search_path(), "TMPDIR": str(self.root), "PYTHONIOENCODING": "utf-8", "PYTHONDONTWRITEBYTECODE": "1", diff --git a/helixharness/scripts/tests/test_codex_lifecycle_scenarios.py b/helixharness/scripts/tests/test_codex_lifecycle_scenarios.py index 15c100c..2ada246 100644 --- a/helixharness/scripts/tests/test_codex_lifecycle_scenarios.py +++ b/helixharness/scripts/tests/test_codex_lifecycle_scenarios.py @@ -17,6 +17,8 @@ from datetime import datetime, timedelta, timezone from pathlib import Path +import env_sandbox + PLUGIN = Path(__file__).resolve().parents[2] THREAD_ONE = "0195f651-0000-7000-8000-000000000001" THREAD_TWO = "0195f651-0000-7000-8000-000000000002" @@ -35,6 +37,7 @@ def setUp(self): (self.telemetry / "config.json").write_text('{"endpoint": ""}') # Allowlist avoids inheriting native session bindings or credentials. self.env = { + **env_sandbox.boot_vars(), "PATH": str(Path(sys.executable).parent) + os.pathsep + os.environ.get("PATH", ""), "PYTHONDONTWRITEBYTECODE": "1", "CODEX_HOME": str(self.codex), diff --git a/helixharness/scripts/tests/test_codex_update_scenarios.py b/helixharness/scripts/tests/test_codex_update_scenarios.py index dc761df..9ed678b 100644 --- a/helixharness/scripts/tests/test_codex_update_scenarios.py +++ b/helixharness/scripts/tests/test_codex_update_scenarios.py @@ -15,6 +15,8 @@ import unittest from pathlib import Path +import env_sandbox + PLUGIN = Path(__file__).resolve().parents[2] REPOSITORY = PLUGIN.parent PUBLIC_ROOTS = {".codex-plugin", ".claude-plugin", ".cursor-plugin", ".qoder-plugin", "package.json", "scripts", "hosts", "commands", "workflows", "reference", "skills", "agents", "templates"} @@ -107,7 +109,8 @@ def setUp(self): # An allowlist avoids inheriting real host identity, credentials, Python # import paths, endpoints or configuration. The actual Codex CLI is shadowed. self.env = { - "PATH": str(bin_dir) + os.pathsep + os.environ.get("PATH", os.defpath), + **env_sandbox.boot_vars(), + "PATH": str(bin_dir) + os.pathsep + env_sandbox.search_path() + os.pathsep + os.environ.get("PATH", os.defpath), "TMPDIR": str(self.root), "LANG": "en_US.UTF-8", "PYTHONDONTWRITEBYTECODE": "1", "CODEX_HOME": str(self.root / "codex-home"), "CODEX_THREAD_ID": "synthetic-" + self.root.name, diff --git a/helixharness/scripts/tests/test_cursor_acceptance_regressions.py b/helixharness/scripts/tests/test_cursor_acceptance_regressions.py index bcc76be..62f1d81 100644 --- a/helixharness/scripts/tests/test_cursor_acceptance_regressions.py +++ b/helixharness/scripts/tests/test_cursor_acceptance_regressions.py @@ -14,6 +14,7 @@ import unittest from pathlib import Path +import env_sandbox import test_workspace PLUGIN = Path(__file__).resolve().parents[2] @@ -29,7 +30,8 @@ def setUp(self) -> None: self.repo = self.fixture.workspace.resolve() self.fixture._write_overview() self.env = { - "PATH": str(Path(sys.executable).parent) + os.pathsep + os.defpath, + **env_sandbox.boot_vars(), + "PATH": env_sandbox.search_path(), "PYTHONDONTWRITEBYTECODE": "1", "PYTHONIOENCODING": "utf-8", "GIT_CONFIG_GLOBAL": os.devnull, diff --git a/helixharness/scripts/tests/test_cursor_command_scenarios.py b/helixharness/scripts/tests/test_cursor_command_scenarios.py index 205b9c8..e084cc1 100644 --- a/helixharness/scripts/tests/test_cursor_command_scenarios.py +++ b/helixharness/scripts/tests/test_cursor_command_scenarios.py @@ -18,6 +18,7 @@ from pathlib import Path from unittest.mock import patch +import env_sandbox import test_workflow import validate_init_outputs import workflow @@ -38,7 +39,8 @@ def setUp(self): self.repo = self.root / "synthetic project 中文 空格" self.repo.mkdir() self.env = { - "PATH": str(Path(sys.executable).parent) + os.pathsep + os.defpath, + **env_sandbox.boot_vars(), + "PATH": env_sandbox.search_path(), "TMPDIR": str(self.root), "PYTHONDONTWRITEBYTECODE": "1", "PYTHONIOENCODING": "utf-8", "CODEX_HOME": str(self.root / "codex"), "CLAUDE_CONFIG_DIR": str(self.root / "claude"), "HELIXHARNESS_CURSOR_HOME": str(self.root / "cursor"), diff --git a/helixharness/scripts/tests/test_cursor_hook_fastpath.py b/helixharness/scripts/tests/test_cursor_hook_fastpath.py index dc1e007..e9d6b74 100644 --- a/helixharness/scripts/tests/test_cursor_hook_fastpath.py +++ b/helixharness/scripts/tests/test_cursor_hook_fastpath.py @@ -14,6 +14,7 @@ import reporting_config from host_runtime import HostRegistry +import env_sandbox from telemetry_hosts.cursor import record_hook ROOT = Path(__file__).resolve().parents[2] @@ -28,6 +29,7 @@ def setUp(self): self.payload = {'conversation_id': 'synthetic-fastpath', 'workspace_roots': [str(self.home)], 'hook_event_name': 'postToolUse', 'tool_use_id': 'synthetic-call', 'tool_name': 'Shell'} self.env = {'PATH': os.defpath, 'PYTHONDONTWRITEBYTECODE': '1', + **env_sandbox.boot_vars(), 'HELIXHARNESS_TELEMETRY_HOME': str(self.home / 'telemetry'), 'HELIXHARNESS_CURSOR_HOME': str(self.home / 'cursor'), 'HELIXHARNESS_FEEDBACK_HOME': str(self.home / 'feedback'), diff --git a/helixharness/scripts/tests/test_cursor_lifecycle_scenarios.py b/helixharness/scripts/tests/test_cursor_lifecycle_scenarios.py index d7916a0..539a5b6 100644 --- a/helixharness/scripts/tests/test_cursor_lifecycle_scenarios.py +++ b/helixharness/scripts/tests/test_cursor_lifecycle_scenarios.py @@ -15,6 +15,8 @@ import unittest from pathlib import Path +import env_sandbox + PLUGIN = Path(__file__).resolve().parents[2] @@ -29,7 +31,8 @@ def setUp(self): self.telemetry.mkdir() (self.telemetry / "config.json").write_text('{"endpoint":""}') self.env = { - "PATH": str(Path(sys.executable).parent) + os.pathsep + os.defpath, + **env_sandbox.boot_vars(), + "PATH": env_sandbox.search_path(), "PYTHONDONTWRITEBYTECODE": "1", "PYTHONIOENCODING": "utf-8", "CODEX_HOME": str(self.root / "codex"), "CLAUDE_CONFIG_DIR": str(self.root / "claude"), From 66e8548704871150630c6b746ba2f7fa4c3f64cb Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Tue, 24 Nov 2026 21:25:41 +0800 Subject: [PATCH 12/37] =?UTF-8?q?Revert=20"ci(windows):=20=E6=8A=8A=20Git\?= =?UTF-8?q?usr\bin=20=E4=B8=80=E5=B9=B6=E5=8A=A0=E5=85=A5=20PATH=20?= =?UTF-8?q?=E8=AE=A9=20sh.exe=20=E5=8F=AF=E8=A7=A3=E6=9E=90"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit c8a733fd0053ecb44122618d7404066c5a33b06f. --- .github/workflows/cross-platform.yml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.github/workflows/cross-platform.yml b/.github/workflows/cross-platform.yml index da63fb3..1dc6848 100644 --- a/.github/workflows/cross-platform.yml +++ b/.github/workflows/cross-platform.yml @@ -29,9 +29,7 @@ jobs: - name: Expose Git Bash for Claude compatibility fixtures if: runner.os == 'Windows' shell: pwsh - run: | - "C:\Program Files\Git\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append - "C:\Program Files\Git\usr\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append + run: '"C:\Program Files\Git\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append' - name: Install platform test dependencies working-directory: helixharness-platform run: python -m pip install -e ".[server,dev]" From e7ceed3839b4b7b5f387436f0b9cf60893ceef4b Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Tue, 24 Nov 2026 21:37:00 +0800 Subject: [PATCH 13/37] =?UTF-8?q?test(windows):=20=E6=8C=89=20argv=20?= =?UTF-8?q?=E4=B8=8E=E5=8F=AA=E8=AF=BB=E4=BD=8D=E6=96=AD=E8=A8=80=20hook?= =?UTF-8?q?=20=E5=91=BD=E4=BB=A4=E5=92=8C=E6=9D=83=E9=99=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Windows 上自生成的 hook 命令是 powershell -EncodedCommand,直接对命令字符串 assertIn 会挂;assertNotIn 更糟——旧 python 路径被 base64 藏起来,用例会假通过。 统一走 hook_argv() 解析回 argv 再断言。权限位同理:Windows 只建模 read-only, 0600/0640 无法还原,按仓库里 feedback_submit 已有的写法收窄。 --- .../tests/test_cursor_lifecycle_scenarios.py | 4 +++- .../scripts/tests/test_init_guidance.py | 5 ++++- .../scripts/tests/test_project_hooks.py | 17 +++++++++++------ helixharness/scripts/tests/test_task_plan.py | 4 +++- helixharness/scripts/tests/test_ut_artifacts.py | 8 ++++++-- 5 files changed, 27 insertions(+), 11 deletions(-) diff --git a/helixharness/scripts/tests/test_cursor_lifecycle_scenarios.py b/helixharness/scripts/tests/test_cursor_lifecycle_scenarios.py index 539a5b6..d83561b 100644 --- a/helixharness/scripts/tests/test_cursor_lifecycle_scenarios.py +++ b/helixharness/scripts/tests/test_cursor_lifecycle_scenarios.py @@ -326,7 +326,9 @@ def test_feedback_draft_binds_cursor_hash_without_private_transcript_or_reposito self.assertIn("claude-code", draft["item"]["transcript_stats"]["reason"]) path = Path(draft["draft_path"]) self.assertEqual(path.parent, self.root / "feedback/drafts") - self.assertEqual(path.stat().st_mode & 0o777, 0o600) + if os.name != "nt": + # Windows records only the read-only bit, so 0600 is unprovable there. + self.assertEqual(path.stat().st_mode & 0o777, 0o600) self.assertEqual(before, self.files(self.repo)) self.assertFalse((self.root / "feedback/outbox").exists()) diff --git a/helixharness/scripts/tests/test_init_guidance.py b/helixharness/scripts/tests/test_init_guidance.py index 2199e46..02f1c69 100644 --- a/helixharness/scripts/tests/test_init_guidance.py +++ b/helixharness/scripts/tests/test_init_guidance.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +import os import subprocess import sys import tempfile @@ -241,7 +242,9 @@ def test_entry_permissions_and_render_without_filesystem_mutation(self): self.assertIn("/helix-bug-fix", rendered["block"]) self.assertEqual(entry.read_text(), "user rules\n") self.cli() - self.assertEqual(entry.stat().st_mode & 0o777, 0o640) + if os.name != "nt": + # Windows records only the read-only bit, so a preserved mode is unprovable there. + self.assertEqual(entry.stat().st_mode & 0o777, 0o640) if __name__ == "__main__": diff --git a/helixharness/scripts/tests/test_project_hooks.py b/helixharness/scripts/tests/test_project_hooks.py index 53b806e..244e4a1 100644 --- a/helixharness/scripts/tests/test_project_hooks.py +++ b/helixharness/scripts/tests/test_project_hooks.py @@ -9,11 +9,16 @@ from unittest.mock import patch from host_runtime.project_hooks import ProjectHooks -from project_hooks_cli import project_hooks +from project_hooks_cli import _parse_posix_command, _parse_windows_command, project_hooks ROOT = Path(__file__).resolve().parents[2] +def hook_argv(command: str) -> list[str]: + """Argv of a self-generated hook command, whichever shell shape the host wrote.""" + return _parse_windows_command(command) or _parse_posix_command(command) or [] + + class ProjectHooksTest(unittest.TestCase): def test_legacy_hooks_are_upgraded_without_losing_user_options(self): from project_hooks_cli import project_hooks @@ -216,10 +221,8 @@ def test_complete_required_hooks_do_not_hide_invalid_user_events(self): def test_qoder_collapse_removes_version_dir_duplicates(self): """Under linter_flag policy, entries differing only in --repo-root collapse.""" - from project_hooks_cli import _parse_posix_command, _parse_windows_command, project_hooks - def linter_name(command: str) -> str | None: - argv = _parse_windows_command(command) or _parse_posix_command(command) + argv = hook_argv(command) if not argv or "--linter" not in argv: return None idx = argv.index("--linter") @@ -441,11 +444,13 @@ def test_cursor_owned_linters_refresh_runtime_and_preserve_user_hooks(self): handlers = document["hooks"]["afterFileEdit"] self.assertEqual(4, len(handlers)) self.assertEqual(23, handlers[0]["timeout"]) - self.assertIn("project_linter.py", handlers[0]["command"]) + self.assertTrue(any(Path(part).name == "project_linter.py" + for part in hook_argv(handlers[0]["command"])), + handlers[0]["command"]) self.assertEqual(custom, handlers[1]) self.assertEqual(scoped, handlers[2]) self.assertEqual([{"command": "echo keep-stop"}], document["hooks"]["stop"]) - self.assertNotIn("Python 'old'", handlers[0]["command"]) + self.assertEqual(new_python, hook_argv(handlers[0]["command"])[0]) def test_flat_target_symlink_cannot_escape_project(self): with tempfile.TemporaryDirectory() as directory: diff --git a/helixharness/scripts/tests/test_task_plan.py b/helixharness/scripts/tests/test_task_plan.py index c3dcefa..0acbc31 100644 --- a/helixharness/scripts/tests/test_task_plan.py +++ b/helixharness/scripts/tests/test_task_plan.py @@ -43,7 +43,9 @@ def test_update_preserves_document_and_mode(self): os.chmod(self.file, 0o640) update_task(self.repo, "demo", "T-01", "in_progress", self.receipt()) self.assertEqual(self.file.read_text(), TEXT.replace("— | pending", "— | in_progress")) - self.assertEqual(self.file.stat().st_mode & 0o777, 0o640) + if os.name != "nt": + # Windows records only the read-only bit, so a preserved mode is unprovable there. + self.assertEqual(self.file.stat().st_mode & 0o777, 0o640) update_task(self.repo, "demo", "T-01", "completed", self.receipt()) self.assertEqual(inspect_plan(self.repo, "demo")["next_task"], "T-02") diff --git a/helixharness/scripts/tests/test_ut_artifacts.py b/helixharness/scripts/tests/test_ut_artifacts.py index 5c42aef..397611a 100644 --- a/helixharness/scripts/tests/test_ut_artifacts.py +++ b/helixharness/scripts/tests/test_ut_artifacts.py @@ -1,5 +1,6 @@ from __future__ import annotations import json +import os from pathlib import Path import tempfile import unittest @@ -141,6 +142,7 @@ def test_other_reproduced_mechanical_failures_and_invalid_marker(self): def test_configuration_is_not_a_mechanical_code_reference(self): (self.repo/'settings.json').write_text('synthetic setting') self.assertEqual(self.findings(1,[self.observation(basis='mechanical',mechanical_kind='data_corruption',code_ref={'path':'settings.json','quote':'synthetic setting'})])['counts']['confirmed_defect'],0) + @unittest.skipIf(os.name == 'nt', 'Windows models only the read-only bit') def test_existing_posix_modes_survive_all_publication_paths(self): import stat for mode in (0o600,0o640,0o750): @@ -174,9 +176,11 @@ def test_replace_failure_preserves_private_mode_and_new_file_default(self): target=self.directory/'unittest-session.md';target.write_text('private');target.chmod(0o600) with patch('atomic_files.os.replace',side_effect=OSError('synthetic failure')): with self.assertRaises(OSError):ut.publish_state(self.repo,'sample',target.name,self.stage(target.name,'replacement')) - self.assertEqual(target.read_text(),'private');self.assertEqual(stat.S_IMODE(target.stat().st_mode),0o600) + self.assertEqual(target.read_text(),'private') name='unittest-summary.md';ut.publish_state(self.repo,'sample',name,self.stage(name,'new')) - self.assertEqual(stat.S_IMODE((self.directory/name).stat().st_mode),0o644) + if os.name != 'nt': + self.assertEqual(stat.S_IMODE(target.stat().st_mode),0o600) + self.assertEqual(stat.S_IMODE((self.directory/name).stat().st_mode),0o644) def test_active_timeout_never_inherits_archived_worker_generation(self): self.findings(1,[]) for suffix in ('findings.json','defects.md'): From 9d0442111f79d3f77a5631b09b95bdd8c9608f81 Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Tue, 24 Nov 2026 21:44:04 +0800 Subject: [PATCH 14/37] =?UTF-8?q?fix(windows):=20=E7=9B=AE=E5=BD=95?= =?UTF-8?q?=E8=90=BD=E7=9B=98=E4=B8=8E=E5=8E=9F=E7=94=9F=E5=AE=89=E8=A3=85?= =?UTF-8?q?=E9=94=81=E8=B7=A8=E5=B9=B3=E5=8F=B0=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit os.open(dir, O_RDONLY) + fsync 是 POSIX 才有的把 rename/unlink 落盘的办法, Windows 打不开目录句柄,直接 PermissionError。抽 atomic_files.fsync_directory() 统一承接四处(其中两处原本各自内联 os.name 判断)。ProjectInstall.locked() 只有 fcntl 分支,按 metrics.py 已有的写法补 msvcrt:msvcrt 锁的是字节区间且不允许越过 EOF,所以先把锁文件垫一个字节再 NBLCK/UNLCK。 --- helixharness/scripts/atomic_files.py | 16 +++++++ helixharness/scripts/cursor_native_install.py | 44 ++++++++++++------- helixharness/scripts/telemetry_consent.py | 8 +--- helixharness/scripts/version_update.py | 15 ++----- 4 files changed, 50 insertions(+), 33 deletions(-) diff --git a/helixharness/scripts/atomic_files.py b/helixharness/scripts/atomic_files.py index cb16d05..0f989fc 100644 --- a/helixharness/scripts/atomic_files.py +++ b/helixharness/scripts/atomic_files.py @@ -12,6 +12,22 @@ class AtomicWriteError(OSError): """Raised when an atomic write target is not safe or cannot be replaced.""" +def fsync_directory(path: Path) -> None: + """Make an entry change inside `path` durable. + + POSIX persists a rename or unlink through the directory handle. Windows has no + openable directory handle and already treats a completed rename as durable, so + the call is a no-op there rather than a PermissionError. + """ + if os.name == "nt": + return + descriptor = os.open(str(path), os.O_RDONLY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + + def atomic_write_text(path: Path, text: str, *, mode: int = 0o644) -> None: """Replace a regular target without following a predictable temp symlink.""" parent = path.parent diff --git a/helixharness/scripts/cursor_native_install.py b/helixharness/scripts/cursor_native_install.py index d504e98..56dcfe5 100644 --- a/helixharness/scripts/cursor_native_install.py +++ b/helixharness/scripts/cursor_native_install.py @@ -12,9 +12,15 @@ import tempfile from urllib.parse import urlsplit +import atomic_files import eval_json from update_hosts.base import BoundedCommandRunner +if os.name == "nt": + import msvcrt +else: + import fcntl + KEY = "helixharness-marketplace/helix" MISSING = {"absent": True} @@ -54,11 +60,7 @@ def atomic(path, value): stream.flush() os.fsync(stream.fileno()) os.replace(name, path) - descriptor = os.open(path.parent, os.O_RDONLY) - try: - os.fsync(descriptor) - finally: - os.close(descriptor) + atomic_files.fsync_directory(path.parent) finally: if os.path.exists(name): os.unlink(name) @@ -143,13 +145,29 @@ def __init__(self, project, home=None): @contextmanager def locked(self): - # Scope is the tested macOS/Linux desktop channel. - import fcntl safe(self.state).mkdir(parents=True, exist_ok=True) lock = safe(self.state / "lock") - with lock.open("a") as stream: - fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB) - yield + with lock.open("a+b") as stream: + if os.name == "nt": + # msvcrt locks a byte range and refuses to lock past end of file, + # so the handle needs one byte before it can be held exclusively. + stream.seek(0, os.SEEK_END) + if not stream.tell(): + stream.write(b"\0") + stream.flush() + stream.seek(0) + msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1) + try: + yield + finally: + stream.seek(0) + msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1) + else: + fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB) + try: + yield + finally: + fcntl.flock(stream, fcntl.LOCK_UN) def configuration(self): value = read(self.settings) @@ -233,11 +251,7 @@ def restore(self, confirmed=False): if not config and not record["settings_existed"]: self.settings.unlink(missing_ok=True) if self.settings.parent.exists(): - fd = os.open(self.settings.parent, os.O_RDONLY) - try: - os.fsync(fd) - finally: - os.close(fd) + atomic_files.fsync_directory(self.settings.parent) else: atomic(self.settings, config) atomic(self.receipt, {**record, "phase": "restored"}) diff --git a/helixharness/scripts/telemetry_consent.py b/helixharness/scripts/telemetry_consent.py index 2720fce..2f359f4 100644 --- a/helixharness/scripts/telemetry_consent.py +++ b/helixharness/scripts/telemetry_consent.py @@ -20,6 +20,7 @@ from urllib.parse import unquote, urlparse from telemetry_hosts import get_host_adapter, normalize_host_id, supported_host_ids +import atomic_files import eval_json from telemetry_async import endpoint_skip @@ -313,12 +314,7 @@ def _atomic_write(path: Path, data: dict[str, Any]) -> None: handle.flush() os.fsync(handle.fileno()) os.replace(temp_name, path) - if os.name != "nt": - directory_fd = os.open(path.parent, os.O_RDONLY) - try: - os.fsync(directory_fd) - finally: - os.close(directory_fd) + atomic_files.fsync_directory(path.parent) finally: try: os.unlink(temp_name) diff --git a/helixharness/scripts/version_update.py b/helixharness/scripts/version_update.py index d1c355b..bceec32 100644 --- a/helixharness/scripts/version_update.py +++ b/helixharness/scripts/version_update.py @@ -15,6 +15,7 @@ from pathlib import Path from typing import Any, Iterator +import atomic_files import eval_json from source_binding import guard_source from update_hosts import ( @@ -381,12 +382,7 @@ def _atomic_write(path: Path, data: dict[str, Any]) -> None: handle.flush() os.fsync(handle.fileno()) os.replace(temp_name, path) - if os.name != "nt": - parent_fd = os.open(path.parent, os.O_RDONLY) - try: - os.fsync(parent_fd) - finally: - os.close(parent_fd) + atomic_files.fsync_directory(path.parent) finally: try: os.unlink(temp_name) @@ -396,12 +392,7 @@ def _atomic_write(path: Path, data: dict[str, Any]) -> None: def _durable_unlink(path: Path) -> None: path.unlink() - if os.name != "nt": - parent_fd = os.open(path.parent, os.O_RDONLY) - try: - os.fsync(parent_fd) - finally: - os.close(parent_fd) + atomic_files.fsync_directory(path.parent) @contextmanager From 1c38f6abb976515aa5e3991e18a8e9fd15e46893 Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Tue, 24 Nov 2026 21:44:30 +0800 Subject: [PATCH 15/37] =?UTF-8?q?test(windows):=20=E6=8A=95=E5=BD=B1?= =?UTF-8?q?=E7=94=A8=E4=BE=8B=E8=A1=A5=20SystemRoot=20=E5=B9=B6=E5=B8=A6?= =?UTF-8?q?=E5=87=BA=20node=20stderr?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 三处 env 只留 PATH,Windows 上子 python 起不来。run_gate 断言 stderr 为空时 unittest 把 diff 折成一行提示,看不到 node 到底说了什么,改成把有界的 stderr 放进断言消息。 --- helixharness/scripts/tests/test_cursor_projection.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/helixharness/scripts/tests/test_cursor_projection.py b/helixharness/scripts/tests/test_cursor_projection.py index c5fe840..9b66dfc 100644 --- a/helixharness/scripts/tests/test_cursor_projection.py +++ b/helixharness/scripts/tests/test_cursor_projection.py @@ -17,6 +17,7 @@ sys.path.insert(0, str(SCRIPTS)) import cursor_skill_projection as projection # noqa: E402 +import env_sandbox # noqa: E402 class CursorProjectionTests(unittest.TestCase): @@ -209,7 +210,7 @@ def test_method_resolution_needs_no_command_file_or_command_projection(self) -> [sys.executable, str(SCRIPTS / "cursor_skill_projection.py"), "--root", str(isolated), "--resolve-entry", "hosts/cursor/skills/helix-d-d2c/SKILL.md"], capture_output=True, text=True, check=False, timeout=10, - env={"PATH": os.environ.get("PATH", "")}, + env={**env_sandbox.boot_vars(), "PATH": os.environ.get("PATH", "")}, ) self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual(json.loads(result.stdout)["canonical"], "skills/d-d2c/SKILL.md") @@ -287,9 +288,9 @@ def run_gate(self, action: str = "stop", *extra: str) -> tuple[int, dict]: "--repo-root", str(self.root), "--page-dir", self.page, "--started-at", self.started, "--action", action, *extra], cwd=self.root, capture_output=True, text=True, check=False, timeout=10, - env={"PATH": os.environ.get("PATH", "")}, + env={**env_sandbox.boot_vars(), "PATH": os.environ.get("PATH", "")}, ) - self.assertEqual(result.stderr, "") + self.assertEqual(result.stderr, "", f"node stderr: {result.stderr[:400]!r}") return result.returncode, json.loads(result.stdout) def test_incomplete_workflow_cannot_stop_or_ask(self) -> None: @@ -380,7 +381,7 @@ def run_checkpoint(self, *arguments: str) -> None: [shutil.which("node"), str(PLUGIN / "skills/d-d2c/scripts/d2c-workflow-checkpoint.cjs"), "--page-dir", self.page, *arguments], cwd=self.root, capture_output=True, text=True, check=False, timeout=10, - env={"PATH": os.environ.get("PATH", "")}, + env={**env_sandbox.boot_vars(), "PATH": os.environ.get("PATH", "")}, ) self.assertEqual(result.returncode, 0, result.stderr) self.state = json.loads(self.state_file.read_text(encoding="utf-8")) From 4a0a0398902084884d2f6e943ed475473827267c Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Tue, 24 Nov 2026 21:54:39 +0800 Subject: [PATCH 16/37] =?UTF-8?q?fix(guidance):=20=E6=8C=89=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E5=B7=B2=E6=9C=89=E6=8D=A2=E8=A1=8C=E6=B8=B2=E6=9F=93?= =?UTF-8?q?=E6=89=98=E7=AE=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit check_text 比较时把 CRLF 归一成 LF,merge_text 却照拼 LF 块,于是 AGENTS.md 用 CRLF 保存时 check 说 pass、merge 说 changed,每次 Init 都把用户的整段换行改写一遍。 改为按被替换区段(或整文件,纯追加时)的换行形态渲染,并补三种形态的用例。 --- helixharness/scripts/init_guidance.py | 21 ++++++++++++++----- .../scripts/tests/test_init_guidance.py | 17 +++++++++++++++ 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/helixharness/scripts/init_guidance.py b/helixharness/scripts/init_guidance.py index 05d290b..f7f5fc4 100644 --- a/helixharness/scripts/init_guidance.py +++ b/helixharness/scripts/init_guidance.py @@ -134,18 +134,29 @@ def check_text(text: str, expected: str) -> None: raise GuidanceError("init_guidance_outdated_or_incorrect") +def _block_like(sample: str, expected: str) -> str: + """Render the managed block with the line endings the surrounding bytes use. + + check_text tolerates CRLF, so writing LF back over a CRLF block would report a + change on every Init and rewrite a Windows editor's bytes each time. + """ + return expected.replace("\n", "\r\n") if "\r\n" in sample else expected + + def merge_text(text: str, expected: str, mode: str) -> str: span = _managed_span(text) if span is not None: if _command_headings(text[:span[0]] + text[span[1]:]): raise GuidanceError("init_guidance_custom_commands_conflict") + result = text[:span[0]] + _block_like(text[span[0]:span[1]], expected) + text[span[1]:] else: span = _legacy_span(text, mode) - if span is not None: - result = text[:span[0]] + expected + text[span[1]:] - else: - separator = "" if not text or text.endswith("\n\n") else "\n" if text.endswith("\n") else "\n\n" - result = text + separator + expected + "\n" + if span is not None: + result = text[:span[0]] + _block_like(text[span[0]:span[1]], expected) + text[span[1]:] + else: + newline = "\r\n" if "\r\n" in text else "\n" + separator = "" if not text or text.endswith(newline * 2) else newline if text.endswith(newline) else newline * 2 + result = text + separator + _block_like(text, expected) + newline check_text(result, expected) return result diff --git a/helixharness/scripts/tests/test_init_guidance.py b/helixharness/scripts/tests/test_init_guidance.py index 02f1c69..9f01bef 100644 --- a/helixharness/scripts/tests/test_init_guidance.py +++ b/helixharness/scripts/tests/test_init_guidance.py @@ -234,6 +234,23 @@ def edit_during_preparation(fd): self.assertEqual(entry.read_bytes(), b"newer user content\n") self.assertEqual({p.name for p in self.repo.iterdir()}, {"AGENTS.md"}) + def test_crlf_entry_is_left_untouched_and_stays_idempotent(self): + # Windows editors save AGENTS.md with CRLF. check_text tolerates that, so a + # merge must not answer "changed" by rewriting the block back to LF. + for platform in ("cursor", "codex", "claude-code"): + with self.subTest(platform=platform): + entry = self.repo / ("CLAUDE.md" if platform == "claude-code" else "AGENTS.md") + entry.write_bytes(self.template("service").replace("\n", "\r\n").encode()) + before = entry.read_bytes() + self.assertFalse(self.cli(platform, "service")["changed"]) + self.assertEqual(entry.read_bytes(), before) + self.assertEqual(self.cli(platform, "service", "check")["status"], "pass") + entry.write_bytes("# 用户规则\r\n\r\n正文\r\n".encode()) + self.assertTrue(self.cli(platform, "service")["changed"]) + merged = entry.read_bytes() + self.assertEqual(merged.count(b"\n"), merged.count(b"\r\n")) + self.assertFalse(self.cli(platform, "service")["changed"]) + def test_entry_permissions_and_render_without_filesystem_mutation(self): entry = self.repo / "AGENTS.md" entry.write_text("user rules\n") From 729e407c5a752a3a07fad20e496b376f650d8ee3 Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Wed, 25 Nov 2026 10:14:02 +0800 Subject: [PATCH 17/37] =?UTF-8?q?docs(qoder):=20=E5=90=8C=E6=AD=A5?= =?UTF-8?q?=E9=99=88=E6=97=A7=E7=BB=91=E5=AE=9A=E7=AD=96=E7=95=A5=E5=88=B0?= =?UTF-8?q?=20Init=20=E4=B8=8E=E5=AE=89=E8=A3=85=E8=AF=B4=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 61593c8 已合入 stale_binding_policy,但文档仍停在旧语义:init.md 把 check 失败一律写成 BLOCKED,installer.md 还要求更新插件后手动删除指向旧版本目录的 handler。两条现在都不成立,且打包脚本按工作树读取,导致验收装到的说明与 PR 里的不是同一份。 --- helixharness/commands/init.md | 8 ++++++-- helixharness/hosts/qoder/installer.md | 12 +++++++----- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/helixharness/commands/init.md b/helixharness/commands/init.md index 7f65210..ecb20d0 100644 --- a/helixharness/commands/init.md +++ b/helixharness/commands/init.md @@ -532,8 +532,12 @@ service 的 `--knowledge` 导入分支在此验证导入产物后,才补做 St `{helix_python} "{plugin_root}/scripts/project_hooks_cli.py" --repo-root {repo_root} --platform {canonical_host_id} merge`。 - `owner=bootstrap` 时由 bootstrap 按原有宿主写入权限执行同一 `merge` 命令;父流程不得绕过宿主配置权限。 - 两种 owner 均由父流程执行同一路径的 `check`,核对实际 settings 的必需 hook、去重与 JSON 结构; - `settings_file=null` 时工具返回明确 skipped。任何缺失、冲突或检查失败均报告 - `BLOCKED: project_hooks_incomplete`,保留其他已生成工件,不得报告 Init 完成。 + `settings_file=null` 时工具返回明确 skipped。`check` 的严格程度按当前 Host Kit 的 + `resources.project_hooks.stale_binding_policy.check` 分档:默认 `fail` 时缺失或重复即抛 + `project_hooks_missing_or_duplicated`;`warn` 时同样条件返回 `warnings` 数组而不阻断,Init 继续 + 把 warnings 原样输出给用户,除非用户显式要求严格模式(`--strict`)才升级为 BLOCKED。任何冲突、 + 坏 JSON 或非形状匹配的重复仍报告 `BLOCKED: project_hooks_incomplete`,保留其他已生成工件, + 不得报告 Init 完成。 绿地额外验收:`project-context.md` 必须明确 `project-mode: greenfield`,未知事实保留 TODO。 此时仍保留 pending 状态,完成下方统计门禁后再进入 Step 4;bootstrap 不写本模式的 state。 diff --git a/helixharness/hosts/qoder/installer.md b/helixharness/hosts/qoder/installer.md index 901618f..a2a2935 100644 --- a/helixharness/hosts/qoder/installer.md +++ b/helixharness/hosts/qoder/installer.md @@ -76,11 +76,13 @@ handler,没有重启也没有新开会话,所以验收项目 hooks 不必换 实测一份把 linter 路径钉在 `.../helix/1.1.0/` 的配置连续 26 次以 exit 1 失败(`missing project linter invariant-check; rerun /helix:init`),整个会话里模型一次都没看到这句话。验收 guardrail 必须去读转录里的 hook 记录,不能以“会话没报错”当作 hook 正常工作的证据。 -- 更新插件后重跑 Init 不会清掉旧 handler(实测):merge 认“自己的旧命令”的条件是 `argv[1:]` 与新命令完全相等, - 而其中同时包含版本目录和 resolve 之后的 repo-root,任一变化就认不出来。把 1.1.0 生成的 handler 交给 1.2.5 - 合并,结果是 4 个 handler:新的两个指向 1.2.5,旧的两个仍指向已删除的 1.1.0 并每次静默失败。macOS 上同一 - 目录写成 `/tmp/...` 会被规范成 `/private/tmp/...`,所以换一种路径写法也会触发同样的重复。结论:更新插件后 - 重新 Init,并检查 `.qoder/settings.json` 里有没有仍指向旧版本目录的条目,动手删掉。 +- 更新插件后重跑 Init 会自动收敛陈旧 handler:本宿主的 `hosts/qoder/project-hooks.json` 声明 + `stale_binding_policy = { recognize: linter_flag, merge: collapse, check: warn }`。merge 按 + `--linter ` 加脚本路径尾部的形状认领自生成命令,同一 linter 的重复项只保留第一条并把 + `command` 改写为当前版本;`check` 默认把仍存在的缺失或重复降级为 `warnings` 返回而不阻断 Init, + 需要严格阻断时传 `--strict`。macOS 上同一目录写成 `/tmp/...` 会被规范成 `/private/tmp/...` + 的情况也一并被折叠,不再需要人工清理。1.1.0 之前遗留的手动删条目步骤可以跳过;如果仍看到 + 指向已卸载版本目录的 handler,说明它形状没被识别(例如自定义 flag),此时才需要用户确认。 - 根 `skills/` 中声明 `disable-model-invocation: true` 的方法 Skill 不进入模型可见列表,属预期行为; 验收按“可见数 ≤ 声明数 − 抑制数”核对,不得据此判定装载失败。实测 1.2.0 会话给出上限那一侧:8 个根方法 Skill 加 9 个薄入口共 17 个声明,3 个声明抑制,可见 `helix:` 条目 14 个。但同一个验收判据在 1.2.1 会话里 From 101ed954d33e8dd8d8971fe81ebac68bd84b1c76 Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Wed, 25 Nov 2026 10:18:16 +0800 Subject: [PATCH 18/37] =?UTF-8?q?test(windows):=20=E5=87=80=E5=8C=96=20env?= =?UTF-8?q?=20=E6=97=B6=E5=90=8C=E6=97=B6=E7=BB=99=E5=87=BA=E6=B2=99?= =?UTF-8?q?=E7=AE=B1=20home?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Windows 的 expanduser 只读 USERPROFILE/HOMEPATH/HOMEDRIVE,不回落 HOME (本机读 ntpath.expanduser 的常量表可证),于是只设 HOME 的夹具在 Windows 上 让 Path.home() 抛 Could not determine home directory.,run 27 里这类错误 24 次, 集中在 update scenarios 与 cursor hook fastpath;反过来完全不给 home 时,POSIX 会经 passwd 库解析到开发者真实家目录,隔离是假的。env_sandbox 增加 home_vars 同时下发两个键,6 处夹具改用它。 --- helixharness/scripts/tests/env_sandbox.py | 19 ++++++++++++++++--- .../tests/test_codex_update_scenarios.py | 1 + .../tests/test_cursor_bundle_update.py | 3 ++- .../tests/test_cursor_hook_fastpath.py | 2 +- .../scripts/tests/test_user_commands.py | 3 ++- .../scripts/tests/test_user_config_notice.py | 3 ++- 6 files changed, 24 insertions(+), 7 deletions(-) diff --git a/helixharness/scripts/tests/env_sandbox.py b/helixharness/scripts/tests/env_sandbox.py index 74c68f2..581f6cd 100644 --- a/helixharness/scripts/tests/env_sandbox.py +++ b/helixharness/scripts/tests/env_sandbox.py @@ -1,10 +1,11 @@ """Scrubbed subprocess environments that still boot Python on every platform. Host scenario fixtures deliberately clear the ambient environment so a developer's -tooling cannot make a case pass. Two facts about Windows break a naive scrub: +tooling cannot make a case pass. Three facts about Windows break a naive scrub: a child `python.exe` aborts in `_Py_HashRandomization_Init` unless `SystemRoot` is -present, and `os.defpath` has no Git install directory, so `git` and `sh` — which -the fixtures themselves execute — cannot be resolved. +present, `os.defpath` has no Git install directory so `git` and `sh` — which the +fixtures themselves execute — cannot be resolved, and a scrubbed environment has no +home directory for `Path.home()` to fall back on. """ from __future__ import annotations @@ -48,6 +49,18 @@ def toolchain_dirs() -> list[str]: return directories +def home_vars(home: Path | str) -> dict[str, str]: + """Environment entries that point `Path.home()` at `home`. + + Windows `expanduser` reads `USERPROFILE` and never falls back to `HOME`, so a + sandboxed home needs both keys: with only `HOME` set, `Path.home()` raises + `Could not determine home directory`, while an unset `HOME` silently resolves + to the developer's real home through the password database. + """ + value = str(home) + return {"HOME": value, "USERPROFILE": value} + + def search_path() -> str: """Minimal PATH: the test interpreter, the fixture binaries, the platform defaults.""" parts = [str(Path(sys.executable).parent), *toolchain_dirs(), os.defpath] diff --git a/helixharness/scripts/tests/test_codex_update_scenarios.py b/helixharness/scripts/tests/test_codex_update_scenarios.py index 9ed678b..073e225 100644 --- a/helixharness/scripts/tests/test_codex_update_scenarios.py +++ b/helixharness/scripts/tests/test_codex_update_scenarios.py @@ -112,6 +112,7 @@ def setUp(self): **env_sandbox.boot_vars(), "PATH": str(bin_dir) + os.pathsep + env_sandbox.search_path() + os.pathsep + os.environ.get("PATH", os.defpath), "TMPDIR": str(self.root), "LANG": "en_US.UTF-8", "PYTHONDONTWRITEBYTECODE": "1", + **env_sandbox.home_vars(self.root / "user-home"), "CODEX_HOME": str(self.root / "codex-home"), "CODEX_THREAD_ID": "synthetic-" + self.root.name, "CLAUDE_CONFIG_DIR": str(self.root / "claude-home"), diff --git a/helixharness/scripts/tests/test_cursor_bundle_update.py b/helixharness/scripts/tests/test_cursor_bundle_update.py index 6d57f16..6358293 100644 --- a/helixharness/scripts/tests/test_cursor_bundle_update.py +++ b/helixharness/scripts/tests/test_cursor_bundle_update.py @@ -11,6 +11,7 @@ import unittest from pathlib import Path, PurePosixPath +import env_sandbox from update_hosts.cursor import _distributed @@ -46,7 +47,7 @@ def test_installed_and_updated_bundle_runs_native_opencode_hooks(self): def _probe(self, plugin, workspace, mode): environment = {key: os.environ[key] for key in ("PATH", "TMPDIR", "LANG", "SystemRoot", "HELIXHARNESS_OPENCODE_BIN") if key in os.environ} - environment.update({"HOME": str(workspace), "NODE_PATH": ""}) + environment.update({**env_sandbox.home_vars(workspace), "NODE_PATH": ""}) result = subprocess.run([BUN, str(PLUGIN / "opencode/tests/managed-bundle-probe.ts"), str(plugin), str(workspace), mode], cwd=workspace, env=environment, capture_output=True, text=True, timeout=60) self.assertEqual(result.returncode, 0, result.stdout + result.stderr) diff --git a/helixharness/scripts/tests/test_cursor_hook_fastpath.py b/helixharness/scripts/tests/test_cursor_hook_fastpath.py index e9d6b74..ad41e9c 100644 --- a/helixharness/scripts/tests/test_cursor_hook_fastpath.py +++ b/helixharness/scripts/tests/test_cursor_hook_fastpath.py @@ -116,7 +116,7 @@ def test_default_and_tilde_home_resolution_preserve_endpoint_selection(self): home = self.home / relative home.mkdir(parents=True) (home / 'config.json').write_text(json.dumps({'endpoint': endpoint})) - env = {**self.env, 'HOME': str(self.home)} + env = {**self.env, **env_sandbox.home_vars(self.home)} if override is None: env.pop('HELIXHARNESS_TELEMETRY_HOME') else: diff --git a/helixharness/scripts/tests/test_user_commands.py b/helixharness/scripts/tests/test_user_commands.py index 0add133..c9dbaea 100644 --- a/helixharness/scripts/tests/test_user_commands.py +++ b/helixharness/scripts/tests/test_user_commands.py @@ -11,6 +11,7 @@ from pathlib import Path from unittest import mock +import env_sandbox import project_status import reporting_config import telemetry_consent @@ -30,7 +31,7 @@ def setUp(self): self.home = self.root / 'home' self.home.mkdir() patch = mock.patch.dict(os.environ, { - 'HOME': str(self.home), 'CODEX_HOME': str(self.home / 'codex'), + **env_sandbox.home_vars(self.home), 'CODEX_HOME': str(self.home / 'codex'), 'CLAUDE_CONFIG_DIR': str(self.home / 'claude'), 'HELIXHARNESS_TELEMETRY_HOME': str(self.home / 'telemetry'), 'HELIXHARNESS_FEEDBACK_HOME': str(self.home / 'feedback'), diff --git a/helixharness/scripts/tests/test_user_config_notice.py b/helixharness/scripts/tests/test_user_config_notice.py index e7a1a7e..2a0c76d 100644 --- a/helixharness/scripts/tests/test_user_config_notice.py +++ b/helixharness/scripts/tests/test_user_config_notice.py @@ -16,6 +16,7 @@ from pathlib import Path from unittest import mock +import env_sandbox import telemetry_consent import user_config @@ -30,7 +31,7 @@ def setUp(self): self.home = self.root / 'home' self.home.mkdir() patch = mock.patch.dict(os.environ, { - 'HOME': str(self.home), 'CODEX_HOME': str(self.home / 'codex'), + **env_sandbox.home_vars(self.home), 'CODEX_HOME': str(self.home / 'codex'), 'CLAUDE_CONFIG_DIR': str(self.home / 'claude'), 'HELIXHARNESS_CURSOR_HOME': str(self.home / 'cursor'), 'HELIXHARNESS_TELEMETRY_HOME': str(self.home / 'telemetry'), From 0be859c8598780bc5785391697519fa38c954dfc Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Wed, 25 Nov 2026 10:26:57 +0800 Subject: [PATCH 19/37] =?UTF-8?q?test(windows):=20=E7=BB=99=20node=20?= =?UTF-8?q?=E5=AD=90=E8=BF=9B=E7=A8=8B=E8=A1=A5=20SystemRoot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit d2c gate 与 bundle 探针把 env 净化成只剩 PATH,Windows 上 node.exe 因此定位不到系统 加密 DLL,在 InitializeOncePerProcessInternal 断言 ncrypto::CSPRNG(nullptr, 0) 后以 134 中止。run 27 的 stderr 原文证实这与断言写法无关,是启动期缺环境变量,和 Python 的 _Py_HashRandomization_Init 同处理:复用 env_sandbox.boot_vars()。 --- .../scripts/tests/test_cursor_bundle_update.py | 3 ++- helixharness/scripts/tests/test_opencode_d2c_gate.py | 12 +++++++----- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/helixharness/scripts/tests/test_cursor_bundle_update.py b/helixharness/scripts/tests/test_cursor_bundle_update.py index 6358293..3f5dd83 100644 --- a/helixharness/scripts/tests/test_cursor_bundle_update.py +++ b/helixharness/scripts/tests/test_cursor_bundle_update.py @@ -140,7 +140,8 @@ def release(version): shutil.copytree(plugin, damaged) (damaged / "opencode" / missing).unlink() process = subprocess.run([BUN, str(PLUGIN / "opencode/tests/managed-bundle-probe.ts"), str(damaged), str(workspace), "setup"], - cwd=workspace, env={"PATH": os.environ.get("PATH", ""), "HOME": str(workspace), "NODE_PATH": ""}, + cwd=workspace, env={**env_sandbox.boot_vars(), **env_sandbox.home_vars(workspace), + "PATH": os.environ.get("PATH", ""), "NODE_PATH": ""}, capture_output=True, text=True, timeout=15) self.assertNotEqual(process.returncode, 0) self.assertIn(missing, process.stderr) diff --git a/helixharness/scripts/tests/test_opencode_d2c_gate.py b/helixharness/scripts/tests/test_opencode_d2c_gate.py index a122d94..46ec85e 100644 --- a/helixharness/scripts/tests/test_opencode_d2c_gate.py +++ b/helixharness/scripts/tests/test_opencode_d2c_gate.py @@ -12,6 +12,8 @@ import zlib from datetime import datetime, timedelta, timezone +import env_sandbox + PLUGIN = Path(__file__).resolve().parents[2] GATE = PLUGIN / "hosts/opencode/d2c_gate.cjs" @@ -58,7 +60,7 @@ def run_gate(self, action="stop", session="synthetic-native-session", *extra): if session is not None: args += ["--session-id", session] result = subprocess.run(args + list(extra), cwd=self.root, capture_output=True, - text=True, timeout=10, env={"PATH": os.environ.get("PATH", "")}) + text=True, timeout=10, env={**env_sandbox.boot_vars(), "PATH": os.environ.get("PATH", "")}) self.assertEqual(result.stderr, "", result.stderr) return result.returncode, json.loads(result.stdout) @@ -336,7 +338,7 @@ def test_git_discovered_source_symlink_rejected_before_external_read(self): "--repo-root", str(self.root), "--page-dir", self.page, "--started-at", self.started, "--session-id", "synthetic-native-session", "--action", "stop"], cwd=self.root, capture_output=True, text=True, timeout=10, - env={"PATH": os.environ.get("PATH", ""), "TEST_OUTSIDE": str(outside), "TEST_OBSERVED": str(observed)}) + env={**env_sandbox.boot_vars(), "PATH": os.environ.get("PATH", ""), "TEST_OUTSIDE": str(outside), "TEST_OBSERVED": str(observed)}) self.assertEqual(result.returncode, 2, result.stdout) self.assertFalse(observed.exists(), "external source was read before the rejection") @@ -417,7 +419,7 @@ def test_canonical_vertical_producer_unresolved_warning_is_preserved(self): "--url", "http://localhost/synthetic", "--page-dir", str(self.page_dir), "--out", str(self.round_dir), "--scope", "synthetic-scope", "--wait", "0"], cwd=self.root, capture_output=True, text=True, timeout=10, - env={"PATH": os.environ.get("PATH", "")}) + env={**env_sandbox.boot_vars(), "PATH": os.environ.get("PATH", "")}) self.assertEqual(result.returncode, 0, (result.stdout, result.stderr)) path = self.round_dir / "vertical-diff.json" original = path.read_bytes() @@ -483,7 +485,7 @@ def test_concurrent_claim_is_exclusive_and_restart_cannot_be_overwritten(self): args = [shutil.which("node"), "--require", str(preload), str(GATE), "--repo-root", str(self.root), "--page-dir", self.page, "--started-at", self.started, "--action", "claim", "--session-id", "first-native-session"] first = subprocess.Popen(args, cwd=self.root, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, - env={"PATH": os.environ.get("PATH", ""), "TEST_ARRIVED": str(arrived), "TEST_RELEASE": str(release)}) + env={**env_sandbox.boot_vars(), "PATH": os.environ.get("PATH", ""), "TEST_ARRIVED": str(arrived), "TEST_RELEASE": str(release)}) try: deadline = time.monotonic() + 5 while not arrived.exists() and time.monotonic() < deadline: @@ -544,7 +546,7 @@ def test_mutating_checkpoint_locks_before_reading_its_state(self): first = subprocess.Popen([shutil.which("node"), "--require", str(preload), str(checkpoint), "--page-dir", self.page, "--pause", "user-cancelled", "--reason", "synthetic-first-operation"], cwd=self.root, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, - env={"PATH": os.environ.get("PATH", ""), "TEST_ARRIVED": str(arrived), "TEST_RELEASE": str(release)}) + env={**env_sandbox.boot_vars(), "PATH": os.environ.get("PATH", ""), "TEST_ARRIVED": str(arrived), "TEST_RELEASE": str(release)}) try: deadline = time.monotonic() + 5 while not arrived.exists() and time.monotonic() < deadline: From 1120f9a7e7d42a58e922d31dfa92c3a7f4bddb59 Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Wed, 25 Nov 2026 10:56:44 +0800 Subject: [PATCH 20/37] =?UTF-8?q?test(windows):=20=E5=AE=BF=E4=B8=BB=20CLI?= =?UTF-8?q?=20=E5=AD=98=E6=A0=B9=E8=A1=A5=E4=B8=80=E4=B8=AA=20PATHEXT=20?= =?UTF-8?q?=E5=8F=AF=E8=A7=81=E7=9A=84=E5=8C=85=E8=A3=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit update host 通过 shutil.which(argv[0]) 解析裸命令名(update_hosts/base.py:71), Windows 的 CreateProcess 只补 .exe,于是只有 shebang 的 bin/codex 起不来:check 没写过 state/cache.json,prepare 读它时经 version_update.py:163 合并成的同一句 "invalid JSON file" 报出,run 28 里这种伪装成 JSON 问题的失败 22 个。env_sandbox 增加 cli_stub,POSIX 仍是 shebang 加执行位,Windows 另写 .cmd 包装,形态沿用 test_claude_event_stream.py 里已有的写法。 --- helixharness/scripts/tests/env_sandbox.py | 16 ++++++++++++++++ .../tests/test_claude_update_scenarios.py | 5 ++--- .../scripts/tests/test_codex_update_scenarios.py | 4 +--- 3 files changed, 19 insertions(+), 6 deletions(-) diff --git a/helixharness/scripts/tests/env_sandbox.py b/helixharness/scripts/tests/env_sandbox.py index 581f6cd..6d52584 100644 --- a/helixharness/scripts/tests/env_sandbox.py +++ b/helixharness/scripts/tests/env_sandbox.py @@ -61,6 +61,22 @@ def home_vars(home: Path | str) -> dict[str, str]: return {"HOME": value, "USERPROFILE": value} +def cli_stub(path: Path, body: str) -> Path: + """Write a fixture host CLI that the platform can actually start. + + POSIX honours the shebang line, and the update hosts resolve bare command + names through `shutil.which`. Windows CreateProcess only appends `.exe`, so + a shebang-only stub is invisible there: the host command fails to start and + the version cache is never written. The `.cmd` wrapper is what PATHEXT finds. + """ + path.write_text("#!" + sys.executable + "\n" + body, encoding="utf-8") + path.chmod(0o700) + if os.name == "nt": + wrapper = path.parent / (path.name + ".cmd") + wrapper.write_text('@"' + sys.executable + '" "' + str(path) + '" %*\n', encoding="utf-8") + return path + + def search_path() -> str: """Minimal PATH: the test interpreter, the fixture binaries, the platform defaults.""" parts = [str(Path(sys.executable).parent), *toolchain_dirs(), os.defpath] diff --git a/helixharness/scripts/tests/test_claude_update_scenarios.py b/helixharness/scripts/tests/test_claude_update_scenarios.py index 838faee..0bc1834 100644 --- a/helixharness/scripts/tests/test_claude_update_scenarios.py +++ b/helixharness/scripts/tests/test_claude_update_scenarios.py @@ -12,6 +12,7 @@ import sys import unittest +import env_sandbox import test_codex_update_scenarios as fixtures NATIVE_STUB = r''' @@ -74,9 +75,7 @@ class ClaudeUpdateScenarioTests(unittest.TestCase): def setUp(self): fixtures.CodexUpdateScenarioTests.setUp(self) self.native(scope_versions={"user": "1.0.0"}, repo_root=str(self.repo)) - stub = self.root / "bin/claude" - stub.write_text("#!" + sys.executable + "\n" + NATIVE_STUB) - stub.chmod(0o700) + env_sandbox.cli_stub(self.root / "bin/claude", NATIVE_STUB) self.env.pop("CODEX_THREAD_ID") self.env["CLAUDE_PLUGIN_ROOT"] = str(self.plugin) self.env["CLAUDE_PROJECT_DIR"] = str(self.repo) diff --git a/helixharness/scripts/tests/test_codex_update_scenarios.py b/helixharness/scripts/tests/test_codex_update_scenarios.py index 073e225..f373f20 100644 --- a/helixharness/scripts/tests/test_codex_update_scenarios.py +++ b/helixharness/scripts/tests/test_codex_update_scenarios.py @@ -103,9 +103,7 @@ def setUp(self): })) bin_dir = self.root / "bin" bin_dir.mkdir() - stub = bin_dir / "codex" - stub.write_text("#!" + sys.executable + "\n" + NATIVE_STUB) - stub.chmod(0o700) + env_sandbox.cli_stub(bin_dir / "codex", NATIVE_STUB) # An allowlist avoids inheriting real host identity, credentials, Python # import paths, endpoints or configuration. The actual Codex CLI is shadowed. self.env = { From d673ecc2d123ffa4081d46819b1a965999902ea8 Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Wed, 25 Nov 2026 10:56:52 +0800 Subject: [PATCH 21/37] =?UTF-8?q?test(windows):=20POSIX=20shell=20?= =?UTF-8?q?=E5=A4=B9=E5=85=B7=E6=98=BE=E5=BC=8F=E8=B7=B3=E8=BF=87=EF=BC=8C?= =?UTF-8?q?=E4=BF=9D=E4=BD=8F=E5=8E=9F=E7=94=9F=E5=91=BD=E4=BB=A4=E6=96=AD?= =?UTF-8?q?=E8=A8=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 这组夹具把 sh 和 dirname 符号链接进一个空的 bin 来隔离 PATH,Windows 上无法 等价:MSYS 只从自身目录启动,而那个目录同时带着真 git 和 python3,正是这些 用例要按意图移除的东西,硬跑会把干净的失败换成语义错误的失败。按 test_runtime_preflight.py:20 的既有先例处理,但只跳过真正执行 shell 命令的 用例,test_native_windows_binding_gates_before_using_the_selected_launcher 与用 ambient PATH 的 argv 保真用例在 Windows 上照跑。同时改掉那句声称 "原生 Git Bash 行为在 Windows CI 另有覆盖"的注释——它本来不成立。 --- .../tests/test_cursor_entry_repairs.py | 34 ++++++++++++++----- .../scripts/tests/test_cursor_hooks.py | 1 + 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/helixharness/scripts/tests/test_cursor_entry_repairs.py b/helixharness/scripts/tests/test_cursor_entry_repairs.py index 15898fa..6de1298 100644 --- a/helixharness/scripts/tests/test_cursor_entry_repairs.py +++ b/helixharness/scripts/tests/test_cursor_entry_repairs.py @@ -37,9 +37,16 @@ def setUp(self): shutil.copyfile(ROOT / "scripts" / name, self.plugin / "scripts" / name) self.bin = self.base / "bin" self.bin.mkdir() - (self.bin / "sh").symlink_to("/bin/sh") - (self.bin / "dirname").symlink_to("/usr/bin/dirname") self.marker = self.base / "resolver-called" + self.shell, dirname = shutil.which("sh"), shutil.which("dirname") + # Linking sh and dirname into an otherwise empty bin directory is how + # this fixture isolates PATH. Windows has no such isolated runtime: MSYS + # only starts from its own directory, which also ships a real git and + # python3 that these cases remove on purpose. + self.posix_ready = os.name != "nt" and bool(self.shell and dirname) + if self.posix_ready: + (self.bin / "sh").symlink_to(self.shell) + (self.bin / "dirname").symlink_to(dirname) self.env = {"PATH": str(self.bin), "SYNTHETIC_RESOLVER_CALL": str(self.marker)} self.registry = HostRegistry.discover(ROOT / "hosts") @@ -68,9 +75,14 @@ def command(self, host: str) -> str: self.assertEqual(1, len(commands)) return commands[0] + def require_posix_shell(self) -> None: + if not self.posix_ready: + self.skipTest("this case runs the emitted sh preflight line under a sandboxed PATH") + def run_command(self, host: str): + self.require_posix_shell() return subprocess.run( - ["/bin/sh", "-c", self.command(host)], env=self.env, + [self.shell, "-c", self.command(host)], env=self.env, text=True, capture_output=True, timeout=10, ) @@ -118,8 +130,9 @@ def test_missing_git_stops_before_resolver_even_when_python_ready(self): self.assert_blocked_all_hosts("ready", "missing") def test_windows_claude_bash_gate_blocks_failures_and_accepts_crlf(self): - # Synthetic Windows selection executed by a real POSIX shell. Native - # Git Bash path/argv behavior is covered separately on Windows CI. + # Synthetic Windows selection executed by a real POSIX shell. Only the + # generated Windows command text is asserted natively below; executing + # it under Git Bash is not covered anywhere, and this case skips there. with patch("lifecycle_service.os", SimpleNamespace(name="nt")): for version, git, code in (("3.12.0\r", True, 0), ("3.9.6\r", True, 2), ("broken\r", True, 2), (None, True, 2), @@ -133,11 +146,12 @@ def test_windows_claude_bash_gate_blocks_failures_and_accepts_crlf(self): self.assertEqual(code == 0, self.marker.exists()) def test_check_keeps_diagnostic_exit_contract_while_require_gates(self): + self.require_posix_shell() self.runtimes(python=None, git=False) outputs = [] for action, exit_code in (("check", 0), ("require", 2)): result = subprocess.run( - ["/bin/sh", str(self.plugin / "scripts/runtime_preflight.sh"), action], + [self.shell, str(self.plugin / "scripts/runtime_preflight.sh"), action], env=self.env, text=True, capture_output=True, timeout=10, ) self.assertEqual(exit_code, result.returncode) @@ -157,12 +171,13 @@ def test_native_windows_binding_gates_before_using_the_selected_launcher(self): self.assertNotIn("require &&", context) def test_ready_guard_runs_real_resolver_with_each_original_host_contract(self): + self.require_posix_shell() for host in ("cursor", "claude-code", "codex"): with self.subTest(host=host): context = startup_context_text(self.registry.require(host)) command = next(line for line in context.splitlines() if line.startswith("sh ")) env = {**os.environ, "PATH": str(Path(sys.executable).parent) + os.pathsep + os.environ.get("PATH", "")} - result = subprocess.run(["/bin/sh", "-c", command], env=env, text=True, capture_output=True, timeout=10) + result = subprocess.run([self.shell, "-c", command], env=env, text=True, capture_output=True, timeout=10) self.assertEqual(0, result.returncode, result.stderr) decoder = json.JSONDecoder() check, offset = decoder.raw_decode(result.stdout) @@ -190,7 +205,10 @@ def test_one_router_process_keeps_entire_message_and_does_not_execute_shell_text "route", "--command", "propose", "--arguments=" + argument, "--arguments-mode", "auto", ]) env = {**os.environ, "PYTHONDONTWRITEBYTECODE": "1"} - result = subprocess.run(["/bin/sh", "-c", command], cwd=repo, env=env, + shell = shutil.which("sh") + if shell is None: + self.skipTest("argv fidelity is only proved through a real shell") + result = subprocess.run([shell, "-c", command], cwd=repo, env=env, text=True, capture_output=True, timeout=10) self.assertEqual(0, result.returncode, result.stderr) routed = json.loads(result.stdout) diff --git a/helixharness/scripts/tests/test_cursor_hooks.py b/helixharness/scripts/tests/test_cursor_hooks.py index eb0000e..1c30775 100644 --- a/helixharness/scripts/tests/test_cursor_hooks.py +++ b/helixharness/scripts/tests/test_cursor_hooks.py @@ -150,6 +150,7 @@ def test_mixed_host_init_preserves_existing_configs_and_repeats_cleanly(self): self.assertEqual(2, len(native["hooks"]["afterFileEdit"])) +@unittest.skipIf(os.name == "nt", "POSIX launcher fixtures; native coverage in test_windows_runtime") class CursorHookBootstrapTest(unittest.TestCase): def test_hook_and_command_preflight_agree_on_python_boundary(self): for version, ready in (((3, 8, 0), False), ((3, 9, 6), False), ((3, 10, 0), True), ((3, 12, 0), True)): From ba2275dc768085b1bfafcbfe61c5351e7db5f662 Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Wed, 25 Nov 2026 11:27:42 +0800 Subject: [PATCH 22/37] =?UTF-8?q?fix(windows):=20JSON=20CLI=20=E8=87=AA?= =?UTF-8?q?=E5=B7=B1=E4=BF=9D=E8=AF=81=20UTF-8=20=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit version_update.py 与 user_config.py 把 ensure_ascii=False 的结果直接写到 stdout。Windows 默认代码页 cp1252 编不出安装路径里的非 ASCII 字符,print 就抛 UnicodeEncodeError,宿主收到的是一段 traceback 而不是它要解析的 JSON。 Windows 3.12 剩余 41 个失败里 26 个是这一个原因(claude 10、codex 10、 codex lifecycle 6,逐帧核对到 version_update.py:1545 和 user_config.py:210)。 这不是夹具该迁就的环境差异:仓库已经把这条契约写成测试 (test_metrics.py 的 consent CLI 在 -X utf8=0 加 Unicode 路径下仍须退出 0), telemetry_consent.py 里也早有对应的 stdio 护栏。所以把护栏提成共享的 scripts/cli_stdio.py,三个入口在 main() 首行调用,不再各自假设调用方一定 经过带 -X utf8 的 {helix_python} 启动器。 新增 test_cli_stdio.py 把契约钉在跨平台可跑的位置:强制 C locale 且关掉 PEP 538 补偿,先用探针确认本机 stdio 真的落到了遗留编码(否则 skip,不让 测试空过),再对子进程 stdout 做严格 UTF-8 解码并断言中文路径原样回环。 本地验证:改前两命令均 UnicodeEncodeError 退出 1,改后输出合法 UTF-8 JSON 退出 0;全量 945 tests OK (skipped=12),新模块 2 tests OK。 --- helixharness/scripts/cli_stdio.py | 20 +++++ helixharness/scripts/telemetry_consent.py | 12 +-- helixharness/scripts/tests/test_cli_stdio.py | 85 ++++++++++++++++++++ helixharness/scripts/user_config.py | 2 + helixharness/scripts/version_update.py | 2 + 5 files changed, 111 insertions(+), 10 deletions(-) create mode 100644 helixharness/scripts/cli_stdio.py create mode 100644 helixharness/scripts/tests/test_cli_stdio.py diff --git a/helixharness/scripts/cli_stdio.py b/helixharness/scripts/cli_stdio.py new file mode 100644 index 0000000..5c05b4e --- /dev/null +++ b/helixharness/scripts/cli_stdio.py @@ -0,0 +1,20 @@ +"""UTF-8 streams for the plugin's JSON command-line contracts.""" + +from __future__ import annotations + +import sys + + +def configure_utf8_stdio() -> None: + """Keep a JSON CLI readable no matter which interpreter invoked it. + + `{helix_python}` appends `-X utf8` and CI exports `PYTHONUTF8=1`, so a normal + run already is UTF-8. The contract must still hold for a caller that does not: + these CLIs echo installation paths with `ensure_ascii=False`, a legacy Windows + code page cannot encode CJK, and the host then receives a traceback instead of + the JSON it parses. + """ + for stream in (sys.stdout, sys.stderr): + reconfigure = getattr(stream, "reconfigure", None) + if reconfigure is not None: + reconfigure(encoding="utf-8", errors="strict") diff --git a/helixharness/scripts/telemetry_consent.py b/helixharness/scripts/telemetry_consent.py index 2f359f4..5a85360 100644 --- a/helixharness/scripts/telemetry_consent.py +++ b/helixharness/scripts/telemetry_consent.py @@ -10,7 +10,6 @@ import re import secrets import subprocess -import sys import tempfile import time from contextlib import contextmanager @@ -23,6 +22,7 @@ import atomic_files import eval_json from telemetry_async import endpoint_skip +from cli_stdio import configure_utf8_stdio SCHEMA_VERSION = "1.0" @@ -41,14 +41,6 @@ } -def _configure_utf8_stdio() -> None: - """Keep the JSON CLI contract UTF-8 under legacy Windows code pages.""" - for stream in (sys.stdout, sys.stderr): - reconfigure = getattr(stream, "reconfigure", None) - if reconfigure is not None: - reconfigure(encoding="utf-8", errors="strict") - - PROJECT_KEY_PATTERN = re.compile(r"^prj_[0-9a-f]{16}$") CONSENT_EPOCH_PATTERN = re.compile(r"^cep_[0-9a-f]{24}$") SCOPE_TIME_FIELDS = {"enabled_at", "disabled_at", "last_prompted_at", "next_prompt_after"} @@ -851,7 +843,7 @@ def _parser() -> argparse.ArgumentParser: def main() -> int: - _configure_utf8_stdio() + configure_utf8_stdio() args = _parser().parse_args() repo: Path | None = None try: diff --git a/helixharness/scripts/tests/test_cli_stdio.py b/helixharness/scripts/tests/test_cli_stdio.py new file mode 100644 index 0000000..dbaecfc --- /dev/null +++ b/helixharness/scripts/tests/test_cli_stdio.py @@ -0,0 +1,85 @@ +"""JSON CLI entries must still answer a caller that runs in legacy Windows mode. + +`{helix_python}` appends `-X utf8`, but a plugin script also gets invoked by +anything that does not use the launcher. These entries echo installation paths, +so a code page that cannot encode them replaces the JSON with a traceback and the +host loses the result entirely. +""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +import env_sandbox + +PLUGIN_ROOT = Path(__file__).resolve().parents[2] +CJK_NAME = "应用 空格" + + +class LegacyCodePageCliTest(unittest.TestCase): + def setUp(self) -> None: + temporary = tempfile.TemporaryDirectory(prefix="helix-cli-stdio-") + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name).resolve() + self.repo = self.root / CJK_NAME + self.repo.mkdir() + self.env = { + **os.environ, + **env_sandbox.boot_vars(), + **env_sandbox.home_vars(self.root / "home"), + "LC_ALL": "C", + "LANG": "C", + "PYTHONUTF8": "0", + "PYTHONCOERCECLOCALE": "0", + "CODEX_HOME": str(self.root / "codex-home"), + "CLAUDE_CONFIG_DIR": str(self.root / "claude-home"), + "HELIXHARNESS_CURSOR_HOME": str(self.root / "cursor-home"), + "HELIXHARNESS_TELEMETRY_HOME": str(self.root / "telemetry-home"), + "HELIXHARNESS_FEEDBACK_HOME": str(self.root / "feedback-home"), + "HELIXHARNESS_TELEMETRY_DISABLE_SCHEDULER": "1", + } + self.env.pop("PYTHONIOENCODING", None) + + def require_legacy_stdio(self) -> None: + probe = subprocess.run( + [sys.executable, "-X", "utf8=0", "-c", + "import sys; print(sys.stdout.encoding.lower())"], + env=self.env, capture_output=True, text=True, timeout=20, + ) + if "utf" in probe.stdout.strip(): + self.skipTest("the C locale still yields UTF-8 stdio on this platform") + + def run_cli(self, script: str, *arguments: str) -> dict: + self.require_legacy_stdio() + completed = subprocess.run( + [sys.executable, "-X", "utf8=0", str(PLUGIN_ROOT / "scripts" / script), + "--platform", "codex", "--repo-root", str(self.repo), *arguments], + env=self.env, cwd=self.repo, capture_output=True, timeout=30, + ) + self.assertEqual(0, completed.returncode, + completed.stdout.decode("utf-8", errors="replace") + + completed.stderr.decode("utf-8", errors="replace")) + # Strict decode: a non-UTF-8 stream here is exactly the reported defect. + stdout = completed.stdout.decode("utf-8") + payload = json.loads(stdout) + self.assertIn(CJK_NAME, stdout) + return payload + + def test_version_update_answers_a_legacy_caller_with_utf8_json(self) -> None: + cache = self.root / ("installed plugin " + CJK_NAME) / "cache.json" + payload = self.run_cli("version_update.py", "--cache-path", str(cache), "resolve") + self.assertIn(CJK_NAME, payload["cache_path"]) + + def test_user_config_answers_a_legacy_caller_with_utf8_json(self) -> None: + payload = self.run_cli("user_config.py") + self.assertTrue(payload["read_only"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/helixharness/scripts/user_config.py b/helixharness/scripts/user_config.py index 213e459..b6baafb 100644 --- a/helixharness/scripts/user_config.py +++ b/helixharness/scripts/user_config.py @@ -12,6 +12,7 @@ import reporting_config import telemetry_consent from atomic_files import atomic_write_text +from cli_stdio import configure_utf8_stdio from telemetry_hosts import get_host_adapter, normalize_host_id @@ -135,6 +136,7 @@ def set_consent(repo: Path, platform: str, scope: str, mode: str, *, user_confir def main(argv: list[str] | None = None) -> int: + configure_utf8_stdio() parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--repo-root', required=True) parser.add_argument('--platform', required=True) diff --git a/helixharness/scripts/version_update.py b/helixharness/scripts/version_update.py index bceec32..281f664 100644 --- a/helixharness/scripts/version_update.py +++ b/helixharness/scripts/version_update.py @@ -17,6 +17,7 @@ import atomic_files import eval_json +from cli_stdio import configure_utf8_stdio from source_binding import guard_source from update_hosts import ( MARKETPLACE, @@ -1466,6 +1467,7 @@ def _parser() -> argparse.ArgumentParser: def main() -> int: + configure_utf8_stdio() guard_source(Path(__file__).resolve().parent.parent) args = _parser().parse_args() try: From a667c9c3f02a8ee594ba0603bc9b7d358a940b24 Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Wed, 25 Nov 2026 11:30:13 +0800 Subject: [PATCH 23/37] =?UTF-8?q?test(windows):=20=E6=8A=8A=E5=9B=9B?= =?UTF-8?q?=E7=BB=84=20Windows=20=E6=96=AD=E8=A8=80=E6=94=B9=E6=88=90?= =?UTF-8?q?=E4=B8=8E=E7=9C=9F=E5=AE=9E=E5=BD=A2=E6=80=81=E4=B8=80=E8=87=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 文档里的检测脚本用裸 `bash` 执行:CI 的 PATH 里 System32 在前,命中的是 WSL 启动器,没有发行版就返回 1 并吐出 UTF-16 文本。改用仓库已有的 git_bash(),它的注释写明“never the Windows/WSL launcher”,其他夹具也这么用。 - 净化 PATH 后只有 System32,而合并出来的 Windows hook 命令以 powershell.exe 开头(project_hooks_cli.py 的 WINDOWS_COMMAND_PREFIX), 实际二进制在 System32\WindowsPowerShell\v1.0。search_path() 补上该目录。 - 两处断言把内嵌 JSON 里的路径当纯文本子串比:Windows 反斜杠在 JSON 里 是双写的,shlex.quote 又把整段值引起来。改比 json.dumps(...)[1:-1], POSIX 下取值不变,因此不影响 macOS/Linux 的判定。 - sessionStart 的门形态断言写死了 POSIX 的 `require &&`;Windows 侧发的是 .ps1 检查形态,按 os.name 选择断言目标,保留“仍然带 preflight 门”的意图。 本地 52 tests OK:这几处改动在 POSIX 上与改前等价,只修 Windows。 --- helixharness/scripts/tests/env_sandbox.py | 25 ++++++++++++++++--- .../tests/test_cursor_hook_fastpath.py | 5 ++-- helixharness/scripts/tests/test_init_state.py | 6 ++++- .../scripts/tests/test_session_context.py | 4 +-- 4 files changed, 31 insertions(+), 9 deletions(-) diff --git a/helixharness/scripts/tests/env_sandbox.py b/helixharness/scripts/tests/env_sandbox.py index 6d52584..4e8b7d5 100644 --- a/helixharness/scripts/tests/env_sandbox.py +++ b/helixharness/scripts/tests/env_sandbox.py @@ -1,11 +1,12 @@ """Scrubbed subprocess environments that still boot Python on every platform. Host scenario fixtures deliberately clear the ambient environment so a developer's -tooling cannot make a case pass. Three facts about Windows break a naive scrub: +tooling cannot make a case pass. Four facts about Windows break a naive scrub: a child `python.exe` aborts in `_Py_HashRandomization_Init` unless `SystemRoot` is present, `os.defpath` has no Git install directory so `git` and `sh` — which the -fixtures themselves execute — cannot be resolved, and a scrubbed environment has no -home directory for `Path.home()` to fall back on. +fixtures themselves execute — cannot be resolved and neither can the `powershell.exe` +a merged Windows hook command starts with, and a scrubbed environment has no home +directory for `Path.home()` to fall back on. """ from __future__ import annotations @@ -77,9 +78,25 @@ def cli_stub(path: Path, body: str) -> Path: return path +def powershell_dirs() -> list[str]: + """Directory holding `powershell.exe`, which shipped Windows hook commands start with. + + A scrubbed PATH can only keep `System32`, and PowerShell lives two levels + deeper, so a fixture that runs the merged Windows command cannot even start + the launcher a real user terminal always finds. + """ + if os.name != "nt": + return [] + root = os.environ.get("SystemRoot") or os.environ.get("windir") + if not root: + return [] + candidate = Path(root) / "System32" / "WindowsPowerShell" / "v1.0" + return [str(candidate)] if (candidate / "powershell.exe").is_file() else [] + + def search_path() -> str: """Minimal PATH: the test interpreter, the fixture binaries, the platform defaults.""" - parts = [str(Path(sys.executable).parent), *toolchain_dirs(), os.defpath] + parts = [str(Path(sys.executable).parent), *toolchain_dirs(), *powershell_dirs(), os.defpath] seen, ordered = set(), [] for part in parts: if part and part not in seen: diff --git a/helixharness/scripts/tests/test_cursor_hook_fastpath.py b/helixharness/scripts/tests/test_cursor_hook_fastpath.py index ad41e9c..1f160c4 100644 --- a/helixharness/scripts/tests/test_cursor_hook_fastpath.py +++ b/helixharness/scripts/tests/test_cursor_hook_fastpath.py @@ -57,7 +57,8 @@ def test_cold_non_lifecycle_events_work_without_lifecycle_or_delivery_imports(se if event == 'beforeSubmitPrompt': context = actual.pop('additional_context') self.assertIn('HELIXHARNESS_CURSOR_CONVERSATION_ID=synthetic-fastpath', context) - self.assertIn(str(self.home), context) + # The roots travel as shlex-quoted JSON, so a Windows path is doubled. + self.assertIn(json.dumps(str(self.home))[1:-1], context) self.assertLessEqual(len(context.encode()), 8192) self.assertEqual(expected, actual) self.assertEqual([], list(self.home.iterdir())) @@ -139,7 +140,7 @@ def test_session_start_still_resolves_bound_host_and_emits_context(self): self.assertEqual(1, discover.call_count) result = json.loads(output.getvalue()) self.assertEqual(str(ROOT), result['env']['HELIXHARNESS_BOUND_PLUGIN_ROOT']) - self.assertIn('require &&', result['additional_context']) + self.assertIn('require &&' if os.name != 'nt' else 'runtime_preflight', result['additional_context']) if __name__ == '__main__': diff --git a/helixharness/scripts/tests/test_init_state.py b/helixharness/scripts/tests/test_init_state.py index 0e0f059..f89dddc 100644 --- a/helixharness/scripts/tests/test_init_state.py +++ b/helixharness/scripts/tests/test_init_state.py @@ -12,6 +12,7 @@ from unittest.mock import patch from project_hooks_cli import project_hooks +from project_linter import git_bash PLUGIN = Path(__file__).resolve().parents[2] SPEC = importlib.util.find_spec("init_state") @@ -216,7 +217,10 @@ def test_detection_reinitializes_a_previously_completed_run(self): (self.repo / "pom.xml").write_text("\n") protocol = (PLUGIN / "reference/project-type-detection.md").read_text() script = protocol.split("```bash\n", 1)[1].split("```", 1)[0] - process = subprocess.run(["bash", "-c", script], cwd=self.repo, + shell = git_bash() + if shell is None: + self.skipTest("the documented detection example needs a POSIX shell") + process = subprocess.run([shell, "-c", script], cwd=self.repo, text=True, capture_output=True, timeout=10) self.assertEqual(process.returncode, 0, process.stdout + process.stderr) self.assertEqual(self.state()["bootstrapStatus"], "pending") diff --git a/helixharness/scripts/tests/test_session_context.py b/helixharness/scripts/tests/test_session_context.py index 2317e22..1a0dd93 100644 --- a/helixharness/scripts/tests/test_session_context.py +++ b/helixharness/scripts/tests/test_session_context.py @@ -85,8 +85,8 @@ def test_skill_and_direct_command_refresh_source_next_to_entry(self): output = json.loads(self.run_hook(json.dumps(payload)).stdout)["hookSpecificOutput"] self.assertEqual(output["hookEventName"], payload["hook_event_name"]) context = output["additionalContext"] - self.assertIn(str(ROOT / "scripts/host_runtime_cli.py"), context) - self.assertIn(str(ROOT / "reference/runtime-preflight.md"), context) + for fragment in ("scripts/host_runtime_cli.py", "reference/runtime-preflight.md"): + self.assertIn(json.dumps(str(ROOT / fragment))[1:-1], context) self.assertIn('"resolved_resources"', context) self.assertNotIn("permissionDecision", output) From 7db9631a41737d7cbef06098503041380aec7cb2 Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Wed, 25 Nov 2026 12:08:48 +0800 Subject: [PATCH 24/37] =?UTF-8?q?fix(windows):=20=E6=8A=8A=20UTF-8=20stdio?= =?UTF-8?q?=20=E5=AE=88=E5=8D=AB=E9=93=BA=E6=BB=A1=E5=85=A8=E9=83=A8=20JSO?= =?UTF-8?q?N=20=E5=91=BD=E4=BB=A4=E8=A1=8C=E5=85=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 上一个入口级修复后 Windows 3.12 仍剩 17 个,说明逐条修不是收敛路径:`scripts/` 与 `hosts/` 里 `main()` 用 `ensure_ascii=False` 打印 JSON 的入口有 25 个,此前只有 3 个调 `configure_utf8_stdio()`。这轮 `metrics.py:721` 是下一个,它的异常又被自身的 `except` 包成 `invalid lite metrics: 'charmap' …`,所以看着像一类新问题。 - 22 个入口补守卫,含 `hosts/claude-code` 与 `hosts/cursor` 两个 hook 入口。 - `test_cli_stdio.py` 增加 AST 覆盖规则:入口内出现非 ASCII JSON 打印就必须先调守卫, 且位置在第一条这样的打印之前。规则当场抓出 `hosts/cursor/hook_entry.py` 这个按行 匹配漏掉的入口,也避免以后新增入口再漏。 - `RUNTIME_FILES` 补 `cli_stdio.py`:统计运行时按清单拷快照并用 `python -I` 执行,缺了 它就是一个起不来的快照;同处加断言守住这层耦合。 - 4 处默认编码文件 IO 显式 `encoding="utf-8"`(`claude_event_stream.py` 两处、 `cursor_native_install.py`、`telemetry_hosts/cursor.py`)。其余 `open()` 逐个核过: 是 `a+b`/`rb` 锁文件或只写 ASCII `"0"`,没有码页风险。 - 更新场景建桩用默认编码读 `.codex-plugin/plugin.json`(实测含 111 个非 ASCII 字节), Windows 上 cp1252 解码失败即 `plugin update step failed: update-default`;建桩改为显式 utf-8。步骤失败信息同时带上底层原因——此前真实原因只落在私有 authorization 文件里。 - `SessionContextTest` 两处断言改回真实形态:`hosts/claude-code/hook_entry.py` 硬编码 `command_shell="bash"`,命令体路径走 `as_posix()`,只有追加的说明句是原生路径。上一次 按 JSON 转义比对是错方向。POSIX 下两种写法取值相同,不改变 macOS/Linux 的判定。 本地 `python scripts/run_tests.py` 949 tests OK(skipped=12),`codex_skill_projection.py --check` PASS。 --- helixharness/hosts/claude-code/hook_entry.py | 2 + helixharness/hosts/cursor/hook_entry.py | 2 + helixharness/scripts/claude_event_stream.py | 5 +- helixharness/scripts/codex_entry_load.py | 2 + .../scripts/cursor_managed_install.py | 2 + helixharness/scripts/cursor_native_install.py | 4 +- .../scripts/cursor_skill_projection.py | 2 + helixharness/scripts/feedback_submit.py | 2 + helixharness/scripts/host_runtime_cli.py | 2 + helixharness/scripts/init_guidance.py | 2 + helixharness/scripts/metrics.py | 2 + helixharness/scripts/package_qoder_plugin.py | 2 + helixharness/scripts/project_status.py | 2 + helixharness/scripts/task_plan.py | 2 + helixharness/scripts/telemetry_async.py | 3 + helixharness/scripts/telemetry_collector.py | 2 + .../scripts/telemetry_hosts/cursor.py | 2 +- helixharness/scripts/telemetry_ledger.py | 2 + helixharness/scripts/telemetryctl.py | 2 + .../tests/test_claude_update_scenarios.py | 4 +- helixharness/scripts/tests/test_cli_stdio.py | 55 +++++++++++++++++++ .../tests/test_codex_update_scenarios.py | 4 +- .../scripts/tests/test_cursor_integration.py | 3 +- .../scripts/tests/test_session_context.py | 6 +- helixharness/scripts/ut_artifacts.py | 2 + helixharness/scripts/ut_precompile.py | 2 + helixharness/scripts/validate_init_outputs.py | 2 + helixharness/scripts/version_update.py | 2 +- helixharness/scripts/workflow.py | 2 + helixharness/scripts/workflow_router.py | 2 + helixharness/scripts/workspace.py | 2 + 31 files changed, 118 insertions(+), 12 deletions(-) diff --git a/helixharness/hosts/claude-code/hook_entry.py b/helixharness/hosts/claude-code/hook_entry.py index 1940ea6..6b9c844 100755 --- a/helixharness/hosts/claude-code/hook_entry.py +++ b/helixharness/hosts/claude-code/hook_entry.py @@ -10,6 +10,7 @@ ROOT = Path(__file__).resolve().parents[2] sys.path.insert(0, str(ROOT / "scripts")) +from cli_stdio import configure_utf8_stdio # noqa: E402 from host_runtime import HostRegistry # noqa: E402 from lifecycle_service import handle_event, startup_context # noqa: E402 @@ -34,6 +35,7 @@ def persist_environment(payload: dict) -> None: def main() -> int: + configure_utf8_stdio() try: payload = json.load(sys.stdin) if not isinstance(payload, dict): diff --git a/helixharness/hosts/cursor/hook_entry.py b/helixharness/hosts/cursor/hook_entry.py index 7c12928..6f6c4f3 100644 --- a/helixharness/hosts/cursor/hook_entry.py +++ b/helixharness/hosts/cursor/hook_entry.py @@ -10,6 +10,7 @@ ROOT = Path(__file__).resolve().parents[2] sys.path.insert(0, str(ROOT / "scripts")) +from cli_stdio import configure_utf8_stdio # noqa: E402 from telemetry_hosts.cursor import HOOK_EVENTS, HOOK_BUDGET_SECONDS, native_identity, native_identity_fields, record_hook # noqa: E402 EVENTS = {"sessionStart": "SessionStart", "sessionEnd": "SessionEnd"} @@ -59,6 +60,7 @@ def _spawn_cleanup(workspaces: list[str]) -> None: def main() -> int: + configure_utf8_stdio() deadline = time.monotonic() + HOOK_BUDGET_SECONDS try: raw = sys.stdin.read(4 * 1024 * 1024 + 1) diff --git a/helixharness/scripts/claude_event_stream.py b/helixharness/scripts/claude_event_stream.py index 8238268..ce42b48 100644 --- a/helixharness/scripts/claude_event_stream.py +++ b/helixharness/scripts/claude_event_stream.py @@ -134,7 +134,7 @@ def run(args: argparse.Namespace) -> int: process = spawn_group(cmd, cwd=project, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=0) (output / "process.json").write_text(json.dumps({"pid": process.pid, "plugin_root": str(root), - "project": str(project)})) + "project": str(project)}), encoding="utf-8") def send(message: dict[str, Any]) -> None: if process.stdin.closed: raise RuntimeError("native task notice arrived after input was closed") @@ -211,7 +211,8 @@ def read_output(): result = {"exit_code": code, "timed_out": timed_out, "driver_error": driver_error, "seconds": round(time.monotonic() - start, 1), "terminal": relay.terminal, "active_tasks": sorted(relay.active), "pending_relays": len(relay.pending_messages)} - (output / "driver-result.json").write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n") + (output / "driver-result.json").write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", + encoding="utf-8") # Native exit 0 and a final reply still do not establish workflow acceptance. return 0 if code == 0 and relay.terminal and not relay.failed and not timed_out and not driver_error else 1 diff --git a/helixharness/scripts/codex_entry_load.py b/helixharness/scripts/codex_entry_load.py index 231c3ce..d42b1f7 100644 --- a/helixharness/scripts/codex_entry_load.py +++ b/helixharness/scripts/codex_entry_load.py @@ -15,6 +15,7 @@ from pathlib import Path, PurePosixPath from source_binding import guard_source from typing import Any, Sequence +from cli_stdio import configure_utf8_stdio SCHEMA_VERSION = "1.1" MAX_RESOURCE_BYTES = 2 * 1024 * 1024 @@ -581,6 +582,7 @@ def finish_entry( def main(argv: Sequence[str] | None = None) -> int: + configure_utf8_stdio() guard_source(Path(__file__).resolve().parent.parent) parser = argparse.ArgumentParser() parser.add_argument("--plugin-root", type=Path, required=True) diff --git a/helixharness/scripts/cursor_managed_install.py b/helixharness/scripts/cursor_managed_install.py index 7985625..f7262e6 100644 --- a/helixharness/scripts/cursor_managed_install.py +++ b/helixharness/scripts/cursor_managed_install.py @@ -9,9 +9,11 @@ from update_hosts.base import BoundedCommandRunner, UpdateHostError from update_hosts.cursor import CursorUpdateAdapter from version_update import _read_json, _version_text +from cli_stdio import configure_utf8_stdio def main() -> int: + configure_utf8_stdio() parser = argparse.ArgumentParser(description=__doc__) commands = parser.add_subparsers(dest="command", required=True) install = commands.add_parser("install") diff --git a/helixharness/scripts/cursor_native_install.py b/helixharness/scripts/cursor_native_install.py index 56dcfe5..1cf8d32 100644 --- a/helixharness/scripts/cursor_native_install.py +++ b/helixharness/scripts/cursor_native_install.py @@ -15,6 +15,7 @@ import atomic_files import eval_json from update_hosts.base import BoundedCommandRunner +from cli_stdio import configure_utf8_stdio if os.name == "nt": import msvcrt @@ -38,7 +39,7 @@ def read(path): return {} if not path.is_file() or path.stat().st_size > 1024 * 1024: raise ValueError("configuration must be a bounded JSON file") - value = eval_json.loads(path.read_text()) + value = eval_json.loads(path.read_text(encoding="utf-8")) if not isinstance(value, dict): raise ValueError("configuration must be a JSON object") return value @@ -276,6 +277,7 @@ def check(self, snapshot, plugin_root): def main(): + configure_utf8_stdio() parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("action", choices=("plan", "configure", "check", "restore")) parser.add_argument("--project-root", required=True) diff --git a/helixharness/scripts/cursor_skill_projection.py b/helixharness/scripts/cursor_skill_projection.py index 8df980f..534ddc5 100644 --- a/helixharness/scripts/cursor_skill_projection.py +++ b/helixharness/scripts/cursor_skill_projection.py @@ -8,6 +8,7 @@ import re from pathlib import Path from typing import Sequence +from cli_stdio import configure_utf8_stdio PLUGIN_ROOT = Path(__file__).resolve().parents[1] @@ -209,6 +210,7 @@ def check(plugin_root: Path) -> None: def main(argv: Sequence[str] | None = None) -> int: + configure_utf8_stdio() parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--root", type=Path, default=PLUGIN_ROOT) actions = parser.add_mutually_exclusive_group(required=True) diff --git a/helixharness/scripts/feedback_submit.py b/helixharness/scripts/feedback_submit.py index 12c25dc..608467c 100755 --- a/helixharness/scripts/feedback_submit.py +++ b/helixharness/scripts/feedback_submit.py @@ -40,6 +40,7 @@ _SECRET_PATTERNS, sanitize_text, ) +from cli_stdio import configure_utf8_stdio SCHEMA_VERSION = "1.0" PLUGIN_ROOT = Path(__file__).resolve().parent.parent @@ -527,6 +528,7 @@ def send(path: Path, digest: str, *, confirmed: bool = False) -> dict[str, Any]: def main() -> int: + configure_utf8_stdio() parser = argparse.ArgumentParser(description="HelixHarness feedback: use the published destination or a private config.json override") actions = parser.add_subparsers(dest="action", required=True) draft = actions.add_parser("prepare", help="prepare a local redacted draft; does not send") diff --git a/helixharness/scripts/host_runtime_cli.py b/helixharness/scripts/host_runtime_cli.py index f462908..d85bf68 100644 --- a/helixharness/scripts/host_runtime_cli.py +++ b/helixharness/scripts/host_runtime_cli.py @@ -11,6 +11,7 @@ from host_runtime import HostContractError, HostManifest, HostRegistry from source_binding import guard_source +from cli_stdio import configure_utf8_stdio PLUGIN_ROOT = Path(__file__).resolve().parent.parent @@ -64,6 +65,7 @@ def _parser() -> argparse.ArgumentParser: def main() -> int: + configure_utf8_stdio() arguments = _parser().parse_args() guard_source(PLUGIN_ROOT, getattr(arguments, "expected_plugin_root", None)) try: diff --git a/helixharness/scripts/init_guidance.py b/helixharness/scripts/init_guidance.py index f7f5fc4..2bd6b3d 100644 --- a/helixharness/scripts/init_guidance.py +++ b/helixharness/scripts/init_guidance.py @@ -15,6 +15,7 @@ from host_runtime import HostContractError, HostRegistry from host_runtime.project_config import load_project_config +from cli_stdio import configure_utf8_stdio PLUGIN_ROOT = Path(__file__).resolve().parent.parent @@ -198,6 +199,7 @@ def project_guidance(repo: Path, platform: str, mode: str, action: str) -> dict: def main() -> int: + configure_utf8_stdio() parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--repo-root", type=Path, required=True) parser.add_argument("--platform", required=True) diff --git a/helixharness/scripts/metrics.py b/helixharness/scripts/metrics.py index 1821953..de74558 100644 --- a/helixharness/scripts/metrics.py +++ b/helixharness/scripts/metrics.py @@ -21,6 +21,7 @@ from git_target import operation_state from telemetry_hosts import get_host_adapter, normalize_host_id from telemetry_session import SessionContextUnavailable +from cli_stdio import configure_utf8_stdio STAGES = ("propose", "apply", "archive") @@ -662,6 +663,7 @@ def _parser() -> argparse.ArgumentParser: def main() -> int: + configure_utf8_stdio() args = _parser().parse_args() repo = Path(args.repo_root).expanduser().resolve() try: diff --git a/helixharness/scripts/package_qoder_plugin.py b/helixharness/scripts/package_qoder_plugin.py index 8f50a6c..c232d8d 100644 --- a/helixharness/scripts/package_qoder_plugin.py +++ b/helixharness/scripts/package_qoder_plugin.py @@ -28,6 +28,7 @@ import zipfile from datetime import datetime, timezone from pathlib import Path, PurePosixPath +from cli_stdio import configure_utf8_stdio PLUGIN_ROOT = Path(__file__).resolve().parents[1] MANIFEST_RELATIVE = PurePosixPath(".qoder-plugin/plugin.json") @@ -297,6 +298,7 @@ def verify_archive(plugin_root: Path, archive_path: Path) -> dict[str, object]: def main(argv: list[str] | None = None) -> int: + configure_utf8_stdio() parser = argparse.ArgumentParser(description="Package this plugin for Qoder.") parser.add_argument( "--output", diff --git a/helixharness/scripts/project_status.py b/helixharness/scripts/project_status.py index 8eb39a2..29764bf 100644 --- a/helixharness/scripts/project_status.py +++ b/helixharness/scripts/project_status.py @@ -20,6 +20,7 @@ WorkspaceError, validate_workspace_overview, workspace_archive_preflight, workspace_completed_preflight, ) +from cli_stdio import configure_utf8_stdio def spec_root(repo: Path, state: str) -> Path: @@ -137,6 +138,7 @@ def snapshot(repo: Path, feature: str | None = None, *, completed: bool = False) def main() -> int: + configure_utf8_stdio() parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--repo-root', required=True) parser.add_argument('--feature') diff --git a/helixharness/scripts/task_plan.py b/helixharness/scripts/task_plan.py index 600cc7b..7c2cf80 100644 --- a/helixharness/scripts/task_plan.py +++ b/helixharness/scripts/task_plan.py @@ -11,6 +11,7 @@ from atomic_files import atomic_write_text from workflow import (WorkflowError, TASK_STATUSES, _repair_lock, feature_dir, frontmatter, markdown_cells, task_rows, validate_task_graph) +from cli_stdio import configure_utf8_stdio def _cell_spans(line: str) -> list[tuple[int, int]]: @@ -111,6 +112,7 @@ def update_task(repo: Path, feature: str, task: str, status: str, expected_recei def main() -> int: + configure_utf8_stdio() parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--repo-root", required=True, type=Path) parser.add_argument("--feature", required=True) diff --git a/helixharness/scripts/telemetry_async.py b/helixharness/scripts/telemetry_async.py index 8bf8644..8d5cb53 100644 --- a/helixharness/scripts/telemetry_async.py +++ b/helixharness/scripts/telemetry_async.py @@ -30,6 +30,7 @@ import reporting_config +from cli_stdio import configure_utf8_stdio DEFAULT_INTERVAL_SECONDS = 600 @@ -47,6 +48,7 @@ MAX_BATCH_ITEMS = 100 BATCH_PAUSE_SECONDS = 0.5 RUNTIME_FILES = ( + "cli_stdio.py", "eval_json.py", "reporting_config.py", "git_target.py", @@ -1685,6 +1687,7 @@ def _parser() -> argparse.ArgumentParser: def main() -> int: + configure_utf8_stdio() args = _parser().parse_args() exit_code = 0 if args.command == "run": diff --git a/helixharness/scripts/telemetry_collector.py b/helixharness/scripts/telemetry_collector.py index 42378e5..7c61e98 100644 --- a/helixharness/scripts/telemetry_collector.py +++ b/helixharness/scripts/telemetry_collector.py @@ -16,6 +16,7 @@ import telemetry_protocol as telemetry_protocol import telemetry_trace as telemetry_trace from telemetry_hosts import get_host_adapter +from cli_stdio import configure_utf8_stdio MAX_TOOL_EVENTS = 20_000 @@ -523,6 +524,7 @@ def _parser() -> argparse.ArgumentParser: def main() -> int: + configure_utf8_stdio() args = _parser().parse_args() if args.entry_id: result: dict[str, Any] = collect_entry(Path(args.repo_root), args.entry_id, home=args.home) diff --git a/helixharness/scripts/telemetry_hosts/cursor.py b/helixharness/scripts/telemetry_hosts/cursor.py index fd01e5d..5d1f0c5 100644 --- a/helixharness/scripts/telemetry_hosts/cursor.py +++ b/helixharness/scripts/telemetry_hosts/cursor.py @@ -326,7 +326,7 @@ def release_session_source(self, repo: Path, source: str) -> int: if locator.is_symlink(): continue try: - value = json.loads(locator.read_text()) + value = json.loads(locator.read_text(encoding="utf-8")) except (OSError, ValueError): # Unreadable attribution is not evidence that a source is unused. return 0 diff --git a/helixharness/scripts/telemetry_ledger.py b/helixharness/scripts/telemetry_ledger.py index 7e1d778..c032cc3 100644 --- a/helixharness/scripts/telemetry_ledger.py +++ b/helixharness/scripts/telemetry_ledger.py @@ -19,6 +19,7 @@ from telemetry_hosts import get_host_adapter, normalize_host_id from git_target import resolve_target_branch +from cli_stdio import configure_utf8_stdio def _plugin_version() -> str: @@ -1058,6 +1059,7 @@ def _parser() -> argparse.ArgumentParser: def main() -> int: + configure_utf8_stdio() args = _parser().parse_args() repo = Path(args.repo_root).expanduser().resolve() try: diff --git a/helixharness/scripts/telemetryctl.py b/helixharness/scripts/telemetryctl.py index 62fcfd9..f39a2cd 100644 --- a/helixharness/scripts/telemetryctl.py +++ b/helixharness/scripts/telemetryctl.py @@ -15,6 +15,7 @@ import telemetry_async as telemetry_async from telemetry_hosts import supported_host_ids +from cli_stdio import configure_utf8_stdio def _duration(value: str) -> timedelta: @@ -45,6 +46,7 @@ def _parser() -> argparse.ArgumentParser: def main() -> int: + configure_utf8_stdio() args = _parser().parse_args() home = telemetry_async.telemetry_home(args.home) outbox = telemetry_async.Outbox(home) diff --git a/helixharness/scripts/tests/test_claude_update_scenarios.py b/helixharness/scripts/tests/test_claude_update_scenarios.py index 0bc1834..4a5cef1 100644 --- a/helixharness/scripts/tests/test_claude_update_scenarios.py +++ b/helixharness/scripts/tests/test_claude_update_scenarios.py @@ -53,9 +53,9 @@ def emit(value): source = Path(state["release_root"]) version = json.loads((source / "reference/version-policy.json").read_text())["latest_version"] manifest = Path(state["plugin_root"]) / ".claude-plugin/marketplace.json" - data = json.loads(manifest.read_text()) + data = json.loads(manifest.read_text(encoding="utf-8")) next(item for item in data["plugins"] if item["name"] == "helix")["version"] = version - manifest.write_text(json.dumps(data)) + manifest.write_text(json.dumps(data), encoding="utf-8") state["scope_versions"][scope] = version state_path.write_text(json.dumps(state)) emit({"updated": True}) diff --git a/helixharness/scripts/tests/test_cli_stdio.py b/helixharness/scripts/tests/test_cli_stdio.py index dbaecfc..32d760f 100644 --- a/helixharness/scripts/tests/test_cli_stdio.py +++ b/helixharness/scripts/tests/test_cli_stdio.py @@ -8,6 +8,7 @@ from __future__ import annotations +import ast import json import os import subprocess @@ -81,5 +82,59 @@ def test_user_config_answers_a_legacy_caller_with_utf8_json(self) -> None: self.assertTrue(payload["read_only"]) +def _non_ascii_json_prints(node: ast.AST) -> list[int]: + """Line numbers of `print(...)` calls that serialize non-ASCII JSON.""" + lines = [] + for call in ast.walk(node): + if not (isinstance(call, ast.Call) and isinstance(call.func, ast.Name) + and call.func.id == "print"): + continue + nested = (inner for inner in ast.walk(call) if isinstance(inner, ast.Call) + and any(keyword.arg == "ensure_ascii" + and isinstance(keyword.value, ast.Constant) + and keyword.value.value is False for keyword in inner.keywords)) + if next(nested, None) is not None: + lines.append(call.lineno) + return lines + + +class Utf8GuardCoverageTest(unittest.TestCase): + """Coverage rule: a JSON entry that prints non-ASCII guards its own streams. + + The failing CLIs are only reachable one platform at a time, so a behaviour test + per entry would still leave the next unguarded `print` to surface as a Windows + only defect. This rule keeps the whole contract in one place. + """ + + def test_every_non_ascii_json_entry_calls_the_guard_first(self) -> None: + findings = [] + for root in (PLUGIN_ROOT / "scripts", PLUGIN_ROOT / "hosts"): + for path in sorted(root.rglob("*.py")): + if "tests" in path.parts or path.name == "cli_stdio.py": + continue + main = next((node for node in ast.parse(path.read_text(encoding="utf-8")).body + if isinstance(node, ast.FunctionDef) and node.name == "main"), None) + if main is None: + continue + prints = _non_ascii_json_prints(main) + if not prints: + continue + guarded = [node.lineno for node in ast.walk(main) + if isinstance(node, ast.Call) + and getattr(node.func, "id", None) == "configure_utf8_stdio"] + if not guarded: + findings.append(f"{path.relative_to(PLUGIN_ROOT)}:{min(prints)} unguarded") + elif min(guarded) > min(prints): + findings.append(f"{path.relative_to(PLUGIN_ROOT)}:{min(prints)} guard after print") + self.assertEqual([], findings) + + def test_installed_runtime_snapshot_carries_the_guard(self) -> None: + # The telemetry runtime copies an explicit file list and runs it with + # `python -I`, so a guarded entry inside that snapshot needs the module there. + import telemetry_async + + self.assertIn("cli_stdio.py", telemetry_async.RUNTIME_FILES) + + if __name__ == "__main__": unittest.main() diff --git a/helixharness/scripts/tests/test_codex_update_scenarios.py b/helixharness/scripts/tests/test_codex_update_scenarios.py index f373f20..f11dab7 100644 --- a/helixharness/scripts/tests/test_codex_update_scenarios.py +++ b/helixharness/scripts/tests/test_codex_update_scenarios.py @@ -37,9 +37,9 @@ def install(): source = Path(state["release_root"]) version = json.loads((source / "reference/version-policy.json").read_text())["latest_version"] manifest = Path(state["plugin_root"]) / ".codex-plugin/plugin.json" - data = json.loads(manifest.read_text()) + data = json.loads(manifest.read_text(encoding="utf-8")) data["version"] = version - manifest.write_text(json.dumps(data)) + manifest.write_text(json.dumps(data), encoding="utf-8") state["version"] = version state_path.write_text(json.dumps(state)) if args == ["plugin", "list", "--json", "--marketplace", "helixharness-marketplace"]: diff --git a/helixharness/scripts/tests/test_cursor_integration.py b/helixharness/scripts/tests/test_cursor_integration.py index 13d7557..d223898 100644 --- a/helixharness/scripts/tests/test_cursor_integration.py +++ b/helixharness/scripts/tests/test_cursor_integration.py @@ -108,7 +108,8 @@ def test_relocated_cursor_bundle_resolves_without_other_host_kits(self): manifest = HostRegistry.discover(PLUGIN / 'hosts').require('cursor') projection = load_command_projection(manifest) resources = {'hosts/cursor/host.json', 'scripts/host_runtime_cli.py', - 'scripts/source_binding.py', 'scripts/eval_json.py'} + 'scripts/source_binding.py', 'scripts/eval_json.py', + 'scripts/cli_stdio.py'} resources.update(str(p.relative_to(PLUGIN)) for p in (PLUGIN / 'scripts/host_runtime').glob('*.py')) resources.update(str(manifest.resolve_resource_adapter(key).relative_to(PLUGIN)) for key in manifest.adapters if manifest.adapter_reference(key).kind == 'resource') diff --git a/helixharness/scripts/tests/test_session_context.py b/helixharness/scripts/tests/test_session_context.py index 1a0dd93..7c071d5 100644 --- a/helixharness/scripts/tests/test_session_context.py +++ b/helixharness/scripts/tests/test_session_context.py @@ -85,8 +85,10 @@ def test_skill_and_direct_command_refresh_source_next_to_entry(self): output = json.loads(self.run_hook(json.dumps(payload)).stdout)["hookSpecificOutput"] self.assertEqual(output["hookEventName"], payload["hook_event_name"]) context = output["additionalContext"] - for fragment in ("scripts/host_runtime_cli.py", "reference/runtime-preflight.md"): - self.assertIn(json.dumps(str(ROOT / fragment))[1:-1], context) + # The guarded preflight command is POSIX shell text, so lifecycle_service + # normalizes its paths; the appended note names the document natively. + self.assertIn((ROOT / "scripts/host_runtime_cli.py").as_posix(), context) + self.assertIn(str(ROOT / "reference/runtime-preflight.md"), context) self.assertIn('"resolved_resources"', context) self.assertNotIn("permissionDecision", output) diff --git a/helixharness/scripts/ut_artifacts.py b/helixharness/scripts/ut_artifacts.py index 40158e6..9192ea7 100644 --- a/helixharness/scripts/ut_artifacts.py +++ b/helixharness/scripts/ut_artifacts.py @@ -15,6 +15,7 @@ import tempfile from typing import Any from atomic_files import atomic_write_text +from cli_stdio import configure_utf8_stdio STATE_NAME = re.compile(r'(?:unittest-(?:queue|session|results|summary|experience)\.md|worker-[1-9][0-9]*-result\.md)\Z') KINDS = ('confirmed_defect', 'unconfirmed_risk', 'optional_improvement') @@ -257,6 +258,7 @@ def aggregate_findings(repo: Path, feature: str, workers: list[int]) -> dict[str def main() -> int: + configure_utf8_stdio() parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--repo-root', type=Path, required=True) parser.add_argument('--feature', required=True) diff --git a/helixharness/scripts/ut_precompile.py b/helixharness/scripts/ut_precompile.py index eb3f6fc..e94bfc2 100644 --- a/helixharness/scripts/ut_precompile.py +++ b/helixharness/scripts/ut_precompile.py @@ -9,6 +9,7 @@ import shutil import subprocess from typing import Any +from cli_stdio import configure_utf8_stdio def _output_path(root: Path, value: Path) -> Path: @@ -94,6 +95,7 @@ def precompile(repo: Path, *, class_directories: list[Path] | None = None) -> di def main(argv: list[str] | None = None) -> int: + configure_utf8_stdio() parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--repo-root", type=Path, required=True) parser.add_argument("--class-directory", type=Path, action="append", diff --git a/helixharness/scripts/validate_init_outputs.py b/helixharness/scripts/validate_init_outputs.py index 828971c..0c9d2e3 100644 --- a/helixharness/scripts/validate_init_outputs.py +++ b/helixharness/scripts/validate_init_outputs.py @@ -15,6 +15,7 @@ from project_hooks_cli import project_hooks from workflow import WorkflowError from workspace import WorkspaceError, load_registry +from cli_stdio import configure_utf8_stdio PLUGIN_ROOT = Path(__file__).resolve().parent.parent @@ -212,6 +213,7 @@ def _parse_args() -> argparse.Namespace: def main() -> int: + configure_utf8_stdio() args = _parse_args() report = validate(args.repo_root, args.mode, args.platform, args.telemetry_mode) print(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True)) diff --git a/helixharness/scripts/version_update.py b/helixharness/scripts/version_update.py index 281f664..009a8de 100644 --- a/helixharness/scripts/version_update.py +++ b/helixharness/scripts/version_update.py @@ -1402,7 +1402,7 @@ def install( _atomic_write(authorization_path, failed) completed = authorization["completed_steps"] raise UpdateError( - f"plugin update step failed: {step.step_id}; completed steps: {completed}" + f"plugin update step failed: {step.step_id}: {exc}; completed steps: {completed}" ) from exc if step.command: executed.append(list(step.command)) diff --git a/helixharness/scripts/workflow.py b/helixharness/scripts/workflow.py index 431712e..0b722fd 100644 --- a/helixharness/scripts/workflow.py +++ b/helixharness/scripts/workflow.py @@ -16,6 +16,7 @@ from pathlib import Path, PurePosixPath from source_binding import guard_source from typing import Any, Iterator +from cli_stdio import configure_utf8_stdio try: from atomic_files import AtomicWriteError, atomic_write_text @@ -2011,6 +2012,7 @@ def parser() -> argparse.ArgumentParser: def main(argv: list[str] | None = None) -> int: + configure_utf8_stdio() guard_source(Path(__file__).resolve().parent.parent) args = parser().parse_args(argv) try: diff --git a/helixharness/scripts/workflow_router.py b/helixharness/scripts/workflow_router.py index fc4a32a..7ee9a00 100644 --- a/helixharness/scripts/workflow_router.py +++ b/helixharness/scripts/workflow_router.py @@ -14,6 +14,7 @@ from workflow import ReviewScopeDrift, WorkflowError, archive_preflight, feature_name, frontmatter, read_regular from workflow_target import WorkflowTargetError, resolve_workflow_target from workspace import WorkspaceError, workspace_archive_preflight, workspace_revision_context +from cli_stdio import configure_utf8_stdio PUBLIC_COMMANDS = ('propose', 'apply', 'archive', 'bug-fix') @@ -268,6 +269,7 @@ def route(repo: Path, *, command: str, feature: str | None = None, def main(argv: list[str] | None = None) -> int: + configure_utf8_stdio() guard_source(Path(__file__).resolve().parent.parent) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--repo-root', required=True) diff --git a/helixharness/scripts/workspace.py b/helixharness/scripts/workspace.py index 8ba3c1a..d674f24 100644 --- a/helixharness/scripts/workspace.py +++ b/helixharness/scripts/workspace.py @@ -12,6 +12,7 @@ import sys from pathlib import Path from typing import Any +from cli_stdio import configure_utf8_stdio try: import workflow as lifecycle @@ -922,6 +923,7 @@ def parser() -> argparse.ArgumentParser: def main(argv: list[str] | None = None) -> int: + configure_utf8_stdio() args = parser().parse_args(argv) try: payload = args.handler(workspace_root(args.workspace_root), args) From c89f64e31cccd6ebdca8e97700b7e78e020346c9 Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Wed, 25 Nov 2026 12:30:53 +0800 Subject: [PATCH 25/37] =?UTF-8?q?fix(windows):=20UTF-8=20stdio=20=E5=AE=88?= =?UTF-8?q?=E5=8D=AB=E6=94=B9=E7=94=A8=20surrogateescape=20=E5=9B=9E?= =?UTF-8?q?=E4=BC=A0=E4=B8=8D=E5=8F=AF=E8=A7=A3=E7=A0=81=E5=AD=97=E8=8A=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit POSIX C locale 下文件系统编码是 ascii+surrogateescape,含 CJK 的路径经 argv 进来就是一串代理项;守卫里的 errors="strict" 在重新编码时直接抛 UnicodeEncodeError,把守卫本身要保护的 JSON 契约又炸回 traceback。 CI 证据(ubuntu-latest 3.10/3.12 LegacyCodePageCliTest): UnicodeEncodeError: 'utf-8' codec can't encode characters in position 148-153: surrogates not allowed 改成 errors="surrogateescape" 后代理项编码回原始字节,调用方读到的正是它传入的路径。 --- helixharness/scripts/cli_stdio.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/helixharness/scripts/cli_stdio.py b/helixharness/scripts/cli_stdio.py index 5c05b4e..a281e42 100644 --- a/helixharness/scripts/cli_stdio.py +++ b/helixharness/scripts/cli_stdio.py @@ -13,8 +13,13 @@ def configure_utf8_stdio() -> None: these CLIs echo installation paths with `ensure_ascii=False`, a legacy Windows code page cannot encode CJK, and the host then receives a traceback instead of the JSON it parses. + + `surrogateescape` covers the mirror case on a POSIX C locale, where the path + arrives as argv bytes that the filesystem encoding could not decode: re-encoding + the surrogates returns those original bytes, so the caller reads back exactly what + it passed. A strict encoder would raise on them instead. """ for stream in (sys.stdout, sys.stderr): reconfigure = getattr(stream, "reconfigure", None) if reconfigure is not None: - reconfigure(encoding="utf-8", errors="strict") + reconfigure(encoding="utf-8", errors="surrogateescape") From 41271b3f8a314d024f0ab62ce8a0a866be3f9d54 Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Wed, 25 Nov 2026 12:39:57 +0800 Subject: [PATCH 26/37] =?UTF-8?q?test(cursor):=20=E8=AE=A9=20prompt=20?= =?UTF-8?q?=E8=BA=AB=E4=BB=BD=20fixture=20=E4=BD=BF=E7=94=A8=E6=9C=AC?= =?UTF-8?q?=E5=B9=B3=E5=8F=B0=E5=8F=AF=E5=88=A4=E5=AE=9A=E7=9A=84=E7=BB=9D?= =?UTF-8?q?=E5=AF=B9=E8=B7=AF=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI 证据(windows-latest 3.10/3.12): KeyError: 'additional_context' AssertionError: 2 != 0 (Path.resolve 调用数) telemetry_hosts/cursor.py 要求 Path(root).is_absolute(),Windows 上不带盘符的 /synthetic/... 判定为 False,身份绑定直接返回 None,7 个用例因此拿不到上下文。 真实宿主在 Windows 发送的是盘符限定的根目录,所以产品行为正确,是 fixture 不跨平台。 新增 native_root() 助手按平台补齐盘符;副作用是 test_missing_conflicting_and_invalid_identity_allow_without_guessing 此前在 Windows 上因所有 case 都缺盘符而空过,现在才校验自己声明的拒绝理由。 --- .../tests/test_cursor_prompt_context.py | 34 +++++++++++++------ 1 file changed, 24 insertions(+), 10 deletions(-) diff --git a/helixharness/scripts/tests/test_cursor_prompt_context.py b/helixharness/scripts/tests/test_cursor_prompt_context.py index b447f92..30816d0 100644 --- a/helixharness/scripts/tests/test_cursor_prompt_context.py +++ b/helixharness/scripts/tests/test_cursor_prompt_context.py @@ -1,6 +1,7 @@ """Bounded current-event identity injection, without filesystem or host discovery.""" import io import json +import os import shlex import sys import time @@ -13,11 +14,22 @@ from telemetry_hosts.cursor import native_identity +def native_root(path: str) -> str: + """A synthetic root that is absolute on the platform running the test. + + Cursor sends drive-qualified roots on Windows, and the identity binder requires + `Path(root).is_absolute()` because guessing a drive for a bare `/synthetic/...` + would bind a prompt to the wrong workspace. A drive-less root therefore gets no + context there, which silently vacuates every rejection case in this file. + """ + return path if os.name != "nt" else "C:" + path.replace("/", "\\") + + class CursorPromptContextTest(unittest.TestCase): def setUp(self): self.entry = load("hook_entry") self.payload = {"hook_event_name": "beforeSubmitPrompt", "conversation_id": "synthetic-prompt", - "workspace_roots": ["/synthetic/repo"]} + "workspace_roots": [native_root("/synthetic/repo")]} def response(self, payload): class Output(io.StringIO): @@ -43,7 +55,7 @@ def bindings(self, response): return dict(value.split("=", 1) for value in shlex.split(response["additional_context"].splitlines()[-1])) def test_real_current_fields_are_shell_quoted_and_flushed_before_recording(self): - roots = ["/synthetic/a b/'quote'/$literal/`literal`", "/synthetic/中文"] + roots = [native_root("/synthetic/a b/'quote'/$literal/`literal`"), native_root("/synthetic/中文")] response = self.response({**self.payload, "workspace_roots": roots}) env = self.bindings(response) self.assertEqual("synthetic-prompt", env["HELIXHARNESS_CURSOR_CONVERSATION_ID"]) @@ -52,7 +64,7 @@ def test_real_current_fields_are_shell_quoted_and_flushed_before_recording(self) self.assertLessEqual(len(response["additional_context"].encode()), 8192) def test_context_path_does_not_resolve_files_or_discover_hosts(self): - roots = ["/synthetic/link/../repo", "/synthetic/link/../repo"] + roots = [native_root("/synthetic/link/../repo"), native_root("/synthetic/link/../repo")] with patch.object(Path, "resolve", side_effect=AssertionError("context resolved filesystem")), patch.dict( sys.modules, {"host_runtime": None, "lifecycle_service": None, "telemetry_consent_state": None} ): @@ -64,7 +76,7 @@ def test_prompt_and_startup_bind_identity_to_actual_exec_launcher(self): startup_payload = {**self.payload, "hook_event_name": "sessionStart"} output = io.StringIO() with patch.object(sys, "stdin", io.StringIO(json.dumps(startup_payload))), redirect_stdout(output), patch.object( - self.entry, "native_identity", return_value=("synthetic-prompt", ["/synthetic/repo"]) + self.entry, "native_identity", return_value=("synthetic-prompt", [native_root("/synthetic/repo")]) ), patch.object(self.entry, "_spawn_cleanup"), patch("lifecycle_service.handle_event"), patch( "telemetry_consent_state._repo_root", return_value=Path("/synthetic/repo") ): @@ -88,7 +100,7 @@ def test_missing_conflicting_and_invalid_identity_allow_without_guessing(self): self.assertEqual({"continue": True}, self.response(payload)) def test_context_caps_do_not_limit_existing_consumer_identity(self): - for roots in (["/synthetic/r" + str(i) for i in range(65)], ["/" + "x" * 9000]): + for roots in ([native_root("/synthetic/r" + str(i)) for i in range(65)], [native_root("/" + "x" * 9000)]): with self.subTest(size=len(roots)): payload = {**self.payload, "workspace_roots": roots} self.assertEqual({"continue": True}, self.response(payload)) @@ -100,19 +112,21 @@ def test_expired_context_budget_returns_neutral_permission(self): self.assertEqual({"continue": True}, result) def test_two_sessions_never_reuse_previous_binding(self): + other = native_root("/synthetic/other") first = self.bindings(self.response(self.payload)) second = self.bindings(self.response({**self.payload, "conversation_id": "other-session", - "workspace_roots": ["/synthetic/other"]})) + "workspace_roots": [other]})) self.assertNotEqual(first, second) self.assertEqual("other-session", second["HELIXHARNESS_CURSOR_CONVERSATION_ID"]) - self.assertEqual(["/synthetic/other"], json.loads(second["HELIXHARNESS_CURSOR_WORKSPACE_ROOTS"])) + self.assertEqual([other], json.loads(second["HELIXHARNESS_CURSOR_WORKSPACE_ROOTS"])) self.assertEqual({"continue": True}, self.response({"hook_event_name": "beforeSubmitPrompt"})) def test_consumer_still_resolves_and_deduplicates_native_roots(self): - with patch.object(Path, "resolve", return_value=Path("/synthetic/real")) as resolve: - result = native_identity({**self.payload, "workspace_roots": ["/synthetic/alias", "/synthetic/real"]}) + real = native_root("/synthetic/real") + with patch.object(Path, "resolve", return_value=Path(real)) as resolve: + result = native_identity({**self.payload, "workspace_roots": [native_root("/synthetic/alias"), real]}) self.assertEqual(2, resolve.call_count) - self.assertEqual(("synthetic-prompt", ["/synthetic/real"]), result) + self.assertEqual(("synthetic-prompt", [real]), result) if __name__ == "__main__": From 58f6a59a49eddb29b9a920a22a84dd5e2654ea3c Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Wed, 25 Nov 2026 13:06:13 +0800 Subject: [PATCH 27/37] =?UTF-8?q?test(platform):=20=E8=B7=A8=E5=8C=85?= =?UTF-8?q?=E9=AA=8C=E6=94=B6=E5=9C=A8=20Windows=20=E4=B8=8A=E8=A1=A5?= =?UTF-8?q?=E9=BD=90=20sh=20=E4=B8=8E=20git=20=E5=B9=B6=E6=B2=BF=E7=94=A8?= =?UTF-8?q?=E6=8F=92=E4=BB=B6=E5=A5=97=E4=BB=B6=E7=9A=84=20Git=20Bash=20?= =?UTF-8?q?=E7=BA=A6=E5=AE=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI 证据(windows-latest 3.10/3.12,Platform suite 首次执行): 3 failed: test_native_cursor_hook_to_local_outbox_to_platform_dashboard FileNotFoundError: [WinError 2] The system cannot find the file specified 内层脚本要真 git 和 Cursor 原生 hook 命令 sh …hook_bootstrap.sh,而它的 PATH 被洗成 python 目录 + os.defpath。POSIX 的 defpath 含 /bin:/usr/bin 两者都在,Windows 的 defpath 只有 system32,既没有 git 也没有 sh,于是在第一步 CreateProcess 就炸。 按 scripts/tests/test_windows_runtime.py 既有约定:从作业 PATH 解析 git/sh 目录并 加入受控 PATH,解析不到则 skip;CURSOR_PLUGIN_ROOT 改用 as_posix(),与同一约定里 传给 sh 的插件根目录形式一致。 --- .../tests/test_cursor_native_usage_pipeline.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/helixharness-platform/web_ui/tests/test_cursor_native_usage_pipeline.py b/helixharness-platform/web_ui/tests/test_cursor_native_usage_pipeline.py index 1a57656..8d1dcbf 100644 --- a/helixharness-platform/web_ui/tests/test_cursor_native_usage_pipeline.py +++ b/helixharness-platform/web_ui/tests/test_cursor_native_usage_pipeline.py @@ -3,6 +3,7 @@ import json import os +import shutil import subprocess import sys from pathlib import Path @@ -80,10 +81,18 @@ def hook(event, **fields): ledger = json.loads((repo / "docs/eval/native-cursor/eval-log.json").read_text()) print(json.dumps({"repo":str(repo), "ledger":ledger, "supplement":envelope["supplement"]})) ''' + # The staged script shells out to real `git` and runs Cursor's native hook + # command, which is `sh …hook_bootstrap.sh`. `os.defpath` carries both on POSIX, + # but on Windows Git for Windows keeps them outside it, so a scrubbed PATH must + # add their directories explicitly or the launcher dies with WinError 2. + tools = [shutil.which(name) for name in ("git", "sh")] + if any(tool is None for tool in tools): + pytest.skip("cross-package acceptance needs the real `git` and the `sh` hook launcher") + tool_dirs = [str(Path(sys.executable).parent), *dict.fromkeys(str(Path(tool).parent) for tool in tools)] environment = { - "PATH": str(Path(sys.executable).parent) + os.pathsep + os.defpath, + "PATH": os.pathsep.join([*tool_dirs, os.defpath]), "PYTHONDONTWRITEBYTECODE": "1", "PYTHONIOENCODING": "utf-8", - "TMPDIR": str(root), "CURSOR_PLUGIN_ROOT": str(plugin), + "TMPDIR": str(root), "CURSOR_PLUGIN_ROOT": plugin.as_posix(), "CODEX_HOME": str(root / "codex"), "CLAUDE_CONFIG_DIR": str(root / "claude"), "HELIXHARNESS_CURSOR_HOME": str(root / "cursor"), "HELIXHARNESS_TELEMETRY_HOME": str(root / "telemetry"), From 3cffa3ee96dee5ac76e137f995a30120ffb749da Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Wed, 25 Nov 2026 13:31:38 +0800 Subject: [PATCH 28/37] =?UTF-8?q?test(platform):=20=E8=B7=A8=E5=8C=85?= =?UTF-8?q?=E9=AA=8C=E6=94=B6=E8=A1=A5=E9=BD=90=20Windows=20=E5=AD=90?= =?UTF-8?q?=E8=A7=A3=E9=87=8A=E5=99=A8=E5=90=AF=E5=8A=A8=E5=8F=98=E9=87=8F?= =?UTF-8?q?=E5=B9=B6=E6=8C=89=20UTF-8=20=E8=AF=BB=E5=8F=96=E5=AD=90?= =?UTF-8?q?=E8=BF=9B=E7=A8=8B=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI 证据(windows-latest 3.10/3.12,WinError 2 之后的下一层): Fatal Python error: _Py_HashRandomization_Init: failed to get random numbers encodings/cp1252.py line 23, in decode → 'NoneType' object has no attribute 'strip' 受控环境没有 SystemRoot/COMSPEC/PATHEXT,Windows 上的子 python.exe 在哈希随机化初始化 阶段就中止,这是 scripts/tests/env_sandbox.py 已记录的同一条事实,本 fixture 此前没跟上。 内层脚本以 python -I 运行,-I 忽略 PYTHONIOENCODING,因此 text=True 退回 locale cp1252 去解宿主 CLI 的 UTF-8 JSON 输出,读线程崩溃后 stdout 变成 None。 两处都改为显式:环境带上启动变量,subprocess 明确 encoding="utf-8"。 --- .../web_ui/tests/test_cursor_native_usage_pipeline.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/helixharness-platform/web_ui/tests/test_cursor_native_usage_pipeline.py b/helixharness-platform/web_ui/tests/test_cursor_native_usage_pipeline.py index 8d1dcbf..132f516 100644 --- a/helixharness-platform/web_ui/tests/test_cursor_native_usage_pipeline.py +++ b/helixharness-platform/web_ui/tests/test_cursor_native_usage_pipeline.py @@ -36,7 +36,7 @@ def _native_stage(root: Path, native_usage: dict | None) -> tuple[Path, dict, di def run(arguments, *, payload=None, env=None): result = subprocess.run(list(map(str, arguments)), cwd=repo, env=env, input=json.dumps(payload) if payload is not None else None, - capture_output=True, text=True, check=False, timeout=30) + capture_output=True, text=True, encoding="utf-8", check=False, timeout=30) assert result.returncode == 0, result.stdout + result.stderr return json.loads(result.stdout) if result.stdout.strip() else None def cli(script, *args, env=None): @@ -91,6 +91,10 @@ def hook(event, **fields): tool_dirs = [str(Path(sys.executable).parent), *dict.fromkeys(str(Path(tool).parent) for tool in tools)] environment = { "PATH": os.pathsep.join([*tool_dirs, os.defpath]), + # Same Windows boot variables the plugin suite carries for a scrubbed + # fixture (scripts/tests/env_sandbox.py): without them a child `python.exe` + # aborts in `_Py_HashRandomization_Init` before it can answer the caller. + **{key: os.environ[key] for key in ("SystemRoot", "COMSPEC", "PATHEXT") if key in os.environ}, "PYTHONDONTWRITEBYTECODE": "1", "PYTHONIOENCODING": "utf-8", "TMPDIR": str(root), "CURSOR_PLUGIN_ROOT": plugin.as_posix(), "CODEX_HOME": str(root / "codex"), "CLAUDE_CONFIG_DIR": str(root / "claude"), @@ -104,7 +108,7 @@ def hook(event, **fields): result = subprocess.run( [sys.executable, "-I", "-c", code], cwd=root, env=environment, input=json.dumps([str(plugin), str(root), native_usage]), - capture_output=True, text=True, check=False, timeout=60, + capture_output=True, text=True, encoding="utf-8", check=False, timeout=60, ) assert result.returncode == 0, result.stdout + result.stderr artifacts = json.loads(result.stdout) From 8144bc81716f634171d3392003035e85c5178879 Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Wed, 25 Nov 2026 14:19:01 +0800 Subject: [PATCH 29/37] =?UTF-8?q?test(cursor):=20=E7=94=A8=E4=BA=8B?= =?UTF-8?q?=E4=BB=B6=E9=A1=BA=E5=BA=8F=E5=8F=96=E4=BB=A3=E5=A2=99=E9=92=9F?= =?UTF-8?q?=E8=80=A6=E5=90=88=EF=BC=8C=E6=B6=88=E9=99=A4=20anchor=E2=86=92?= =?UTF-8?q?lock=20=E8=BD=AC=E6=8D=A2=E7=94=A8=E4=BE=8B=E7=9A=84=20macOS=20?= =?UTF-8?q?=E9=9A=8F=E6=9C=BA=E7=BA=A2=E7=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 本分支最近 10 次 run 里 test_anchor_to_new_lock_transition_keeps_original_deadline 在 macos-latest 3.10 失败 4 次,全是同一条断言 assertEqual(2, len(deadlines)) 拿到 1。 原因是读线程 hook 预算只有 begin+0.16s,而主线程要等被调度才会创建新 lock 文件并释放 anchor;runner 满载时先到期就走了 else: yield,第二次 _acquire_read_lock 根本不发生。 本机单独 40 次 + 8 路 busy-loop 加压 30 次复现不了,只在 CI 全量套件下红。 改为把转换放进第一次尝试内部:记录 deadline 后先发布并独占新 lock 文件,再放开 anchor, 于是复用同一 deadline 的第二次等待必然出现,用例只受线程启动开销影响。 预算与上界由同一个 budget 推导并留调度余量。两条变异(递归换新 deadline → 1 != 2; 递归丢掉 deadline → 阻塞触发 join 超时)都仍然失败,属性未被弱化。生产代码未改动。 --- .../scripts/tests/test_cursor_hook_budget.py | 28 ++++++++++++------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/helixharness/scripts/tests/test_cursor_hook_budget.py b/helixharness/scripts/tests/test_cursor_hook_budget.py index e49f237..c268f24 100644 --- a/helixharness/scripts/tests/test_cursor_hook_budget.py +++ b/helixharness/scripts/tests/test_cursor_hook_budget.py @@ -96,18 +96,27 @@ def test_anchor_to_new_lock_transition_keeps_original_deadline(self): cache.parent.mkdir(parents=True) anchor = os.open(self.root, os.O_RDONLY) fcntl.flock(anchor, fcntl.LOCK_EX) - waiting = threading.Event() outcomes = [] deadlines = [] + owners = [] acquire = consent._acquire_read_lock + budget = 0.2 def observed(fd, deadline): deadlines.append(deadline) - waiting.set() + if len(deadlines) == 1: + # Publish and hold the new lock file, then hand the anchor over, all + # before the first wait begins. A main-thread transition raced the hook + # deadline on a busy runner and lost, so the second attempt never + # happened and the reused deadline was never observed. + owner = cache.with_suffix(".json.lock").open("w") + fcntl.flock(owner, fcntl.LOCK_EX) + owners.append(owner) + fcntl.flock(anchor, fcntl.LOCK_UN) return acquire(fd, deadline) begin = time.monotonic() def reader(): try: - with consent._cache_lock(cache, deadline=begin + 0.16): + with consent._cache_lock(cache, deadline=begin + budget): outcomes.append("unexpected acquisition") except consent.ConsentError: outcomes.append("deadline") @@ -115,18 +124,17 @@ def reader(): with patch.object(consent, "_acquire_read_lock", observed): thread = threading.Thread(target=reader) thread.start() - self.assertTrue(waiting.wait(1)) - time.sleep(0.04) - with cache.with_suffix(".json.lock").open("w") as owner: - fcntl.flock(owner, fcntl.LOCK_EX) - fcntl.flock(anchor, fcntl.LOCK_UN) - thread.join(1) + thread.join(2) self.assertFalse(thread.is_alive()) self.assertEqual(["deadline"], outcomes) self.assertEqual(2, len(deadlines)) self.assertEqual(1, len(set(deadlines))) - self.assertLess(time.monotonic() - begin, 0.4) + # The wait must stop at the hook budget; the slack absorbs thread + # scheduling, which this case does not measure. + self.assertLess(time.monotonic() - begin, budget + 0.4) finally: + for owner in owners: + owner.close() os.close(anchor) def test_windows_lock_preserves_default_timeout_and_tighter_hook_deadline(self): From 09b7950bd4d1fb2a91164adf11b9359fcee265e4 Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Wed, 25 Nov 2026 21:48:20 +0800 Subject: [PATCH 30/37] =?UTF-8?q?docs(hosts):=20=E8=A1=A5=E9=BD=90=20Qoder?= =?UTF-8?q?=20=E6=94=AF=E6=8C=81=E8=AF=B4=E6=98=8E=EF=BC=8C=E5=B9=B6?= =?UTF-8?q?=E6=8A=8A=20Cursor=20Windows=20=E8=BA=AB=E4=BB=BD=E7=BB=91?= =?UTF-8?q?=E5=AE=9A=E8=AE=B0=E4=B8=BA=E5=B7=B2=E7=9F=A5=E9=99=90=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 入口文档此前只列 Codex / Claude Code / Cursor / OpenCode,Qoder 只在 installation.md 出现, 读者无法从用户指南与跨平台矩阵得知它的安装形态和能力边界。补充内容只覆盖已实测事实:App 本地 ZIP 安装、版本目录整体替换、公共入口是 helix: Skill、/helix:update 返回阻断、 本宿主未接入统计上报。 Cursor 在 Windows 上没有留下任何实机会话证据:POSIX sh 启动器只在 CI 里靠 Git for Windows 的 PATH 满足,注入 prompt 的身份变量前缀也只有 POSIX 引号形式。这里把它写进 host.json 的 limitations 与 Cursor 支持报告,而不是改成 PowerShell 语法——目标宿主的终端 shell 未经实测, 改写法只能靠猜。 --- README.md | 2 +- README.zh-CN.md | 2 +- docs/cursor-testing.md | 4 ++++ docs/installation.md | 4 ++-- docs/platform-support.md | 1 + docs/user-guide.md | 30 +++++++++++++++++------------ docs/user-guide.zh-CN.md | 30 +++++++++++++++++------------ helixharness/hosts/cursor/host.json | 3 ++- 8 files changed, 47 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index d08e478..c9d9303 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ Knowledge accumulates as **reviewable repository documents**. You control what b Requirements: Python 3.10+, Git and a plugin-capable Codex, Claude Code, Cursor, OpenCode installation (macOS, 2.3.2; see the [support matrix](docs/opencode-testing.md)) or Qoder Desktop / CLI. Make sure the host is signed in or has its model configuration set up and is working normally. -For macOS and native Windows setup, interpreter detection and host-specific requirements, see [platform support](docs/platform-support.md). Windows Codex uses PowerShell; Windows Claude Code uses Git for Windows Bash. Cursor native acceptance currently covers macOS; Windows Cursor is outside this release's verified scope. +For macOS and native Windows setup, interpreter detection and host-specific requirements, see [platform support](docs/platform-support.md). Windows Codex uses PowerShell; Windows Claude Code uses Git for Windows Bash. Cursor native acceptance currently covers macOS; Windows Cursor is outside this release's verified scope. Qoder's Host Kit contract tests run in the CI matrix, but the Qoder App has no Windows acceptance yet and only the POSIX hook launcher exists. After the repository is public, install Codex and Claude Code plugins with the terminal commands below. Cursor uses the marketplace UI described afterward. Qoder installs through a locally built ZIP because it has no marketplace CLI. These marketplace routes do not require a manual source clone: diff --git a/README.zh-CN.md b/README.zh-CN.md index 00a382b..aad5fed 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -65,7 +65,7 @@ Knowledge 与 Harness 通过索引引导上下文加载,Specs 保存每个需 需要 Python 3.10+、Git,以及支持插件的 Codex、Claude Code、Cursor、OpenCode(macOS、2.3.2;见[支持矩阵](docs/opencode-testing.md))或 Qoder Desktop / CLI。先确保宿主已完成登录或模型配置,能够正常使用。 -macOS 与原生 Windows 的依赖、解释器探测及宿主要求见[跨平台说明](docs/platform-support.md)。Windows Codex 使用 PowerShell;Windows Claude Code 使用 Git for Windows Bash。Cursor 实机验收目前覆盖 macOS,Windows Cursor 不在本期已验证范围。 +macOS 与原生 Windows 的依赖、解释器探测及宿主要求见[跨平台说明](docs/platform-support.md)。Windows Codex 使用 PowerShell;Windows Claude Code 使用 Git for Windows Bash。Cursor 实机验收目前覆盖 macOS,Windows Cursor 不在本期已验证范围。Qoder 的 Host Kit 契约测试已进入 CI 矩阵,但 Qoder App 尚未完成 Windows 实机验收,且只提供 POSIX hook 启动器。 仓库公开后,Codex 和 Claude Code 使用下方终端命令,Cursor 使用随后说明的市场界面安装,Qoder 使用随后说明的本地 ZIP 安装流程;市场安装方式无需先手动克隆源码: diff --git a/docs/cursor-testing.md b/docs/cursor-testing.md index 9b1e916..a79704d 100644 --- a/docs/cursor-testing.md +++ b/docs/cursor-testing.md @@ -8,8 +8,12 @@ Cursor 桌面接入按已声明的能力边界标记为 `stable`、可发布。 The integrated source follows GitHub main's Python 3.10+ runtime contract. The Python 3.9.6 native sample below belongs to an earlier Cursor candidate; it does not validate this integrated source or promise current Python 3.9 support. Native Windows Cursor is outside this release's verified scope. +That scope gap has a specific shape, and it is recorded here rather than patched on a guess. Every Cursor hook command is `sh "${CURSOR_PLUGIN_ROOT}/hosts/cursor/hook_bootstrap.sh" `: the Windows CI job adds Git for Windows' `bin` directory to PATH (`.github/workflows/cross-platform.yml`), so the launcher runs there, but a native Windows Cursor installation does not guarantee that. `hosts/cursor/hook_entry.py` also injects `HELIXHARNESS_BOUND_PLUGIN_ROOT`, `HELIXHARNESS_CURSOR_CONVERSATION_ID` and `HELIXHARNESS_CURSOR_WORKSPACE_ROOTS` into prompt context as a POSIX `KEY='value'` prefix, asking the model to hand them to the runtime launcher or export them in the current shell; no Windows Cursor session has been recorded, so there is no evidence for which shell that terminal actually uses, and neither form has an evidence base there. When the prefix cannot be applied, `scripts/telemetry_hosts/cursor.py` reports the session context unavailable, `scripts/metrics.py` skips that record and feedback falls back to an `unknown` session — workflows still run and only statistics degrade. It stays a limitation instead of being rewritten for PowerShell, because changing the syntax on an unaccepted host could only be guesswork. Closing it takes one native Windows Cursor session that records the shell the terminal uses and whether an identity assignment made by the model reaches the plugin script. + 整合后的源码沿用 GitHub 主干的 Python 3.10+ 运行时合同。下方 Python 3.9.6 实机样例属于较早的 Cursor 候选,不代表整合版本已实机通过,也不承诺当前支持 Python 3.9。Windows Cursor 不在本期已验证范围。 +那个缺口有具体形状,记录在此而不是按猜测修补。每条 Cursor hook 命令都是 `sh "${CURSOR_PLUGIN_ROOT}/hosts/cursor/hook_bootstrap.sh" `:CI 的 Windows 任务把 Git for Windows 的 `bin` 目录加进了 PATH(`.github/workflows/cross-platform.yml`),所以启动器在 CI 里可跑,但原生 Windows Cursor 安装并不保证这一点。`hosts/cursor/hook_entry.py` 还会把 `HELIXHARNESS_BOUND_PLUGIN_ROOT`、`HELIXHARNESS_CURSOR_CONVERSATION_ID` 和 `HELIXHARNESS_CURSOR_WORKSPACE_ROOTS` 以 POSIX `KEY='value'` 形式注入 prompt 上下文,要求模型转交给运行器或在当前 shell 导出;由于从未记录过任何 Windows Cursor 会话,它的终端实际使用哪种 shell 没有证据,两种形态在当地因此都缺少证据基础。若前缀无法生效,`scripts/telemetry_hosts/cursor.py` 会给出会话上下文不可用,`scripts/metrics.py` 跳过该条记录,反馈里的会话退化为 `unknown`——工作流照常执行,只有统计降级。把它记为限制而不是改成 PowerShell 写法,是因为在未验收的宿主上改写语法只能靠猜。要收口这个结论,需要在原生 Windows Cursor 里跑一次会话,记录终端实际使用的 shell,以及模型设置的身份变量能否传到插件脚本。 + | Capability / 能力 | Evidence and boundary / 证据与边界 | | --- | --- | | Commands and workflows / 命令与流程 | Synthetic contract tests cover all nine entries. Native samples cover Single and Workspace implementation/archive, active Single BugFix, frontend Init and Java UT. / 合同测试覆盖九个入口;实机样例覆盖单仓及多仓实施/归档、活跃单仓 BugFix、前端 Init 和 Java UT。 | diff --git a/docs/installation.md b/docs/installation.md index 80b8cd3..53657b9 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -6,7 +6,7 @@ Python 3.10+, Git and a plugin-capable Codex, Claude Code, Cursor, OpenCode installation (macOS, 2.3.2; see the [support matrix](opencode-testing.md)) or Qoder Desktop / CLI are required. Make sure the host is signed in or has its model configuration set up and is working normally. The platform is optional. Cursor desktop support follows the release scope and limitations below; Qoder installs through a locally built plugin ZIP because the App has no marketplace CLI. -The shared runtime supports macOS, native Windows and Linux; see [platform support and verification](platform-support.md). Windows Codex uses the PowerShell entrypoint, while Claude Code hooks require Git for Windows Bash. Cursor native acceptance currently covers macOS; Windows Cursor is outside this release's verified scope. +The shared runtime supports macOS, native Windows and Linux; see [platform support and verification](platform-support.md). Windows Codex uses the PowerShell entrypoint, while Claude Code hooks require Git for Windows Bash. Cursor native acceptance currently covers macOS; Windows Cursor is outside this release's verified scope. Qoder's Host Kit contract tests run in the CI matrix, but the Qoder App has no Windows acceptance yet and only the POSIX hook launcher exists. Unless marked PowerShell, 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). @@ -174,7 +174,7 @@ Use the host's plugin management to uninstall `helix@helixharness-marketplace`; ## 中文说明 -需要 Python 3.10+、Git,以及支持插件的 Codex、Claude Code、Cursor、OpenCode(macOS、2.3.2;见[支持矩阵](opencode-testing.md))或 Qoder。Cursor 使用上面的 [Cursor 独立安装流程](#cursor-preview),Qoder 使用上面的 [Qoder 本地 ZIP 安装流程](#qoder)。先确保宿主已完成登录或模型配置,能够正常使用。平台不是安装插件的前置条件。共享运行时的 Windows 支持不代表 Windows Cursor 已完成验收;Cursor 实机验收目前覆盖 macOS。 +需要 Python 3.10+、Git,以及支持插件的 Codex、Claude Code、Cursor、OpenCode(macOS、2.3.2;见[支持矩阵](opencode-testing.md))或 Qoder。Cursor 使用上面的 [Cursor 独立安装流程](#cursor-preview),Qoder 使用上面的 [Qoder 本地 ZIP 安装流程](#qoder)。先确保宿主已完成登录或模型配置,能够正常使用。平台不是安装插件的前置条件。共享运行时的 Windows 支持不代表 Windows Cursor 已完成验收;Cursor 实机验收目前覆盖 macOS。Qoder 的 Host Kit 契约测试已进入 CI 矩阵,但 Qoder App 尚未完成 Windows 实机验收,且只提供 POSIX hook 启动器。 **OpenCode Stable 支持(macOS、2.3.2):** 当前源码候选的支持范围与边界见[支持矩阵](opencode-testing.md)。OpenCode 2.2.2、2.3.0 仅有自动化兼容覆盖。 diff --git a/docs/platform-support.md b/docs/platform-support.md index 6b6a03c..b0e07f2 100644 --- a/docs/platform-support.md +++ b/docs/platform-support.md @@ -9,6 +9,7 @@ HelixHarness 面向 macOS、原生 Windows 与 Linux,要求 Python 3.10+、Git | Codex plugin / 插件 | POSIX preflight and hooks | PowerShell preflight; Codex `commandWindows` hooks | | Claude Code plugin / 插件 | Bash hooks | Git for Windows Bash; set `CLAUDE_CODE_GIT_BASH_PATH` if auto-discovery fails | | Cursor plugin / 插件 | POSIX entrypoints; native acceptance on macOS, managed Local updates on macOS/Linux / POSIX 入口;macOS 实机验收,macOS/Linux 托管 Local 更新 | Outside this release's verified scope / 不在本期已验证范围 | +| Qoder plugin / 插件 | Plugin ZIP installed by the App; POSIX `sh` SessionStart hook; native acceptance on macOS / 由 App 安装插件 ZIP;POSIX `sh` SessionStart hook;macOS 实机验收 | Host Kit contract tests run in the CI matrix; no native Windows acceptance yet, and only the POSIX hook launcher exists / Host Kit 契约测试已进入 CI 矩阵;尚未完成 Windows 实机验收,且仅有 POSIX hook 启动器 | | Project linters / 项目检查 | Python scripts | Same Python scripts; legacy `.sh` scripts require Git Bash | | Platform Web, Demo, eval / 平台 | Python service | Same Python service, PowerShell environment syntax | | Scheduled usage sync / 定时同步 | crontab | Task Scheduler, current user logged in; cron matching in Python | diff --git a/docs/user-guide.md b/docs/user-guide.md index b10d331..961f016 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, Claude Code, Cursor and [OpenCode (macOS Stable)](opencode-testing.md), with a companion platform for usage dashboards, version evaluation and evolution.** +**A development workflow for Codex, Claude Code, Cursor, [OpenCode (macOS Stable)](opencode-testing.md) and [Qoder](../helixharness/hosts/qoder/installer.md), 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 / Cursor / [OpenCode (macOS Stable)](opencode-testing.md) · Single repo / multi-repo Workspace · Apache-2.0** +**9 public commands · 3 core stages · Codex / Claude Code / Cursor / [OpenCode (macOS Stable)](opencode-testing.md) / [Qoder](../helixharness/hosts/qoder/installer.md) · 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,16 +49,16 @@ Install **HelixHarness** for everyday development. Add **helixharness-platform** | Use case | Requirements | | --- | --- | -| HelixHarness plugin | Python 3.10+, Git, and a plugin-capable Codex, Claude Code, Cursor or OpenCode installation (macOS, 2.3.2; see the [support matrix](opencode-testing.md)) 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, Cursor, OpenCode installation (macOS, 2.3.2; see the [support matrix](opencode-testing.md)) or Qoder Desktop / CLI that is signed in or has its model configuration set up and works normally | | 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 | -The terminal examples below use Bash / Zsh. Codex/Claude Code marketplace installation does not require a manual clone. The OpenCode 2.3.2 route below uses a source clone and local-directory configuration; running the platform or developing the plugin also requires a source checkout. +The terminal examples below use Bash / Zsh. Codex/Claude Code marketplace installation does not require a manual clone. The OpenCode 2.3.2 route below uses a source clone and local-directory configuration; running the platform or developing the plugin also requires a source checkout. The Qoder route below needs a source checkout too, because that App has no marketplace CLI. ### 1. Install the Plugin -After the repository is public, use the terminal commands below for Codex/Claude Code or the marketplace UI for Cursor. For testing before publication or modifying the plugin, use [developer installation from local source](installation.md#developer-installation). +After the repository is public, use the terminal commands below for Codex/Claude Code, the marketplace UI for Cursor, or the plugin ZIP you build from a checkout for Qoder. For testing before publication or modifying the plugin, use [developer installation from local source](installation.md#developer-installation). **Codex** @@ -92,9 +92,15 @@ After installation, open a new agent session in the application repository you w Install `helix` through **Customize → helix → Install** after the release repository is available in your Cursor marketplace. Use the [marketplace setup and optional installation paths](installation.md#cursor-preview) for administrator setup, fixed-source configuration or managed Local installation. Reload the window and open a new Agent. Cursor's nine `/helix-{command}` Skills use the same arguments and business gates as the `/helix:*` examples below. Statistics require consent and current-session identity and may be partial. Native marketplace updates are managed by Cursor; `/helix-update` supports registered managed-local installations. See [support and verification boundaries](cursor-testing.md). +**Qoder** + +Build the plugin ZIP from a checkout: run `python3 scripts/package_qoder_plugin.py` in the plugin directory, then use **Extensions → Install local plugin** in the App and pick `dist/helix-.zip`, or ask the assistant to install that absolute path with the App installation tool. Packaging scope and the two install entries are described in [Qoder](installation.md#qoder); the full capability boundaries are in the [Qoder install contract](../helixharness/hosts/qoder/installer.md). + +Review and trust the plugin hooks in the App, then open a new session: the manifest, skills, agents and plugin hooks load at session start, and a session that was already open keeps the plugin root it bound earlier. Qoder exposes the nine public entries as `helix:` skills instead of slash commands, so the `/helix:*` examples below are invoked through those entries. The nine commands use the same arguments and business gates. Statistics reporting is not wired up for this host. Reinstalling a newer ZIP is the only upgrade path, and `/helix:update` returns a blocked status. + ### 2. Build Your First Feature -Enter commands **in your coding agent's conversation**, not in a terminal shell. The examples below use the Codex / Claude Code / OpenCode prefix `/helix:`. In Cursor, replace that prefix with `/helix-`, keeping the command name and arguments unchanged; for example, `/helix:init` becomes `/helix-init`, and `/helix:bug-fix` becomes `/helix-bug-fix`. +Enter commands **in your coding agent's conversation**, not in a terminal shell. The examples below use the Codex / Claude Code / OpenCode prefix `/helix:`. In Cursor, replace that prefix with `/helix-`, keeping the command name and arguments unchanged; for example, `/helix:init` becomes `/helix-init`, and `/helix:bug-fix` becomes `/helix-bug-fix`. In Qoder, keep the name unchanged but invoke it through the `helix:` skill entry rather than the slash-command menu. Initialize your application repository: @@ -102,7 +108,7 @@ Initialize your application repository: /helix:init ``` -Claude Code, Codex and Cursor initialization writes project documentation and host project settings. OpenCode merges `AGENTS.md` without creating `.opencode/` settings or project hooks. 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. +Claude Code, Codex, Cursor and Qoder initialization writes project documentation and host project settings. OpenCode merges `AGENTS.md` without creating `.opencode/` settings or project hooks. 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. Create a small, concrete requirement: @@ -165,7 +171,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 / Cursor / [OpenCode (macOS Stable)](opencode-testing.md) sessions and application repositories | +| [`helixharness/`](../helixharness/README.md) | Developers using AI coding agents | Project initialization, requirements, implementation, testing, review, and archiving | Codex / Claude Code / Cursor / [OpenCode (macOS Stable)](opencode-testing.md) / Qoder 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 @@ -194,7 +200,7 @@ Keep three directories distinct: **HelixHarness plugin source**, **application r ## Commands -There are nine public commands. `--loop` is an option on `propose`. The examples use `/helix:` for Codex / Claude Code / OpenCode; in Cursor, use the `/helix-` prefix with the same arguments. +There are nine public commands. `--loop` is an option on `propose`. The examples use `/helix:` for Codex / Claude Code / OpenCode; in Cursor, use the `/helix-` prefix with the same arguments; in Qoder, use the same names as the `helix:` skill entries. | Command | Purpose | Example | | --- | --- | --- | @@ -416,7 +422,7 @@ Paths below are relative to your platform's base URL: ### Model Configuration -For everyday plugin use, configure models in Codex / Claude Code / Cursor / [OpenCode (macOS Stable)](opencode-testing.md). 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 / Cursor / [OpenCode (macOS Stable)](opencode-testing.md) or Qoder. 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. @@ -628,7 +634,7 @@ The repository contains two independently installable projects: ├── helixharness/ │ ├── commands/ # Nine public command entrypoints │ ├── workflows/ # single/ execution and workspace/ coordination -│ ├── hosts/ # Codex / Claude Code / Cursor / OpenCode (macOS Stable) adapters +│ ├── hosts/ # Codex / Claude Code / Cursor / OpenCode (macOS Stable) / Qoder adapters │ ├── skills/ # Reusable workflow methods │ └── scripts/ # Routing, artifact validation, and telemetry └── helixharness-platform/ @@ -651,7 +657,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 and Cursor each install these eight method skills alongside the nine public entry skills; Claude Code discovers the root `skills/` directly; OpenCode registers the same root files as `helix-` method skills. 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 and Cursor each install these eight method skills alongside the nine public entry skills; Claude Code discovers the root `skills/` directly; OpenCode registers the same root files as `helix-` method skills; Qoder declares both skill roots in `.qoder-plugin/plugin.json`, so it sees these eight method skills plus nine `helix:` entry skills. 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. diff --git a/docs/user-guide.zh-CN.md b/docs/user-guide.zh-CN.md index 7d3bc3f..5ac314c 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、Cursor 与 [OpenCode(macOS Stable)](opencode-testing.md)的研发工作流,以及提供数据看板、版本评测与自进化的配套平台。** +**面向 Codex、Claude Code、Cursor、[OpenCode(macOS Stable)](opencode-testing.md) 与 [Qoder](../helixharness/hosts/qoder/installer.md) 的研发工作流,以及提供数据看板、版本评测与自进化的配套平台。** 从一个需求到有验证依据的代码变更:明确边界、拆分任务、实现、测试、评审,再把结果归档到项目中。HelixHarness 将这些步骤作为可复用的工作流交给编码助手,需求和执行进度保存在仓库里,便于检查和续跑。 @@ -14,7 +14,7 @@ Propose → Apply → Archive └─ 测试 + 代码评审 + 验证依据 ``` -**9 个公开命令 · 3 个核心阶段 · Codex / Claude Code / Cursor / [OpenCode(macOS Stable)](opencode-testing.md) · 单仓 / 多仓 Workspace · Apache-2.0** +**9 个公开命令 · 3 个核心阶段 · Codex / Claude Code / Cursor / [OpenCode(macOS Stable)](opencode-testing.md) / [Qoder](../helixharness/hosts/qoder/installer.md) · 单仓 / 多仓 Workspace · Apache-2.0** 只做日常开发,安装 **HelixHarness** 即可。需要观测使用情况、评测和改进 **HelixHarness 框架本身**,再运行 **helixharness-platform**。开发场景的结果用于判断框架行为,平台不是通用的业务代码评分服务。 @@ -50,16 +50,16 @@ Propose → Apply → Archive | 用途 | 要求 | | --- | --- | -| 使用 HelixHarness | Python 3.10+、Git,以及支持插件的 Codex、Claude Code、Cursor 或 OpenCode(macOS、2.3.2;见[支持矩阵](opencode-testing.md));宿主已完成登录或模型配置,能够正常使用 | +| 使用 HelixHarness | Python 3.10+、Git,以及支持插件的 Codex、Claude Code、Cursor、OpenCode(macOS、2.3.2;见[支持矩阵](opencode-testing.md))或 Qoder Desktop / CLI;宿主已完成登录或模型配置,能够正常使用 | | 运行平台 Demo / 使用看板 | Python 3.10+、Git;安装平台 `server` 依赖 | | 真实版本评测 | 平台依赖、可用的 Codex 执行环境、模型凭据、可访问的 Git 仓库,以及 Case 所需的构建与测试工具 | | 前端预览与视觉验证 | 项目自身的 Node.js、包管理器及浏览器工具;设计服务按实际使用情况配置 | -下面的终端示例使用 Bash / Zsh。Codex/Claude Code 的市场安装无需先手动克隆源码;下方 OpenCode 2.3.2 安装步骤采用源码克隆与本地目录配置,运行平台或开发插件也需要源码副本。 +下面的终端示例使用 Bash / Zsh。Codex/Claude Code 的市场安装无需先手动克隆源码;下方 OpenCode 2.3.2 安装步骤采用源码克隆与本地目录配置,运行平台或开发插件也需要源码副本。下文 Qoder 安装同样需要源码副本,因为该 App 没有等价的市场 CLI。 ### 1. 安装 HelixHarness 插件 -仓库公开后,Codex 和 Claude Code 使用下方对应终端命令,Cursor 使用市场界面安装。发布前测试或修改插件时,使用[开发者安装(本地源码)](installation.md#developer-installation)。 +仓库公开后,Codex 和 Claude Code 使用下方对应终端命令,Cursor 使用市场界面安装,Qoder 使用从源码副本构建的插件 ZIP。发布前测试或修改插件时,使用[开发者安装(本地源码)](installation.md#developer-installation)。 **Codex** @@ -93,9 +93,15 @@ OpenCode 适配使用原生工具和会话 Hook,但未提供等价的 SessionS 发行仓库已加入可访问的 Cursor 市场后,通过 **Customize → helix → Install** 安装。管理员配置、高级固定来源配置及托管 Local 安装见[市场安装与可选路径](installation.md#cursor-preview)。安装后重载窗口并新建 Agent。Cursor 的九个 `/helix-{command}` Skill 与下文 `/helix:*` 示例使用相同参数和业务门禁。统计需授权及本次会话身份,数据可能为 partial。原生市场更新由 Cursor 管理,`/helix-update` 支持已登记的托管 Local。详见[支持与验证边界](cursor-testing.md)。 +**Qoder** + +Qoder 通过源码副本构建的插件 ZIP 安装:在插件目录执行 `python3 scripts/package_qoder_plugin.py`,然后在 App 内选择 **扩展 → 安装本地插件** 并指定 `dist/helix-.zip`,或让助手用 App 安装工具按该绝对路径安装。打包范围与两种安装入口见 [Qoder 安装流程](installation.md#qoder),完整能力边界见 [Qoder 安装合同](../helixharness/hosts/qoder/installer.md)。 + +先在 App 内审阅并信任插件 hooks,再开启新会话:插件清单、skills、agents 与插件 hook 在会话启动时装载,已开启的会话仍沿用它先前绑定的插件根目录。Qoder 的九个公共入口是 `helix:` 形态的 Skill 而非斜杠命令,因此下文 `/helix:*` 示例通过这些入口调用,参数和业务门禁完全相同。本宿主未接入统计上报。升级只能重新打包并安装新版 ZIP,`/helix:update` 会返回阻断状态。 + ### 2. 完成第一个需求 -命令应**输入到编码助手会话中**,不是终端 Shell 命令。以下示例使用 Codex / Claude Code / OpenCode 的 `/helix:` 前缀;在 Cursor 中将该前缀替换为 `/helix-`,命令名和参数保持不变。例如 `/helix:init` 对应 `/helix-init`,`/helix:bug-fix` 对应 `/helix-bug-fix`。 +命令应**输入到编码助手会话中**,不是终端 Shell 命令。以下示例使用 Codex / Claude Code / OpenCode 的 `/helix:` 前缀;在 Cursor 中将该前缀替换为 `/helix-`,命令名和参数保持不变。例如 `/helix:init` 对应 `/helix-init`,`/helix:bug-fix` 对应 `/helix-bug-fix`。在 Qoder 中命令名不变,但通过 `helix:` 形态的 Skill 入口调用,不依赖斜杠命令菜单。 先在业务仓库初始化项目: @@ -103,7 +109,7 @@ OpenCode 适配使用原生工具和会话 Hook,但未提供等价的 SessionS /helix:init ``` -Claude Code、Codex 和 Cursor 初始化会写入项目文档和宿主项目配置。OpenCode 只合并 `AGENTS.md`,不创建 `.opencode/` settings 或项目 hooks。宿主提示当前项目配置目录的写权限时,确认本项目后授权。自动化运行也需显式响应授权:Claude Code 的 `acceptEdits` 模式不会自动批准 `.claude/settings.json`,保护 `.codex/` 的沙箱也可能使 Codex hooks 未完成。开始需求前先检查初始化结果。 +Claude Code、Codex、Cursor 和 Qoder 初始化会写入项目文档和宿主项目配置。OpenCode 只合并 `AGENTS.md`,不创建 `.opencode/` settings 或项目 hooks。宿主提示当前项目配置目录的写权限时,确认本项目后授权。自动化运行也需显式响应授权:Claude Code 的 `acceptEdits` 模式不会自动批准 `.claude/settings.json`,保护 `.codex/` 的沙箱也可能使 Codex hooks 未完成。开始需求前先检查初始化结果。 再创建一个范围清晰的需求: @@ -166,7 +172,7 @@ python -m web_ui.demo --port 7860 --data-dir /path/to/demo-runtime | 项目 | 面向谁 | 负责什么 | 运行位置 | | --- | --- | --- | --- | -| [`helixharness/`](../helixharness/README.md) | 日常使用 AI 编码的开发者 | 初始化项目、收敛需求、实现、测试、评审、归档 | Codex / Claude Code / Cursor / [OpenCode(macOS Stable)](opencode-testing.md) 会话及业务仓库 | +| [`helixharness/`](../helixharness/README.md) | 日常使用 AI 编码的开发者 | 初始化项目、收敛需求、实现、测试、评审、归档 | Codex / Claude Code / Cursor / [OpenCode(macOS Stable)](opencode-testing.md) / Qoder 会话及业务仓库 | | [`helixharness-platform/`](../helixharness-platform/README.md) | 观测和改进 HelixHarness 框架的维护者 | 数据看板、版本评测、自进化 | 独立 Python Web 服务与评测 Worker | ```mermaid @@ -195,7 +201,7 @@ flowchart LR ## 命令参考 -公开命令共九个,`--loop` 是 `propose` 的参数。表中示例使用 Codex / Claude Code / OpenCode 的 `/helix:`;在 Cursor 中使用 `/helix-` 前缀,参数相同。 +公开命令共九个,`--loop` 是 `propose` 的参数。表中示例使用 Codex / Claude Code / OpenCode 的 `/helix:`;在 Cursor 中使用 `/helix-` 前缀,参数相同;在 Qoder 中使用同名 Skill 入口 `helix:`。 | 命令 | 用途 | 示例 | | --- | --- | --- | @@ -417,7 +423,7 @@ DEFAULT_FEEDBACK_ENDPOINT = "" ### 模型配置 -日常使用插件时,模型由 Codex / Claude Code / Cursor / [OpenCode(macOS Stable)](opencode-testing.md) 宿主配置。平台自身的模型配置用于平台发起的评测、分析等任务。 +日常使用插件时,模型由 Codex / Claude Code / Cursor / [OpenCode(macOS Stable)](opencode-testing.md) 或 Qoder 宿主配置。平台自身的模型配置用于平台发起的评测、分析等任务。 配置模板见 [`helixharness-platform/.env.example`](../helixharness-platform/.env.example)。服务读取**进程环境变量,不会自动加载 `.env.example`**;将真实值注入启动 Web 和 Worker 的环境。 @@ -629,7 +635,7 @@ Candidate 生成在普通用户(包括 macOS 本地用户)下默认使用 Co ├── helixharness/ │ ├── commands/ # 九个公共命令入口和路由 │ ├── workflows/ # single/ 单仓执行,workspace/ 多仓协调 -│ ├── hosts/ # Codex / Claude Code / Cursor / OpenCode(macOS Stable) 适配 +│ ├── hosts/ # Codex / Claude Code / Cursor / OpenCode(macOS Stable) / Qoder 适配 │ ├── skills/ # 工作流复用的方法 │ └── scripts/ # 路由、工件校验与遥测 └── helixharness-platform/ @@ -652,7 +658,7 @@ Candidate 生成在普通用户(包括 macOS 本地用户)下默认使用 Co | [`systematic-debugging`](../helixharness/skills/systematic-debugging/SKILL.md) | 复现异常、验证假设、定位根因与验证修复 | 由用户明确调用,独立使用 | | [`feedback`](../helixharness/skills/feedback/SKILL.md) | 提交 HelixHarness 使用问题 | 独立辅助能力;需启动平台并配置地址 | -Codex 与 Cursor 安装目录各包含九个公开入口 Skill 和上述八个方法 Skill;Claude Code 直接发现根 `skills/`;OpenCode 从相同根文件注册 `helix-` 方法 Skill。四个生命周期命令继续使用工作流路由;`status`、`config` 与辅助 Skill 不增加研发阶段。正式 Spec/Tasks、执行进度和完成验证仍由对应研发阶段负责。 +Codex 与 Cursor 安装目录各包含九个公开入口 Skill 和上述八个方法 Skill;Claude Code 直接发现根 `skills/`;OpenCode 从相同根文件注册 `helix-` 方法 Skill;Qoder 在 `.qoder-plugin/plugin.json` 中同时声明两个 skill 根,因此可见上述八个方法 Skill 与九个 `helix:` 入口 Skill。四个生命周期命令继续使用工作流路由;`status`、`config` 与辅助 Skill 不增加研发阶段。正式 Spec/Tasks、执行进度和完成验证仍由对应研发阶段负责。 `git-diff-impact` 无需 Init、活跃 feature 或平台服务。示例:“使用 HelixHarness git-diff-impact,分析当前未提交改动,--no-save”;也可明确提供两个提交或分支,以及 `--req` / `--design` 文档。默认保存 Markdown 到 `diff-impact-reports/`,`--out` 可指定位置。它不自动修复代码,也不改变评审结论。 diff --git a/helixharness/hosts/cursor/host.json b/helixharness/hosts/cursor/host.json index 3fd68e6..bc084f8 100644 --- a/helixharness/hosts/cursor/host.json +++ b/helixharness/hosts/cursor/host.json @@ -13,7 +13,8 @@ "Automatic plugin updates require a Helix-managed local installation on macOS/Linux. Marketplace-managed or unregistered copies are not modified.", "D2C uses an explicit checkpoint gate; no native skill-scoped Stop or user-question hook is claimed. An owner-bound completion requires the real current session identity; missing identity cannot be bypassed.", "sessionEnd delivery/execution is best effort. Explicit consent revocation cleans this repository; a later sessionStart retries scoped cleanup while consent remains disabled. Closing a window does not guarantee cleanup.", - "Pinned native project installation is supported on the tested desktop build. Native automatic updates are unsupported; check provides current-installation facts and manual steps without consuming managed-local authorization. Statistics may remain partial." + "Pinned native project installation is supported on the tested desktop build. Native automatic updates are unsupported; check provides current-installation facts and manual steps without consuming managed-local authorization. Statistics may remain partial.", + "Native Windows Cursor has no recorded acceptance session, so the POSIX sh hook launcher and the shell-quoted HELIXHARNESS_* identity prefix have no Windows evidence base; an unapplied prefix only skips statistics." ] }, "capabilities": { From 4e25eb3787ca1dae054dea443135ff4aa3844dc8 Mon Sep 17 00:00:00 2001 From: zhangdelong Date: Thu, 26 Nov 2026 11:35:00 +0800 Subject: [PATCH 31/37] =?UTF-8?q?fix(qoder):=20=E7=99=BD=E5=90=8D=E5=8D=95?= =?UTF-8?q?=E6=89=93=E5=8C=85=E3=80=81=E4=BF=9D=E7=95=99=E5=9B=A2=E9=98=9F?= =?UTF-8?q?=20Hook=20=E5=8F=82=E6=95=B0=E5=B9=B6=E4=BF=AE=E5=A4=8D=20OpenC?= =?UTF-8?q?ode=20=E9=81=A5=E6=B5=8B=E8=AF=81=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 打包由 rglob 排除表改为正向白名单,拒绝未跟踪文件与越过插件根的符号链接 - hook 合并仅认领无额外参数的自生成命令,团队 handler 原样保留并告警 - 阶段遥测 evidence 补 schema,平台快照保留「未采集」语义 --- .../eval/stage_supplements.py | 4 + .../eval/tests/test_stage_supplements.py | 21 +++++ helixharness/hosts/qoder/installer.md | 24 +++-- helixharness/scripts/package_qoder_plugin.py | 71 +++++++++++++- helixharness/scripts/project_hooks_cli.py | 82 +++++++++++------ helixharness/scripts/telemetry_collector.py | 8 +- .../scripts/tests/test_opencode_telemetry.py | 3 + .../scripts/tests/test_project_hooks.py | 39 ++++++++ .../scripts/tests/test_qoder_host_contract.py | 92 +++++++++++++++++++ 9 files changed, 306 insertions(+), 38 deletions(-) diff --git a/helixharness-platform/eval/stage_supplements.py b/helixharness-platform/eval/stage_supplements.py index c3786f0..b0a6565 100644 --- a/helixharness-platform/eval/stage_supplements.py +++ b/helixharness-platform/eval/stage_supplements.py @@ -177,6 +177,10 @@ def _snapshot_payload(item: dict[str, Any]) -> dict[str, Any]: evidence = item.get("evidence") if isinstance(item.get("evidence"), dict) else {} snapshot["evidence"] = {"schema": EVIDENCE_SCHEMA} + for field in ("status", "reason_code"): + value = evidence.get(field) + if isinstance(value, str) and value.strip(): + snapshot["evidence"][field] = value[:64] for field, allowed in ( ("interaction_summary", ("user_turns", "assistant_messages")), ("coverage", ("in_window", "retained")), diff --git a/helixharness-platform/eval/tests/test_stage_supplements.py b/helixharness-platform/eval/tests/test_stage_supplements.py index f51b29e..fb96f6b 100644 --- a/helixharness-platform/eval/tests/test_stage_supplements.py +++ b/helixharness-platform/eval/tests/test_stage_supplements.py @@ -180,6 +180,27 @@ def test_link_finalizes_sanitized_snapshot_once(tmp_path) -> None: assert "private fallback" not in serialized +def test_stage_facts_only_evidence_keeps_unavailable_semantics(tmp_path) -> None: + store = StageSupplementStore(tmp_path / "supplements.db") + item = _supplement() + item["platform"] = "opencode" + # 阶段事实型宿主(opencode)没有会话转录,只能上报 unavailable。 + item["evidence"] = { + "schema": "helixharness-evolution-evidence/1.0", + "status": "unavailable", + "reason_code": "host_transcript_not_collected", + } + assert store.ingest(item) == {"supplement_id": "supp_0123456789abcdef", "status": "accepted", "linked": False} + assert store.refresh_links([_write_ledger(tmp_path)]) == 1 + snapshot = store.active_linked_records()[0].payload + # 快照必须保留“未采集”语义,不能让 unavailable 退化成空证据。 + assert snapshot["evidence"] == { + "schema": "helixharness-evolution-evidence/1.0", + "status": "unavailable", + "reason_code": "host_transcript_not_collected", + } + + def test_finalized_entry_rejects_later_revision(tmp_path) -> None: store = StageSupplementStore(tmp_path / "supplements.db") ledger_root = _write_ledger(tmp_path) diff --git a/helixharness/hosts/qoder/installer.md b/helixharness/hosts/qoder/installer.md index a2a2935..0d38fda 100644 --- a/helixharness/hosts/qoder/installer.md +++ b/helixharness/hosts/qoder/installer.md @@ -13,8 +13,14 @@ python3 scripts/package_qoder_plugin.py # 产出 dist/helix-.zip ``` -脚本排除 `.claude-plugin/`、`.codex-plugin/`、`hosts/claude-code/`、`hosts/codex/`、根 `SKILL.md`、 -`__pycache__` 与本地状态,把 `hosts/qoder/hooks.json` 复制到 ZIP 根 `hooks/hooks.json`,并为每个 +脚本按白名单收文件:清单与 `hooks/hooks.json`、`agents/`、`commands/`、`scripts/`、`reference/`、 +`skills/`、`templates/`、`workflows/`、`hosts/qoder/`、`hosts/shared/`、 +`hosts/host-manifest-v1.schema.json`,以及 `README.md`、`PLUGIN_USAGE.md` 与许可证文件。其他宿主表面和 +本地文件(`hosts/cursor/`、`hosts/opencode/`、`hosts/claude-code/`、`hosts/codex/`、`opencode/`、 +`package.json`、`tsconfig.json`、根 `SKILL.md`、`.claude-plugin/`、`.codex-plugin/`、`.cursor-plugin/`、 +`AGENTS.md`、`CLAUDE.md` 等)一律不收。在 git 仓库内构建时,白名单路径下未纳入版本控制的文件会直接 +报错,符号链接解析到插件根之外也会报错——本地状态不能随包发出。脚本还会把 `hosts/qoder/hooks.json` +复制到 ZIP 根 `hooks/hooks.json`,并为每个 `agents/*.md` 注入与文件名一致的 `name` frontmatter——Qoder 按 `name` 注册子代理角色,这是本宿主的 分发细节,不写回共享源文件。`commands/*.md` 随包保留:它不进入宿主命令面,但它是薄入口与 Host Runtime 投影指向的唯一公共契约,缺少它投影就无法解析。 @@ -77,12 +83,14 @@ handler,没有重启也没有新开会话,所以验收项目 hooks 不必换 invariant-check; rerun /helix:init`),整个会话里模型一次都没看到这句话。验收 guardrail 必须去读转录里的 hook 记录,不能以“会话没报错”当作 hook 正常工作的证据。 - 更新插件后重跑 Init 会自动收敛陈旧 handler:本宿主的 `hosts/qoder/project-hooks.json` 声明 - `stale_binding_policy = { recognize: linter_flag, merge: collapse, check: warn }`。merge 按 - `--linter ` 加脚本路径尾部的形状认领自生成命令,同一 linter 的重复项只保留第一条并把 - `command` 改写为当前版本;`check` 默认把仍存在的缺失或重复降级为 `warnings` 返回而不阻断 Init, - 需要严格阻断时传 `--strict`。macOS 上同一目录写成 `/tmp/...` 会被规范成 `/private/tmp/...` - 的情况也一并被折叠,不再需要人工清理。1.1.0 之前遗留的手动删条目步骤可以跳过;如果仍看到 - 指向已卸载版本目录的 handler,说明它形状没被识别(例如自定义 flag),此时才需要用户确认。 + `stale_binding_policy = { recognize: linter_flag, merge: collapse, check: warn }`。merge 只认领 + “` -X utf8