diff --git a/base_harness/claude-code/README.md b/base_harness/claude-code/README.md index 37cf3d23..c9972e73 100644 --- a/base_harness/claude-code/README.md +++ b/base_harness/claude-code/README.md @@ -14,6 +14,11 @@ python3 tools/configure_claude_harness.py /path/to/claude-harness --claude /abso harnessgrad run --harness-path /path/to/claude-harness ... ``` +On Linux x86-64, `harnessgrad harness install claude-code` installs the official +`@anthropic-ai/claude-code-linux-x64` package from npm and prints the prepared +harness path. Omitting `--version` selects the latest verified release, +currently `2.1.335`. The installed native executable is a fixed runtime. + The binding checks executable contents and permissions, optional official npm package metadata, the host version and a network-isolated native sandbox version probe. It records the canonical executable and metadata as read-only runtime diff --git a/base_harness/codex/README.md b/base_harness/codex/README.md index 4871dc4c..2dea962d 100644 --- a/base_harness/codex/README.md +++ b/base_harness/codex/README.md @@ -18,7 +18,7 @@ HARNESS_DIR=$(harnessgrad harness install codex) Use the printed directory with `harnessgrad run --harness-path`. Omitting `--version` selects the latest verified Codex release listed by `harnessgrad -harness list`, currently `0.172.0`, and reports the choice on stderr. Use +harness list`, currently `0.173.0`, and reports the choice on stderr. Use `--install-root` to choose a dedicated store outside the platform checkout and shared temporary directories. By default the store is `harnessgrad/base-harnesses` under the user data directory. Each release has its own package lock and binding. diff --git a/base_harness/hermes-agent/README.md b/base_harness/hermes-agent/README.md index a5bf02ca..5e8b3283 100644 --- a/base_harness/hermes-agent/README.md +++ b/base_harness/hermes-agent/README.md @@ -4,20 +4,20 @@ Install on Linux x86-64 with Git and uv on `PATH`. The default mode is `editable`. Select `--mode fixed` to improve the adapter against a fixed Hermes runtime. -Omitting `--version` selects the latest verified release. An exact unverified -version prints a warning to stderr and attempts to use that release's Git tag -and `uv.lock`. The installer records the resolved commit and selects exact +Omitting `--version` selects the latest verified release, currently `0.23.6`. +An exact unverified version prints a warning to stderr and attempts to use that +release's Git tag and `uv.lock`. The installer records the resolved commit and selects exact public registry pins for the Linux x86-64 Python environment. A successful version check still leaves the installation marked unverified. ```sh -hermes_harness="$(harnessgrad harness install hermes-agent --version v0.23.4)" +hermes_harness="$(harnessgrad harness install hermes-agent)" harnessgrad run --dataset demo --tasks t01 --harness-path "$hermes_harness" \ --rounds 0 --improver none ``` -The installer verifies tag `v0.23.4` against commit -`8fc0374447313e276f6b9a2764bfc750190c966a` in a bare Git cache and exports +The installer verifies tag `v0.23.6` against commit +`a6d60eda2aa6d0bf59189a79647ca8e35600a141` in a bare Git cache and exports the headless source into the base candidate's `hermes/` directory. The source includes the upstream license, Python packages, and runtime resources. The export excludes upstream CI, tests, evaluations, the website, contributor @@ -36,7 +36,7 @@ For improvement rounds, pass your experiment method to `--method-entrypoint` and select a configured `--improver`. To prepare the fixed mode, run -`harnessgrad harness install hermes-agent --version v0.23.4 --mode fixed`. +`harnessgrad harness install hermes-agent --mode fixed`. Pass the printed path to `--harness-path` in the same way. The candidate contains the adapter. The installer exports the same release from the bare Git cache into a separate read-only runtime and binds it in the launch @@ -48,8 +48,8 @@ The sandbox uses a private `/tmp` during the version check and task execution. The installer provisions CPython 3.14.10 and prepares the base dependencies through HarnessGrad's managed Python runtime. The candidate's `requirements.lock` pins the Linux x86-64 base dependencies selected from the -upstream `hermes/uv.lock`, including its Pillow override. A source-only edit -reuses the dependency environment. Both install modes use that same locked +upstream release's `hermes/uv.lock`, including its Pillow override. A source-only +edit reuses the dependency environment. Both install modes use that same locked environment. To change Python dependencies for an editable candidate, update its `requirements.lock`. Any new wheels must be available in the operator's offline cache before evaluation. Use the same managed runtime store during diff --git a/base_harness/hermes-agent/hermes_runtime.py b/base_harness/hermes-agent/hermes_runtime.py index d321d468..2d29aadc 100644 --- a/base_harness/hermes-agent/hermes_runtime.py +++ b/base_harness/hermes-agent/hermes_runtime.py @@ -11,7 +11,10 @@ RECORD = "_hermes_runtime" FIXED_SCHEMA = 2 -RELEASES = {"0.23.4": "8fc0374447313e276f6b9a2764bfc750190c966a"} +RELEASES = { + "0.23.4": "8fc0374447313e276f6b9a2764bfc750190c966a", + "0.23.6": "a6d60eda2aa6d0bf59189a79647ca8e35600a141", +} RELEASE_VERSION = re.compile(r"(?:0|[1-9][0-9]*)(?:\.(?:0|[1-9][0-9]*)){2}(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?") PYTHON = "3.14.10" BOOTSTRAP = ( diff --git a/base_harness/hermes-agent/requirements-0.23.6.lock b/base_harness/hermes-agent/requirements-0.23.6.lock new file mode 100644 index 00000000..432a0fbd --- /dev/null +++ b/base_harness/hermes-agent/requirements-0.23.6.lock @@ -0,0 +1,77 @@ +# Hermes Agent v0.23.6 base dependencies from upstream uv.lock. +# Target: Linux x86-64, CPython 3.14.10. +aiohappyeyeballs==2.7.1 +aiohttp==3.14.5 +aiosignal==1.4.0 +annotated-doc==0.0.5 +annotated-types==0.8.0 +anyio==4.15.1 +attrs==26.1.0 +browser-harness==0.1.13 +cdp-use==1.4.5 +certifi==2026.10.19 +cffi==2.1.1 +charset-normalizer==3.5.2 +click==8.5.0 +croniter==6.2.4 +cryptography==50.0.2 +distro==1.9.0 +fastapi==0.133.1 +fetch-use==0.4.0 +fire==0.7.1 +firecrawl-anydoc==0.2.4 +frozenlist==1.8.0 +h11==0.16.0 +httpcore==1.0.9 +httptools==0.8.0 +httpx==0.28.1 +idna==3.20 +jinja2==3.1.6 +jiter==0.17.0 +markdown==3.11.2 +markdown-it-py==4.2.0 +markupsafe==3.0.4 +mdurl==0.1.2 +multidict==6.9.1 +nemo-relay==0.11.0 +openai==2.54.0 +packaging==26.3 +pathspec==1.1.1 +pillow==13.0.0 +pillow-heif==1.8.1 +prompt-toolkit==3.0.53 +propcache==0.5.4 +psutil==7.2.2 +ptyprocess==0.7.0 +pycparser==3.11 +pydantic==2.14.1 +pydantic-core==2.50.1 +pygments==2.21.0 +pyjwt==2.15.1 +pypng==0.20220715.0 +python-dateutil==2.9.0.post0 +python-dotenv==1.2.4 +python-multipart==0.0.32 +qrcode==7.4.2 +requests==2.34.2 +resvg-py==0.5.0 +rich==14.3.4 +ruamel-yaml==0.18.16 +ruamel-yaml-clib==0.2.15 +six==1.17.0 +sniffio==1.3.1 +snowballstemmer==3.1.1 +socksio==1.0.0 +starlette==1.9.0 +termcolor==3.3.0 +tomli-w==1.2.0 +tqdm==4.70.1 +truststore==0.10.5 +typing-extensions==4.16.0 +typing-inspection==0.4.4 +urllib3==2.8.0 +uvicorn==0.54.0 +watchfiles==1.3.0 +wcwidth==0.9.2 +websockets==15.0.1 +yarl==1.25.1 diff --git a/base_harness/oh-my-pi/README.md b/base_harness/oh-my-pi/README.md index 6960810c..42ea8bea 100644 --- a/base_harness/oh-my-pi/README.md +++ b/base_harness/oh-my-pi/README.md @@ -7,8 +7,8 @@ HARNESS_DIR=$(harnessgrad harness install oh-my-pi) harnessgrad run --harness-path "$HARNESS_DIR" ... ``` -The installer defaults to `19.2.0`. It downloads the glibc Linux x86-64 executable from the -[v19.2.0 release](https://github.com/can1357/oh-my-pi/releases/tag/v19.2.0), +The installer defaults to `19.4.1`. It downloads the glibc Linux x86-64 executable from the +[v19.4.1 release](https://github.com/can1357/oh-my-pi/releases/tag/v19.4.1), verifies its pinned SHA-256, and checks the version inside a network-isolated sandbox. Ubuntu x86-64 is the tested target. The executable bundles Bun. The command prints the prepared adapter path. Set `--install-root` to use diff --git a/base_harness/oh-my-pi/omp_runtime.py b/base_harness/oh-my-pi/omp_runtime.py index ac83994a..e10173b7 100644 --- a/base_harness/oh-my-pi/omp_runtime.py +++ b/base_harness/oh-my-pi/omp_runtime.py @@ -15,6 +15,9 @@ "19.2.0": { "x86_64": ("omp-linux-x64", "74cb641d3fcdc22fa3f2141dafa4e66c9fc581d7d2d71753e690160980472c31"), }, + "19.4.1": { + "x86_64": ("omp-linux-x64", "475506912c5973958ceafb8ccfb1a52ef0208a46eb37daf74b726d7faad0a9cc"), + }, } diff --git a/base_harness/openclaw/README.md b/base_harness/openclaw/README.md index d32ef367..950cc236 100644 --- a/base_harness/openclaw/README.md +++ b/base_harness/openclaw/README.md @@ -1,7 +1,7 @@ # OpenClaw harness -Harness adapter `0.7.0` has verified **OpenClaw 2026.11.3 (`847611d`)** and -**2026.11.2 (`b556fdf`)**. The checked-in +Harness adapter `0.7.0` has verified **OpenClaw 2026.12.1 (`6a27c35`)**, +**2026.11.3 (`847611d`)**, and **2026.11.2 (`b556fdf`)**. The checked-in Harness is a portable adapter template. OpenClaw and Node are external read-only dependencies. Each reviewed release selects an adapter profile for its configuration and session format. @@ -24,7 +24,7 @@ harnessgrad harness install openclaw ``` The installer defaults to the latest verified release in `harnessgrad harness list`, -currently `2026.11.3`. It reports the selected version on stderr. Use `--version` +currently `2026.12.1`. It reports the selected version on stderr. Use `--version` to select an exact `YYYY.M.D` release. An unlisted release produces a warning on stderr and is tried with the latest verified release's adapter profile. The binding records the exact release and its unverified status. Its config @@ -35,7 +35,7 @@ Use `--install-root` to choose a dedicated runtime store outside the platform checkout and `/tmp`. The default is `harnessgrad/base-harnesses` under the user data directory. The installer retains the npm lockfile and rechecks the binding when reusing an installation. It uses `npm ci --ignore-scripts` to install from -the lockfile. For 2026.11.2, 2026.11.3, and unverified releases, it then targets +the lockfile. For currently verified and unverified releases, it then targets the locked OpenClaw package directory with `npm rebuild` to run that package's lifecycle scripts in the installation sandbox. Verified releases use a pinned package digest. For other releases, npm checks the archive against the digest recorded @@ -132,7 +132,7 @@ to another version can pass runtime admission if its binding validates. Its adapter must also support that version's configuration and session format for the task to complete. -The 2026.11.2 and 2026.11.3 releases share a profile that writes the keyed agent +The verified releases share a profile that writes the keyed agent configuration and reads transcript messages through `sessions export-trajectory`. The export stays in the task's private OpenClaw state. The adapter translates replies, completed tool calls and usage into the HarnessGrad trace format. @@ -235,7 +235,7 @@ Enabling these capabilities changes the harness baseline and may add background network activity or resource usage. Native child sessions are retained in the trace separately from the parent answer. -The shared 2026.11.2 and 2026.11.3 profile reads child runs stored inside the +The shared profile reads child runs stored inside the SQLite registry's `parentCompletion` wrapper. It waits for terminal execution, cleanup bookkeeping and any pending or dispatching requester continuation. A run with `delivery.status = "not_required"` needs no completion notification. diff --git a/base_harness/opencode/README.md b/base_harness/opencode/README.md index cd5d27fc..118e0410 100644 --- a/base_harness/opencode/README.md +++ b/base_harness/opencode/README.md @@ -1,21 +1,20 @@ # OpenCode Harness -Install OpenCode on Linux x86-64 with Bubblewrap. +Install OpenCode v2 on Linux x86-64 with Bubblewrap. ```sh HARNESS_DIR=$(harnessgrad harness install opencode) harnessgrad harness install opencode --mode fixed -harnessgrad harness install opencode --mode fixed --version 2.4.1 -harnessgrad harness install opencode --version 1.19.5 +harnessgrad harness install opencode --version 2.4.1 ``` Use the printed directory with `harnessgrad run --harness-path`. Omitting `--version` selects the latest verified release for the selected mode, currently -`2.4.3`. +`2.4.4`. `--install-root` selects the dedicated store, which defaults to `harnessgrad/base-harnesses` under the user data directory. -**Editable** is the default for the latest verified v2 release. The installer verifies the source archive, prepares +**Editable** is the default. The installer verifies the source archive, prepares Bun 1.4.4 and populates a dependency store using the upstream lockfile. The H0 candidate contains OpenCode source in `opencode/`, where the improve agent can edit it. Evaluation uses the current candidate's TypeScript and mounts Bun and @@ -24,30 +23,27 @@ The installer materializes internal source file links for portable snapshots. Both source preparation and the CLI run use locked dependencies. Evaluation requires a sandbox and uses no package downloads. -**Fixed** uses a Linux x86-64 executable. Verified GitHub Release versions are `2.4.0`, `2.4.1`, `2.4.2`, and `2.4.3`. +**Fixed** installs a Linux x86-64 executable from GitHub Releases. +Verified versions are `2.2.6`, `2.2.7`, `2.3.0`, +`2.4.0`, `2.4.1`, `2.4.2`, `2.4.3`, and `2.4.4`. The installer verifies the archive and executable and probes the CLI version with network access disabled. Evaluation mounts the executable read-only, and the candidate contains the adapter. -The fixed installer also supports native npm packages. OpenCode 1.x uses -`opencode-linux-x64`, and npm installations of 2.x use `@opencode/cli-linux-x64`. -The installer verifies the archive digest of known packages, retains the lockfile, -and binds the executable and package metadata read-only. Requesting 1.x, a -verified npm-only version (2.2.6, 2.2.7 or 2.3.0), or 2.4.1 without a mode -selects a fixed installation. - -Verification is tracked per installation mode. An explicit release -unverified for the selected mode produces a warning and installation proceeds +Verification is tracked per installation mode. An explicit v2 release +verified only for `fixed` uses that mode when `--mode` is omitted. If the release +is unverified for the selected mode, the installer prints a warning and proceeds without a confirmation prompt. -To bind an existing v1 or v2 native npm installation, run +Existing v2 native npm installations can be selected from their recorded +installation directories. To bind one manually, run `python3 tools/configure_opencode_harness.py "$HARNESS_DIR" --opencode "$OPENCODE_BIN"`. `OPENCODE_BIN` points to the Linux x86-64 ELF executable at `bin/opencode` inside its native npm package, with `package.json` at the package root. -Both release series use `run --format json` for tool events. The adapter reads -the final answer and usage from `export` in v1 and `session export` in v2. -It keeps OpenCode's configuration and state local to the task and passes the task's model endpoint and credential. Set +The adapter uses `run --format json` for tool events and `session export` for +the final answer and usage. It keeps OpenCode's configuration and state local +to the task and passes the task's model endpoint and credential. Set `HG_AGENT_OPENCODE_WIRE` to `responses` for a Responses endpoint. The default transport is Chat Completions (`chat`). The platform records the effective transport in the measurement's runtime identity. Cache reuse, H0 reuse, and @@ -57,13 +53,9 @@ the transport, start a new run and measure again. Start a new run when switching versions or installation modes. Historical schema 2 source bindings require the original platform revision to resume. -The task prompt does not prohibit native subagents. Parent and child sessions are -recorded separately; child text cannot replace the parent answer. For 2.x, token -usage is combined only when the complete session tree is available. The 1.x CLI -can omit auxiliary requests from exports, so delegated total usage is marked -unknown even when partial usage is available. Delegation can increase time and -cost. Use a fresh baseline after this adapter change. - +The adapter records native parent and child sessions separately. The parent +session supplies the final answer. Token usage is combined when the complete +session tree is available. ## Versioned native resources @@ -84,12 +76,11 @@ Supported native resource locations are: | Custom primary agents and subagents | `.opencode/agents/**/*.md` (singular `agent/` also supported) | | Commands | `.opencode/commands/**/*.md` (singular `command/` also supported) | | Plugins and their hooks | `.opencode/plugins/*.{js,ts}` (singular `plugin/` also supported) | -| Custom native v1 tools | `.opencode/tools/*.{js,ts}` (singular `tool/` also supported) | -| MCP and LSP declarations | Native `mcp` / `lsp` fields in `opencode.json`; local programs under `.opencode/servers/` | +| MCP servers | Native `mcp` field in `opencode.json`. Local programs under `.opencode/servers/`. | | Behavioral settings | Native fields in `opencode.json` | Resource paths in `instructions` are relative to the copied `.opencode/` root. -Local MCP/LSP command arguments that name candidate-owned files are relocated +Local MCP command arguments that name candidate-owned files are relocated from `./servers/x.py`, `servers/x.py`, or `.opencode/servers/x.py` to that copied root. Bare executable names, flags and task-relative arguments that do not name candidate files keep their native meaning. Executable source modes are retained. @@ -102,47 +93,18 @@ variant or step budgets. Parsing agent/command YAML frontmatter requires **PyYAML in the adapter's Python environment**. Its absence fails explicitly before the native CLI starts; it does not skip validation or silently drop agents. -OpenCode 1.19.5 and 2.4.1 have different native plugin APIs. In v1, plugins export -plugin functions and may return native hook objects; in v2, plugins export a -default object with `id` and `setup`, and register hooks explicitly. V2 custom -tools use the native plugin `ctx.tool.transform` API; the old standalone `tools/` -module directory is rejected for v2. Commands are executable through v1 -`run --command`, and through the v2 native `session.command` API. A JSON or file -being copied is not a successful qualification: it must affect native behavior. - -**LSP is qualified on native 1.19.5 only.** The 2.4.1 control accepted the LSP -configuration but did not start the configured server during native file writes; -its API/tool catalog also exposed no LSP diagnostics operation. Prepared 2.4.1 -candidates therefore refuse an active `lsp` resource declaration with an explicit -qualification diagnostic. This is a documented version boundary, not a claim that -all future OpenCode v2 versions lack LSP. - -Pure local JavaScript resources need no package installation. Their copied config -root is read-only after staging, avoiding a native v1 startup-time attempt to -install `@opencode-ai/plugin` into every fresh task. Plugins that require npm -dependencies may instead supply **both** `.opencode/package.json` and -`.opencode/package-lock.json`. The adapter requires an npm v2/v3 lock with matching -root dependencies and locked package versions/integrities; v1 must explicitly pin -`@opencode-ai/plugin`. This selects native task-local dependency-install mode and -can incur download/install overhead. Lifecycle scripts must be prepared separately. -A separate native 1.19.5 control at -`tests/fixtures/opencode_surfaces/qualify_dependencies.py` qualified an actual -locked `@opencode-ai/plugin@1.19.5` import, including its 32-package dependency -graph. The native adapter installed the exact lock in its task-local writable -config, executed the imported SDK's custom tool, and recorded the resolved -package/entry hashes and version. Source and native package/lock hashes matched. -That control used 16.5 s for registry lock preparation and 12.7 s for native -execution including dependency installation and three local stub model requests; -these are observed one-control times, not general throughput estimates. Arbitrary -dependency-heavy plugins and v2 dependency installation still need their own -qualification before an experiment. - -A native qualification helper is provided at -`tests/fixtures/opencode_surfaces/qualify.py`. It runs a synthetic task against a -local deterministic model endpoint and local MCP/LSP programs. The v1 control -checks instructions, output style, skill execution, command expansion, custom -primary agent selection, nested subagent model requests, plugin hooks, custom tool -execution, MCP calls, LSP diagnostics, and settings. The v2 control checks the -corresponding supported paths, including its native command API and plugin tool -registration, and explicitly lists LSP as unqualified. These controls make no -paid model calls and do not establish benchmark scores. +Plugins export a default object with `id` and `setup` and register hooks +explicitly. Register custom tools with the native plugin `ctx.tool.transform` +API. Commands use the native `session.command` API. + +Pure local JavaScript resources need no package installation. Plugins that +require npm dependencies can supply both `.opencode/package.json` and +`.opencode/package-lock.json` to use a writable task-local dependency directory. +The adapter requires an npm v2/v3 lock with matching root dependencies and exact +locked versions and integrities. Prepare lifecycle scripts separately. Native +dependency installation still needs qualification on OpenCode v2. + +The native qualification helper at `tests/fixtures/opencode_surfaces/qualify.py` +runs a synthetic task against a local deterministic model endpoint and MCP +server. It checks effects including native commands, plugin tool registration, +and subagent requests. diff --git a/base_harness/opencode/agent.py b/base_harness/opencode/agent.py index 339a873e..f84b3390 100644 --- a/base_harness/opencode/agent.py +++ b/base_harness/opencode/agent.py @@ -19,10 +19,6 @@ import time ROOT = Path(__file__).resolve().parent -RELEASE_COMMANDS = { - "1": ([], ["export"]), - "2": (["--standalone"], ["session", "export"]), -} def prepared_installation(env): @@ -111,7 +107,7 @@ def task_prompt(task: dict) -> str: "Create all requested artifacts and perform required environment submissions.\n\n" + public) -def configuration(env: dict, profile: str) -> dict: +def configuration(env: dict) -> dict: model = env.get("HG_AGENT_MODEL", "") base = env.get("HG_AGENT_BASE_URL", "") if not model or not base or not env.get("HG_AGENT_API_KEY"): @@ -121,27 +117,22 @@ def configuration(env: dict, profile: str) -> dict: raise ValueError("HG_AGENT_OPENCODE_WIRE must be chat or responses") settings = {"baseURL": base, "apiKey": "{env:HG_AGENT_API_KEY}", "timeout": int(float(env.get("HG_AGENT_TIMEOUT_S", "60")) * 1000)} - model_config = {"name": model, "limit": { - "context": int(env.get("HG_AGENT_CONTEXT_WINDOW", "32768")), - "output": int(env.get("HG_AGENT_MAX_OUTPUT_TOKENS", "2048")), - }} - provider = {"name": "HarnessGrad task endpoint", "models": {model: model_config}} - config = {"model": f"harnessgrad/{model}"} - agents = {"build": {"steps": int(env.get("HG_AGENT_MAX_STEPS", "12"))}} - if profile == "1": - provider.update(npm="@ai-sdk/openai" if wire == "responses" else "@ai-sdk/openai-compatible", - options=settings) - config.update(provider={"harnessgrad": provider}, share="disabled", autoupdate=False, - agent=agents) - else: - model_config.update(modelID=model, capabilities={"tools": True, "input": ["text"], "output": ["text"]}) - package = "@opencode/ai/providers/openai-compatible" - provider.update(package=package + ("/responses" if wire == "responses" else ""), settings=settings) - config.update(providers={"harnessgrad": provider}, agents=agents) - return config - - -def child_environment(parent: dict, state: Path, profile: str = "1") -> dict: + model_config = { + "name": model, "modelID": model, + "capabilities": {"tools": True, "input": ["text"], "output": ["text"]}, + "limit": {"context": int(env.get("HG_AGENT_CONTEXT_WINDOW", "32768")), + "output": int(env.get("HG_AGENT_MAX_OUTPUT_TOKENS", "2048"))}, + } + package = "@opencode/ai/providers/openai-compatible" + if wire == "responses": + package += "/responses" + provider = {"name": "HarnessGrad task endpoint", "models": {model: model_config}, + "package": package, "settings": settings} + return {"model": f"harnessgrad/{model}", "providers": {"harnessgrad": provider}, + "agents": {"build": {"steps": int(env.get("HG_AGENT_MAX_STEPS", "12"))}}} + + +def child_environment(parent: dict, state: Path) -> dict: # Retain task service endpoints/PATH; the platform has already selected task credentials. excluded = {"OPENAI_API_KEY", "ANTHROPIC_API_KEY", "DEEPSEEK_API_KEY", "BUN_OPTIONS", "CODEX_HOME", "OPENCODE_SERVER", "OPENCODE_CONFIG", "NODE_OPTIONS", "NODE_PATH"} @@ -161,19 +152,19 @@ def child_environment(parent: dict, state: Path, profile: str = "1") -> dict: "OPENCODE_DISABLE_PROJECT_CONFIG": "1", "OPENCODE_DISABLE_CLAUDE_CODE": "1", "OPENCODE_DISABLE_FILEWATCHER": "1", "OPENCODE_DISABLE_FFF": "1", "OPENCODE_DISABLE_DEFAULT_PLUGINS": "1", - "OPENCODE_CONFIG_CONTENT": json.dumps(configuration(parent, profile)), + "OPENCODE_CONFIG_CONTENT": json.dumps(configuration(parent)), }) if parent.get("HG_AGENT_GIT_BASH_PATH"): env["OPENCODE_GIT_BASH_PATH"] = parent["HG_AGENT_GIT_BASH_PATH"] return env -def prepare_surfaces(state: Path, env: dict, profile: str, *, version: str | None = None) -> dict: +def prepare_surfaces(state: Path, env: dict, *, version: str | None = None) -> dict: spec = importlib.util.spec_from_file_location("_opencode_surfaces", ROOT / "surface_runtime.py") helper = importlib.util.module_from_spec(spec) spec.loader.exec_module(helper) return helper.prepare(ROOT, Path(env["OPENCODE_CONFIG_DIR"]), - json.loads(env["OPENCODE_CONFIG_CONTENT"]), profile, version=version) + json.loads(env["OPENCODE_CONFIG_CONTENT"]), version=version) def timeout_seconds(env: dict) -> float: @@ -271,12 +262,12 @@ def child_reference(part: dict) -> tuple[bool, str | None]: return state.get("status") not in ("error", "failed"), None -def snapshot_children(snapshot: dict, profile: str) -> tuple[set[str], bool]: +def snapshot_children(snapshot: dict) -> tuple[set[str], bool]: children, incomplete = set(), False for message in snapshot.get("messages", []): if not isinstance(message, dict): continue - parts = message.get("parts", []) if profile == "1" else message.get("content", []) + parts = message.get("content", []) for part in parts if isinstance(parts, list) else []: if not isinstance(part, dict): continue @@ -311,7 +302,6 @@ def __init__(self, record): self.child_messages = 0 self.child_usage_incomplete = False self.session_tokens = None - self.profile = None def feed(self, line: str): if not line.strip(): @@ -385,18 +375,13 @@ def final_text(self) -> str: return "" return self.text.get(self.finishes[-1].get("messageID", ""), "") - def reconcile(self, snapshot: dict, profile: str = "2"): + def reconcile(self, snapshot: dict): """The CLI's persisted replay can omit step_finish; use its public export.""" - self.profile = profile info = snapshot.get("info") or {} - if profile == "1": - messages = [{**m["info"], "content": m["parts"]} for m in snapshot.get("messages", []) - if m.get("info", {}).get("role") == "assistant"] - else: - messages = [m for m in snapshot.get("messages", []) if m.get("type") == "assistant"] + messages = [m for m in snapshot.get("messages", []) if m.get("type") == "assistant"] if self.primary_session != info.get("id"): raise ValueError("OpenCode session export does not match emitted session") - if self.provider_errors or (profile == "2" and info.get("outcome") != "succeeded"): + if self.provider_errors or info.get("outcome") != "succeeded": raise ValueError("OpenCode session did not succeed") if not messages or messages[-1].get("error") or messages[-1].get("finish") != "stop": raise ValueError("OpenCode session has no completed final assistant turn") @@ -415,7 +400,7 @@ def reconcile(self, snapshot: dict, profile: str = "2"): self.record({"step": len(self.finishes), "reply": json.dumps(reply, ensure_ascii=False), "source": "session_export"}) self.session_tokens = info.get("tokens") - children, incomplete = snapshot_children(snapshot, profile) + children, incomplete = snapshot_children(snapshot) self.child_sessions.update(children) self.child_usage_incomplete |= incomplete self.record({"opencode_session": {"id": info["id"], "outcome": "succeeded"}}) @@ -444,14 +429,9 @@ def usage(self) -> dict: parent_usage = dict(usage) if self.sessions - {self.primary_session} - self.child_sessions: self.child_usage_incomplete = True - if self.profile == '1': - # Native v1's export omits separately generated title/auxiliary - # requests even when the session's own token fields are present. - usage = {key: None for key in usage} - scope = 'native_v1_session_partial' if self.child_sessions or self.child_usage_incomplete: if (self.child_usage_incomplete or len(self.child_tokens) != len(self.child_sessions) - or not complete_session_tokens(self.session_tokens) or self.profile == '1'): + or not complete_session_tokens(self.session_tokens)): usage = {key: None for key in usage} scope = "subagent_usage_incomplete" else: @@ -469,7 +449,7 @@ def usage(self) -> dict: "reported_steps": len(tokens), "completed_steps": len(self.finishes)} -def collect_child_sessions(stream, export_one, profile: str) -> None: +def collect_child_sessions(stream, export_one) -> None: """Collect referenced child exports once; never replace the parent's answer. If any child is missing or lacks complete usage, the total is unknown rather @@ -498,17 +478,17 @@ def collect_child_sessions(stream, export_one, profile: str) -> None: messages = snapshot.get("messages") if not isinstance(messages, list): raise ValueError("missing child messages") - assistants = [m.get("info", {}) if profile == "1" else m for m in messages if isinstance(m, dict)] - assistants = [m for m in assistants if m.get("role", m.get("type")) == "assistant"] + assistants = [m for m in messages + if isinstance(m, dict) and m.get("role", m.get("type")) == "assistant"] if (not assistants or assistants[-1].get("error") or assistants[-1].get("finish") != "stop" - or (profile == "2" and info.get("outcome") != "succeeded")): + or info.get("outcome") != "succeeded"): raise ValueError("child session not complete") tokens = info.get("tokens") if not complete_session_tokens(tokens): raise ValueError("child token usage is incomplete") stream.child_tokens.append(tokens) stream.child_messages += len(assistants) - children, incomplete = snapshot_children(snapshot, profile) + children, incomplete = snapshot_children(snapshot) stream.child_usage_incomplete |= incomplete stream.child_sessions.update(children) pending.extend(sorted(children - seen)) @@ -574,14 +554,11 @@ def record(value): expires = started + timeout_seconds(parent) prompt = task_prompt(task) installed = prepared_installation(parent) - profile = installed["version"].split(".", 1)[0] - stream.profile = profile - startup, export_command = RELEASE_COMMANDS[profile] state = work / ".opencode-state" - env = child_environment(parent, state, profile) + env = child_environment(parent, state) if installed.get("editable"): source_environment(env, installed["version"], installed["argv"][-1], state) - surfaces = prepare_surfaces(state, env, profile, version=installed["version"]) + surfaces = prepare_surfaces(state, env, version=installed["version"]) env["OPENCODE_CONFIG_CONTENT"] = json.dumps(surfaces["config"]) env["PWD"] = str(work) record({"harness_identity": {"harness": "opencode", "agent_backend": "openai", @@ -590,7 +567,7 @@ def record(value): "wire": parent.get("HG_AGENT_OPENCODE_WIRE", "chat"), "runtime": installed}, "task_id": task.get("task_id")}) record({"opencode_resources": surfaces}) - prefix = [*installed["argv"], *startup] + prefix = [*installed["argv"], "--standalone"] argv = [*prefix, "run", "--format", "json", "--auto", "--model", "harnessgrad/" + parent["HG_AGENT_MODEL"], "--agent", surfaces["selected_agent"]] before = answer_stamp(work) @@ -631,7 +608,7 @@ def export_one(session_id): remaining = expires - time.monotonic() if remaining <= 0: raise ValueError("OpenCode session export exceeded the task deadline") - export = subprocess.Popen([*prefix, *export_command, session_id], cwd=work, env=env, + export = subprocess.Popen([*prefix, "session", "export", session_id], cwd=work, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace", start_new_session=os.name != "nt") @@ -654,8 +631,8 @@ def export_one(session_id): else: rendered = json.dumps(redact(snapshot, secrets), ensure_ascii=False) (work / "opencode.session.json").write_text(rendered, encoding="utf-8") - stream.reconcile(snapshot, profile) - collect_child_sessions(stream, export_one, profile) + stream.reconcile(snapshot) + collect_child_sessions(stream, export_one) answer, origin = save_answer(work, before, stream.final_text(), task=task) record({"submitted": True, "answer": answer, "answer_source": origin, **({"submitted_files": submission_paths(task)} if origin == "files" else {})}) diff --git a/base_harness/opencode/harness.json b/base_harness/opencode/harness.json index 027cfe7b..9be83641 100644 --- a/base_harness/opencode/harness.json +++ b/base_harness/opencode/harness.json @@ -12,7 +12,7 @@ "exec" ], "runtime_paths": [], - "notes": "Install OpenCode with harnessgrad harness install opencode. Use editable v2 source or a fixed native release.", + "notes": "Install OpenCode v2 with harnessgrad harness install opencode. Use editable source or a fixed native release.", "plugin_capabilities": { "skill": {"format": "agent-skills", "directory": ".opencode/skills"}, "workbench": {"format": "static-html"} @@ -45,8 +45,6 @@ ".opencode/prompts/**" ], "tools": [ - ".opencode/tool/**", - ".opencode/tools/**", ".opencode/plugin/**", ".opencode/plugins/**", ".opencode/servers/**" diff --git a/base_harness/opencode/opencode_runtime.py b/base_harness/opencode/opencode_runtime.py index 73f54c4f..23baf1bf 100644 --- a/base_harness/opencode/opencode_runtime.py +++ b/base_harness/opencode/opencode_runtime.py @@ -15,9 +15,14 @@ RELEASE_SCHEMA = 4 SOURCE_RECORD = "_opencode_source" REMEDY = "prepare this Harness with tools/configure_opencode_harness.py" -PACKAGES = {"1": "opencode-linux-x64", "2": "@opencode/cli-linux-x64"} -NPM_PACKAGE = PACKAGES["2"] +NPM_PACKAGE = "@opencode/cli-linux-x64" RELEASES = { + "2.2.6": ("08bb21d6326ce740d91cce7ebe88a6536933f6e1e30353b91a06b01f25da306c", + "50503d24577fa4117a7c95ee85b2cd679606a87eacf20ca54ed5db5c9e1cf895"), + "2.2.7": ("89a6cee227b54bc011179c528a5e63176032462b1a5e21723b616801cddc2ca7", + "589253d36810f21217edd51545cd435b328cdc3cf4f451fbe0cce6f88afcf5e1"), + "2.3.0": ("fc0f81522aceeabac47693d88389efa2bc517ce74c2c38fd6967819fcc6e4d3b", + "2e0e4656521ca56e5ba16a00d48429958b8105b3fa6466710a4350e68759381f"), "2.4.0": ("66cf6adeb02fbfe9ccbb1f6497fcf46cecf2d299a1dc3a7a32e01ea30ff20201", "7915c1cf09fac2fa475dc5f2e008486579da1c181a439699e2097ac3866f1da3"), "2.4.1": ("9ddd18e3faf64eaeccf6a0fcbc96a5c7a14520ae5fd5b61e5be51d894f478b47", @@ -26,12 +31,16 @@ "523b1502d1d556998b0904235cef65eb1d8cf8362b4e2faa7ae7a170c9a44cd4"), "2.4.3": ("1bf509e8055b00693bf14d1623fd74712a7c6c107565e2acf38044944e7535d7", "a96b460eb050b92ae49ab6598d6652790870c8e211c325ad907f89ebd54ea184"), + "2.4.4": ("c70a43cb2fbbf9724aaba2c7fa47124f5af434f382083fab01508e08ed51c93c", + "fcd03c183ab007679b84b4d0ade27cc8d71c009db5a1f5f306c87b2380c0bb40"), } SOURCE_RELEASES = { "2.4.2": ("fc31a485317970bcf6be7b431a9830aaef875731", "306007d4b26be266f54249723028753647082f081ca6abc28beac68226bc0db4"), "2.4.3": ("4e517ca4987fd57daffef1b47dd16c31c165b114", "d91c6b946249011ba86a93442daf0b4ffff7da2bb88d0260df265acc172e8c14"), + "2.4.4": ("5b84793faccfc258d866080ae3d9bdc3586c6ae9", + "2a4015c8328bc3c5a4139c78db4f826e572ee4e9c1ac51f6ac97fc00e72286e8"), } UNVERIFIED_RECEIPT = "unverified-installation.json" @@ -174,12 +183,11 @@ def installation(binary: Path, version=None, *, forbidden: tuple[Path, ...] = () raise ValueError(f"OpenCode npm executable must be a Linux x86-64 ELF binary; {REMEDY}") package = json.loads(metadata.read_text(encoding="utf-8")) version = package.get("version") - if not isinstance(version, str) or not re.fullmatch(r"[12]\.[0-9]+\.[0-9]+", version): - raise ValueError("OpenCode native package must declare an exact v1 or v2 release") - profile = version.split(".", 1)[0] - if package.get("name") != PACKAGES[profile]: - raise ValueError("OpenCode native package name does not match its release series") - return {"schema": SCHEMA, "argv": [str(binary)], "version": version, "profile": profile, + require_v2(version) + if package.get("name") != NPM_PACKAGE: + raise ValueError(f"OpenCode requires the native {NPM_PACKAGE} package; {REMEDY}") + # Match the records written for pre-existing npm installs. + return {"schema": SCHEMA, "argv": [str(binary)], "version": version, "profile": "2", "runtime_paths": [str(binary), str(metadata)], "sha256": [digest(binary), digest(metadata)], "modes": [stat.S_IMODE(path.stat().st_mode) for path in (binary, metadata)], @@ -192,13 +200,13 @@ def resolve(harness: Path, _env: dict, *, forbidden: tuple[Path, ...] = ()) -> d record = manifest.get(RECORD) if not isinstance(record, dict) or record.get("schema") not in (SCHEMA, RELEASE_SCHEMA): raise ValueError(f"OpenCode release is unprepared; {REMEDY}") + require_v2(record.get("version")) argv, paths = record.get("argv"), record.get("runtime_paths") if (not isinstance(argv, list) or len(argv) != 1 or not isinstance(argv[0], str) or not isinstance(paths, list) or manifest.get("runtime_paths") != paths): raise ValueError(f"invalid OpenCode runtime binding; {REMEDY}") binary = Path(argv[0]) if record["schema"] == RELEASE_SCHEMA: - require_v2(record.get("version")) if not binary.is_absolute() or binary.resolve() != binary or paths != [str(binary)]: raise ValueError("invalid OpenCode release binding") expected = installation(binary, record.get("version"), forbidden=(*forbidden, harness), diff --git a/base_harness/opencode/surface_runtime.py b/base_harness/opencode/surface_runtime.py index d6cf1f18..63f770cb 100644 --- a/base_harness/opencode/surface_runtime.py +++ b/base_harness/opencode/surface_runtime.py @@ -56,7 +56,7 @@ def _config(path: Path) -> dict: return result -def prepare(source: Path, config_root: Path, config: dict, profile: str, *, version: str | None = None) -> dict: +def prepare(source: Path, config_root: Path, config: dict, *, version: str | None = None) -> dict: """Return the effective config and a digest manifest after native staging. This is called after task-local state creation, before native OpenCode starts. @@ -113,12 +113,10 @@ def prepare(source: Path, config_root: Path, config: dict, profile: str, *, vers item=lock.get('packages',{}).get('node_modules/'+name) if not isinstance(item,dict) or not isinstance(item.get('version'),str) or not item.get('integrity'): raise ValueError('OpenCode plugin dependency is missing a locked version and integrity: '+name) - if profile=='1' and '@opencode-ai/plugin' not in package.get('dependencies',{}): - raise ValueError('OpenCode v1 plugin dependencies must pin @opencode-ai/plugin explicitly') tun=_config(source/'opencode.json') if version=='2.4.1' and tun.get('lsp') not in (None,False,{}): - raise ValueError('OpenCode 2.4.1 LSP resource execution is not qualified; use native 1.19.5 for LSP experiments') - if profile=='2' and any(p.relative_to(extension).parts[0] in ('tool','tools') for p in files): + raise ValueError('OpenCode 2.4.1 LSP resource execution is not qualified') + if any(p.relative_to(extension).parts[0] in ('tool','tools') for p in files): raise ValueError('OpenCode v2 custom tools must be registered by its native plugin tool.transform API') config_root.mkdir(parents=True,exist_ok=True) manifest={} @@ -133,12 +131,8 @@ def prepare(source: Path, config_root: Path, config: dict, profile: str, *, vers if instruction.is_symlink() or not instruction.is_file(): raise ValueError('OpenCode AGENTS.md must be an owned file') dest=config_root/'AGENTS.md';shutil.copyfile(instruction,dest) - instructions=tun.setdefault('instructions',[]) - if not isinstance(instructions,list) or not all(isinstance(x,str) for x in instructions): - raise ValueError('OpenCode instructions must be a list of paths') - # v2 reads the config-root AGENTS.md as ambient instructions itself. - if profile == '1': - instructions.insert(0,str(dest)) + # OpenCode reads the config-root AGENTS.md as ambient instructions. + tun.setdefault('instructions',[]) manifest['AGENTS.md']=hashlib.sha256(instruction.read_bytes()).hexdigest() if 'instructions' in tun: if not isinstance(tun['instructions'],list) or not all(isinstance(x,str) for x in tun['instructions']): @@ -204,9 +198,8 @@ def relocate(argument): if not isinstance(selected,str) or not selected.strip(): raise ValueError('OpenCode default_agent must name a native primary agent') if selected!='build': - key='agent' if profile=='1' else 'agents' - agents=dict(effective.get(key,{})) + agents=dict(effective.get('agents',{})) agents[selected]={'steps':agents.get('build',{}).get('steps',12)} - effective[key]=agents + effective['agents']=agents return {'config':effective,'files':manifest,'native_config':str(path) if path.exists() else None, - 'profile':profile,'native_dependency_install':bool(metadata),'selected_agent':selected,'scope':'candidate resources; native discovery; platform model/budget overlay'} + 'profile':'2','native_dependency_install':bool(metadata),'selected_agent':selected,'scope':'candidate resources; native discovery; platform model/budget overlay'} diff --git a/base_harness/pi/README.md b/base_harness/pi/README.md index 3e97c646..593df4d5 100644 --- a/base_harness/pi/README.md +++ b/base_harness/pi/README.md @@ -7,7 +7,7 @@ HARNESS_DIR=$(harnessgrad harness install pi) harnessgrad run --harness-path "$HARNESS_DIR" ... ``` -The default release is [Pi v1.6.0](https://github.com/earendil-works/pi/releases/tag/v1.6.0). +The default release is [Pi v1.7.0](https://github.com/earendil-works/pi/releases/tag/v1.7.0). - **Editable (default, Linux x86-64).** The installer verifies the upstream source archive and places it under `pi/` in the H0 harness. The improve agent @@ -20,7 +20,7 @@ The default release is [Pi v1.6.0](https://github.com/earendil-works/pi/releases extracted binary and its embedded Bun runtime read-only outside the candidate. The improve agent can edit the adapter. -Use `--version 1.6.0` to select the release explicitly and `--install-root` to +Use `--version 1.7.0` to select the release explicitly and `--install-root` to choose a dedicated store outside the platform and temporary storage. Omitting `--version` selects the latest verified release for the chosen mode. On Linux x86-64, an exact unverified version prints a warning to stderr and diff --git a/base_harness/pi/pi_runtime.py b/base_harness/pi/pi_runtime.py index 4997c6a5..00706bfb 100644 --- a/base_harness/pi/pi_runtime.py +++ b/base_harness/pi/pi_runtime.py @@ -17,6 +17,8 @@ SOURCE_RELEASES = { "1.6.0": ("faac585884ae2c013a6b1400f3e9e77f10b34bac", "14519e288e84e713629b220bb6ade6818e32d4ff23f205fd80a7cc49dedc413e"), + "1.7.0": ("fb0fe823539f6d04850f6e34748c01f01f212e1f", + "e563ac817144441720a91873451260509fea21769b570d5a155f71f34798267f"), } NODE_VERSION = "24.22.2" NPM_VERSION = "11.19.1" @@ -30,6 +32,10 @@ "x86_64": ("pi-linux-x64.tar.gz", "ef77dbe4379b3bdeb425a1e1b862fa3c915c255000dfe4965c98eee96a5765d1"), "aarch64": ("pi-linux-arm64.tar.gz", "5404547b9739be596d50ae7142c52535899e8e7dd37a7bace9be593e0355b468"), }, + "1.7.0": { + "x86_64": ("pi-linux-x64.tar.gz", "42f7ed67e83f727fe51dd2746d50dc45c7d1784159a9518296a282402ac68f4a"), + "aarch64": ("pi-linux-arm64.tar.gz", "cd209cfc90fb94fb4b00ccd785a8d64a4a154f924e52f88febeb6cf36d5c9a24"), + }, } diff --git a/eval/containers/external_runtime.py b/eval/containers/external_runtime.py index 1b5c0a29..fd0aa7ee 100644 --- a/eval/containers/external_runtime.py +++ b/eval/containers/external_runtime.py @@ -192,7 +192,9 @@ def identities(repo, env=None, *, content=False, _npm_mount_paths=None): raise ValueError(f'Unverified {name} differs from its external installation receipt') if fixed: from harnessgrad.execution.python_runtime import python_harness_runtime - declaration = (Path(record['runtime_paths'][0]) if unverified + source = Path(record['runtime_paths'][0]) + # Older verified snapshots used the lock shipped with the adapter. + declaration = (source if unverified or (source / 'harness.json').is_file() else ROOT / 'base_harness/hermes-agent') python_harness_runtime.admit_external_artifact( repo, declaration, record['artifact']) diff --git a/harnessgrad/execution/harness_validation.py b/harnessgrad/execution/harness_validation.py index 2c9c1215..dfd499bb 100644 --- a/harnessgrad/execution/harness_validation.py +++ b/harnessgrad/execution/harness_validation.py @@ -16,7 +16,6 @@ import hashlib import json import os -import shutil import stat import subprocess import sys @@ -461,11 +460,11 @@ def charge(amount): reserved += amount try: charge(4096) - directory = Path(tempfile.mkdtemp(prefix=prefix,dir=parent)) - yield directory,charge + directory = tempfile.TemporaryDirectory(prefix=prefix, dir=parent) + yield Path(directory.name), charge finally: if directory is not None: - shutil.rmtree(directory) + directory.cleanup() if reserved and io_budget is not None: io_budget(-reserved) diff --git a/pyproject.toml b/pyproject.toml index 4bb738cb..bcae3c96 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -93,6 +93,7 @@ exclude = ["data.authored*", "data.candidates*", "console.uat*"] "deepseek-harness/AGENTS.md", "deepseek-harness/cordis.patch.yml", "deepseek-harness/profile.json", "deepseek-harness/settings.json", "hermes-agent/harness.json", "hermes-agent/README.md", "hermes-agent/requirements.lock", + "hermes-agent/requirements-0.23.6.lock", "oh-my-pi/harness.json", "oh-my-pi/README.md", "claude-code/harness.json", "claude-code/README.md", "claude-code/CLAUDE.md", "claude-code/settings.json", "claude-code/.mcp.json", "claude-code/.lsp.json", "claude-code/.claude-plugin/plugin.json", diff --git a/tests/fixtures/opencode_surfaces/qualify.py b/tests/fixtures/opencode_surfaces/qualify.py index f475b351..21be392d 100644 --- a/tests/fixtures/opencode_surfaces/qualify.py +++ b/tests/fixtures/opencode_surfaces/qualify.py @@ -2,20 +2,20 @@ """Synthetic native OpenCode resource effects; no remote model or benchmark. prepare writes a controlled surface candidate. verify executes a real pinned -OpenCode CLI against a local deterministic provider plus local MCP/LSP servers. +OpenCode CLI against a local deterministic provider and MCP server. """ from __future__ import annotations import base64 -import argparse, importlib.util, json, os, shutil, subprocess, sys, threading, time, socket, signal, urllib.request +import argparse, importlib.util, json, os, subprocess, sys, threading, time, socket, signal, urllib.request from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path -SURFACES=('instructions','output_style','skill','command','agent','plugin','hook','tool','mcp','lsp','settings','subagent') +SURFACES=('instructions','output_style','skill','command','agent','plugin','hook','tool','mcp','settings','subagent') ROOT=Path(__file__).resolve().parents[3] def marker(name,expected):return 'HG_SURFACE_'+name.upper()+'_'+expected -def write_candidate(candidate: Path, expected='BEFORE', profile='1'): +def write_candidate(candidate: Path, expected='BEFORE'): def put(rel,text): p=candidate/rel;p.parent.mkdir(parents=True,exist_ok=True);p.write_text(text) m=lambda x:marker(x,expected) @@ -25,12 +25,6 @@ def put(rel,text): put('.opencode/agents/hg-probe.md','---\ndescription: Native custom agent probe\nmode: primary\n---\n'+m('agent')+'\n') put('.opencode/agents/hg-child.md','---\ndescription: Native child agent probe\nmode: subagent\n---\n'+m('subagent')+'\n') put('.opencode/commands/hg-probe.md','---\ndescription: Native command probe\nagent: hg-probe\n---\n'+m('command')+' $ARGUMENTS\n') - put('.opencode/plugins/hg-probe.js', '''import fs from 'node:fs/promises'; -export const SurfacePlugin = async ({directory}) => ({ - 'experimental.chat.system.transform': async (_input, output) => { output.system.push(%s); await fs.writeFile(directory+'/.surface-hook.txt',%s); }, -}); -'''%(json.dumps(m('plugin')),json.dumps(m('hook')))) - put('.opencode/tools/hg_probe.js', 'export default {description:'+json.dumps(m('tool'))+',args:{},execute:async()=>'+json.dumps(m('tool'))+'};\n') put('.opencode/servers/mcp.py', '''import json,sys from pathlib import Path for line in sys.stdin: @@ -44,47 +38,20 @@ def put(rel,text): elif method=='tools/call':result={'content':[{'type':'text','text':%s}]} print(json.dumps({'jsonrpc':'2.0','id':q['id'],'result':result}),flush=True) '''%(json.dumps(m('mcp')),json.dumps(m('mcp')))) - put('.opencode/servers/lsp.py', '''import json,sys -from pathlib import Path -inp=sys.stdin.buffer;out=sys.stdout.buffer -while True: - headers={} - while True: - ln=inp.readline() - if not ln:raise SystemExit - if ln in (b'\\r\\n',b'\\n'):break - k,v=ln.decode().split(':',1);headers[k.lower()]=v.strip() - q=json.loads(inp.read(int(headers['content-length']))) - with Path('.surface-lsp.jsonl').open('a') as f:f.write(json.dumps(q)+'\\n') - def send(x): - b=json.dumps(x).encode();out.write(('Content-Length: '+str(len(b))+'\\r\\n\\r\\n').encode()+b);out.flush() - if 'id' in q: - result={'capabilities':{'textDocumentSync':1},'serverInfo':{'name':%s,'version':'1'}} if q.get('method')=='initialize' else None - send({'jsonrpc':'2.0','id':q['id'],'result':result}) - if q.get('method') in ('textDocument/didOpen','textDocument/didChange'): - send({'jsonrpc':'2.0','method':'textDocument/publishDiagnostics','params':{'uri':q['params']['textDocument']['uri'],'diagnostics':[{'range':{'start':{'line':0,'character':0},'end':{'line':0,'character':1}},'severity':2,'message':%s,'source':'hg-probe'}]}}) -'''%(json.dumps(m('lsp')),json.dumps(m('lsp')))) - config={'instructions':['./instructions/output.md'],'agent':{'build':{'prompt':m('settings')}}, - 'mcp':{'hg_surface':{'type':'local','command':[sys.executable,'./servers/mcp.py'],'enabled':True}}, - 'lsp':{'hg_surface':{'command':[sys.executable,'./servers/lsp.py'],'extensions':['.hgprobe']}}} - if profile=='2': - config.pop('lsp');(candidate/'.opencode/servers/lsp.py').unlink() - config['agents']={'build':{'system':m('settings')}};config.pop('agent') - config['mcp']={'servers':config['mcp']} - config['mcp']['servers']['hg_surface'].pop('enabled') - put('.opencode/plugins/hg-probe.js', '''import fs from 'node:fs/promises'; + put('.opencode/plugins/hg-probe.js', '''import fs from 'node:fs/promises'; export default {id:'hg-surface',setup:async(ctx)=>{ await ctx.tool.transform(draft=>draft.add({name:'hg_probe',description:%s,input:{type:'object',properties:{},additionalProperties:false},options:{codemode:false},execute:async()=>({content:%s})})); await ctx.agent.transform(async draft=>{await fs.writeFile(process.cwd()+'/.surface-hook.txt',%s);for(const a of draft.list()){draft.update(a.id,item=>{item.system=(item.system||'')+'\\n'+%s;});}}); }}; '''%(json.dumps(m('tool')),json.dumps(m('tool')),json.dumps(m('hook')),json.dumps(m('plugin')))) - (candidate/'.opencode/tools/hg_probe.js').unlink() + config={'instructions':['./instructions/output.md'],'agents':{'build':{'system':m('settings')}}, + 'mcp':{'servers':{'hg_surface':{'type':'local','command':[sys.executable,'./servers/mcp.py']}}}} put('opencode.json',json.dumps(config,indent=2)+'\n') def adapter(candidate): spec=importlib.util.spec_from_file_location('opencode_surface_adapter',candidate/'agent.py');m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m);return m -def verify(candidate: Path, native: Path, output: Path, expected='AFTER', profile='1', scope='all'): +def verify(candidate: Path, native: Path, output: Path, expected='AFTER'): output.mkdir(parents=True,exist_ok=True);m=adapter(candidate);requests=[] class Handler(BaseHTTPRequestHandler): def log_message(self,*a):pass @@ -103,9 +70,9 @@ def do_POST(self): if name=='skill' and 'id' in properties:args={'id':'hg-probe'} if name=='write' and 'path' in properties:args={'path':str(output/'work-main/probe.hgprobe'),'content':'probe\n'} calls.append({'index':len(calls),'id':'call_'+name,'type':'function','function':{'name':name,'arguments':json.dumps(args)}}) - if profile=='2' and tools and not tool_results and not child and 'execute' in tools: + if tools and not tool_results and not child and 'execute' in tools: calls.append({'index':len(calls),'id':'call_search','type':'function','function':{'name':'execute','arguments':json.dumps({'code':'console.log(await search("HG_SURFACE_MCP")); console.log(await search("LSP"));'})}}) - if profile=='2' and tools and tool_results and not child and 'execute' in tools and any(x.get('tool_call_id')=='call_search' for x in tool_results) and not any(x.get('tool_call_id')=='call_mcp' for x in tool_results): + if tools and tool_results and not child and 'execute' in tools and any(x.get('tool_call_id')=='call_search' for x in tool_results) and not any(x.get('tool_call_id')=='call_mcp' for x in tool_results): calls.append({'index':len(calls),'id':'call_mcp','type':'function','function':{'name':'execute','arguments':json.dumps({'code':'console.log(await tools.hg_surface.probe());'})}}) delta={'role':'assistant','tool_calls':calls} if calls else {'role':'assistant','content':'HG_NATIVE_SURFACE_DONE'} payload={'id':'chatcmpl-probe','object':'chat.completion.chunk','created':1,'model':'hg-stub','choices':[{'index':0,'delta':delta,'finish_reason':None}]} @@ -116,10 +83,10 @@ def do_POST(self): parent=dict(os.environ);parent.update(HG_AGENT_MODEL='hg-stub',HG_AGENT_BASE_URL=f'http://127.0.0.1:{server.server_port}/v1',HG_AGENT_API_KEY='local-stub-key',HG_AGENT_MAX_STEPS='8',HG_AGENT_MAX_OUTPUT_TOKENS='1024') runs=[] try: - for label,extra in [('main',[]),('command',['--command','hg-probe'] if profile=='1' else ['--agent','hg-probe'])]: - work=output/('work-'+label);work.mkdir(exist_ok=True);env=m.child_environment(parent,output/('state-'+label),profile);resources=m.prepare_surfaces(output/('state-'+label),env,profile);env['OPENCODE_CONFIG_CONTENT']=json.dumps(resources['config']);env['CI']='1';env['PWD']=str(work);env['NO_PROXY']='127.0.0.1,localhost' - args=[str(native),*(['--standalone'] if profile=='2' else []),'run','--format','json','--auto','--model','harnessgrad/hg-stub',*extra,'/hg-probe' if profile=='2' and label=='command' else 'Synthetic native surface qualification'] - if profile=='2' and label=='command': + for label,extra in [('main',[]),('command',['--agent','hg-probe'])]: + work=output/('work-'+label);work.mkdir(exist_ok=True);env=m.child_environment(parent,output/('state-'+label));resources=m.prepare_surfaces(output/('state-'+label),env);env['OPENCODE_CONFIG_CONTENT']=json.dumps(resources['config']);env['CI']='1';env['PWD']=str(work);env['NO_PROXY']='127.0.0.1,localhost' + args=[str(native),'--standalone','run','--format','json','--auto','--model','harnessgrad/hg-stub',*extra,'/hg-probe' if label=='command' else 'Synthetic native surface qualification'] + if label=='command': with socket.socket() as available: available.bind(('127.0.0.1',0));port=available.getsockname()[1] env['OPENCODE_SERVER_PASSWORD']='local-qualifier-only' @@ -153,16 +120,13 @@ def api(path,body=None): effects['subagent']=any(marker('subagent',expected) in str(x.get('content','')) for q in requests for x in q.get('messages',[]) if x.get('role')=='system') hook=output/'work-main/.surface-hook.txt';effects['hook']=hook.exists() and marker('hook',expected) in hook.read_text() mcp=output/'work-main/.surface-mcp.jsonl';effects['mcp']=effects['mcp'] and mcp.exists() and 'tools/call' in mcp.read_text() - lsp=output/'work-main/.surface-lsp.jsonl';effects['lsp']=marker('lsp',expected) in (output/'main.stdout.jsonl').read_text() and lsp.exists() and 'textDocument/didOpen' in lsp.read_text() - if scope=='legacy11':effects.pop('subagent',None) - if profile=='2':effects.pop('lsp',None) - receipt={'requested_scope':scope,'unqualified':(['subagent'] if scope=='legacy11' else [])+(['lsp'] if profile=='2' else []),'native':str(native),'native_version':subprocess.check_output([str(native),'--version'],text=True).strip(),'expected':expected,'effects':effects,'runs':runs,'requests':len(requests),'all_requests_use_selected_model':all(q.get('model')=='hg-stub' for q in requests),'paid_model_calls':0,'scope':'real native CLI and deterministic local provider; synthetic task only'} + receipt={'requested_scope':'all','unqualified':['lsp'],'native':str(native),'native_version':subprocess.check_output([str(native),'--version'],text=True).strip(),'expected':expected,'effects':effects,'runs':runs,'requests':len(requests),'all_requests_use_selected_model':all(q.get('model')=='hg-stub' for q in requests),'paid_model_calls':0,'scope':'real native CLI and deterministic local provider; synthetic task only'} (output/'receipt.json').write_text(json.dumps(receipt,indent=2));print(json.dumps({'effects':effects,'runs':[(x['label'],x['exit_code']) for x in runs],'requests':len(requests),'receipt':str(output/'receipt.json')})) return 0 if all(effects.values()) and all(x['exit_code']==0 for x in runs) and receipt['all_requests_use_selected_model'] else 1 finally:server.shutdown();server.server_close() def main(): - p=argparse.ArgumentParser();p.add_argument('action',choices=['prepare','verify']);p.add_argument('--candidate',type=Path,required=True);p.add_argument('--native',type=Path);p.add_argument('--output',type=Path);p.add_argument('--expected',default='AFTER');p.add_argument('--profile',choices=['1','2'],default='1');p.add_argument('--scope',choices=['all','legacy11'],default='all');a=p.parse_args() - if a.action=='prepare':write_candidate(a.candidate,a.expected,a.profile);return 0 - return verify(a.candidate,a.native,a.output,a.expected,a.profile,a.scope) + p=argparse.ArgumentParser();p.add_argument('action',choices=['prepare','verify']);p.add_argument('--candidate',type=Path,required=True);p.add_argument('--native',type=Path);p.add_argument('--output',type=Path);p.add_argument('--expected',default='AFTER');a=p.parse_args() + if a.action=='prepare':write_candidate(a.candidate,a.expected);return 0 + return verify(a.candidate,a.native,a.output,a.expected) if __name__=='__main__':raise SystemExit(main()) diff --git a/tests/fixtures/opencode_surfaces/qualify_dependencies.py b/tests/fixtures/opencode_surfaces/qualify_dependencies.py deleted file mode 100644 index 52c7879e..00000000 --- a/tests/fixtures/opencode_surfaces/qualify_dependencies.py +++ /dev/null @@ -1,116 +0,0 @@ -#!/usr/bin/env python3 -"""Real locked npm plugin dependency control against native OpenCode 1.19.5. - -Only registry dependency setup may use the network. The model endpoint is an -in-process deterministic HTTP stub; no remote model or benchmark is called. -""" -from __future__ import annotations -import argparse, hashlib, importlib.util, json, os, shutil, subprocess, sys, threading, time -from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from pathlib import Path - -ROOT=Path(__file__).resolve().parents[3] -PACKAGE='@opencode-ai/plugin';VERSION='1.19.5';MARKER='HG_LOCKED_NPM_DEPENDENCY_EXECUTED' - -def digest(p):return hashlib.sha256(p.read_bytes()).hexdigest() -def save(p,data):p.write_text(json.dumps(data,indent=2)+'\n') -def run(args): - out=args.output.resolve();out.mkdir(parents=True,exist_ok=False) - record={'scope':'native OpenCode with actual locked npm plugin import and local model control', - 'status':'starting','package':PACKAGE,'package_version':VERSION,'paid_model_calls':0, - 'network_scope':'npm registry setup/install only; model calls use loopback HTTP', - 'created':time.time()};receipt=out/'receipt.json';save(receipt,record) - server=None - try: - candidate=out/'candidate';shutil.copytree(ROOT/'base_harness/opencode',candidate) - conf=candidate/'.opencode';(conf/'plugins').mkdir(parents=True) - package={'name':'hg-opencode-locked-dependency-control','private':True,'type':'module','dependencies':{PACKAGE:VERSION}} - save(conf/'package.json',package) - (conf/'plugins/dependency-probe.js').write_text('''import {tool} from '@opencode-ai/plugin'; -import fs from 'node:fs'; -import crypto from 'node:crypto'; -export const DependencyProbe = async ({directory}) => ({tool:{dependency_probe:tool({ - description:'Execute the real locked npm dependency probe', - args:{value:tool.schema.string()}, - async execute({value}){ - const entry=import.meta.resolve('@opencode-ai/plugin'); - const packageUrl=new URL('../package.json',entry); - const bytes=fs.readFileSync(packageUrl);const pkg=JSON.parse(bytes); - fs.writeFileSync(directory+'/.dependency-effect.json',JSON.stringify({marker:'HG_LOCKED_NPM_DEPENDENCY_EXECUTED',value,entry,package:pkg.name,version:pkg.version,package_sha256:crypto.createHash('sha256').update(bytes).digest('hex')})); - return 'HG_LOCKED_NPM_DEPENDENCY_EXECUTED:'+value; - } -})}}); -''') - environment={'PATH':os.defpath,'HOME':str(out/'setup-home'),'CI':'1', - 'npm_config_cache':str(out/'npm-cache'),'npm_config_audit':'false','npm_config_fund':'false', - 'npm_config_ignore_scripts':'true'} - Path(environment['HOME']).mkdir() - if args.proxy: - for key in ('HTTP_PROXY','HTTPS_PROXY','http_proxy','https_proxy','npm_config_proxy','npm_config_https_proxy'): - environment[key]=args.proxy - started=time.monotonic() - command=[str(args.node),str(args.npm_cli),'install','--package-lock-only','--ignore-scripts','--no-audit','--no-fund'] - with (out/'setup.stdout.log').open('w') as stdout,(out/'setup.stderr.log').open('w') as stderr: - setup=subprocess.run(command,cwd=conf,env=environment,stdout=stdout,stderr=stderr,timeout=180) - record['setup']={'command':command,'exit_code':setup.returncode,'wall_s':time.monotonic()-started} - save(receipt,record) - if setup.returncode:raise RuntimeError('npm lock preparation failed; inspect setup logs') - lock=json.loads((conf/'package-lock.json').read_bytes());locked=lock['packages']['node_modules/'+PACKAGE] - assert locked['version']==VERSION and locked['integrity'] - record['source']={'package_sha256':digest(conf/'package.json'),'lock_sha256':digest(conf/'package-lock.json'), - 'plugin_sha256':digest(conf/'plugins/dependency-probe.js'),'locked_integrity':locked['integrity']} - sys.path.insert(0,str(ROOT)) - from tools.harness_setup.configure_opencode_harness import configure - prepared=configure(candidate,args.native,expected_version=VERSION) - record['native_runtime']=prepared;save(receipt,record) - calls=[] - class Handler(BaseHTTPRequestHandler): - def log_message(self,*args):pass - def do_POST(self): - body=json.loads(self.rfile.read(int(self.headers['content-length'])));calls.append(body) - save(out/'provider-requests.partial.json',calls) - tools={t['function']['name'] for t in body.get('tools',[])} - results=[m for m in body.get('messages',[]) if m.get('role')=='tool'] - invoke='dependency_probe' in tools and not results - delta={'role':'assistant','tool_calls':[{'index':0,'id':'call_dependency','type':'function','function':{'name':'dependency_probe','arguments':json.dumps({'value':'locked-import-control'})}}]} if invoke else {'role':'assistant','content':'HG_DEPENDENCY_CONTROL_DONE'} - first={'id':'chatcmpl-local','object':'chat.completion.chunk','created':1,'model':'hg-stub','choices':[{'index':0,'delta':delta,'finish_reason':None}]} - last={'id':'chatcmpl-local','object':'chat.completion.chunk','created':1,'model':'hg-stub','choices':[{'index':0,'delta':{},'finish_reason':'tool_calls' if invoke else 'stop'}],'usage':{'prompt_tokens':10,'completion_tokens':5,'total_tokens':15,'prompt_tokens_details':{'cached_tokens':0}}} - self.send_response(200);self.send_header('content-type','text/event-stream');self.end_headers() - self.wfile.write(('data: '+json.dumps(first)+'\n\ndata: '+json.dumps(last)+'\n\ndata: [DONE]\n\n').encode());self.wfile.flush() - server=ThreadingHTTPServer(('127.0.0.1',0),Handler);threading.Thread(target=server.serve_forever,daemon=True).start() - work=out/'work';work.mkdir();task=out/'task.json';save(task,{'task_id':'synthetic/locked-npm-plugin','goal':'Run the dependency_probe tool and report completion.'}) - env=dict(environment);env.update(HG_AGENT_MODEL='hg-stub',HG_AGENT_BASE_URL=f'http://127.0.0.1:{server.server_port}/v1',HG_AGENT_API_KEY='local-stub-key',HG_AGENT_MAX_STEPS='6',HG_AGENT_OPENCODE_TIMEOUT_S='150',NO_PROXY='127.0.0.1,localhost',no_proxy='127.0.0.1,localhost') - started=time.monotonic() - command=[sys.executable,str(candidate/'agent.py'),'--task',str(task),'--workdir',str(work)] - with (out/'native.stdout.log').open('w') as stdout,(out/'native.stderr.log').open('w') as stderr: - native=subprocess.run(command,cwd=work,env=env,stdout=stdout,stderr=stderr,timeout=180) - record['execution']={'exit_code':native.returncode,'wall_s':time.monotonic()-started,'model_requests':len(calls)} - save(out/'provider-requests.json',calls);save(receipt,record) - if native.returncode:raise RuntimeError('native task adapter failed; inspect native.stderr.log and work/trace.jsonl') - trace=list(map(json.loads,(work/'trace.jsonl').read_text().splitlines())) - resources=next(r['opencode_resources'] for r in trace if 'opencode_resources' in r) - assert resources['native_dependency_install'] is True - actual=json.loads((work/'.dependency-effect.json').read_bytes()) - assert actual['marker']==MARKER and actual['value']=='locked-import-control' and actual['package']==PACKAGE and actual['version']==VERSION - state=work/'.opencode-state/config/opencode';installed=state/'node_modules'/PACKAGE/'package.json' - assert digest(installed)==actual['package_sha256'] - entry=Path(actual['entry'].removeprefix('file://')).resolve() - assert entry.is_relative_to((state/'node_modules').resolve()) - assert all(q['model']=='hg-stub' for q in calls) - assert any(MARKER in str(m.get('content','')) for q in calls for m in q.get('messages',[]) if m.get('role')=='tool') - assert digest(conf/'package.json')==record['source']['package_sha256'] and digest(conf/'package-lock.json')==record['source']['lock_sha256'] - record.update(status='passed',effect=actual,resources=resources, - actual_dependency={'package_sha256':digest(installed),'entry_sha256':digest(entry), - 'native_lock_sha256':digest(state/'package-lock.json'), - 'native_package_sha256':digest(state/'package.json')}, - all_requests_use_selected_model=True,completed=time.time()) - save(receipt,record);print(json.dumps({'status':record['status'],'setup':record['setup'],'execution':record['execution'],'receipt':str(receipt)}));return 0 - except Exception as exc: - record.update(status='failed',error=type(exc).__name__+': '+str(exc),completed=time.time());save(receipt,record) - print(json.dumps({'status':'failed','error':record['error'],'receipt':str(receipt)}));return 1 - finally: - if server:server.shutdown();server.server_close() - -def main(): - p=argparse.ArgumentParser();p.add_argument('--output',type=Path,required=True);p.add_argument('--native',type=Path,required=True);p.add_argument('--node',type=Path,required=True);p.add_argument('--npm-cli',type=Path,required=True);p.add_argument('--proxy',default='');return run(p.parse_args()) -if __name__=='__main__':raise SystemExit(main()) diff --git a/tests/quality/test_claude_installer.py b/tests/quality/test_claude_installer.py index 20fb156f..09698512 100644 --- a/tests/quality/test_claude_installer.py +++ b/tests/quality/test_claude_installer.py @@ -7,8 +7,9 @@ from eval.containers import external_runtime -def test_native_claude_recipe_checks_integrity_without_install_scripts(tmp_path): - release = install_harness._recipe('claude-code', '2.1.201') +@pytest.mark.parametrize('version', ['2.1.201', '2.1.335']) +def test_native_claude_recipe_checks_integrity_without_install_scripts(tmp_path, version): + release = install_harness._recipe('claude-code', version) assert release.package == '@anthropic-ai/claude-code-linux-x64' assert release.rebuild is False lock = tmp_path / 'package-lock.json' @@ -29,8 +30,8 @@ def test_claude_cli_selects_explicit_verified_default(tmp_path, monkeypatch, cap monkeypatch.setattr(install_harness, 'install_harness', lambda name, version, root: seen.append((name, version, root)) or root) assert install_harness.main(['install', 'claude-code', '--install-root', str(tmp_path)]) == 0 - assert seen == [('claude-code', '2.1.201', tmp_path)] - assert 'Using latest verified Claude Code version 2.1.201' in capsys.readouterr().err + assert seen == [('claude-code', '2.1.335', tmp_path)] + assert 'Using latest verified Claude Code version 2.1.335' in capsys.readouterr().err def test_unprepared_claude_template_cannot_claim_external_identity(tmp_path): diff --git a/tests/quality/test_console_launch_service.py b/tests/quality/test_console_launch_service.py index f2586474..1cf50426 100644 --- a/tests/quality/test_console_launch_service.py +++ b/tests/quality/test_console_launch_service.py @@ -155,14 +155,8 @@ def test_console_selects_legacy_opencode_npm_only_as_fixed(old_opencode_npm): old_v1 = release.with_name("1.19.5") shutil.copytree(release, old_v1) old_manifest = old_v1 / harness.relative_to(release) / "harness.json" - modules = old_manifest.parent.parent / "package/node_modules" - package = modules / opencode_runtime.PACKAGES["1"] - (modules / opencode_runtime.NPM_PACKAGE).rename(package) - (package / "package.json").write_text(json.dumps({"name": package.name, "version": "1.19.5"})) - legacy = opencode_runtime.installation(package / "bin/opencode") fields = json.loads(old_manifest.read_text()) - fields.update(runtime_paths=legacy["runtime_paths"]) - fields[opencode_runtime.RECORD] = legacy + fields[opencode_runtime.RECORD].update(version="1.19.5", profile="1") old_manifest.write_text(json.dumps(fields)) old_receipt = old_v1 / "installation.json" receipt = json.loads(old_receipt.read_text()) @@ -171,7 +165,7 @@ def test_console_selects_legacy_opencode_npm_only_as_fixed(old_opencode_npm): options = installation_store.catalogue(root, ["opencode"], install_harness.verified_versions, install_harness._version_key)["opencode"] assert options == {"default_mode": "editable", "modes": { - "editable": [], "fixed": [{"version": "2.4.2", "verified": True}, {"version": "1.19.5", "verified": True}], + "editable": [], "fixed": [{"version": "2.4.2", "verified": True}], }} def select(mode, version): @@ -184,7 +178,8 @@ def select(mode, version): assert selected["verified"] with pytest.raises(ValueError, match="No usable installation of opencode editable"): select(None, None) - assert select("fixed", "1.19.5")["argv"][:2] == ["--harness-path", str(old_manifest.parent)] + with pytest.raises(ValueError, match="requires an exact v2 release"): + select("fixed", "1.19.5") lock = harness.parent / "package/package-lock.json" lock.write_text("changed lock\n") diff --git a/tests/quality/test_harness_decoding.py b/tests/quality/test_harness_decoding.py index 2c483afc..9e4e8227 100644 --- a/tests/quality/test_harness_decoding.py +++ b/tests/quality/test_harness_decoding.py @@ -153,7 +153,7 @@ def _verified_upstream_site(site): 'tools/prepare_h0.py:149': 'Candidate runtime admission returns a validated identity JSON envelope.', 'tools/prepare_h0.py:188': 'Verification preflight returns a validated context JSON envelope.', 'tools/prepare_ds1000_runtime.py:161': 'Interpreter target probe returns a structured platform identity.', - 'tools/install_harness.py:131': 'Node and npm version strings must match exact pinned versions.', + 'tools/install_harness.py:123': 'Node and npm version strings must match exact pinned versions.', 'base_harness/claude-code/claude_runtime.py:40': 'Native Claude version output must exactly identify the bound release.', 'tools/harness_setup/configure_claude_harness.py:30': 'Sandboxed Claude version output must exactly match the bound native executable.', 'tools/harness_setup/configure_opencode_harness.py:59': 'OpenCode version output must match the selected installation.', diff --git a/tests/quality/test_harness_installer.py b/tests/quality/test_harness_installer.py index 198c5a37..ffe6db0a 100644 --- a/tests/quality/test_harness_installer.py +++ b/tests/quality/test_harness_installer.py @@ -19,18 +19,24 @@ def test_invalid_version_never_creates_installation(tmp_path, capsys): assert "openclaw 2026.3.13" not in supported assert "openclaw 2026.11.2" in supported assert "openclaw 2026.11.3" in supported + assert "openclaw 2026.12.1" in supported assert "codex 0.166.0" in supported assert "codex 0.167.0" in supported assert "codex 0.167.1" in supported assert "codex 0.167.2" in supported assert "codex 0.169.0" in supported assert "codex 0.172.0" in supported - for version in ("1.19.5", "2.2.6", "2.2.7", "2.3.0"): - assert f"opencode {version} (fixed npm release, Linux x86-64)" in supported - assert "opencode 2.4.0 (fixed GitHub Release, Linux x86-64)" in supported - assert "opencode 2.4.1 (fixed GitHub Release, Linux x86-64)" in supported + assert "codex 0.173.0" in supported + assert "opencode 1." not in supported + for version in ("2.2.6", "2.2.7", "2.3.0", "2.4.0", "2.4.1"): + assert f"opencode {version} (fixed GitHub Release, Linux x86-64)" in supported assert "opencode 2.4.2 (editable Bun 1.4.4; fixed GitHub Release" in supported assert "opencode 2.4.3 (editable Bun 1.4.4; fixed GitHub Release" in supported + assert "opencode 2.4.4 (editable Bun 1.4.4; fixed GitHub Release" in supported + for name, versions in (("pi", ("1.6.0", "1.7.0")), ("oh-my-pi", ("19.2.0", "19.4.1")), + ("hermes-agent", ("0.23.4", "0.23.6"))): + for version in versions: + assert f"{name} {version} (" in supported assert "deepseek-harness 0.2.2-rc.1" in supported assert "deepseek-harness 0.2.2-rc.3" in supported assert "deepseek-harness 0.2.2-rc.5" in supported @@ -42,9 +48,10 @@ def test_invalid_version_never_creates_installation(tmp_path, capsys): @pytest.mark.parametrize("name, latest, earlier, label", [ - ("openclaw", "2026.11.3", "2026.11.2", "OpenClaw"), - ("codex", "0.172.0", "0.169.0", "Codex"), - ("opencode", "2.4.3", "2.4.2", "OpenCode"), + ("openclaw", "2026.12.1", "2026.11.3", "OpenClaw"), + ("codex", "0.173.0", "0.172.0", "Codex"), + ("opencode", "2.4.4", "2.4.3", "OpenCode"), + ("oh-my-pi", "19.4.1", "19.2.0", "Oh My Pi"), ]) @pytest.mark.parametrize("explicit", [False, True]) def test_install_selects_latest_verified_version_only_when_omitted(tmp_path, capsys, monkeypatch, @@ -90,7 +97,7 @@ def test_deepseek_default_accepts_verified_prereleases(tmp_path, capsys, monkeyp def test_hermes_fixed_is_opt_in(tmp_path, monkeypatch, capsys): def install(version, root, *, mode): - assert version == "0.23.4" + assert version == "0.23.6" return root / mode monkeypatch.setattr(install_harness.hermes, "install", install) @@ -106,11 +113,11 @@ def install(version, root, *, mode): def test_opencode_defaults_to_editable_and_accepts_fixed(tmp_path, monkeypatch, capsys): def editable(version, root): - assert version == "2.4.3" + assert version == "2.4.4" return root / "editable" def fixed(version, root, **kwargs): - assert version == "2.4.3" + assert version == "2.4.4" assert kwargs["repository"] == "anomalyco/opencode" return root / "fixed" @@ -168,7 +175,7 @@ def probe(argv, *, repo, **kwargs): monkeypatch.setattr(installer.sandbox, "run", probe) with tempfile.TemporaryDirectory(prefix="hg-opencode-seed-", dir=Path.home()) as directory: - argv = ["harness", "install", "opencode", "--install-root", directory] + argv = ["harness", "install", "opencode", "--version", "2.4.3", "--install-root", directory] assert main(argv) == 0 seed = Path(capsys.readouterr().out.strip()) assert not check(seed) @@ -211,14 +218,68 @@ def probe(argv, *, repo, **kwargs): assert len(probes) == (2 if stale_template else 1) -def test_opencode_rejects_editable_v1_without_creating_installation(tmp_path, capsys): +@pytest.mark.parametrize("mode", [None, "editable", "fixed"]) +def test_opencode_rejects_v1_without_creating_installation(tmp_path, capsys, mode): root = tmp_path / "store" - assert main(["harness", "install", "opencode", "--version", "1.19.6", "--mode", "editable", - "--install-root", str(root)]) == 1 + argv = ["harness", "install", "opencode", "--version", "v1.19.6", "--install-root", str(root)] + if mode is not None: + argv.extend(["--mode", mode]) + assert main(argv) == 1 assert "OpenCode requires an exact v2 release" in capsys.readouterr().err assert not root.exists() +@pytest.mark.parametrize("mode", [None, "fixed"]) +@pytest.mark.parametrize("version", ["v2.2.6", "2.2.7", "2.3.0", "2.4.0", "2.4.1"]) +def test_opencode_fixed_installs_and_publishes_the_native_release(tmp_path, monkeypatch, version, mode): + chosen = version.removeprefix("v") + seed = tmp_path / "opencode" / chosen / "candidate" + + def fixed(release, root, **kwargs): + assert (release, root) == (chosen, tmp_path) + assert kwargs["repository"] == "anomalyco/opencode" + assert kwargs["runtime"].asset(release, "x86_64")[0] == "opencode-linux-x64.tar.gz" + seed.mkdir(parents=True) + (seed / "harness.json").write_text(json.dumps({ + "name": "opencode", "_opencode_runtime": {"version": release}, + })) + return seed + + monkeypatch.setattr(install_harness.opencode, "install_native_release", fixed) + assert install_harness.install_harness("opencode", version, tmp_path, mode=mode) == seed + options = install_harness.installation_store.catalogue( + tmp_path, ["opencode"], install_harness.verified_versions, install_harness._version_key, + ) + assert options["opencode"]["modes"] == {"editable": [], "fixed": [{"version": chosen, "verified": True}]} + + +@pytest.mark.parametrize("name", ["pi", "hermes-agent"]) +@pytest.mark.parametrize("verified_modes, requested_mode, expected_mode", [ + (("fixed",), None, "fixed"), + (("fixed",), "editable", "editable"), + ((), None, "editable"), +]) +def test_install_resolves_a_mode_for_any_multimode_harness( + tmp_path, monkeypatch, name, verified_modes, requested_mode, expected_mode): + version = "9.0.0" + seed = tmp_path / "candidate" + published = [] + + def verified_versions(harness, mode): + assert harness == name + return {version} if mode in verified_modes else set() + + def dispatch(harness, release, root, *, mode): + assert (harness, release, root, mode) == (name, version, tmp_path, expected_mode) + return seed + + monkeypatch.setattr(install_harness, "verified_versions", verified_versions) + monkeypatch.setattr(install_harness, "_install_harness", dispatch) + monkeypatch.setattr(install_harness.installation_store, "publish", lambda *args: published.append(args)) + assert install_harness.install_harness(name, version, tmp_path, mode=requested_mode) == seed + assert published == [(tmp_path, name, version, expected_mode, seed)] + + def test_pi_defaults_to_editable_and_accepts_fixed(tmp_path, monkeypatch, capsys): def editable(version, root, provision_node): assert version == "1.7.0" @@ -226,11 +287,9 @@ def editable(version, root, provision_node): return root / "editable" def fixed(version, root, **kwargs): - assert version == "1.6.0" + assert version == "1.7.0" return root / "fixed" - monkeypatch.setitem(install_harness.pi.pi_runtime.SOURCE_RELEASES, "1.7.0", - install_harness.pi.pi_runtime.SOURCE_RELEASES["1.6.0"]) monkeypatch.setattr(install_harness.pi, "_editable", editable) monkeypatch.setattr(install_harness.pi, "install_native_release", fixed) monkeypatch.setattr(install_harness.installation_store, "publish", lambda *_: None) diff --git a/tests/quality/test_hermes_source_snapshot.py b/tests/quality/test_hermes_source_snapshot.py index 197e4111..c618fb88 100644 --- a/tests/quality/test_hermes_source_snapshot.py +++ b/tests/quality/test_hermes_source_snapshot.py @@ -117,10 +117,12 @@ def release(tmp_path, monkeypatch): "commit", "--quiet", "--no-gpg-sign", "-m", "Pinned release") git(upstream, "tag", "v0.23.4") git(upstream, "tag", "v0.23.5") + git(upstream, "tag", "v0.23.6") pin = git(upstream, "rev-parse", "HEAD").decode().strip() monkeypatch.setattr(hermes, "UPSTREAM", str(upstream)) monkeypatch.setitem(hermes.RELEASES, "0.23.4", pin) + monkeypatch.setitem(hermes.RELEASES, "0.23.6", pin) artifact = {"python": "/usr/bin/python3", "runtime_paths": ["/usr/bin/python3"]} monkeypatch.setattr(hermes, "_prepare_python", lambda _: artifact) monkeypatch.setattr(hermes, "_probe", lambda candidate, artifact: @@ -280,6 +282,33 @@ def test_native_override_names_must_come_from_exact_pins(): python_harness_runtime.declaration_identity({"runtime": {**runtime, "overrides": value}}, lock) +def test_verified_hermes_selects_the_release_lock_in_both_modes(release, monkeypatch): + root, artifact = release + prepared_locks = [] + + def prepare(harness): + prepared_locks.append((harness / "requirements.lock").read_bytes()) + return artifact + + monkeypatch.setattr(hermes, "_prepare_python", prepare) + legacy_lock = (hermes.TEMPLATE / "requirements.lock").read_bytes() + new_lock = (hermes.TEMPLATE / "requirements-0.23.6.lock").read_bytes() + assert legacy_lock != new_lock + for version, expected in (("0.23.4", legacy_lock), ("0.23.6", new_lock)): + editable = hermes.install(version, root) + assert prepared_locks[-1] == expected + assert (editable / "requirements.lock").read_bytes() == expected + assert not list(editable.glob("requirements-*.lock")) + fixed = hermes.install(version, root, mode="fixed") + assert prepared_locks[-1] == expected + source = Path(hermes.hermes_runtime.resolve(fixed, {})["runtime_paths"][0]) + if version == "0.23.6": + assert (source / "requirements.lock").read_bytes() == expected + assert (source / "harness.json").is_file() + else: + assert not (source / "harness.json").exists() + + def test_unverified_hermes_uses_its_own_locked_dependencies(release, monkeypatch, capsys): root, artifact = release monkeypatch.setattr(hermes, "_provision_python", lambda: Path("/usr/bin/uv")) diff --git a/tests/quality/test_opencode_adapter.py b/tests/quality/test_opencode_adapter.py index e958a3f3..6743c511 100644 --- a/tests/quality/test_opencode_adapter.py +++ b/tests/quality/test_opencode_adapter.py @@ -116,16 +116,6 @@ def test_export_does_not_duplicate_stream_usage_or_text(self): self.assertEqual(stream.usage()["task_steps"]["input_tokens"], 40) self.assertEqual(stream.usage()["completed_steps"], 1) - def test_v1_export_uses_assistant_info_and_parts(self): - stream, _ = self.collect([event("text", text="alpha")]) - stream.reconcile({"info": {"id": "s1"}, "messages": [ - {"info": {"id": "m1", "role": "assistant", "finish": "stop"}, - "parts": [{"type": "text", "text": "alpha"}]}, - ]}, "1") - self.assertEqual(stream.final_text(), "alpha") - self.assertIsNone(stream.usage()['input_tokens']) - self.assertEqual(stream.usage()['scope'], 'native_v1_session_partial') - def test_rejects_wrong_session_failed_or_truncated_export(self): for variation in ("session", "outcome", "finish"): with self.subTest(variation=variation): @@ -188,7 +178,7 @@ def test_child_export_adds_cost_without_replacing_parent_answer(self): "input": 20, "output": 3, "reasoning": 0, "cache": {"read": 5, "write": 0}}}, "messages": [{"id": "child-msg", "type": "assistant", "finish": "stop", "content": [{"type": "text", "text": "child answer"}]}]} - self.adapter.collect_child_sessions(stream, lambda _: child, "2") + self.adapter.collect_child_sessions(stream, lambda _: child) self.assertEqual(stream.final_text(), "alpha") self.assertEqual(stream.usage()["input_tokens"], 105) self.assertEqual(stream.usage()["scope"], "session_tree_including_auxiliary") @@ -204,7 +194,7 @@ def test_missing_child_usage_is_unknown_not_parent_cost(self): stream.reconcile(self.snapshot()) def missing(_): raise ValueError('missing') - self.adapter.collect_child_sessions(stream, missing, "2") + self.adapter.collect_child_sessions(stream, missing) self.assertIsNone(stream.usage()["input_tokens"]) self.assertIsNone(stream.usage()["subagent_messages"]) self.assertEqual(stream.usage()["scope"], "subagent_usage_incomplete") @@ -227,7 +217,7 @@ def child(session): "metadata": {"sessionID": "ses_grandchild"}}}] if session == 'ses_child' else []) return {"info": {"id": session, "outcome": "succeeded", "tokens": tokens}, "messages": [{"id": session, "type": "assistant", "finish": "stop", "content": content}]} - self.adapter.collect_child_sessions(stream, child, "2") + self.adapter.collect_child_sessions(stream, child) self.assertEqual(stream.usage()["input_tokens"], 86) self.assertEqual(stream.usage()["subagent_sessions"], 2) diff --git a/tests/quality/test_opencode_native_delegation.py b/tests/quality/test_opencode_native_delegation.py index d6e039db..baad8fe3 100644 --- a/tests/quality/test_opencode_native_delegation.py +++ b/tests/quality/test_opencode_native_delegation.py @@ -97,12 +97,9 @@ def do_POST(self): identity = next(row['harness_identity'] for row in records if 'harness_identity' in row) resources = next(row['opencode_resources'] for row in records if 'opencode_resources' in row) assert identity['runtime']['version'] == version - assert resources['profile'] == version.split('.', 1)[0] - if version.startswith('1.'): - assert usage['scope'] == 'subagent_usage_incomplete' and usage['input_tokens'] is None - else: - assert usage['scope'] == 'session_tree_including_auxiliary' - assert usage['input_tokens'] == len(server.requests) * 10 + assert resources['profile'] == '2' + assert usage['scope'] == 'session_tree_including_auxiliary' + assert usage['input_tokens'] == len(server.requests) * 10 assert usage['subagent_sessions'] == 1 assert (work / 'answer.txt').read_text() == 'PARENT_COMPLETE' diff --git a/tests/quality/test_opencode_runtime_paths.py b/tests/quality/test_opencode_runtime_paths.py index 65560e4d..cec7b35c 100644 --- a/tests/quality/test_opencode_runtime_paths.py +++ b/tests/quality/test_opencode_runtime_paths.py @@ -165,22 +165,40 @@ def test_version_mismatch_leaves_manifest_unprepared(installed, version_probe, r assert manifest.read_bytes() == original -def test_existing_v1_npm_binding_is_admitted(installed, monkeypatch): +def test_preparation_rejects_v1_npm_package(installed, monkeypatch): harness, binary = installed metadata = binary.parent.parent / "package.json" metadata.write_text(json.dumps({"name": "opencode-linux-x64", "version": "1.19.5"})) - record = runtime.installation(binary) - assert (record["schema"], record["profile"]) == (3, "1") + manifest_path = harness / "harness.json" + original = manifest_path.read_bytes() + + def unexpected_probe(*args, **kwargs): + pytest.fail("v1 reached the sandbox version probe") + + monkeypatch.setattr(prepare.sandbox, "command", unexpected_probe) + with pytest.raises(ValueError, match="requires an exact v2 release"): + prepare.configure(harness, binary) + assert manifest_path.read_bytes() == original + + +@pytest.mark.parametrize("fixed_release", [False, True]) +def test_existing_v1_binding_is_rejected(installed, monkeypatch, fixed_release): + harness, binary = installed + if fixed_release: + record = runtime.installation(binary, "2.99.0", unverified_sha256="a" * 64) + else: + record = runtime.installation(binary) + record["profile"] = "1" + record["version"] = "1.19.5" path = harness / "harness.json" manifest = json.loads(path.read_text()) manifest.update(runtime_paths=record["runtime_paths"], _opencode_runtime=record) path.write_text(json.dumps(manifest)) - assert external_runtime.identities(harness, {})["opencode"]["cacheable"] + with pytest.raises(external_runtime.RuntimeUnavailable, match="requires an exact v2 release"): + external_runtime.identities(harness, {}) monkeypatch.setattr(agent, "ROOT", harness) - assert agent.prepared_installation({}) == record - metadata.write_text(json.dumps({"name": "@opencode/cli-linux-x64", "version": "1.19.5"})) - with pytest.raises(ValueError, match="package name"): - runtime.resolve(harness, {}) + with pytest.raises(ValueError, match="requires an exact v2 release"): + agent.prepared_installation({}) def test_old_opencode_source_declaration_is_refused(tmp_path): diff --git a/tests/quality/test_opencode_submission.py b/tests/quality/test_opencode_submission.py index bb2372e7..9c74bf6d 100644 --- a/tests/quality/test_opencode_submission.py +++ b/tests/quality/test_opencode_submission.py @@ -149,6 +149,7 @@ def test_session_export_stays_raw_for_submission_and_protects_diagnostics( artifact=False, key=key, public=public) assert code == 0 and (work / "answer.txt").read_text() == key identity = rows[0]["harness_identity"] + assert any("opencode_resources" in row for row in rows) assert identity["harness"] == "opencode" and identity["agent_backend"] == "openai" assert identity["agent_model"] == "fixture-local" and identity["wire"] == "chat" expected = key if public else "" diff --git a/tests/quality/test_opencode_surfaces.py b/tests/quality/test_opencode_surfaces.py index 02864601..e7fe2fb3 100644 --- a/tests/quality/test_opencode_surfaces.py +++ b/tests/quality/test_opencode_surfaces.py @@ -16,14 +16,14 @@ def test_owned_native_files_and_modes_are_staged_with_digests(tmp_path): src=candidate(tmp_path);(src/'AGENTS.md').write_text('candidate instruction') d=src/'.opencode/skills/test';d.mkdir(parents=True);(d/'SKILL.md').write_text('native skill') server=src/'.opencode/servers/probe.py';server.parent.mkdir();server.write_text('print(1)');server.chmod(0o755) - (src/'opencode.json').write_text(json.dumps({'instructions':['instructions/output.md'],'mcp':{'probe':{'command':['python3','./servers/probe.py']}}})) - dest=tmp_path/'runtime/config';r=helper.prepare(src,dest,{'model':'platform/model'},'1') + (src/'opencode.json').write_text(json.dumps({'instructions':['instructions/output.md'],'mcp':{'servers':{'probe':{'command':['python3','./servers/probe.py']}}}})) + dest=tmp_path/'runtime/config';r=helper.prepare(src,dest,{'model':'platform/model'}) assert (dest/'AGENTS.md').read_text()=='candidate instruction' assert (dest/'skills/test/SKILL.md').read_text()=='native skill' assert (dest/'servers/probe.py').stat().st_mode & 0o111 cfg=json.loads((dest/'opencode.json').read_bytes()) assert str(dest/'instructions/output.md') in cfg['instructions'] - assert cfg['mcp']['probe']['command'][1]==str(dest/'servers/probe.py') + assert cfg['mcp']['servers']['probe']['command'][1]==str(dest/'servers/probe.py') assert r['config']['model']=='platform/model' assert set(r['files'])=={'AGENTS.md','.opencode/skills/test/SKILL.md','.opencode/servers/probe.py','opencode.json'} assert dest.stat().st_mode & 0o222 == 0 @@ -31,32 +31,32 @@ def test_owned_native_files_and_modes_are_staged_with_digests(tmp_path): def test_platform_model_provider_and_step_budget_cannot_be_replaced(tmp_path): for i,config in enumerate([{'model':'other'},{'providers':{}},{'agent':{'build':{'steps':1000}}},{'agents':{'child':{'model':'other'}}}]): src=tmp_path/str(i);src.mkdir();(src/'opencode.json').write_text(json.dumps(config)) - with pytest.raises(ValueError):helper.prepare(src,tmp_path/('out'+str(i)),{},'1') + with pytest.raises(ValueError):helper.prepare(src,tmp_path/('out'+str(i)),{}) def test_dangling_instruction_and_resource_symlinks_are_rejected(tmp_path): src=candidate(tmp_path);(src/'AGENTS.md').symlink_to(tmp_path/'missing') - with pytest.raises(ValueError):helper.prepare(src,tmp_path/'dest',{},'1') + with pytest.raises(ValueError):helper.prepare(src,tmp_path/'dest',{}) (src/'AGENTS.md').unlink();d=src/'.opencode/skills';d.mkdir(parents=True);(d/'SKILL.md').symlink_to(tmp_path/'missing') - with pytest.raises(ValueError):helper.prepare(src,tmp_path/'dest2',{},'1') + with pytest.raises(ValueError):helper.prepare(src,tmp_path/'dest2',{}) def test_instruction_paths_cannot_escape_candidate_resources(tmp_path): for i,entry in enumerate(['../private.md','/outside/private.md']): src=tmp_path/str(i);src.mkdir();(src/'opencode.json').write_text(json.dumps({'instructions':[entry]})) - with pytest.raises(ValueError):helper.prepare(src,tmp_path/('out'+str(i)),{},'1') + with pytest.raises(ValueError):helper.prepare(src,tmp_path/('out'+str(i)),{}) def test_nested_mcp_v2_local_script_is_relocated(tmp_path): src=candidate(tmp_path);d=src/'.opencode/servers';d.mkdir(parents=True);(d/'probe.py').write_text('pass');(src/'opencode.json').write_text(json.dumps({'mcp':{'servers':{'probe':{'command':['python3','./servers/probe.py']}}}})) - dst=tmp_path/'runtime';helper.prepare(src,dst,{},'2');config=json.loads((dst/'opencode.json').read_bytes()) + dst=tmp_path/'runtime';helper.prepare(src,dst,{});config=json.loads((dst/'opencode.json').read_bytes()) assert config['mcp']['servers']['probe']['command'][1]==str(dst/'servers/probe.py') def test_agent_markdown_cannot_change_model_or_budget(tmp_path): src=candidate(tmp_path);d=src/'.opencode/agents';d.mkdir(parents=True);(d/'child.md').write_text('---\nmodel: other\n---\nprivate prompt') - with pytest.raises(ValueError):helper.prepare(src,tmp_path/'runtime',{},'1') + with pytest.raises(ValueError):helper.prepare(src,tmp_path/'runtime',{}) @pytest.mark.parametrize('head',['"model": other','{model: other}','steps: 999','"maxSteps": 999']) def test_quoted_and_flow_yaml_keys_cannot_change_identity(tmp_path,head): src=candidate(tmp_path);d=src/'.opencode/agents';d.mkdir(parents=True);(d/'child.md').write_text('---\n'+head+'\n---\nprompt') - with pytest.raises(ValueError,match='platform model or step budget'):helper.prepare(src,tmp_path/'runtime',{},'1') + with pytest.raises(ValueError,match='platform model or step budget'):helper.prepare(src,tmp_path/'runtime',{}) def test_frontmatter_missing_yaml_parser_fails_explicitly(tmp_path,monkeypatch): import builtins @@ -66,36 +66,36 @@ def no_yaml(name,*a,**kw): if name=='yaml':raise ImportError('test missing dependency') return old(name,*a,**kw) monkeypatch.setattr(builtins,'__import__',no_yaml) - with pytest.raises(ValueError,match='PyYAML is required'):helper.prepare(src,tmp_path/'runtime',{},'1') + with pytest.raises(ValueError,match='PyYAML is required'):helper.prepare(src,tmp_path/'runtime',{}) @pytest.mark.parametrize('argument',['./servers/probe.py','servers/probe.py','.opencode/servers/probe.py']) def test_owned_script_relative_spellings_survive_relocation(tmp_path,argument): src=candidate(tmp_path);d=src/'.opencode/servers';d.mkdir(parents=True);(d/'probe.py').write_text('pass') - (src/'opencode.json').write_text(json.dumps({'mcp':{'probe':{'command':['python3',argument]}}})) - out=tmp_path/'task-state/config';helper.prepare(src,out,{},'1') - assert json.loads((out/'opencode.json').read_bytes())['mcp']['probe']['command']==['python3',str(out/'servers/probe.py')] + (src/'opencode.json').write_text(json.dumps({'mcp':{'servers':{'probe':{'command':['python3',argument]}}}})) + out=tmp_path/'task-state/config';helper.prepare(src,out,{}) + assert json.loads((out/'opencode.json').read_bytes())['mcp']['servers']['probe']['command']==['python3',str(out/'servers/probe.py')] def test_unpaired_or_mismatched_dependency_lock_is_rejected(tmp_path): - src=candidate(tmp_path);d=src/'.opencode';d.mkdir();(d/'package.json').write_text(json.dumps({'dependencies':{'@opencode-ai/plugin':'1.19.5'}})) - with pytest.raises(ValueError,match='together'):helper.prepare(src,tmp_path/'runtime',{},'1') - (d/'package-lock.json').write_text(json.dumps({'lockfileVersion':3,'packages':{'':{'dependencies':{'@opencode-ai/plugin':'different'}}}})) - with pytest.raises(ValueError,match='declarations differ'):helper.prepare(src,tmp_path/'runtime',{},'1') + src=candidate(tmp_path);d=src/'.opencode';d.mkdir();(d/'package.json').write_text(json.dumps({'dependencies':{'fixture-plugin':'1.0.0'}})) + with pytest.raises(ValueError,match='together'):helper.prepare(src,tmp_path/'runtime',{}) + (d/'package-lock.json').write_text(json.dumps({'lockfileVersion':3,'packages':{'':{'dependencies':{'fixture-plugin':'different'}}}})) + with pytest.raises(ValueError,match='declarations differ'):helper.prepare(src,tmp_path/'runtime',{}) def test_complete_locked_dependencies_select_explicit_native_install_mode(tmp_path): - src=candidate(tmp_path);d=src/'.opencode';d.mkdir();deps={'@opencode-ai/plugin':'1.19.5'} + src=candidate(tmp_path);d=src/'.opencode';d.mkdir();deps={'fixture-plugin':'1.0.0'} (d/'package.json').write_text(json.dumps({'dependencies':deps})) - (d/'package-lock.json').write_text(json.dumps({'lockfileVersion':3,'packages':{'':{'dependencies':deps},'node_modules/@opencode-ai/plugin':{'version':'1.19.5','integrity':'sha512-test'}}})) - out=tmp_path/'runtime';receipt=helper.prepare(src,out,{},'1') + (d/'package-lock.json').write_text(json.dumps({'lockfileVersion':3,'packages':{'':{'dependencies':deps},'node_modules/fixture-plugin':{'version':'1.0.0','integrity':'sha512-test'}}})) + out=tmp_path/'runtime';receipt=helper.prepare(src,out,{}) assert receipt['native_dependency_install'] is True assert out.stat().st_mode & 0o200 @pytest.mark.parametrize('config', [{'commands':{'x':{'model':'other'}}},{'command':{'x':{'variant':'other'}}}]) def test_command_json_cannot_select_another_model(tmp_path,config): src=candidate(tmp_path);(src/'opencode.json').write_text(json.dumps(config)) - with pytest.raises(ValueError,match='platform model'):helper.prepare(src,tmp_path/'runtime',{},'1') + with pytest.raises(ValueError,match='platform model'):helper.prepare(src,tmp_path/'runtime',{}) def test_unqualified_v2_lsp_and_obsolete_tools_fail_clearly(tmp_path): src=candidate(tmp_path);(src/'opencode.json').write_text(json.dumps({'lsp':{'probe':{'command':['probe']}}})) - with pytest.raises(ValueError,match='LSP resource execution is not qualified'):helper.prepare(src,tmp_path/'a',{},'2',version='2.4.1') + with pytest.raises(ValueError,match='LSP resource execution is not qualified'):helper.prepare(src,tmp_path/'a',{},version='2.4.1') (src/'opencode.json').write_text('{}');d=src/'.opencode/tools';d.mkdir(parents=True);(d/'probe.js').write_text('export default {}') - with pytest.raises(ValueError,match='native plugin tool.transform'):helper.prepare(src,tmp_path/'b',{},'2',version='2.4.1') + with pytest.raises(ValueError,match='native plugin tool.transform'):helper.prepare(src,tmp_path/'b',{},version='2.4.1') diff --git a/tests/quality/test_python_candidate_smoke.py b/tests/quality/test_python_candidate_smoke.py index 57d7076c..ec96135a 100644 --- a/tests/quality/test_python_candidate_smoke.py +++ b/tests/quality/test_python_candidate_smoke.py @@ -8,6 +8,7 @@ import pytest from eval.containers import sandbox +from harnessgrad.execution import harness_validation from harnessgrad.execution.python_runtime import python_harness_runtime from tools import validate_harness as validator @@ -15,6 +16,20 @@ ROOT = Path(__file__).resolve().parents[2] +def test_smoke_cleans_read_only_task_resources(tmp_path): + reservations = [] + with harness_validation._smoke_temporary(tmp_path, "smoke-", reservations.append) as (work, charge): + resource = work / "sealed" / "nested" + resource.mkdir(parents=True) + (resource / "instructions.md").write_text("authored resource") + charge(8192) + resource.chmod(0o555) + resource.parent.chmod(0o555) + + assert not work.exists() + assert reservations == [4096, 8192, -12288] + + @pytest.fixture def managed(tmp_path): root=tmp_path/'candidate';root.mkdir() diff --git a/tools/harness_setup/configure_openclaw_harness.py b/tools/harness_setup/configure_openclaw_harness.py index e17ff188..f6c6521a 100644 --- a/tools/harness_setup/configure_openclaw_harness.py +++ b/tools/harness_setup/configure_openclaw_harness.py @@ -37,6 +37,8 @@ class Release: adapter_profile="entries", rebuild=True), "2026.11.3": Release("847611d", "sha512-FBq/q0TCaoA2b7qfdV0q81fHhI6RBB1zAQfJQREc1u2TlK5khVgCUsAlXskLWthyVqRz5PWEj+oOmfYgK58dHg==", adapter_profile="entries", rebuild=True), + "2026.12.1": Release("6a27c35", "sha512-Q7cZpHrc9cpDloKHQBMS05Lia0I6q3ZRn8QmFyOoDjs8oGCfb7apeFe8bMiR9U9Kwl+IHP52dSH+49V6QjJSeA==", + adapter_profile="entries", rebuild=True), } diff --git a/tools/harness_setup/configure_opencode_harness.py b/tools/harness_setup/configure_opencode_harness.py index 8d8926d5..853ec2b9 100644 --- a/tools/harness_setup/configure_opencode_harness.py +++ b/tools/harness_setup/configure_opencode_harness.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Bind an installed OpenCode npm native executable.""" +"""Bind an installed OpenCode v2 npm native executable.""" from __future__ import annotations import argparse diff --git a/tools/harness_setup/install_hermes_harness.py b/tools/harness_setup/install_hermes_harness.py index 94116bee..e5e99efa 100644 --- a/tools/harness_setup/install_hermes_harness.py +++ b/tools/harness_setup/install_hermes_harness.py @@ -25,6 +25,10 @@ UPSTREAM = "https://github.com/NousResearch/hermes-agent.git" hermes_runtime = import_module("base_harness.hermes-agent.hermes_runtime") RELEASES = hermes_runtime.RELEASES +VERIFIED_REQUIREMENTS = { + "0.23.4": "requirements.lock", + "0.23.6": "requirements-0.23.6.lock", +} # These trees belong to upstream CI, evaluation, docs, or desktop/mobile builds. # The headless Python packages and their runtime data stay in the candidate. @@ -153,7 +157,7 @@ def _bind_fixed(harness, fixed, artifact, version, forbidden, *, verified=True): source = harness.parent / "fixed-source" / "source" source.parent.mkdir() (harness / "hermes").rename(source) - if not verified: + if not verified or VERIFIED_REQUIREMENTS[version] != "requirements.lock": declaration = source / "harness.json" lock = source / manifest["runtime"]["requirements"] if any(path.exists() or path.is_symlink() for path in (declaration, lock)): @@ -203,17 +207,21 @@ def install(version, root, *, mode="editable"): raise ValueError("Hermes source storage must belong to the installation root") seeds.mkdir(parents=True, exist_ok=True) repository, commit = _repository(release, version, pin) - artifact = _prepare_python(TEMPLATE) if mode == "fixed" and verified else None + artifact = None with tempfile.TemporaryDirectory(prefix=".prepare-", dir=seeds) as directory: stage = Path(directory) prepared = stage / "harness" - shutil.copytree(TEMPLATE, prepared, ignore=shutil.ignore_patterns("__pycache__", "*.pyc")) + shutil.copytree(TEMPLATE, prepared, ignore=shutil.ignore_patterns( + "__pycache__", "*.pyc", "requirements-*.lock")) files = _export(repository, prepared / "hermes", stage / "source.tar", version, commit, verified=verified) - if not verified: + if verified: + requirements = VERIFIED_REQUIREMENTS[version] + if requirements != "requirements.lock": + shutil.copyfile(TEMPLATE / requirements, prepared / "requirements.lock") + else: _release_dependencies(prepared) if mode == "fixed": - if artifact is None: - artifact = _prepare_python(prepared) + artifact = _prepare_python(prepared) _bind_fixed(prepared, seeds.parent / "fixed", artifact, version, forbidden, verified=verified) else: manifest_path = prepared / "harness.json" diff --git a/tools/harness_setup/install_opencode_harness.py b/tools/harness_setup/install_opencode_harness.py index a9e985ec..2dc9cfcd 100644 --- a/tools/harness_setup/install_opencode_harness.py +++ b/tools/harness_setup/install_opencode_harness.py @@ -124,7 +124,8 @@ def _provision_bun(installation, source): if name in os.environ: env[name] = os.environ[name] result = subprocess.run([str(binary), "--config=/dev/null", "--no-env-file", "pm", "fetch"], - cwd=source, env=env, capture_output=True, text=True, timeout=900) + cwd=source, env=env, capture_output=True, text=True, + encoding="utf-8", errors="replace", timeout=900) if result.returncode: raise ValueError(f"OpenCode dependency fetch failed: {result.stderr[-2000:]}") diff --git a/tools/harness_setup/installation_store.py b/tools/harness_setup/installation_store.py index 660a23b1..b660c628 100644 --- a/tools/harness_setup/installation_store.py +++ b/tools/harness_setup/installation_store.py @@ -189,7 +189,7 @@ def read(root, name, mode, version, *, approved): root = root.expanduser().resolve() if mode not in MODES[name] or not _VERSION.fullmatch(version): raise ValueError("invalid installed version or mode") - if name == "opencode" and mode == "editable": + if name == "opencode": opencode_runtime.require_v2(version) index = _records(root, name, mode) / f"{version}.json" if index.exists() or index.is_symlink(): @@ -237,6 +237,8 @@ def select(root, name, mode, version, *, verified_versions, version_key, env, cu mode = mode or MODES[name][0] if mode not in MODES[name] or version and not _VERSION.fullmatch(version): raise ValueError(f"Invalid installation mode or version for {name}.") + if name == "opencode" and version: + opencode_runtime.require_v2(version) approved = verified_versions(name, mode) command = ["harnessgrad", "harness", "install", name] if len(MODES[name]) > 1: diff --git a/tools/harness_surface_qualification/probes/native_extensions.py b/tools/harness_surface_qualification/probes/native_extensions.py index 5806313c..94fd159e 100644 --- a/tools/harness_surface_qualification/probes/native_extensions.py +++ b/tools/harness_surface_qualification/probes/native_extensions.py @@ -11,13 +11,12 @@ ROOT=Path(__file__).resolve().parents[3] def main(): - p=argparse.ArgumentParser();p.add_argument('--owner',choices=['codex','claude','opencode','dsh','dsh-services','openclaw'],required=True);p.add_argument('--candidate',type=Path,required=True);p.add_argument('--phase',choices=['baseline','candidate'],required=True);p.add_argument('--receipt',type=Path,required=True);p.add_argument('--native',type=Path,required=True);p.add_argument('--control',type=Path);p.add_argument('--legacy-baseline',action='store_true');p.add_argument('--runtime-root',type=Path);p.add_argument('--profile',default='1');p.add_argument('--bundle',action='store_true');p.add_argument('--sandbox',action='store_true');a=p.parse_args() + p=argparse.ArgumentParser();p.add_argument('--owner',choices=['codex','claude','opencode','dsh','dsh-services','openclaw'],required=True);p.add_argument('--candidate',type=Path,required=True);p.add_argument('--phase',choices=['baseline','candidate'],required=True);p.add_argument('--receipt',type=Path,required=True);p.add_argument('--native',type=Path,required=True);p.add_argument('--control',type=Path);p.add_argument('--runtime-root',type=Path);p.add_argument('--bundle',action='store_true');p.add_argument('--sandbox',action='store_true');a=p.parse_args() root=a.receipt.parent;raw=root/'native-receipt.json';before=a.phase=='baseline' if a.owner in ('codex','claude'): script=a.control or ROOT/('tests/quality/test_codex_surfaces.py' if a.owner=='codex' else 'tests/quality/test_claude_surfaces.py');marker='HG_INITIAL' if before else 'HG_EDITED';cmd=[sys.executable,str(script),'--candidate',str(a.candidate),'--marker',marker,'--receipt',str(raw),'--native',str(a.native)] elif a.owner=='opencode': script=a.control or ROOT/'tests/fixtures/opencode_surfaces/qualify.py';marker='BEFORE' if before else 'AFTER';cmd=[sys.executable,str(script),'verify','--candidate',str(a.candidate),'--native',str(a.native),'--output',str(root/'native-effect'),'--expected',marker] - if a.owner=='opencode':cmd+=['--profile',a.profile] if a.owner in ('dsh','dsh-services'): script=a.control or ROOT/('tests/quality/test_dsh_surfaces.py' if a.owner=='dsh' else 'tests/quality/test_dsh_native_services.py');marker='HG_INITIAL' if before else 'HG_EDITED' cmd=[sys.executable,str(script),'--candidate',str(a.candidate),'--marker',marker,'--receipt',str(raw),'--node',str(a.native),'--runtime-root' if a.owner=='dsh' else '--runtime',str(a.runtime_root)] @@ -25,7 +24,6 @@ def main(): script=a.control or ROOT/'tests/quality/test_openclaw_surfaces.py';marker='HG_INITIAL' if before else 'HG_EDITED';cmd=[sys.executable,str(script),'--candidate',str(a.candidate),'--prefix',marker,'--output',str(root/'native-effect')] if a.owner in ('dsh','dsh-services') and a.sandbox:cmd+=['--sandbox'] if a.owner=='openclaw' and a.bundle:cmd+=['--bundle'] - if a.owner=='opencode' and before and a.legacy_baseline:cmd+=['--scope','legacy11'] with (root/'control.stdout.log').open('xb') as out,(root/'control.stderr.log').open('xb') as err: proc=subprocess.run(cmd,cwd=ROOT,env=os.environ.copy(),stdin=subprocess.DEVNULL,stdout=out,stderr=err,timeout=900) if a.owner in ('opencode','openclaw'):raw=root/'native-effect/receipt.json' @@ -51,8 +49,6 @@ def main(): captured='\n'.join(p.read_text(errors='replace') for p in work.rglob('*request*.json') if p.is_file()) if not captured:captured=json.dumps(obj.get('native',{})) absent=forbidden not in captured - if a.owner=='opencode' and before and a.legacy_baseline: - rows['subagent']=absent and 'HG_SURFACE_SUBAGENT_AFTER' not in captured identity={'cli_sha256':hashlib.sha256((a.runtime_root/'apps/cli/lib/bin.js').read_bytes()).hexdigest() if a.runtime_root else None,'executable':str(a.native),'executable_sha256':hashlib.sha256(a.native.read_bytes()).hexdigest(),'control_sha256':hashlib.sha256(script.read_bytes()).hexdigest(),'control':str(script),'native_version':obj.get('native_version')} evidence=[{'native_receipt':str(raw),'sha256':hashlib.sha256(raw.read_bytes()).hexdigest() if raw.is_file() else None,'phase':a.phase}] surfaces={k:{'status':('absent' if before else 'passed') if v is True and proc.returncode==0 and (absent or not before) else 'failed','evidence':evidence} for k,v in rows.items()} diff --git a/tools/install_harness.py b/tools/install_harness.py index 910b1f01..4f3d5f0c 100644 --- a/tools/install_harness.py +++ b/tools/install_harness.py @@ -21,7 +21,6 @@ from tools import loop_releases as loop from tools.harness_setup import configure_codex_harness as codex from tools.harness_setup import configure_dsh_harness as dsh -from tools.harness_setup import configure_opencode_harness as opencode_npm from tools.harness_setup import configure_openclaw_harness as openclaw from tools.harness_setup import configure_claude_harness as claude from tools.harness_setup import install_hermes_harness as hermes @@ -62,14 +61,10 @@ "sha512-yHf/6wbw4Zvha2M2ylDhDrU9FgfKLYgV6xSzSjlz3gxQNsiVLkXo+fPGwBqvP0A5geLtZs9wAbq+1v7+ZVWJ0g==", "sha512-YJq6Wz3PFXV5LZ0OQc3/o+gpM3pLmQ/8n8uM2zF/m0O/8zED+uSPT8Ln1KGRrqR8Q6eon9YdWlhueAunVTZ+eg==", ), -} -OPENCODE_PACKAGES = {"1": "opencode-linux-x64", "2": "@opencode/cli-linux-x64"} -OPENCODE_NPM_RELEASES = { - "1.19.5": "sha512-i1qh7VooLGML9xX6ud93y0JA8j/1aPeDYRKjsmYXrJX1TjIWHgBBMkEbEJPZthpWbsJg//XfBgR6Kb7+NPaJiQ==", - "2.2.6": "sha512-g1NShGt+20y/7nzQvqAnO7bQshC8nZGaz8WC7J8vjgXIOZ1uzoxz5OiLnCbUWertf2CM3Dlh9tzrmZJf0ic9Aw==", - "2.2.7": "sha512-wk/DPHxr4maiW+FmQp8ztoXlo/vC5qsmEIHsLNaNLZL2iaIYfhyqFRe6CRsCVxy+ib0sfK07X2IepFw7ZSKqNQ==", - "2.3.0": "sha512-8T3K8L6Nd4fSG5BSgofqhmIDQ1ZvzDZZ2J7bFVB9RK1d5Hjqh24IcxgbcwpgGKkdvItrayi4Rl+wrSmhl17FFg==", - "2.4.1": "sha512-FYQAnneVlLmqy862674vvRVkj8yHuZAFHJGV3UCGQxo8aKG58IHPKrspbxruVajnIEpb0t8PeO63H/oW4vJG5A==", + "0.173.0": ( + "sha512-DmeLXq5gNEktKqi4k3/VolB8oS5g36gtGbd5Oovuwj7wk5pRbtRb90KOvtUz4+2nZPh2GKC0apNxkVyYz/OD1A==", + "sha512-1iXZmfXdp3fWRIAeqrExaXVubw695SpJS/HEMM7dfwTVkUdbGK1fVLkQIFT68HNwOAUkHZpvjEDargiRzNfBAg==", + ), } DSH_RELEASES = { "0.2.2-rc.1": "sha512-ijR9UEVYkG15Q/Q79JzvzLBzQOQfc63VLr9n6flpwHPhr5IKn2UxthnSoto/P9l7qGd7pPvI1Ra6TW7LH3oKpg==", @@ -80,6 +75,7 @@ # wrapper's postinstall download while retaining the registry's exact integrity. CLAUDE_RELEASES = { "2.1.201": "sha512-pJaih99BHjY2WvBoPYvDMFhs90DwTXUaC8LIqQe/W+2g4jJr7VYMTVv0C60vIoxg17nxaMUTtlBhY87U3qP5kA==", + "2.1.335": "sha512-HOLW4KEPmT7OkedzJgz3D1RnPgNvstmu1LIfZZy65sJR5o/ZP5DPLr4RpD5vu7CbtzBEeKTf8/4Db8ZC+MEavA==", } EXACT_SEMVER = r"(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)" LABELS = {"loop": "Loop", "openclaw": "OpenClaw", "codex": "Codex", "opencode": "OpenCode", @@ -102,11 +98,6 @@ def _recipe(name: str, version: str) -> NpmRelease: raise ValueError("Codex version must be an exact X.Y.Z release") wrapper, native = CODEX_RELEASES.get(version, (None, None)) return NpmRelease(CODEX_PACKAGE, version, wrapper, native_integrity=native) - if name == "opencode": - if not re.fullmatch(r"[12]\.[0-9]+\.[0-9]+", version): - raise ValueError("OpenCode version must be an exact v1 or v2 release") - package = OPENCODE_PACKAGES[version.split(".", 1)[0]] - return NpmRelease(package, version, OPENCODE_NPM_RELEASES.get(version)) if name == "deepseek-harness": if not re.fullmatch(EXACT_SEMVER + r"(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?", version): raise ValueError("DeepSeek Harness version must be an exact X.Y.Z release or prerelease") @@ -283,20 +274,21 @@ def verified_versions(name, mode=None): if name == "pi": return pi.RELEASES if mode == "fixed" else pi.pi_runtime.SOURCE_RELEASES if name == "opencode": - return (OPENCODE_NPM_RELEASES | opencode.RELEASES) if mode == "fixed" else opencode.SOURCE_RELEASES + return opencode.RELEASES if mode == "fixed" else opencode.SOURCE_RELEASES return {"loop": loop.RELEASES, "openclaw": openclaw.RELEASES, "codex": CODEX_RELEASES, "claude-code": CLAUDE_RELEASES, "deepseek-harness": DSH_RELEASES, "oh-my-pi": omp.RELEASES, "hermes-agent": hermes.RELEASES}[name] def install_harness(name: str, version: str, root: Path, *, mode: str | None = None) -> Path: - if (name == "opencode" and mode is None - and (version.startswith("1.") or version in OPENCODE_NPM_RELEASES and version not in opencode.SOURCE_RELEASES)): - mode = "fixed" + modes = installation_store.MODES.get(name, ()) + normalized_version = version.removeprefix("v") + if mode is None and len(modes) > 1: + verified_modes = (choice for choice in modes if normalized_version in verified_versions(name, choice)) + mode = next(verified_modes, modes[0]) harness = _install_harness(name, version, root, mode=mode) - if name in installation_store.MODES: - installation_store.publish(root, name, version.removeprefix("v"), - mode or installation_store.MODES[name][0], harness) + if modes: + installation_store.publish(root, name, normalized_version, mode or modes[0], harness) return harness @@ -309,8 +301,7 @@ def _install_harness(name: str, version: str, root: Path, *, mode: str | None) - return loop.install(version, root) if name == "pi": return pi.install(version, root, mode=mode, provision_node=_toolchain) - if name == "opencode" and not (mode == "fixed" and (version.startswith("1.") - or version in OPENCODE_NPM_RELEASES and version not in opencode.RELEASES)): + if name == "opencode": return opencode.install(version, root, mode=mode) if name == "oh-my-pi": return omp.install(version, root) @@ -321,10 +312,6 @@ def _install_harness(name: str, version: str, root: Path, *, mode: str | None) - template = ROOT / "base_harness/codex" helper, source = codex._adapter, None entrypoint, expected_version = "bin/codex.js", f"codex-cli {version}" - elif name == "opencode": - template = ROOT / "base_harness/opencode" - helper, source = opencode_npm._helper, None - entrypoint, expected_version = "bin/opencode", version elif name == "deepseek-harness": template = dsh.TEMPLATE helper, source = dsh._helper, None @@ -357,7 +344,7 @@ def _install_harness(name: str, version: str, root: Path, *, mode: str | None) - node_root = _toolchain(root) node = node_root / "bin/node" launcher_path = Path("package/node_modules") / recipe.package / entrypoint - prefix = [] if name in ("claude-code", "opencode") else [str(node)] + prefix = [] if name == "claude-code" else [str(node)] if source is None and recipe.integrity is None: print(f"Warning: {LABELS[name]} {version} is unverified. Trying its adapter.", file=sys.stderr) archived_receipt = None @@ -385,9 +372,7 @@ def _install_harness(name: str, version: str, root: Path, *, mode: str | None) - shutil.copytree(template, harness, ignore=shutil.ignore_patterns( ".git", ".env", ".state", "__pycache__", "*.pyc")) env = {"PATH": os.defpath} - if name == "opencode": - record = opencode_npm.configure(harness, launcher, expected_version=version) - elif name == "deepseek-harness": + if name == "deepseek-harness": record = dsh.configure(harness, lockfile.parent, str(node), npm_version=version)["identity"] elif name == "claude-code": record = claude.configure(harness, launcher, expected_version=version) @@ -423,13 +408,14 @@ def main(argv: list[str] | None = None) -> int: actions.add_parser("list", help="list verified harness versions") install = actions.add_parser("install", help="install and bind a harness version") catalogs = {"loop": loop.RELEASES, "openclaw": openclaw.RELEASES, "codex": CODEX_RELEASES, - "opencode": dict.fromkeys((*OPENCODE_NPM_RELEASES, *opencode.RELEASES, *opencode.SOURCE_RELEASES)), + "opencode": dict.fromkeys((*opencode.RELEASES, *opencode.SOURCE_RELEASES)), "claude-code": CLAUDE_RELEASES, "deepseek-harness": DSH_RELEASES, "pi": dict.fromkeys((*pi.RELEASES, *pi.pi_runtime.SOURCE_RELEASES)), "oh-my-pi": omp.RELEASES, "hermes-agent": hermes.RELEASES} install.add_argument("harness", choices=catalogs) install.add_argument("--version", help="exact release version (default: latest verified version)") install.add_argument("--mode", choices=("editable", "fixed"), - help="installation mode for Pi, OpenCode and Hermes Agent (default: editable)") + help="installation mode for Pi, OpenCode and Hermes Agent " + "(default: editable unless the version is verified only for fixed)") install.add_argument("--install-root", type=Path, default=default_root()) args = parser.parse_args(argv) if args.action == "list": @@ -452,8 +438,6 @@ def main(argv: list[str] | None = None) -> int: modes.append(f"editable Bun {opencode.BUN_VERSION}") if version in opencode.RELEASES: modes.append("fixed GitHub Release") - elif version in OPENCODE_NPM_RELEASES: - modes.append("fixed npm release") print(f"{name} {version} ({'; '.join(modes)}, Linux x86-64)") elif name == "hermes-agent": print(f"{name} {version} (editable or fixed, CPython {hermes.hermes_runtime.PYTHON}, Linux x86-64)")