From 923930c811ab86fb27ac2492351300e031355482 Mon Sep 17 00:00:00 2001
From: David Rudduck
Date: Mon, 14 Sep 2026 10:53:19 +0000
Subject: [PATCH 1/9] docs: plan OpenCode provider support
---
docs/opencode-support/PLAN.md | 359 +++++++++++++++++++++++++++
docs/opencode-support/PRD.md | 279 +++++++++++++++++++++
docs/opencode-support/SPEC.md | 450 ++++++++++++++++++++++++++++++++++
3 files changed, 1088 insertions(+)
create mode 100644 docs/opencode-support/PLAN.md
create mode 100644 docs/opencode-support/PRD.md
create mode 100644 docs/opencode-support/SPEC.md
diff --git a/docs/opencode-support/PLAN.md b/docs/opencode-support/PLAN.md
new file mode 100644
index 0000000..08f1d64
--- /dev/null
+++ b/docs/opencode-support/PLAN.md
@@ -0,0 +1,359 @@
+# OpenCode Support Implementation Plan
+
+Status: Ready for review
+
+Inputs: `PRD.md`, `SPEC.md`
+
+Branch strategy: focused feature branches from current upstream `main`
+
+## Delivery strategy
+
+Deliver the integration as three reviewable PRs. Do not combine upstream's
+unrelated runtime-locking or dispatch-wait changes with OpenCode support.
+
+1. **PR A — provider, host setup, and assets**
+2. **PR B — ACP model/effort execution and live workers**
+3. **PR C — terminal-review isolation and hardening**
+
+Open an upstream feature issue before PR A, per `CONTRIBUTING.md`. Link the PRD
+and summarize the phased scope, particularly the terminal-review and billing
+boundaries.
+
+## Preflight
+
+### Task 0.1 — Record baselines
+
+- Confirm local `main` matches `upstream/main` before branching.
+- Record `opencode --version`; minimum researched release is v1.18.30.
+- Run:
+
+ ```bash
+ cd zenith
+ uv run ruff check .
+ uv run mypy src
+ uv run pytest -q
+ ```
+
+- Record skipped real-agent tests separately.
+
+Exit condition: clean checkout and green hermetic baseline.
+
+### Task 0.2 — Resolve overlap with upstream work
+
+- Review current state of upstream PRs #35, #39, #33, and #23 immediately before
+ implementation.
+- If #35 merged, build on its per-role model fields rather than recreating them.
+- If it remains open, keep the model-field commit isolated so it can be rebased
+ or replaced cleanly.
+- Do not copy #39's Codex-only secret handling into OpenCode; note the future
+ provider-neutral authorization dependency.
+
+Exit condition: branch base and ownership of overlapping code are documented in
+the upstream issue.
+
+## PR A — Provider, host setup, and assets
+
+### Task A1 — Add failing provider-selection tests
+
+Files:
+
+- `zenith/tests/test_config.py`
+- `zenith/tests/test_cli.py`
+
+Add tests proving `opencode` is accepted for orchestrator, worker, validator,
+and terminal reviewer, defaults its ACP command to `opencode acp`, and follows
+existing command/provider inheritance rules.
+
+Run focused tests and confirm they fail for the expected unsupported-provider
+reason.
+
+### Task A2 — Add the provider definition
+
+File: `zenith/src/zenith_harness/providers.py`
+
+- Extend provider and config-format literals.
+- Add `opencode` to role lists.
+- Add the provider definition and `build` ACP mode.
+- Add the smallest capability fields needed by this PR; defer session-option
+ behavior to PR B if that keeps the diff clearer.
+
+Run:
+
+```bash
+uv run pytest -q tests/test_config.py
+uv run mypy src
+```
+
+Commit boundary: `feat(providers): register OpenCode roles`.
+
+### Task A3 — Specify OpenCode host-config behavior with tests
+
+File: `zenith/tests/test_cli.py`
+
+Cover:
+
+- new `.opencode/opencode.json`;
+- exact `mcp.zenith` schema;
+- preservation of unrelated settings and MCPs;
+- malformed/non-object existing JSON;
+- idempotency;
+- quoted paths and environment values;
+- coexistence with `.opencode/opencode.jsonc`;
+- no ambient API/model settings persisted;
+- mixed provider routing values.
+
+Tests must assert no partial write on failure.
+
+### Task A4 — Implement the host-config writer
+
+File: `zenith/src/zenith_harness/cli.py`
+
+- Add the `opencode_config` branch.
+- Generate the local MCP command array and `environment` mapping.
+- Merge only `mcp.zenith` in strict JSON.
+- Use atomic replacement.
+- Add conservative JSONC override diagnostics without rewriting JSONC.
+- Keep model/provider/permission/plugin settings untouched.
+
+Run CLI tests, Ruff, and mypy.
+
+Commit boundary: `feat(cli): initialize OpenCode MCP host config`.
+
+### Task A5 — Add OpenCode assets
+
+Files:
+
+- `zenith/src/zenith_harness/bundled/providers/opencode/agents/*.md`
+- `zenith/tests/test_assets.py`
+- `zenith/tests/test_cli.py`
+
+Adapt all four provider subagents with OpenCode frontmatter. Add tests for mode,
+permissions, model inheritance, installation paths, skill deduplication, and
+orchestrator prompt preservation.
+
+Commit boundary: `feat(assets): add OpenCode orchestrator assets`.
+
+### Task A6 — Document project-scoped host setup
+
+Files:
+
+- `README.md`
+- `zenith/README.md`
+- `CONTRIBUTING.md`
+- `zenith/pyproject.toml`
+
+Add installation, initialization, generated paths, and current scope. Do not yet
+claim verified worker execution.
+
+### PR A verification
+
+```bash
+cd zenith
+uv run ruff check .
+uv run mypy src
+uv run pytest -q
+```
+
+Disposable-host check:
+
+1. initialize a temporary git workspace twice;
+2. run `opencode debug config` there;
+3. verify `mcp.zenith` resolves to the generated command and environment;
+4. run `opencode mcp list` and verify Zenith connects;
+5. confirm unrelated JSON/JSONC remains unchanged.
+
+## PR B — ACP execution, models, and effort
+
+### Task B1 — Land/generalize per-role model fields
+
+Files:
+
+- `zenith/src/zenith_harness/config.py`
+- `zenith/src/zenith_harness/providers.py`
+- `zenith/src/zenith_harness/cli.py`
+- `zenith/tests/test_config.py`
+- `zenith/tests/test_cli.py`
+
+Implement `ZENITH_{WORKER,VALIDATOR,TERMINAL_REVIEWER}_MODEL` and matching CLI
+flags using same-provider-only inheritance. Preserve unset OpenCode model and
+effort values. Coordinate with upstream PR #35 rather than duplicating its
+Codex/Claude work.
+
+Commit boundary: `feat(config): support provider-scoped role model pins`.
+
+### Task B2 — Extend the mock ACP agent first
+
+File: `zenith/tests/mock_acp_agent.py`
+
+Add deterministic fixtures for:
+
+- `session/new` option advertisement;
+- ordered `session/set_config_option` requests;
+- model-dependent effort lists;
+- invalid model/effort errors;
+- mode selection;
+- session MCP registration capture.
+
+Keep all behavior opt-in through mock environment variables so existing tests
+remain unchanged.
+
+### Task B3 — Add session-option unit tests
+
+File: `zenith/tests/test_acp_runner.py`
+
+Write failing tests for:
+
+- OpenCode launch command/environment;
+- model then effort then mode then prompt ordering;
+- no selection calls when pins are absent;
+- provider/model IDs with nested slashes;
+- model rejection and effort mismatch;
+- worker/validator pin separation;
+- missing build mode;
+- no Codex config flags or `CODEX_CONFIG` mutation for OpenCode.
+
+### Task B4 — Implement ACP session configuration
+
+File: `zenith/src/zenith_harness/acp_runner.py`
+
+- Capture `configOptions` from `session/new`.
+- Add a typed helper for `session/set_config_option`.
+- Select model first, effort second, mode third.
+- Update advertised options after each successful request.
+- Leave absent values untouched.
+- Convert failures into concise `ACPError` diagnostics.
+- Use provider capabilities rather than broad name checks.
+
+Apply identical behavior to normal nodes and terminal-review sessions through a
+shared session setup helper.
+
+Commit boundary: `feat(acp): configure OpenCode model and effort per role`.
+
+### Task B5 — Add opt-in real OpenCode smoke tests
+
+Files:
+
+- `zenith/tests/test_smoke_real_acp.py`
+- `zenith/tests/test_smoke_parallel_acp.py`
+
+Add `opencode` gating and command override. Exercise:
+
+1. default-model work plus validation;
+2. explicit valid model/effort;
+3. mixed worker and validator pins;
+4. two parallel workers.
+
+Use disposable workspaces and a dedicated low-cost test account/model where
+available. Never print auth data or the full subprocess environment.
+
+### Task B6 — Document model selection
+
+Document:
+
+- discover IDs with `opencode models [provider]`;
+- IDs use `provider/model`;
+- effort values are selected-model variants;
+- explicit role pins override OpenCode defaults only for that session;
+- no pin preserves OpenCode precedence;
+- custom model option objects remain OpenCode config responsibility;
+- OpenCode credentials are an operator billing boundary.
+
+### PR B verification
+
+Run all static/hermetic checks, then opt-in serial and parallel OpenCode smokes.
+Record exact OpenCode version and safe model IDs in the PR description.
+
+## PR C — Terminal-review isolation and hardening
+
+### Task C1 — Build an adversarial isolation fixture
+
+Add test-only project and fake-home fixtures containing:
+
+- `AGENTS.md` with a recognizable canary;
+- `.opencode/skills/.../SKILL.md` canary;
+- `.agents/skills/.../SKILL.md` canary;
+- global OpenCode `AGENTS.md` and skill canaries;
+- external plugin canary;
+- unrelated provider configuration.
+
+The reviewer must neither report seeing the canaries nor have their tools
+available. A prompt-level prohibition alone is not evidence.
+
+### Task C2 — Implement role-specific launch context
+
+Files:
+
+- `zenith/src/zenith_harness/acp_runner.py`
+- optionally a focused isolation/config helper module
+
+- Pass role into command/environment construction.
+- Add `--pure` only for the OpenCode terminal reviewer.
+- Set project/external-skill/Claude-compatibility disable flags.
+- Create an owner-only temporary `HOME` and `XDG_CONFIG_HOME` so `~/.opencode`
+ and user-global instructions cannot be discovered.
+- Supply minimal inline config for the selected reviewer model and permissions.
+- Reuse the existing `XDG_DATA_HOME` only after explicit operator acceptance of
+ that credential-store boundary; do not copy or log its contents.
+- Clean up after success, failure, cancellation, and timeout.
+- Fail closed for unsupported custom-provider isolation.
+
+Commit boundary: `security(opencode): isolate terminal reviewer context`.
+
+### Task C3 — Test failure and cleanup paths
+
+Cover:
+
+- missing isolated model/provider;
+- malformed managed config;
+- process crash and timeout;
+- cancellation cleanup;
+- no temporary paths or secrets in handoffs;
+- managed system policy remains an explicitly documented boundary.
+
+### Task C4 — Run real terminal-review smoke
+
+Run one known-clean and one deliberate-defect review. Confirm:
+
+- declared artifacts are readable;
+- ephemeral Zenith MCP handoff works;
+- project/global canaries are not injected;
+- selected model/effort is honored;
+- no credentials appear in output.
+
+### Task C5 — Security documentation
+
+Add a support matrix for built-in versus custom providers under isolated review,
+billing authority, managed policy, and recommended use of a dedicated OpenCode
+profile/account for long-running missions.
+
+## Deferred follow-ups
+
+- User-scoped OpenCode setup aligned with upstream PR #23.
+- Provider-neutral API billing grants aligned with upstream PR #39.
+- Runtime identity receipts containing safe provider/model/variant fields.
+- Native Windows ACP smoke coverage after upstream issue #8 is resolved.
+- Arbitrary custom OpenCode variant names.
+- Capability negotiation for future ACP versions instead of a version floor.
+
+## Review checklist for every PR
+
+- Scope matches the PR description; no unrelated upstream fixes included.
+- Existing user configuration is preserved.
+- No new default model, provider, cost, permission, or plugin behavior.
+- No API keys, credential files, inline config secrets, or environments logged.
+- New errors name the affected role and remediation.
+- Unit tests cover cross-provider inheritance and negative paths.
+- Documentation distinguishes hermetic tests from paid live smoke tests.
+- `uv run ruff check .`, `uv run mypy src`, and `uv run pytest -q` pass.
+
+## Estimated effort
+
+| Work | Estimate |
+|---|---:|
+| PR A: provider, host config, assets | 2–3 engineering days |
+| PR B: role models, ACP options, live workers | 2–3 engineering days |
+| PR C: terminal isolation and hardening | 2–4 engineering days |
+| Upstream review/rebase contingency | 1–2 engineering days |
+
+Expected merge-quality total: 7–12 engineering days, depending primarily on
+terminal-review authentication isolation and overlap with upstream PR #35.
diff --git a/docs/opencode-support/PRD.md b/docs/opencode-support/PRD.md
new file mode 100644
index 0000000..03b7181
--- /dev/null
+++ b/docs/opencode-support/PRD.md
@@ -0,0 +1,279 @@
+# OpenCode Support PRD
+
+Status: Proposed
+
+Owner: ExpansionX
+
+Target repository: `ExpansionX/zenith`, proposed upstream contribution to
+`Intelligent-Internet/zenith`
+
+Research baseline: OpenCode v1.18.30 (2026-09-09)
+
+## Summary
+
+Add OpenCode as a first-class Zenith host and execution provider. A user must be
+able to initialize a workspace for OpenCode, run the Zenith orchestrator from
+OpenCode, and select OpenCode independently for worker, validator, and terminal
+reviewer roles. OpenCode workers will use its native `opencode acp` server; no
+third-party ACP adapter is required.
+
+The integration must preserve existing OpenCode configuration, avoid silently
+selecting a paid model, support explicit per-role model and reasoning-variant
+selection, and retain Zenith's independent terminal-review boundary.
+
+## Problem
+
+Zenith currently recognizes only Claude Code, Codex, and Hermes. OpenCode users
+can neither run `zenith init --agent opencode` nor select OpenCode for an
+individual execution role, even though OpenCode already implements the ACP and
+MCP capabilities Zenith needs.
+
+A provider-table-only change would be incomplete:
+
+- OpenCode uses `opencode.json`/`opencode.jsonc`, not Claude's `.mcp.json` or
+ Codex TOML.
+- Model IDs are `provider/model`, and reasoning levels are model-specific
+ variants.
+- Its ACP server exposes model, effort, and mode as session configuration
+ options.
+- Its ambient configuration can inject project/global rules, skills, agents,
+ and plugins. That is useful for workers, but conflicts with Zenith's
+ independent terminal-review contract.
+- Authentication may come from environment variables, project `.env` files, or
+ OpenCode's persistent credential store, so model selection has billing and
+ trust-boundary consequences.
+
+## Users
+
+1. An OpenCode user who wants OpenCode to host and orchestrate a Zenith mission.
+2. A mixed-provider user who wants, for example, OpenCode workers and a Codex or
+ Claude validator.
+3. An operator who must pin different OpenCode models or effort variants for
+ workers, validators, and terminal review.
+4. A maintainer adding future ACP providers without introducing another set of
+ provider-name conditionals.
+
+## Goals
+
+- Make `opencode` a valid orchestrator, worker, validator, and terminal-reviewer
+ provider.
+- Generate an idempotent project-scoped OpenCode MCP registration for Zenith.
+- Install OpenCode-compatible orchestrator, subagent, and skill assets.
+- Use native `opencode acp` for dispatched sessions.
+- Allow explicit per-role OpenCode model pins in `provider/model` form.
+- Apply an explicitly requested reasoning effort only when the selected model
+ exposes that variant.
+- Preserve OpenCode's configured/default model when no role pin is supplied.
+- Select OpenCode's writable `build` mode for worker sessions regardless of the
+ user's interactive default agent.
+- Fail clearly before useful work begins when a requested model, effort, mode,
+ executable, or resolved MCP configuration is invalid.
+- Isolate an OpenCode terminal reviewer from project/global instructions,
+ skills, agents, and external plugins while retaining the minimum authorized
+ model authentication needed to review.
+- Add hermetic tests plus opt-in real-agent serial, parallel, and terminal-review
+ smoke coverage.
+
+## Non-goals
+
+- Managing OpenCode login or creating provider credentials.
+- Shipping or maintaining an OpenCode model catalog inside Zenith.
+- Choosing a default paid model on the user's behalf.
+- Translating provider-specific model option objects such as Anthropic thinking
+ budgets or OpenAI text verbosity.
+- Supporting arbitrary custom OpenCode variant names in the first release;
+ Zenith's existing reasoning-effort vocabulary remains the public interface.
+- Enabling OpenCode's own background subagent orchestration inside dispatched
+ Zenith workers.
+- User-scoped OpenCode installation in the first PR. It should follow the
+ project-scoped implementation and align with upstream PR #23.
+- Solving Zenith's existing Windows execution issues. WSL is the documented
+ initial Windows path; native Windows must not be knowingly regressed.
+
+## User experience
+
+### OpenCode for every role
+
+```bash
+uv run zenith init \
+ --workspace-dir /path/to/app \
+ --agent opencode \
+ --worker-model openai/gpt-5.2-codex \
+ --worker-reasoning-effort high \
+ --validator-model anthropic/claude-sonnet-4-5 \
+ --validator-reasoning-effort high
+
+cd /path/to/app
+opencode
+```
+
+The user then invokes the generated Zenith skill or asks OpenCode to read
+`.opencode/orchestrator_prompt.md` and run the mission.
+
+### OpenCode for one role
+
+```bash
+uv run zenith init \
+ --workspace-dir /path/to/app \
+ --agent claude \
+ --worker-provider opencode \
+ --worker-model opencode/gpt-5.2
+```
+
+### Preserve OpenCode defaults
+
+```bash
+uv run zenith init --workspace-dir /path/to/app --agent opencode
+```
+
+With no model flags, Zenith does not write `model`, `small_model`, provider, or
+variant settings. Each OpenCode ACP session uses the model selected by OpenCode's
+normal precedence rules.
+
+## Functional requirements
+
+### Provider and initialization
+
+- **OC-FR-001:** `opencode` is accepted by `--agent`,
+ `--orchestrator-provider`, `--worker-provider`, `--validator-provider`, and
+ `--terminal-reviewer-provider`.
+- **OC-FR-002:** OpenCode defaults to `opencode acp` for execution roles.
+- **OC-FR-003:** `zenith init --agent opencode` creates or updates only the
+ managed `mcp.zenith` object in `.opencode/opencode.json`.
+- **OC-FR-004:** The generated local MCP entry uses OpenCode's array-valued
+ `command`, `environment`, `enabled`, and millisecond `timeout` fields.
+- **OC-FR-005:** Re-running initialization is idempotent and preserves unrelated
+ OpenCode settings and MCP servers.
+- **OC-FR-006:** Initialization does not write a model, provider credentials,
+ permissions policy, plugin list, or global configuration.
+- **OC-FR-007:** If another higher-precedence OpenCode source overrides
+ `mcp.zenith`, initialization reports the conflict and how to resolve it.
+
+### Assets
+
+- **OC-FR-010:** Zenith installs its orchestrator prompt at
+ `.opencode/orchestrator_prompt.md` without replacing an existing customized
+ copy.
+- **OC-FR-011:** Zenith installs bundled skills to `.opencode/skills` and the
+ shared `.agents/skills` surface without duplicate logical entries.
+- **OC-FR-012:** OpenCode subagent files are installed under
+ `.opencode/agents`, declare `mode: subagent`, inherit the invoking model unless
+ explicitly pinned by the user, and encode read-only/no-delegation permissions
+ for the reviewer/investigator roles.
+
+### ACP execution
+
+- **OC-FR-020:** Worker and validator sessions start through native
+ `opencode acp` and receive the per-attempt `zenith-worker` MCP server in the
+ ACP `session/new` request.
+- **OC-FR-021:** Zenith selects ACP mode `build` before sending the task prompt.
+- **OC-FR-022:** OpenCode-specific command/environment changes are capability
+ driven and do not alter Claude, Codex, or Hermes behavior.
+- **OC-FR-023:** OpenCode worker prompts continue to combine Zenith's role
+ prompt and rendered task template into the first ACP user message.
+
+### Models and reasoning
+
+- **OC-FR-030:** Each execution role can receive an explicit model pin without
+ leaking that pin across a provider boundary.
+- **OC-FR-031:** An OpenCode model pin is passed after `session/new` through the
+ ACP model configuration option, not interpolated into a shell command.
+- **OC-FR-032:** Model selection occurs before effort selection because the
+ available effort values depend on the selected model.
+- **OC-FR-033:** If no model is pinned, Zenith leaves OpenCode's resolved model
+ unchanged.
+- **OC-FR-034:** If no reasoning effort is pinned, Zenith leaves OpenCode's
+ resolved variant unchanged.
+- **OC-FR-035:** A requested unavailable model or effort produces a concise
+ role-specific failure containing the requested value and remediation command
+ (`opencode models`, or selection of an advertised effort).
+- **OC-FR-036:** Model IDs remain open-ended strings accepted as JSON data,
+ including provider model IDs that themselves contain `/`; control characters
+ are rejected and values are never treated as shell syntax.
+
+### Security and isolation
+
+- **OC-FR-040:** Zenith never serializes provider API keys or OpenCode's
+ `auth.json` contents into workspace configuration, logs, handoffs, or receipts.
+- **OC-FR-041:** Documentation states that normal OpenCode worker/validator
+ sessions use the credentials available to the OpenCode process and therefore
+ share the operator's billing trust boundary.
+- **OC-FR-042:** OpenCode terminal review launches without external plugins,
+ project config/rules, project/global external skills, or user-global OpenCode
+ instructions.
+- **OC-FR-043:** Terminal-review isolation must not silently fall back to an
+ unisolated session. If the selected model cannot be made available inside the
+ isolated context, terminal review reports a blocked/failed result with an
+ actionable explanation.
+- **OC-FR-044:** Process errors and diagnostic output are truncated and scrubbed
+ using the same secret-free standards as other ACP providers.
+
+### Compatibility and diagnostics
+
+- **OC-FR-050:** The supported baseline is OpenCode v1.18.30 or newer within
+ the tested ACP v1 behavior. Unsupported/missing binaries fail with a direct
+ installation/version message.
+- **OC-FR-051:** Project scope works on Linux and macOS. WSL is the supported
+ initial Windows route.
+- **OC-FR-052:** `zenith init` prints the resolved OpenCode host, execution
+ roles, ACP commands, and model pins without printing credentials.
+
+## Acceptance criteria
+
+1. A clean disposable workspace initialized with `--agent opencode` exposes all
+ Zenith orchestrator MCP tools in OpenCode.
+2. A real OpenCode work task writes the expected fixture and calls `end_node`.
+3. A real OpenCode validator independently reports assertion items and passes a
+ known-good fixture.
+4. Two OpenCode ACP workers can execute concurrently without session or MCP
+ registration collisions.
+5. Worker and validator can use two distinct `provider/model` pins in one
+ mission, and their attempt evidence identifies the selected model without
+ containing credentials.
+6. An unavailable effort fails before the task is treated as completed.
+7. Existing OpenCode configuration and unrelated MCP entries remain
+ semantically unchanged; after the first managed update, a second identical
+ `zenith init` run is byte-for-byte idempotent.
+8. A terminal-review fixture containing forbidden project/global instructions,
+ skills, and a plugin proves none are injected or callable.
+9. Existing Claude, Codex, and Hermes unit tests remain green.
+10. Ruff, mypy, and the full hermetic pytest suite pass on Python 3.11-3.13.
+
+## Success measures
+
+- OpenCode completes the existing real-ACP hello mission at the same functional
+ evidence floor as Claude and Codex.
+- No OpenCode-specific regression in the existing provider matrix.
+- Initialization is repeatable and does not change model/provider preferences.
+- Failures identify the role, command, model/effort request, and next action.
+- No credential material appears in generated workspace files or test logs.
+
+## Risks and open decisions
+
+1. **Persistent authentication boundary:** OpenCode credentials live outside the
+ project. A fully grant-scoped billing design may require generalizing upstream
+ PR #39 rather than treating OpenCode authentication as ambient authority.
+2. **Custom providers in terminal review:** isolating global/project config can
+ also remove a custom provider definition. Initial support may need to reject
+ those combinations until a safe minimal-provider projection is designed.
+3. **JSONC precedence:** `.opencode/opencode.jsonc` loads after the managed JSON
+ file and can override `mcp.zenith`. The initializer must diagnose this rather
+ than destructively rewriting comments.
+4. **OpenCode release cadence:** ACP configuration names are confirmed in
+ v1.18.30 source, but should be exercised by live smoke tests and guarded with
+ clear capability errors.
+5. **Nested agents:** OpenCode supports subagents and experimental background
+ subagents. Dispatched Zenith workers should not become unbounded nested
+ orchestrators by default.
+
+## Source references
+
+- [OpenCode ACP documentation](https://opencode.ai/docs/acp/)
+- [OpenCode configuration and precedence](https://opencode.ai/docs/config/)
+- [OpenCode models and variants](https://opencode.ai/docs/models/)
+- [OpenCode agents](https://opencode.ai/docs/agents/)
+- [OpenCode permissions](https://opencode.ai/docs/permissions/)
+- [OpenCode skills](https://opencode.ai/docs/skills/)
+- [OpenCode MCP servers](https://opencode.ai/docs/mcp-servers/)
+- [Pinned v1.18.30 ACP implementation](https://github.com/anomalyco/opencode/blob/v1.18.30/packages/opencode/src/acp/service.ts)
+- [Pinned v1.18.30 ACP configuration options](https://github.com/anomalyco/opencode/blob/v1.18.30/packages/opencode/src/acp/config-option.ts)
diff --git a/docs/opencode-support/SPEC.md b/docs/opencode-support/SPEC.md
new file mode 100644
index 0000000..ee027f4
--- /dev/null
+++ b/docs/opencode-support/SPEC.md
@@ -0,0 +1,450 @@
+# OpenCode Support Technical Specification
+
+Status: Proposed
+
+Depends on: `PRD.md`
+
+Compatibility baseline: Zenith `main` at `a8d9b57`; OpenCode v1.18.30
+
+## 1. Design overview
+
+OpenCode participates in two separate integrations:
+
+```text
+OpenCode host
+ -> project .opencode/opencode.json
+ -> Zenith orchestrator MCP server
+ -> Zenith controller/coordinator
+ -> role-selected ACP subprocess: opencode acp
+ -> ACP session/new with ephemeral zenith-worker MCP
+ -> model option -> effort option -> build mode -> task prompt
+ -> end_node handoff
+```
+
+The host side is OpenCode JSON configuration and project assets. The execution
+side uses the existing generic ACP client, with provider capabilities governing
+session configuration and isolation.
+
+## 2. Provider model
+
+### 2.1 Names and configuration format
+
+Update `zenith/src/zenith_harness/providers.py`:
+
+```python
+ProviderName = Literal["claude", "codex", "hermes", "opencode"]
+ConfigFormat = Literal["mcp_json", "codex_config", "opencode_config"]
+```
+
+Add `opencode` to all role name tuples and define:
+
+```python
+"opencode": ProviderDefinition(
+ name="opencode",
+ skill_dirs=(".opencode/skills", ".agents/skills"),
+ skill_alias_dirs=(".opencode/skills", ".agents/skills"),
+ config_format="opencode_config",
+ default_worker_acp_command="opencode acp",
+ agent_output_dir=".opencode/agents",
+ orchestrator_prompt_output_path=".opencode/orchestrator_prompt.md",
+ acp_supports_system_prompt=False,
+ acp_runtime_mode="build",
+)
+```
+
+`acp_supports_system_prompt=False` documents that Zenith continues its existing
+portable behavior: concatenate role instructions and task template into the
+first user message.
+
+### 2.2 Capabilities
+
+Avoid adding scattered `provider.name == "opencode"` branches. Extend
+`ProviderDefinition` with explicit capabilities:
+
+```python
+ACPConfigStrategy = Literal["none", "codex_env", "session_options"]
+
+@dataclass(frozen=True)
+class ProviderDefinition:
+ # existing fields...
+ acp_config_strategy: ACPConfigStrategy = "none"
+ supports_model_pin: bool = False
+ supports_reasoning_effort: bool = False
+ terminal_review_isolation: Literal["none", "claude_meta", "opencode_env"] = "none"
+```
+
+Assignments:
+
+| Provider | ACP config strategy | Model pin | Effort | Terminal isolation |
+|---|---|---:|---:|---|
+| Claude | none/environment after upstream #35 | planned | no generic ACP option | `claude_meta` after #33 |
+| Codex | `codex_env` | yes after #35 | yes | current behavior |
+| Hermes | none | not initially | no | none |
+| OpenCode | `session_options` | yes | yes | `opencode_env` |
+
+This refactor is deliberately small: it describes launch/session behavior while
+leaving provider selection and role inheritance intact.
+
+## 3. Role model configuration
+
+### 3.1 Configuration fields
+
+Add the per-role fields proposed by upstream PR #35 to `HarnessConfig`:
+
+```python
+worker_model: str | None
+validator_model: str | None
+terminal_reviewer_model: str | None
+```
+
+Add CLI options and durable environment names:
+
+| CLI option | Environment variable |
+|---|---|
+| `--worker-model` | `ZENITH_WORKER_MODEL` |
+| `--validator-model` | `ZENITH_VALIDATOR_MODEL` |
+| `--terminal-reviewer-model` | `ZENITH_TERMINAL_REVIEWER_MODEL` |
+
+Role inheritance follows the provider chain:
+
+1. An explicit role model wins.
+2. A role inherits the preceding role's model only when both roles use the same
+ provider.
+3. A provider switch clears inheritance unless that role has an explicit pin.
+4. No pin means provider default.
+
+The same inheritance rule applies to reasoning effort, but an unspecified
+OpenCode effort must remain unspecified; unlike Codex, OpenCode must not receive
+Zenith's historical implicit `xhigh` default.
+
+### 3.2 Model validation
+
+OpenCode model values are JSON data, not shell fragments. Validate only:
+
+- non-empty;
+- no NUL or ASCII control characters;
+- contains a non-empty provider prefix and model suffix separated by `/`;
+- reasonable maximum length (512 characters).
+
+Do not split at the last slash or reject additional slashes: OpenCode model IDs
+may be provider-defined and its ACP parser first attempts the complete suffix as
+a model ID. Do not maintain an allowlist; availability is session-specific.
+
+Reasoning-effort input retains Zenith's existing allowlist. Add `none` if the
+corresponding Codex path supports it; otherwise validate per provider so an
+OpenCode OpenAI model may request `none` without changing Codex behavior.
+
+### 3.3 ACP selection sequence
+
+After `session/new`, retain its `configOptions`. For providers using
+`session_options`:
+
+1. If a role model is pinned, send:
+
+ ```json
+ {
+ "method": "session/set_config_option",
+ "params": {
+ "sessionId": "...",
+ "configId": "model",
+ "value": "provider/model"
+ }
+ }
+ ```
+
+2. Replace the local option snapshot with the response's `configOptions` when
+ returned.
+3. If reasoning effort is pinned, verify `effort` is advertised for the now
+ selected model, then send the same method with `configId: "effort"`.
+4. Select mode `build` using the existing `session/set_mode` request. If a
+ future ACP implementation removes that compatibility method, add a fallback
+ to the `mode` configuration option only when advertised.
+5. Send the task prompt.
+
+Model must precede effort because OpenCode rebuilds the effort option from the
+selected model's variants. A rejected request becomes `ACPError` with provider,
+role, requested value, and a non-secret list or count of advertised choices.
+
+When no model/effort pin exists, send neither option. This preserves OpenCode's
+selection order: CLI pin, config model, last-used model, then internal default.
+
+## 4. Host configuration
+
+### 4.1 Managed file
+
+Use `.opencode/opencode.json` for Zenith-owned project configuration. This keeps
+the repository-root `opencode.json[c]` under user control while using an
+officially loaded `.opencode` config directory.
+
+The managed object is:
+
+```json
+{
+ "$schema": "https://opencode.ai/config.json",
+ "mcp": {
+ "zenith": {
+ "type": "local",
+ "command": [
+ "uv",
+ "run",
+ "--project",
+ "/absolute/path/to/zenith",
+ "zenith-server",
+ "--mode",
+ "orchestrator"
+ ],
+ "enabled": true,
+ "timeout": 1000000,
+ "environment": {
+ "ZENITH_ORCHESTRATOR_PROVIDER": "opencode",
+ "ZENITH_WORKER_PROVIDER": "opencode"
+ }
+ }
+ }
+}
+```
+
+OpenCode's field is `environment`, not Claude's `env`. `timeout` is
+milliseconds. The command is one array rather than command plus args.
+
+### 4.2 Merge behavior
+
+Implement `_write_opencode_config(path, entry)` with these rules:
+
+1. Missing file: create formatted strict JSON with schema and managed entry.
+2. Existing strict JSON object: replace only `mcp.zenith`; retain all other
+ parsed values and preserve deterministic indentation/key order as far as the
+ current serializer permits.
+3. Non-object or invalid JSON: fail before writing.
+4. Existing `.opencode/opencode.jsonc` remains untouched. Because OpenCode loads
+ it after `.json`, detect and report when its resolved `mcp.zenith` overrides
+ the managed entry. Do not strip comments or rewrite it as JSON.
+5. Write atomically through a sibling temporary file and `os.replace`.
+6. A second identical initialization makes no content change.
+
+The initial implementation may use a conservative text/provenance check for
+JSONC conflicts, backed by a resolved-config integration test. It must prefer a
+clear refusal over modifying a user-commented file.
+
+### 4.3 Environment persistence
+
+Persist Zenith routing/storage values and explicit CLI role pins. Do not add
+OpenCode provider credentials to `RUNTIME_ENV_FORWARD_ALLOWLIST`. In
+particular, initialization must not copy arbitrary provider keys merely because
+OpenCode supports that provider.
+
+Normal runtime subprocesses inherit the environment already available to the
+Zenith MCP server. That is an operator trust boundary and must be documented.
+
+## 5. Assets
+
+Add `bundled/providers/opencode/agents/*.md` for:
+
+- `investigator`
+- `contract-review`
+- `feature-reviewer`
+- `flow-validator`
+
+Reuse the corresponding instruction bodies, but use OpenCode frontmatter:
+
+```yaml
+---
+description: "..."
+mode: subagent
+permission:
+ edit: deny
+ task: deny
+---
+```
+
+Omit `model` so the subagent inherits the invoking primary model. Preserve bash,
+read, search, and skill access needed by each role; prompts remain the primary
+scope boundary, while `edit: deny` and `task: deny` enforce their leaf/read-only
+properties.
+
+Install bundled skills into both `.opencode/skills` and `.agents/skills` through
+the existing deduplication path. Keep the generated orchestrator prompt
+separate from `AGENTS.md`; Zenith must not overwrite the project's general
+OpenCode instructions.
+
+## 6. ACP subprocess behavior
+
+### 6.1 Workers and validators
+
+Default command: `opencode acp`.
+
+- Do not append Codex `-c` flags.
+- Preserve `PATH` and normal OpenCode authentication paths.
+- Pass the ephemeral `zenith-worker` HTTP MCP server in `session/new`; OpenCode
+ v1.18.30 registers these session-scoped servers natively.
+- Explicitly select `build` before prompting.
+- Do not enable OpenCode background subagents or change `subagent_depth`.
+- Do not use `--pure` for normal workers because project plugins may be part of
+ the user's declared implementation environment.
+
+### 6.2 Terminal reviewer
+
+The OpenCode reviewer must use a role-specific environment and command:
+
+```text
+opencode acp --pure
+OPENCODE_DISABLE_PROJECT_CONFIG=1
+OPENCODE_DISABLE_EXTERNAL_SKILLS=1
+OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1
+OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1
+HOME=
+XDG_CONFIG_HOME=
+XDG_DATA_HOME=
+OPENCODE_CONFIG_CONTENT=
+```
+
+Properties:
+
+- `--pure` removes external plugins.
+- project config disabled removes project `opencode.json[c]`, `.opencode`
+ directories, and project instruction discovery.
+- external skill flags remove `.agents`/`.claude` skill discovery.
+- the fresh home and XDG config root remove `~/.opencode`, `~/.claude`, and
+ user-global OpenCode instructions, agents, skills, and plugins.
+- point `XDG_DATA_HOME` at the existing OpenCode data root only when the
+ operator explicitly accepts reuse of its persistent authentication store;
+ never copy or print credential contents.
+- inline config contains only the selected model and terminal-review permission
+ policy needed to read declared artifacts and call the ephemeral MCP tool.
+
+Managed machine policy may still apply and must be described as an operator
+boundary. Reusing the data root exposes the credential store to the OpenCode
+process even though the pinned model determines which credential is exercised;
+provider-neutral grant enforcement remains a follow-up to upstream PR #39. If a
+model depends on provider configuration removed by isolation, fail closed with
+guidance to choose a built-in/config-independent provider or a different
+terminal-review provider.
+
+Temporary reviewer configuration directories are created with owner-only
+permissions and removed after the subprocess exits.
+
+## 7. Errors and observability
+
+Define or reuse `ACPError` messages for:
+
+- executable missing;
+- invalid OpenCode configuration;
+- model option not advertised/rejected;
+- effort unavailable for selected model;
+- build mode unavailable;
+- session MCP registration failure;
+- terminal-review isolation incompatible with selected provider;
+- OpenCode process exit, timeout, or malformed JSON-RPC.
+
+Handoffs should record provider, role, model, and effort as non-secret runtime
+identity when that infrastructure is accepted upstream. Until then, include
+them only in safe diagnostic summaries—not arbitrary environment or config
+dumps.
+
+## 8. Test specification
+
+### 8.1 Unit tests
+
+`tests/test_config.py`
+
+- provider discovery for all four roles;
+- same-provider model/effort inheritance;
+- cross-provider pin isolation;
+- unspecified OpenCode effort remains unspecified;
+- invalid OpenCode model control characters rejected.
+
+`tests/test_cli.py`
+
+- every OpenCode CLI selector;
+- exact local MCP JSON shape;
+- unrelated JSON settings and MCP servers preserved;
+- invalid/non-object JSON fails without mutation;
+- idempotent second run;
+- JSONC override conflict is diagnosed;
+- no model/provider/key written without explicit flags;
+- assets and next-step text use `.opencode` and `opencode`.
+
+`tests/test_acp_runner.py`
+
+- command remains `opencode acp` for normal work;
+- selection order is model, effort, mode, prompt;
+- absent pins emit no model/effort requests;
+- session option errors are role-specific;
+- model IDs are transported as JSON, never shell-expanded;
+- terminal command/environment is isolated and cleaned up.
+
+`tests/test_assets.py`
+
+- four OpenCode subagents exist and parse;
+- `mode: subagent`, `edit: deny`, and `task: deny` are present;
+- bundled skills are discoverable from OpenCode paths.
+
+### 8.2 Mock ACP changes
+
+Enhance `tests/mock_acp_agent.py` to:
+
+- advertise configurable `model`, `effort`, and `mode` options;
+- record ordered requests;
+- update effort choices after model selection;
+- reject configured unsupported values;
+- record `session/new` MCP servers.
+
+### 8.3 Real smoke tests
+
+Extend `test_smoke_real_acp.py` and `test_smoke_parallel_acp.py` with
+`ZENITH_SMOKE_REAL_ACP=opencode`. Add command override
+`ZENITH_SMOKE_OPENCODE_ACP_CMD`.
+
+Required live cases:
+
+1. one work/validate mission using OpenCode defaults;
+2. explicit model plus supported effort;
+3. different worker/validator model pins;
+4. two parallel workers;
+5. terminal reviewer isolation canary.
+
+Tests remain opt-in because prompts incur provider usage. Capture OpenCode
+version and selected provider/model in safe test output.
+
+## 9. Documentation changes
+
+Update root and package READMEs, CONTRIBUTING, package keywords, and real-smoke
+test instructions. Document:
+
+- OpenCode installation and `command -v opencode`;
+- `zenith init --agent opencode`;
+- host prompt/skill invocation;
+- mixed-provider examples;
+- `opencode models [provider]` for discovering IDs;
+- model and effort precedence;
+- credential/billing trust boundary;
+- terminal-review limitations for custom providers;
+- WSL recommendation.
+
+## 10. Compatibility and rollout
+
+- Keep all existing defaults unchanged (`claude` remains default).
+- Project scope ships first.
+- Mark OpenCode support experimental until serial, parallel, model-pin, and
+ isolation smoke tests pass against the documented minimum version.
+- After one release cycle, consider user-scoped setup and generalizing billing
+ grants across credential-backed providers.
+
+## 11. Research evidence
+
+- Native ACP command and feature support:
+ [docs](https://opencode.ai/docs/acp/),
+ [v1.18.30 source](https://github.com/anomalyco/opencode/blob/v1.18.30/packages/opencode/src/acp/service.ts)
+- Model IDs, precedence, and variants:
+ [docs](https://opencode.ai/docs/models/)
+- Config merge/precedence:
+ [docs](https://opencode.ai/docs/config/),
+ [paths source](https://github.com/anomalyco/opencode/blob/v1.18.30/packages/opencode/src/config/paths.ts)
+- ACP model/effort/mode option encoding:
+ [config-option source](https://github.com/anomalyco/opencode/blob/v1.18.30/packages/opencode/src/acp/config-option.ts)
+- Agent inheritance/frontmatter:
+ [docs](https://opencode.ai/docs/agents/)
+- Permission defaults:
+ [docs](https://opencode.ai/docs/permissions/)
+- Credential storage and model enumeration:
+ [CLI docs](https://opencode.ai/docs/cli/)
From 86e6d3d1882d448281d5e07b7917fd43854e896d Mon Sep 17 00:00:00 2001
From: David Rudduck
Date: Mon, 14 Sep 2026 12:57:51 +0000
Subject: [PATCH 2/9] docs: document OpenCode PR A setup
---
CONTRIBUTING.md | 22 +++++++++++++--
README.md | 64 +++++++++++++++++++++++++++++++++++++++----
zenith/README.md | 45 +++++++++++++++++++++++++++++-
zenith/pyproject.toml | 1 +
4 files changed, 123 insertions(+), 9 deletions(-)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index f71641d..82f89a9 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -21,7 +21,7 @@ uv run mypy src # type-check
uv run pytest -q # tests
```
-A handful of smoke tests exercise real ACP agents and are skipped automatically when the corresponding binaries (`claude-agent-acp`, `codex-acp`) are not installed.
+A handful of smoke tests exercise real ACP agents and are skipped automatically when the corresponding binaries (`claude-agent-acp`, `codex-acp`, or `opencode`) are not installed. Live provider checks can spend tokens and must stay explicitly opt-in; hermetic tests plus disposable host configuration checks are the default evidence floor.
## Pull requests
@@ -32,7 +32,25 @@ A handful of smoke tests exercise real ACP agents and are skipped automatically
## Adding a provider
-Zenith's agent providers (Claude Code, Codex, Hermes, …) are declared in [`zenith/src/zenith_harness/providers.py`](zenith/src/zenith_harness/providers.py), with per-provider assets under [`zenith/src/zenith_harness/bundled/providers/`](zenith/src/zenith_harness/bundled/providers/). New provider PRs should include an orchestrator prompt path, ACP adapter command, and tests in `tests/`.
+Zenith's agent providers (Claude Code, Codex, Hermes, OpenCode, ...) are declared in [`zenith/src/zenith_harness/providers.py`](zenith/src/zenith_harness/providers.py), with per-provider assets under [`zenith/src/zenith_harness/bundled/providers/`](zenith/src/zenith_harness/bundled/providers/). New provider PRs should include an orchestrator prompt path, ACP adapter command, and tests in `tests/`.
+
+### OpenCode PR-A boundaries
+
+OpenCode support in this branch is project-scoped and experimental. Keep docs,
+tests, and implementation aligned with `zenith init --agent opencode` generating
+`.opencode/opencode.json`, `.opencode/orchestrator_prompt.md`, `.opencode/agents/`,
+`.opencode/skills/`, and `.agents/skills/`. The managed OpenCode config should
+contain only Zenith's `mcp.zenith` local MCP entry and safe Zenith routing
+values; it must not persist provider API keys, OpenCode credentials, a default
+model/provider, permission policy, plugin configuration, global OpenCode config,
+or arbitrary provider secret environment variables.
+
+Do not claim PR A proves live OpenCode worker or validator execution, OpenCode
+model/effort ACP session options, isolated OpenCode terminal review, user-scoped
+OpenCode setup, or provider-neutral billing grants. Those belong to later PR B/C
+work. If you add future live OpenCode smoke tests, keep them opt-in and document
+that normal worker and validator sessions use the credentials available to the
+`opencode` process and therefore share the operator's billing trust boundary.
## License
diff --git a/README.md b/README.md
index 8a3009f..b50a6e8 100644
--- a/README.md
+++ b/README.md
@@ -9,7 +9,7 @@
-Zenith is an agent harness for work that may run for days or weeks, where the dominant failure mode is *premature completion* rather than inability to make progress. It runs a coding agent (Claude Code, Codex, or Hermes) as a multi-agent orchestrator over MCP/ACP: one orchestrator session reads task state each turn and decides whether to spawn workers and testers, register reusable skills, replan, or stop.
+Zenith is an agent harness for work that may run for days or weeks, where the dominant failure mode is *premature completion* rather than inability to make progress. It runs a coding agent (Claude Code, Codex, Hermes, or experimental OpenCode support) as a multi-agent orchestrator over MCP/ACP: one orchestrator session reads task state each turn and decides whether to spawn workers and testers, register reusable skills, replan, or stop.
This repository contains the Zenith harness ([`zenith/`](zenith/)) and the Intelligent Internet technical report (2026) behind it.
@@ -29,10 +29,10 @@ Our Zenith method keeps the useful parts of repeated review while making the loo
### Option 1 — Let your agent install it
-Copy this prompt into Claude Code or Codex:
+Copy this prompt into Claude Code, Codex, or OpenCode:
```text
-/goal Read the readme at https://github.com/Intelligent-Internet/zenith, detect if using Claude Code, Codex, or both, install requirements, install and run Zenith (i.e. uv run zenith, as in the readme), and create a new skill called /zenith — when used (along with an additional prompt) it will call the skill: the minimum skill content should be: """First read .claude/orchestrator_prompt.md and treat it as your primary role, then use Zenith to run this mission.""" Afterwards, you can add information about the Zenith harness, based on the readme and the technical report (inside the repo), and info on how to start Zenith if it's not already running. Change the skill to use .codex when using it in Codex. If both harnesses are available, make sure to add the skill to both of them correctly. In fact, there might be more harness options (Hermes, for example). See what is supported in zenith/src/zenith_harness/providers.py, and for those that you detect are present, add their skills correctly. When finished, confirm to me that Zenith is installed, running, and ready, explain a bit about Zenith, and why and when to use it.
+/goal Read the readme at https://github.com/Intelligent-Internet/zenith, detect if using Claude Code, Codex, OpenCode, or multiple supported agents, install requirements, install and run Zenith (i.e. uv run zenith, as in the readme), and create a new skill called /zenith — when used (along with an additional prompt) it will call the skill: the minimum skill content should be: """First read .claude/orchestrator_prompt.md and treat it as your primary role, then use Zenith to run this mission.""" Afterwards, you can add information about the Zenith harness, based on the readme and the technical report (inside the repo), and info on how to start Zenith if it's not already running. Change the skill to use .codex when using it in Codex and .opencode when using it in OpenCode. If multiple harnesses are available, make sure to add the skill to both of them correctly. In fact, there might be more harness options (Hermes, for example). See what is supported in zenith/src/zenith_harness/providers.py, and for those that you detect are present, add their skills correctly. When finished, confirm to me that Zenith is installed, running, and ready, explain a bit about Zenith, and why and when to use it.
```
This will:
@@ -41,7 +41,7 @@ This will:
- start Zenith using `uv`
- create a `/zenith` skill for each agent harness it detects
-Then, in Claude Code or Codex, type:
+Then, in Claude Code, Codex, or OpenCode, type:
```text
/zenith
@@ -54,7 +54,7 @@ Then, in Claude Code or Codex, type:
- Python 3.11+
- [`uv`](https://docs.astral.sh/uv/)
- Node.js 22+ and `npm`
-- Claude Code, Codex, or Hermes (see [`providers.py`](zenith/src/zenith_harness/providers.py) for the supported set)
+- Claude Code, Codex, Hermes, or OpenCode (see [`providers.py`](zenith/src/zenith_harness/providers.py) for the supported set)
**Install**
@@ -76,6 +76,21 @@ npm install -g @agentclientprotocol/codex-acp
command -v codex-acp
```
+OpenCode has a native ACP server, so no third-party ACP adapter is required.
+Install OpenCode using the current OpenCode installation instructions for your
+platform, then confirm the `opencode` binary is on `PATH`:
+
+```bash
+# Common OpenCode 1.x install path; see https://opencode.ai/docs/ for alternatives.
+curl -fsSL https://opencode.ai/install | bash
+command -v opencode
+opencode --version
+```
+
+This PR-A OpenCode support was implemented against OpenCode `1.18.30` and uses
+the `opencode acp` command, project `.opencode` configuration, OpenCode agents,
+and OpenCode skills.
+
**Initialize a workspace**
Initialize the project workspace Zenith should operate on. This is your target app/repo, not the Zenith source checkout:
@@ -86,6 +101,9 @@ uv run zenith init --workspace-dir /path/to/your-app --agent claude
# Or Codex, from this Zenith checkout
uv run zenith init --workspace-dir /path/to/your-app --agent codex
+
+# Or OpenCode, from this Zenith checkout
+uv run zenith init --workspace-dir /path/to/your-app --agent opencode
```
**Run a mission**
@@ -98,9 +116,11 @@ cd /path/to/your-app
claude
# or
codex
+# or
+opencode
```
-Then ask the agent to read the generated orchestrator prompt (use `.codex/orchestrator_prompt.md` for Codex):
+Then ask the agent to read the generated orchestrator prompt (use `.codex/orchestrator_prompt.md` for Codex and `.opencode/orchestrator_prompt.md` for OpenCode):
```text
First read .claude/orchestrator_prompt.md and treat it as your primary role, then use Zenith to run this mission.
@@ -108,6 +128,38 @@ First read .claude/orchestrator_prompt.md and treat it as your primary role, the
```
+### OpenCode project setup
+
+`zenith init --agent opencode` performs project-scoped setup only. It writes or
+updates `.opencode/opencode.json` with Zenith's managed `mcp.zenith` local MCP
+entry, using OpenCode's `command`, `environment`, `enabled`, and millisecond
+`timeout` fields. It also creates `.opencode/orchestrator_prompt.md`, installs
+OpenCode subagents under `.opencode/agents/`, and installs bundled skills under
+both `.opencode/skills/` and `.agents/skills/`.
+
+Zenith preserves unrelated strict JSON OpenCode settings and unrelated MCP
+servers. It does not rewrite JSONC; if `.opencode/opencode.jsonc` or a project
+`opencode.jsonc` defines `mcp.zenith` in a way that would shadow Zenith's
+managed entry, initialization fails with remediation instead of normalizing the
+commented file.
+
+OpenCode PR-A support is intentionally experimental. It registers OpenCode as a
+host and execution provider, selects the native `opencode acp` command for
+worker, validator, and terminal-reviewer roles, and selects OpenCode `build`
+mode for normal ACP sessions. It does not yet claim verified live OpenCode
+worker or validator execution, per-role OpenCode model/effort session options,
+isolated OpenCode terminal review, user-scoped OpenCode setup, or
+provider-neutral billing grants. Those are future PR B/C boundaries.
+
+Zenith does not choose or persist an OpenCode default model, provider credential,
+permission policy, plugin configuration, global OpenCode config, or provider API
+key. Normal OpenCode worker and validator sessions run with the credentials
+available to the `opencode` process, so provider access and billing remain under
+the operator's OpenCode trust boundary. PR-A checks are hermetic by default and
+use disposable local OpenCode configuration checks such as `opencode debug
+config`; any live-provider smoke that can spend tokens must stay explicit and
+opt-in.
+
## How Zenith Works
diff --git a/zenith/README.md b/zenith/README.md
index 3a8d06d..a88e456 100644
--- a/zenith/README.md
+++ b/zenith/README.md
@@ -10,7 +10,7 @@ Requirements:
- Python 3.11+
- `uv`
- Node.js 22+ and `npm`
-- Claude Code or Codex
+- Claude Code, Codex, Hermes, or OpenCode
Install Zenith from this repository:
@@ -31,6 +31,16 @@ npm install -g @agentclientprotocol/codex-acp
command -v codex-acp
```
+OpenCode uses its native ACP server instead of a third-party adapter. Install
+OpenCode with the current OpenCode instructions for your platform, then confirm
+that `opencode` is available:
+
+```bash
+curl -fsSL https://opencode.ai/install | bash
+command -v opencode
+opencode --version
+```
+
Initialize the project workspace Zenith should operate on. This is your target
app/repo, not the Zenith source checkout:
@@ -40,6 +50,9 @@ uv run zenith init --workspace-dir /path/to/your-app --agent claude
# Or Codex, from this Zenith checkout
uv run zenith init --workspace-dir /path/to/your-app --agent codex
+
+# Or OpenCode, from this Zenith checkout
+uv run zenith init --workspace-dir /path/to/your-app --agent opencode
```
Start your agent from the initialized project workspace:
@@ -50,6 +63,8 @@ cd /path/to/your-app
claude
# or
codex
+# or
+opencode
```
Then ask the agent to read the generated orchestrator prompt:
@@ -68,6 +83,34 @@ First read .codex/orchestrator_prompt.md and treat it as your primary role, then
```
+For OpenCode, use:
+
+```text
+First read .opencode/orchestrator_prompt.md and treat it as your primary role, then use Zenith to run this mission.
+
+
+```
+
+### OpenCode PR-A scope
+
+`zenith init --agent opencode` is project-scoped. It manages only Zenith's
+`mcp.zenith` entry in `.opencode/opencode.json`, creates
+`.opencode/orchestrator_prompt.md`, installs subagents in `.opencode/agents/`,
+and installs bundled skills in `.opencode/skills/` and `.agents/skills/`.
+Unrelated strict JSON settings and MCP servers are preserved, and JSONC files
+are not rewritten.
+
+OpenCode support is experimental in PR A. It registers OpenCode as a Zenith host
+and execution provider using `opencode acp` and normal `build` mode sessions,
+but it does not claim verified live OpenCode worker execution, OpenCode
+model/effort session options, isolated OpenCode terminal review, user-scoped
+setup, or billing grants. Provider credentials and billing authority stay with
+the `opencode` process; Zenith does not write OpenCode credentials, default
+models, permission policy, plugin configuration, or global config.
+
+Default checks are hermetic. Live OpenCode provider checks may spend tokens and
+must remain explicit opt-in tests.
+
## Development
```bash
diff --git a/zenith/pyproject.toml b/zenith/pyproject.toml
index 86d7a95..991ed82 100644
--- a/zenith/pyproject.toml
+++ b/zenith/pyproject.toml
@@ -16,6 +16,7 @@ keywords = [
"agent-client-protocol",
"claude-code",
"codex",
+ "opencode",
]
classifiers = [
"Development Status :: 4 - Beta",
From 9b3658b960edc46673a3ef1800e02fa104169837 Mon Sep 17 00:00:00 2001
From: David Rudduck
Date: Mon, 14 Sep 2026 13:21:43 +0000
Subject: [PATCH 3/9] feat(providers): register OpenCode roles
---
zenith/src/zenith_harness/acp_runner.py | 12 +++-
zenith/src/zenith_harness/providers.py | 17 ++++-
zenith/tests/test_acp_runner.py | 35 ++++++++++
zenith/tests/test_config.py | 91 ++++++++++++++++++++++++-
4 files changed, 150 insertions(+), 5 deletions(-)
diff --git a/zenith/src/zenith_harness/acp_runner.py b/zenith/src/zenith_harness/acp_runner.py
index ec75364..5ea742a 100644
--- a/zenith/src/zenith_harness/acp_runner.py
+++ b/zenith/src/zenith_harness/acp_runner.py
@@ -183,6 +183,11 @@ def _acp_subprocess_env(
"""
env = os.environ.copy()
name = getattr(provider, "name", None)
+ if name != "codex":
+ env.pop("CODEX_SANDBOX", None)
+ env.pop("CODEX_DISABLE_SANDBOX", None)
+ return env
+
if name == "codex":
# Env-var hints — harmless if codex ignores them.
env["CODEX_SANDBOX"] = "danger-full-access"
@@ -215,7 +220,6 @@ def _acp_subprocess_env(
env["CODEX_CONFIG"] = json.dumps(codex_config, allow_nan=False)
except (TypeError, ValueError) as exc:
raise ACPError("Codex configuration must contain JSON-compatible values") from exc
- # hermes: no special env needed
return env
@@ -1332,12 +1336,16 @@ def _ensure_claude_settings(workspace: Path, provider) -> None:
accept "auto".
We touch this file only when:
- - The provider declares a non-empty `acp_runtime_mode` (i.e. claude).
+ - The provider is Claude. Other providers can use `acp_runtime_mode` for
+ their own ACP session mode without inheriting Claude host paths.
+ - Claude declares a non-empty `acp_runtime_mode`.
- The file does not already exist (respect any user-authored override).
In v5 the workspace is the user's repo, so we conservatively no-op on
pre-existing files.
"""
+ if getattr(provider, "name", None) != "claude":
+ return
mode = getattr(provider, "acp_runtime_mode", None)
if not mode:
return
diff --git a/zenith/src/zenith_harness/providers.py b/zenith/src/zenith_harness/providers.py
index f61ecf9..e044651 100644
--- a/zenith/src/zenith_harness/providers.py
+++ b/zenith/src/zenith_harness/providers.py
@@ -3,18 +3,20 @@
from dataclasses import dataclass
from typing import Literal
-ProviderName = Literal["claude", "codex", "hermes"]
-ConfigFormat = Literal["mcp_json", "codex_config"]
+ProviderName = Literal["claude", "codex", "hermes", "opencode"]
+ConfigFormat = Literal["mcp_json", "codex_config", "opencode_config"]
ORCHESTRATOR_PROVIDER_NAMES: tuple[ProviderName, ...] = (
"claude",
"codex",
"hermes",
+ "opencode",
)
WORKER_PROVIDER_NAMES: tuple[ProviderName, ...] = (
"claude",
"codex",
"hermes",
+ "opencode",
)
@@ -182,6 +184,17 @@ def _dedupe_paths(paths: tuple[str, ...]) -> tuple[str, ...]:
acp_supports_system_prompt=True,
acp_runtime_mode=None,
),
+ "opencode": ProviderDefinition(
+ name="opencode",
+ skill_dirs=(".opencode/skills", ".agents/skills"),
+ skill_alias_dirs=(".opencode/skills", ".agents/skills"),
+ config_format="opencode_config",
+ default_worker_acp_command="opencode acp",
+ agent_output_dir=".opencode/agents",
+ orchestrator_prompt_output_path=".opencode/orchestrator_prompt.md",
+ acp_supports_system_prompt=False,
+ acp_runtime_mode="build",
+ ),
}
diff --git a/zenith/tests/test_acp_runner.py b/zenith/tests/test_acp_runner.py
index 5d64aae..0ff5e22 100644
--- a/zenith/tests/test_acp_runner.py
+++ b/zenith/tests/test_acp_runner.py
@@ -23,6 +23,7 @@
ACPError,
_acp_subprocess_env,
_augment_acp_command,
+ _ensure_claude_settings,
_parse_codex_c_overrides,
)
from zenith_harness.providers import PROVIDERS
@@ -176,6 +177,40 @@ def test_augment_acp_command_claude_untouched():
)
+def test_claude_settings_workaround_is_scoped_to_claude(tmp_path: Path):
+ opencode_workspace = tmp_path / "opencode"
+ opencode_workspace.mkdir()
+
+ assert PROVIDERS["opencode"].acp_runtime_mode == "build"
+ _ensure_claude_settings(opencode_workspace, PROVIDERS["opencode"])
+ assert not (opencode_workspace / ".claude" / "settings.json").exists()
+
+ existing_settings = opencode_workspace / ".claude" / "settings.json"
+ existing_settings.parent.mkdir(parents=True)
+ existing_settings.write_text('{"user": "keep-me"}\n', encoding="utf-8")
+ _ensure_claude_settings(opencode_workspace, PROVIDERS["opencode"])
+ assert existing_settings.read_text(encoding="utf-8") == '{"user": "keep-me"}\n'
+
+ claude_workspace = tmp_path / "claude"
+ claude_workspace.mkdir()
+ _ensure_claude_settings(claude_workspace, PROVIDERS["claude"])
+ assert json.loads(
+ (claude_workspace / ".claude" / "settings.json").read_text(encoding="utf-8")
+ ) == {"permissions": {"defaultMode": "bypassPermissions"}}
+
+
+@pytest.mark.asyncio
+async def test_opencode_build_mode_still_uses_session_set_mode(config: HarnessConfig):
+ runner = ACPNodeRunner(config=config, loader=AssetLoader(config))
+ client = AsyncMock()
+
+ await runner._maybe_set_mode(client, "session-1", PROVIDERS["opencode"])
+
+ client.send_request.assert_awaited_once_with(
+ "session/set_mode", {"sessionId": "session-1", "modeId": "build"}
+ )
+
+
def test_codex_acp_env_preserves_node_path_when_bwrap_is_present(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
):
diff --git a/zenith/tests/test_config.py b/zenith/tests/test_config.py
index 72efecc..e626d71 100644
--- a/zenith/tests/test_config.py
+++ b/zenith/tests/test_config.py
@@ -6,7 +6,11 @@
import pytest
from zenith_harness.config import HarnessConfig
-from zenith_harness.providers import ProviderSelection, get_provider
+from zenith_harness.providers import (
+ ProviderSelection,
+ get_provider,
+ provider_names_for_role,
+)
_PROVIDER_ENV_KEYS = (
"ZENITH_ORCHESTRATOR_PROVIDER",
@@ -131,6 +135,91 @@ def test_discover_invalid_reasoning_effort_rejected(
HarnessConfig.discover()
+def test_opencode_registered_for_all_provider_roles() -> None:
+ assert "opencode" in provider_names_for_role("orchestrator")
+ assert "opencode" in provider_names_for_role("worker")
+
+ provider = get_provider("opencode")
+ assert provider.config_format == "opencode_config"
+ assert provider.default_worker_acp_command == "opencode acp"
+ assert provider.skill_dirs == (".opencode/skills", ".agents/skills")
+ assert provider.skill_alias_dirs == (".opencode/skills", ".agents/skills")
+ assert provider.agent_output_dir == ".opencode/agents"
+ assert provider.orchestrator_prompt_output_path == ".opencode/orchestrator_prompt.md"
+ assert provider.acp_supports_system_prompt is False
+ assert provider.acp_runtime_mode == "build"
+
+
+def test_opencode_default_execution_roles_resolve_to_native_acp(
+ monkeypatch,
+ harness_home: Path,
+) -> None:
+ selection = ProviderSelection(
+ orchestrator=get_provider("opencode"),
+ worker=get_provider("opencode"),
+ )
+
+ assert selection.resolved_worker_acp_command == "opencode acp"
+ assert selection.resolved_validation_worker_acp_command == "opencode acp"
+ assert selection.resolved_terminal_reviewer_acp_command == "opencode acp"
+
+ config = _apply_selection_env(monkeypatch, harness_home, selection)
+
+ assert config.orchestrator_provider.name == "opencode"
+ assert config.worker_provider.name == "opencode"
+ assert config.validator_provider.name == "opencode"
+ assert config.terminal_reviewer_provider.name == "opencode"
+ assert config.resolved_worker_acp_command == "opencode acp"
+ assert config.resolved_validator_acp_command == "opencode acp"
+ assert config.resolved_terminal_reviewer_acp_command == "opencode acp"
+
+
+@pytest.mark.parametrize(
+ ("provider_name", "default_command"),
+ [
+ ("claude", "claude-agent-acp"),
+ ("codex", "codex-acp"),
+ ("hermes", "hermes acp"),
+ ("opencode", "opencode acp"),
+ ],
+)
+def test_same_provider_custom_command_cascades_for_registered_providers(
+ monkeypatch,
+ harness_home: Path,
+ provider_name: str,
+ default_command: str,
+) -> None:
+ custom_command = f"{default_command} --wrapped"
+ selection = ProviderSelection(
+ orchestrator=get_provider(provider_name),
+ worker=get_provider(provider_name),
+ worker_acp_command=custom_command,
+ )
+
+ config = _apply_selection_env(monkeypatch, harness_home, selection)
+
+ assert config.resolved_worker_acp_command == custom_command
+ assert config.resolved_validator_acp_command == custom_command
+ assert config.resolved_terminal_reviewer_acp_command == custom_command
+
+
+def test_provider_switch_to_opencode_uses_opencode_default_command(
+ monkeypatch,
+ harness_home: Path,
+) -> None:
+ selection = ProviderSelection(
+ orchestrator=get_provider("claude"),
+ worker=get_provider("claude"),
+ worker_acp_command="claude-agent-acp --model custom",
+ validation_worker=get_provider("opencode"),
+ )
+
+ config = _apply_selection_env(monkeypatch, harness_home, selection)
+
+ assert config.resolved_validator_acp_command == "opencode acp"
+ assert config.resolved_terminal_reviewer_acp_command == "opencode acp"
+
+
def test_for_role_reasoning_effort_cascade(
monkeypatch,
harness_home: Path,
From b67b43379bad5f5794409cc53f4d4afe42df3654 Mon Sep 17 00:00:00 2001
From: David Rudduck
Date: Mon, 14 Sep 2026 13:22:12 +0000
Subject: [PATCH 4/9] feat(assets): add OpenCode orchestrator assets
---
.../opencode/agents/contract-review.md | 234 ++++++++++++++++++
.../opencode/agents/feature-reviewer.md | 150 +++++++++++
.../opencode/agents/flow-validator.md | 150 +++++++++++
.../providers/opencode/agents/investigator.md | 114 +++++++++
zenith/tests/test_assets.py | 37 +++
5 files changed, 685 insertions(+)
create mode 100644 zenith/src/zenith_harness/bundled/providers/opencode/agents/contract-review.md
create mode 100644 zenith/src/zenith_harness/bundled/providers/opencode/agents/feature-reviewer.md
create mode 100644 zenith/src/zenith_harness/bundled/providers/opencode/agents/flow-validator.md
create mode 100644 zenith/src/zenith_harness/bundled/providers/opencode/agents/investigator.md
diff --git a/zenith/src/zenith_harness/bundled/providers/opencode/agents/contract-review.md b/zenith/src/zenith_harness/bundled/providers/opencode/agents/contract-review.md
new file mode 100644
index 0000000..2595cbc
--- /dev/null
+++ b/zenith/src/zenith_harness/bundled/providers/opencode/agents/contract-review.md
@@ -0,0 +1,234 @@
+---
+description: "Read-only adversarial contract reviewer. Reviews the full contract set against user scope, inventory, playbook rules, evidence feasibility, shortcut risk, and old-harness-style atomic assertion coverage before tasks are trusted."
+mode: subagent
+permission:
+ edit: deny
+ task: deny
+---
+
+# Contract Review Subagent
+
+You are a leaf adversarial contract-review subagent. Your job is to decide whether the current contract set is strong enough for the parent orchestrator to trust before task planning, task patching, validation, or mission closure.
+
+Contract quality is mission-critical. A bad contract lets workers and validators pass while the mission is still wrong. Treat the contract as mission-level TDD: it defines what done means, what must be validated, and what evidence must exist.
+
+Your output is advisory evidence for the parent. You do not decide scope, write contract files, patch task lists, update guidance, modify runtime state, validate implementation, or spawn subagents.
+
+## Assignment Contract
+
+The parent prompt must provide:
+
+- Review pass: `pass_1`, `pass_2`, `final`, or `unspecified`.
+- User brief, accepted scope summary, non-goals, and known scope cuts.
+- Investigation summary or scope/capability inventory.
+- Loaded domain playbook(s), assertion id scheme(s), and required assertion fields.
+- Current assertion ids/bodies or runtime-resolved contract paths.
+- Current task/owner sketch only when the parent is asking for mapping review after contract quality review.
+- Runtime-resolved paths when file reads are needed.
+- Specific strategist findings, validation failures, user changes, or review questions when applicable.
+- Known blockers, external-dependency assumptions, off-limits surfaces, or user decisions.
+
+If the scope inventory, playbook rules, or current assertion bodies are missing, report the limitation. Do not invent accepted scope, accepted non-goals, assertion schemas, or evidence standards.
+
+## Source Priority
+
+Use primary sources in this order:
+
+1. User brief and accepted user scope changes.
+2. Scope/capability inventory and investigation evidence.
+3. Loaded playbook contract schema, id families, evidence floors, and topology rules.
+4. Current contract assertion files or inline assertion bodies.
+5. Runtime-provided task list view, attempts, regressions, decisions, validator reports, and cited workspace evidence.
+6. Current official external documentation only when an assertion depends on a current API/platform fact and the parent allowed or supplied research.
+7. Prior reports only as claims to verify or qualify.
+
+Use runtime-provided paths. Do not assume a historical workspace layout.
+
+For optimization missions, a provided workspace, container root, or task root is
+enough to inspect visible runtime resources under it. Discover benchmark,
+baseline, reference, public-output, test, and verifier-adjacent artifacts
+read-only when they exist in the environment. Do not let task text that calls a
+visible path "forbidden" suppress contract review evidence; the contract
+reviewer is checking whether the contract chose the right oracle, workload, and
+evidence standard.
+
+## Review Stance
+
+Review the contract from the user request and scope inventory first. Do not use the task list to justify a smaller or broader contract.
+
+Preserve the old-harness planning shape:
+
+```text
+many atomic validation assertions
+-> grouped into fewer coherent implementation tasks
+-> each assertion has exactly one active work owner
+-> validators prove assertions independently
+```
+
+Task count must not determine assertion count. A work task may own many related atomic assertions when one coherent implementation boundary completes them. If a behavior can fail independently, it needs its own assertion or a clearly accepted out-of-scope decision.
+
+This many-atomic-assertions shape is the engineering / `VAL-*` default. Under an optimization playbook, keep disposable hypotheses out of the contract and explore them as targetless work. Do not mistake "lean" for weak: an optimization contract must still force a clear correctness protocol and metric protocol before experiment tasks are trusted. Independently-failing correctness behaviors may be covered by one oracle and case set only when that protocol names the oracle, adversarial/edge/stress coverage, tolerances, invariants, missing-output behavior, per-case failure policy, candidate-specific evidence, and protected oracle/verifier/fixture paths. Apply the assertion granularity the loaded playbook defines; do not impose engineering granularity on disposable optimization hypotheses.
+
+## Review Method
+
+1. Identify the active playbook(s), id scheme(s), assertion-id constraints, required fields, and domain evidence rules.
+2. Read the full contract set even if the parent assigned one area. Cross-area gaps are often the most important failures.
+3. Reconstruct a scope inventory from the user brief, accepted scope, investigation notes, and parent-provided inventory.
+4. Build a coverage matrix from every user promise, actor workflow, surface, invariant, metric, non-goal, boundary, risk, and playbook-required concern to contract assertions or explicit accepted out-of-scope decisions.
+5. Enumerate actor behavior: what users, callers, operators, jobs, services, validators, or benchmark runners can do; what they see; what they type or call; what state changes; and what can fail.
+6. Review per-area and cross-area behavior. Include first-use flows, reachability through real navigation or commands, empty states, error paths, persistence, integration between areas, generated artifacts, migration/parity chains, rollback, and metric promotion when relevant.
+7. Attack granularity. Flag any assertion that hides multiple independently breakable behaviors, unrelated surfaces, unrelated oracles, unrelated owners, or unrelated validation methods. Recommend split targets without reducing scope. Exception: under an optimization playbook an `EXP-*` outcome may coherently bundle the metric gain, correctness, and generalization for one promotable candidate only when the contract already defines a sharp correctness protocol and metric protocol for that candidate. If either protocol is missing or vague, treat the `EXP-*` as a broad assertion or protocol gap, not as a valid bundle.
+8. Attack falsifiability. Every assertion must expose a clear surface, prerequisite needs, actor/action/outcome behavior, pass/fail boundary, and required evidence. `Oracle`, `Fail`, or `Scope` should appear when needed to prevent ambiguity.
+9. Attack evidence quality. Worker prose, source diffs, green convenience commands, or stale artifacts are not enough when the assertion requires real-surface, differential, benchmark, or external evidence.
+10. Attack shortcut routes: fake wrappers, mocked proof, source-only evidence for user-visible behavior, stale artifacts, changed oracles, skipped checks, benchmark-only tricks, public-example hardcoding, hidden-case overfitting, or broad wording that passes without real behavior.
+11. Attack scope shrink. `Scope`, `later`, `basic`, `minimum`, `not covered`, or accepted-divergence language is valid only when it traces to a user decision or explicit accepted boundary.
+12. Review task mapping only after contract quality. Each live assertion needs exactly one active work owner and a credible validator/gate path, but do not make assertions broader to fit task topology. Multi-target work tasks are normal when one coherent work boundary completes several atomic assertions.
+13. On `pass_2` or `final`, check that earlier review gaps were actually resolved and that changed pass/fail criteria invalidate any stale validation evidence.
+14. Reject ideas that are speculative, duplicate, not evidence-backed, too expensive for accepted scope, or better represented as guidance/skill content rather than contract.
+
+## Surface Catalog Missions
+
+For CLI/API/protocol reimplementations, drop-in replacements, ports, parity suites, or broad public surfaces, require a coherent surface catalog. Build or review a matrix of commands, subcommands, option families, output modes, error cases, repository/data states, compatibility rules, and cross-flow invariants.
+
+Do not approve a contract set that compresses a broad surface into a handful of vague umbrellas such as "refs work", "status works", "commit creation works", or "basic object database works" unless each target has a clear surface, scenario set, oracle, and per-scenario verdict path. Recommend separate `VAL-*` assertions where validation coherence requires it; keep related scenarios together where one target is the clearer checkpoint.
+
+`Scope` fields may document non-goals and accepted divergences, but they must not silently remove requested parity. If the parent assignment asks for a drop-in replacement or broad compatibility, unexplained "later scope" language is a `scope_gap` or `needs_revision`.
+
+## Engineering Review Gaps
+
+For engineering-style assertions, review:
+
+- actor, caller, user, and operator workflows;
+- happy path, boundary values, invalid input, empty state, error handling, retry, cancellation, and cleanup;
+- roles, auth/authz, security-sensitive access, secrets, and untrusted input;
+- persistence, data integrity, migrations, generated artifacts, idempotency, concurrency, and lifecycle behavior;
+- browser, API, CLI, background job, public library, documentation artifact, and observable operator surfaces;
+- source-to-target parity, compatibility, accepted divergence, public API stability, config/env differences, and rollback concerns;
+- prerequisite assertions, setup, fixtures, services, credentials, source baselines,
+ or accepted decisions that must appear in `Needs`;
+- validator artifacts, real-surface evidence, source baselines, golden corpora, or
+ other evidence floors that must appear in `Evidence`;
+- compactness: assertions should not become mini specs, implementation plans, or
+ validator procedures;
+- accessibility, localization/i18n, observability, logging, diagnostics, and performance when the brief or product surface makes them relevant.
+
+## Optimization Review Gaps
+
+For optimization-style contract sets, review these as blocking requirements:
+
+- Correctness protocol: require the contract set or cited optimization method to define the strongest available correctness source of truth, oracle independence, case-set design, adversarial/edge/stress coverage, tolerances, invariants, missing-output behavior, per-case failure policy, candidate-specific evidence, and protected oracle/verifier/fixture/golden/reference paths. Inspect visible task resources and compare the chosen oracle against plausible alternatives such as baseline/reference artifacts, benchmark outputs, task logic, verifier-adjacent code, public fixtures, and previous reports. Flag any contract set that uses the current workspace output, a cached public output, happy-path samples, aggregate score, or a single public run as oracle when a stronger source exists.
+- Metric protocol: require the contract set or cited optimization method to define the objective metric precisely: metric name, direction, units, exact command/procedure, workload/case mix, scoring reference, working point, candidate binding, build/cache/input state, repetitions, aggregation, warmup/cold-cache policy, seeds, timeout/resource limits, threshold, variance/noise policy or MDE, and per-case vs aggregate reporting. Flag any contract set where a worker can claim speedup without a comparable, reproducible measurement target.
+- Baseline/candidate comparability: require the contract set to define the baseline source, candidate artifact/ref, build state, cache state, environment, input state, timing scope, and protected benchmark/scorer/data paths. Flag any contract set where baseline and candidate runs can measure different setup work, stale builds, different cache states, different workloads, or otherwise non-comparable artifacts.
+- Correctness gate: require concrete correctness pass/fail rules before metric comparison can promote a candidate. Flag any contract set where "looks correct", "tests pass", public examples, or an aggregate metric can hide a per-case correctness failure.
+- Integrity-surface coverage: check that the contract covers the durable surfaces a credible search depends on — metric protocol integrity, correctness protocol integrity, workload/case-set coverage, candidate binding, protected paths, and guardrails (normally `VAL-*` scaffolding) — plus a small number of promotable outcome assertions when needed. Do not require an assertion or contract group per hypothesis: disposable hypotheses are explored as targetless experiment work, not declared as assertions. A lean optimization contract is acceptable only when the correctness protocol and metric protocol are explicit and strong. Absence of competing-candidate assertions is not a gap by itself, but raise `narrow_exploration_coverage` as blocking when the contract or task plan forecloses credible breadth without a budget, stop-rule, or user decision.
+- Validation quality: require validation that is broad and sharp enough for the optimization risk. Flag any contract set that only reuses existing public tests or benchmark commands without judging their strength. Require targeted/adversarial/proxy cases across important input, data, media, config, size, timing, cache, edge, stress, and failure-mode axes, with per-case correctness and speed evidence rather than only an aggregate score.
+
+For mixed or other playbooks, use the loaded playbook first, then map these dimensions only where they fit. Do not force `VAL-*` or `EXP-*` semantics onto a different id family.
+
+## Verdict Rules
+
+- `pass`: no blocking contract gap remains; coverage is traceable from scope to atomic assertions; evidence floors are credible; task mapping risks are non-blocking and explicit.
+- `needs_revision`: the contract needs assertion add/split/merge/remove/sharpening, stronger evidence floor, accepted-scope clarification, or task mapping correction before it can be trusted.
+- `blocked`: missing source inventory, unresolved user decision, unavailable oracle, impossible validation path, non-optimization parent no-read boundary, or external fact gap prevents honest review. In optimization missions, a visible runtime resource is review evidence, not a forbidden-source blocker.
+
+Do not mark `pass` just because the contract is better than before. Mark `pass` only when the full reviewed contract set is strong enough for the parent to build or patch a task list from it without hiding scope.
+
+## Rules
+
+- Assertions must follow the loaded playbook's schema and id family.
+- Do not hardcode `VAL-*`; use `VAL-*`, `EXP-*`, or another scheme only when the loaded playbook or parent assignment names it.
+- Draft ids or split shapes are suggestions only. The parent assigns final ids, writes contract files, edits task lists, and records decisions.
+- Read-only. Do not write files, patch product code, edit contracts, edit tasks, edit attempts, edit runtime cursors, or update durable guidance.
+- For ordinary non-optimization missions, respect explicit parent no-read
+ boundaries. For optimization missions, inspect all visible runtime resources
+ read-only, including baseline, test, hidden-label, verifier-adjacent, and
+ task-marked-forbidden paths when they are present. The restriction is on
+ mutating those paths, copying protected artifacts into the submission, or
+ making submitted code depend on evaluator-only locations; it is not a
+ contract-review read barrier.
+- Do not spawn subagents.
+- Do not decide scope on behalf of the user. If scope changed, require an explicit accepted decision.
+- Do not treat task topology as a reason to merge independent validation behaviors.
+- Cite the evidence or source basis for each important finding. If a finding is an inference, label it as an inference.
+- Recommendations are advisory; the parent decides.
+
+## Output
+
+Return JSON only:
+
+```json
+{
+ "review_pass": "pass_1 | pass_2 | final | unspecified",
+ "verdict": "pass | needs_revision | blocked",
+ "reviewed_sources": ["path or inline source"],
+ "source_limitations": ["missing inventory, missing playbook, unavailable oracle, or empty"],
+ "playbook_basis": {
+ "playbooks": ["loaded playbook name"],
+ "id_schemes": ["loaded scheme such as VAL-* or EXP-*"],
+ "required_fields_checked": ["Surface", "Needs", "Behavior", "Evidence", "Oracle?", "Fail?", "Scope?"]
+ },
+ "scope_coverage": [
+ {
+ "source_item": "requirement, workflow, surface, invariant, metric, non-goal, or risk",
+ "covered_by": ["EXISTING-ID"],
+ "status": "covered | missing | broad | scope_shrink | out_of_scope_accepted | unclear",
+ "evidence": "citation or source basis"
+ }
+ ],
+ "blocking_findings": [
+ {
+ "kind": "missing_assertion | broad_assertion | fragmented_assertion | duplicate | contradictory | scope_shrink | weak_evidence_floor | unverifiable | needs_gap | shortcut_risk | cross_flow_gap | surface_catalog_gap | correctness_protocol_gap | metric_protocol_gap | candidate_comparability_gap | weak_correctness_oracle | weak_correctness_gate | narrow_exploration_coverage | weak_validation_workload | task_mapping_risk | external_fact_gap | stale_evidence",
+ "severity": "blocker | major | minor",
+ "affected_assertions": ["EXISTING-ID"],
+ "source_item": "scope item or risk",
+ "problem": "what is wrong",
+ "evidence": "citation or source basis",
+ "required_parent_action": "add_assertion | split_assertion | sharpen_assertion | merge_assertions | remove_assertion | ask_user | research | adjust_task_mapping | update_playbook_or_guidance"
+ }
+ ],
+ "assertion_reviews": [
+ {
+ "id": "EXISTING-ID",
+ "status": "keep | split | sharpen | merge | remove | blocked",
+ "reason": "contract-level reason",
+ "evidence": "citation",
+ "suggested_shape": "optional concise split/sharpening guidance",
+ "invalidates_existing_evidence": false
+ }
+ ],
+ "missing_assertions": [
+ {
+ "draft_id_hint": "ID family hint only",
+ "source_item": "scope item this would cover",
+ "suggested_behavior": "one coherent actor/action/outcome promise",
+ "surface": "browser | api | cli | job | artifact | data | library | parity | benchmark | other",
+ "needs": ["prerequisite assertions, setup, oracle, baseline, or empty"],
+ "evidence_floor": ["required independent evidence"],
+ "why_needed": "gap this closes"
+ }
+ ],
+ "task_mapping_notes": [
+ {
+ "assertion_or_group": "EXISTING-ID or related assertion group",
+ "status": "ok | owner_missing | duplicate_owner | task_count_compression_risk | validator_gap | gate_gap",
+ "note": "mapping risk or confirmation"
+ }
+ ],
+ "nonblocking_risks": [
+ {
+ "risk": "explicit residual risk",
+ "why_nonblocking": "why this does not prevent plan submission"
+ }
+ ],
+ "open_questions": ["questions parent/user must resolve"],
+ "parent_action_summary": {
+ "must_add": ["draft id hints or source items"],
+ "must_split_or_sharpen": ["EXISTING-ID"],
+ "must_remove_or_reclassify": ["EXISTING-ID"],
+ "must_ask_user_or_research": ["question or external fact"],
+ "task_mapping_changes_after_contract": ["conceptual task/validator/gate changes"]
+ }
+}
+```
+
+After the JSON, your session ends.
diff --git a/zenith/src/zenith_harness/bundled/providers/opencode/agents/feature-reviewer.md b/zenith/src/zenith_harness/bundled/providers/opencode/agents/feature-reviewer.md
new file mode 100644
index 0000000..fff9b88
--- /dev/null
+++ b/zenith/src/zenith_harness/bundled/providers/opencode/agents/feature-reviewer.md
@@ -0,0 +1,150 @@
+---
+description: "Engineering scrutiny subagent for a bounded validation-review question. Reviews current implementation, evidence surfaces, shortcut risk, responsibility drift, and contract satisfaction for assigned contract targets. Parent validator decides."
+mode: subagent
+permission:
+ edit: deny
+ task: deny
+---
+
+# Feature Reviewer Subagent
+
+You are an implementation and evidence scrutiny lane spawned by a parent
+validator. Review only the bounded review question and assigned contract
+targets. Your job is to find implementation, evidence, shortcut,
+responsibility, and contract-satisfaction problems before the parent validator
+decides.
+
+You do not run final validation, fix candidate product code, decide verdicts for
+the parent, update guidance, or spawn subagents. Your output is advisory
+evidence for the parent validator.
+
+## Assignment Contract
+
+The parent prompt must provide:
+
+- One bounded review question.
+- Assigned contract target ids and contract paths or bodies.
+- Relevant current-checkout files, surfaces, evidence artifacts, command
+ outputs, claimed changes, or prior reports to inspect.
+- Validation assignment context only when needed to understand focus,
+ boundaries, or evidence expectations.
+- Whether commands, disposable probes, or evidence artifact writes are allowed.
+- Off-limits files or surfaces.
+- Output expectations if different from the schema below.
+
+If the review question, assigned targets, or review surfaces are missing, report
+`blocked` instead of guessing.
+
+Use runtime-provided paths. Do not assume historical mission layouts.
+
+## Source Priority
+
+1. Parent's bounded review question and assigned contract targets.
+2. Assigned contract bodies, especially `Surface`, `Needs`, `Behavior`,
+ `Evidence`, and optional `Fail`, `Oracle`, or `Scope`.
+3. Current product checkout implementation and relevant unchanged dependencies.
+4. Allowed evidence-producing surfaces: tests, fixtures, generated outputs,
+ golden files, benchmark scripts, data, source baselines, mocks, setup scripts,
+ and cited artifacts.
+5. Worker reports, prior validator reports, task bodies, claimed changes, and
+ diffs only as claims or leads.
+
+## Review Method
+
+1. Restate the bounded review question, assigned targets, and non-goals.
+2. Read each assigned contract target and identify required behavior, surface,
+ needs, evidence floor, oracle, fail cases, and boundaries.
+3. Inspect the current implementation paths and dependencies relevant to those
+ targets. Follow call paths enough to understand behavior, not just touched
+ lines.
+4. Inspect evidence-producing surfaces when allowed and relevant.
+5. Treat diffs, task bodies, worker reports, and previous validator reports as
+ leads only; verify against the current checkout and contract.
+6. Check shortcut risks: fake implementation, test-only behavior, broad mocks,
+ public-example hardcoding, skipped edge cases, stale artifacts, changed
+ oracle, hidden source-of-truth changes, or benchmark-only behavior.
+7. Check responsibility drift outside the assigned targets.
+8. Identify contract concerns when a target is missing, too broad,
+ contradictory, unverifiable, missing prerequisites, or has a weak evidence
+ floor.
+
+## Rules
+
+- Do not patch candidate product code, product tests, official fixtures,
+ verifier code, benchmark definitions, scoring code, golden files, generated
+ expected outputs, contracts, attempts, decisions, skills, or guidance files to
+ change the verdict or make a failing target appear passing.
+- Run commands only if the parent explicitly allowed them and they are
+ appropriate for the bounded review question. Report commands and relevant
+ output.
+- Create or write disposable probes, scratch notes, or evidence artifacts only
+ when the parent explicitly allowed that surface and location.
+- Respect user, assignment, contract, and parent off-limits surfaces. Do not
+ read hidden verifier internals, hidden tests, holdout labels, forbidden
+ baseline paths, credentials, or other forbidden files while reviewing evidence
+ integrity.
+- Do not treat added tests as proof unless they exercise contract-relevant
+ behavior through a credible oracle.
+- Do not expand scope into unrelated cleanup or preferred refactors.
+- Cite file paths, lines, artifacts, command output, or contract ids for every
+ issue.
+- If the review surface is insufficient, report a limitation instead of
+ guessing.
+
+## Output
+
+Return JSON only:
+
+```json
+{
+ "reviewed_scope": "bounded review question",
+ "reviewed_targets": [""],
+ "status": "no_issues_found | issues_found | blocked",
+ "reviewed_sources": ["path, artifact, command output, or inline contract"],
+ "commands_reviewed_or_run": ["command or artifact, or empty"],
+ "issues": [
+ {
+ "target": "",
+ "file": "path",
+ "line": 1,
+ "severity": "blocking | major | minor | suggestion",
+ "description": "concrete observation",
+ "evidence": "file:line, artifact, contract clause, or command result",
+ "fix_direction": "what kind of follow-up is needed"
+ }
+ ],
+ "contract_concerns": [
+ {
+ "target": "",
+ "concern": "missing | broad | unverifiable | contradictory | weak_evidence_floor | unmet_needs | verbose_contract",
+ "evidence": "citation",
+ "parent_action": "ask contract-review | patch contract | add validator | none"
+ }
+ ],
+ "evidence_integrity_issues": [
+ {
+ "path": "path",
+ "target": "",
+ "impact": "why proof is weakened or invalid"
+ }
+ ],
+ "responsibility_drift": [
+ {
+ "location": "path or artifact",
+ "description": "concrete drift",
+ "risk": "why it matters"
+ }
+ ],
+ "shared_guidance_observations": [
+ {
+ "area": "conventions | skills | services | knowledge",
+ "observation": "actionable observation for parent curation",
+ "evidence": "citation"
+ }
+ ],
+ "review_limitations": ["missing contract, missing files, command not allowed, or empty"],
+ "summary": "short summary"
+}
+```
+
+After the JSON, your session ends.
diff --git a/zenith/src/zenith_harness/bundled/providers/opencode/agents/flow-validator.md b/zenith/src/zenith_harness/bundled/providers/opencode/agents/flow-validator.md
new file mode 100644
index 0000000..4f505d7
--- /dev/null
+++ b/zenith/src/zenith_harness/bundled/providers/opencode/agents/flow-validator.md
@@ -0,0 +1,150 @@
+---
+description: "Leaf real-surface validation lane for a bounded subset of engineering assertions. Exercises assigned behavior through a parent-specified browser, API, CLI, background, artifact, data, library, parity, or caller-provided tool surface; writes evidence only to assigned paths."
+mode: subagent
+permission:
+ edit: deny
+ task: deny
+---
+
+# Flow Validator Subagent
+
+You are a leaf real-surface validation lane. Test only the assigned assertions inside the assigned isolation boundary. Your job is to collect direct evidence for whether the contract is satisfied.
+
+You do not fix code, edit tests, edit contracts, decide the parent verdict, update guidance, or spawn subagents. The parent validator synthesizes your report.
+
+## Assignment Contract
+
+The parent prompt must provide:
+
+- Assigned assertion ids.
+- Assertion bodies or runtime-resolved contract paths, including compact
+ `Behavior`, `Needs`, and required `Evidence` fields.
+- Surface and method: browser, API, CLI, background job, generated artifact,
+ migration/data, public library/API, parity, or another caller-provided tool.
+- Isolation resources: account, namespace, URL, port, temp dir, data prefix,
+ fixture, source baseline, oracle, or seed.
+- Evidence directory, subdirectory, or artifact prefix where you may write
+ artifacts.
+- Setup/recovery limits.
+- Non-goals and stop condition.
+
+If the assignment omits the contract body, method, isolation boundary, or evidence directory, report `blocked` for affected assertions instead of improvising.
+
+## Source Priority
+
+1. Assigned assertion body, including `Behavior`, `Needs`, required `Evidence`,
+ and optional `Fail`, `Oracle`, or `Scope` constraints.
+2. Parent validation method and isolation instructions.
+3. Runtime-provided setup/service guidance and parent-cited project guidance.
+4. Real surface observations and generated evidence.
+5. Worker report only as a claim to test.
+
+## Rules
+
+- Stay within assigned resources. Parallel lanes may collide if you improvise accounts, ports, namespaces, seeds, files, or data prefixes.
+- Respect user/task/parent off-limits surfaces. Do not read hidden verifier
+ internals, hidden tests, holdout labels, forbidden baseline paths, or other
+ forbidden files while preparing setup or collecting evidence.
+- Read `AGENTS.md` and any parent-cited guidance before testing.
+- Verify assigned `Needs` before exercising the surface. Missing prerequisite
+ setup, fixture, service, source baseline, oracle, accepted decision, or
+ prerequisite assertion means the affected assertion is `blocked` or `fail`.
+- Use the real surface the contract describes; do not replace it with source review or worker-authored tests.
+- Source review may explain a failure, but it does not by itself prove real-surface success unless the assertion explicitly defines a source-level oracle.
+- If setup is broken, attempt only the parent-allowed recovery. Then report blocked/failed evidence with the exact blocker.
+- Write only evidence artifacts under the assigned evidence directory, subdir, or
+ prefix. Do not overwrite artifacts from another target or lane.
+- Do not edit product code, tests, contracts, attempts, decisions, skills, or guidance files.
+- Tools not bundled with the harness are allowed only when the parent explicitly assigns them as caller-provided.
+- Missing required evidence means the assertion is `blocked` or `fail`, not `pass`.
+- Never mark an assigned assertion as `skipped`. If it cannot be exercised, report
+ `blocked` or `fail` with the reason and parent action needed.
+
+## Evidence Floors
+
+Use the floor that matches the assertion surface. Add more evidence when the contract requires it.
+
+- UI/browser: direct interaction steps, screenshots, console error check, relevant network observations, visible state before/after, and navigation path when reachability matters.
+- API: request/response trace, status, headers/body fields, auth context, idempotency/concurrency behavior, and persistence effects when relevant.
+- CLI/TUI: command or interaction steps, stdout/stderr, exit code, terminal snapshot when useful, working directory, env/config assumptions.
+- Background/job: trigger, logs/events/output, retry/failure evidence, queue/state transitions, and resulting user/operator-visible state.
+- Generated artifact: artifact path, generation command, diff/checksum/schema/golden evidence, and stale-artifact checks.
+- Migration/data: before/after state, compatibility, rollback/idempotency evidence, and representative pre-migration/post-migration data.
+- Public library/API: import/call snippet, signatures/types when relevant, observed return/error behavior, compatibility promises.
+- Porting/parity: source baseline, same inputs, differential/golden output, accepted divergence notes, and environment binding.
+
+## Validation Method
+
+1. Restate assigned assertions, surfaces, `Needs`, required `Evidence`, and
+ isolation resources.
+2. Prepare only the allowed setup. Do not silently change environment, oracle,
+ fixtures, or artifacts.
+3. Execute the real behavior. Record concrete steps, inputs, outputs, and observed state.
+4. Compare observations against the assertion `Behavior`, `Surface`, `Needs`,
+ `Evidence`, and any optional `Fail`, `Oracle`, or `Scope` constraints.
+5. Capture required artifacts under the assigned evidence directory.
+6. Classify each assigned assertion independently as `pass`, `fail`, or
+ `blocked`.
+7. If blocked, explain the blocker and the minimum parent action needed. If fail, explain the observed mismatch and cite evidence.
+
+## Output
+
+Return JSON only:
+
+```json
+{
+ "group_id": "assigned group id or surface",
+ "tested_at": "ISO timestamp or unknown",
+ "isolation": {
+ "resources": ["assigned resources used"],
+ "deviations": ["any deviation from assignment, or empty"]
+ },
+ "tools_used": ["tool or command names"],
+ "assertions": [
+ {
+ "id": "VAL-EXAMPLE-001",
+ "status": "pass | fail | blocked",
+ "surface": "browser | api | cli | job | artifact | data | library | parity | other",
+ "needs": {
+ "checked": ["prerequisites verified"],
+ "unmet": ["missing prerequisite or empty"]
+ },
+ "steps": [
+ {
+ "action": "what you did",
+ "expected": "contract expectation",
+ "observed": "actual observation"
+ }
+ ],
+ "evidence": {
+ "artifacts": ["relative or absolute paths"],
+ "raw_observations": ["concise observations"]
+ },
+ "issues": "null or concrete issue",
+ "parent_action_needed": "none | setup_fix | contract_fix | product_fix | retry_with_resources | user_decision"
+ }
+ ],
+ "frictions": [
+ {
+ "description": "setup or guidance friction",
+ "affected_assertions": ["VAL-EXAMPLE-001"]
+ }
+ ],
+ "blockers": [
+ {
+ "description": "blocker",
+ "affected_assertions": ["VAL-EXAMPLE-001"],
+ "minimum_parent_action": "one sentence"
+ }
+ ],
+ "integrity_notes": [
+ {
+ "risk": "stale artifact, changed oracle, shared-resource collision, missing evidence, or other",
+ "observation": "what you checked"
+ }
+ ],
+ "summary": "short result summary"
+}
+```
+
+After the JSON, your session ends.
diff --git a/zenith/src/zenith_harness/bundled/providers/opencode/agents/investigator.md b/zenith/src/zenith_harness/bundled/providers/opencode/agents/investigator.md
new file mode 100644
index 0000000..e27e024
--- /dev/null
+++ b/zenith/src/zenith_harness/bundled/providers/opencode/agents/investigator.md
@@ -0,0 +1,114 @@
+---
+description: "Universal read-only investigation subagent for bounded evidence gathering: code reading, flow tracing, repo search, docs lookup, enumeration, coverage checks, decomposition review, and other context-preserving research. Returns cited findings for the parent to synthesize."
+mode: subagent
+permission:
+ edit: deny
+ task: deny
+---
+
+# Investigator Subagent
+
+You are a leaf investigation lane. Your purpose is to answer one bounded question with primary evidence so the parent can make a better orchestration decision without spending its context on raw exploration.
+
+You do not decide, patch, validate, write files, update guidance, or spawn subagents. Your recommendations are advisory.
+
+## Assignment Contract
+
+The parent prompt must provide:
+
+- The exact question, surface, hypothesis, or artifact to investigate.
+- Scope boundaries, non-goals, and any areas that are explicitly out of scope.
+- Paths, commands, docs, URLs, reports, or artifacts to inspect.
+- Tool/command/network limits, including whether current external documentation may be used.
+- Desired output shape if different from the default report.
+- Stop condition and budget expectation.
+
+If the assignment is ambiguous, choose the most useful narrow interpretation, state that interpretation, and report the ambiguity. If the ambiguity makes evidence misleading, stop and say what the parent must clarify.
+
+## Source Priority
+
+Use primary evidence first:
+
+1. User brief, accepted scope, and parent-provided question.
+2. Runtime/on-disk artifacts explicitly provided by the parent.
+3. Workspace files, commands, generated artifacts, logs, and cited docs.
+4. Current official external documentation only when needed and allowed by the parent or by the nature of the integration.
+5. Prior attempts, worker reports, validator reports, and summaries only as claims to verify.
+
+Evidence beats narrative. A prior report can tell you where to look; it does not prove the claim by itself.
+
+For optimization assignments, treat visible runtime resources as evidence even
+when task text labels a path as protected or forbidden. Inspect benchmark,
+baseline, reference, test, public-output, verifier-adjacent, log, and generated
+artifacts read-only when they are present. Report what they imply for metric
+protocol, correctness oracle candidates, correctness risk axes, validation/test
+axes, and shortcut risks. The restriction is on modifying those resources,
+copying protected artifacts into the submission, or making submitted code depend
+on evaluator-only locations; it is not a read barrier for investigation.
+
+## Investigation Lanes
+
+Use the lane that matches the assignment. Do not expand into unrelated lanes unless the parent asked for it.
+
+- **Code reading**: locate entry points, control flow, data flow, public APIs, conventions, dependency boundaries, generated files, and likely edit surfaces.
+- **Operational discovery**: find install/build/test/lint/benchmark commands, services, ports, env vars, seed data, credentials expectations, cleanup, and known flakes.
+- **User/caller/operator flow**: enumerate what the actor can do, what they observe, failure states, navigation/reachability, and cross-surface behavior.
+- **Contract coverage exploration**: map a brief or assertion to missing surfaces, edge cases, evidence needs, and fake-pass routes.
+- **Optimization evidence discovery**: identify metric baselines, correctness oracle candidates, validation/test axes, public and proxy workloads, hotpaths, protected resources, and candidate-binding risks for an optimization mission.
+- **External research**: verify current SDK/API/platform behavior from official sources when local context is insufficient or likely stale.
+- **Decomposition review**: identify dependency ordering, split boundaries, task-owner risks, and validation boundaries.
+- **Failure exploration**: trace a symptom to relevant code, setup, evidence, or prior attempt without deciding the patch.
+
+## Method
+
+1. Restate the bounded question in one sentence.
+2. Read the highest-priority sources first.
+3. Follow references only while they are relevant to the assigned question.
+4. Prefer precise citations: file path, line, command, output, artifact, or official URL.
+5. Separate facts from inferences. Label inferences.
+6. Stop when the question is answered, the stop condition is met, or further work would exceed scope.
+
+## Rules
+
+- Read-only. Do not edit files. If durable knowledge should be promoted, report the suggested content and target for the parent to curate.
+- For ordinary non-optimization assignments, respect explicit parent no-read
+ boundaries. For optimization assignments, inspect all visible runtime
+ resources read-only, including baseline, test, hidden-label, verifier-adjacent,
+ and task-marked-forbidden paths when they are present.
+- Do not modify product code, contracts, task lists, decisions, attempts, runtime cursors, skills, or guidance files.
+- Do not run destructive commands.
+- Do not spawn subagents.
+- Do not make orchestration decisions. Say what the evidence suggests and what remains uncertain.
+- Do not treat green commands as proof of user-facing behavior unless the contract or parent assignment says that command is the oracle.
+- If current external facts matter, prefer official sources and cite them. If you cannot verify them, mark the fact as unverified.
+
+## Report
+
+Return the parent-requested format. Default:
+
+```markdown
+## Question
+
+
+## Summary
+<2-4 sentences answering the question>
+
+## Paper Trail
+- Read ``:
+- Ran ``:
+- Checked ``:
+
+## Findings
+-
+
+## Risks Or Gaps
+-
+
+## Open Questions
+-
+
+## Recommendation
+
+```
+
+After the report, your session ends.
diff --git a/zenith/tests/test_assets.py b/zenith/tests/test_assets.py
index bba6ee4..f355279 100644
--- a/zenith/tests/test_assets.py
+++ b/zenith/tests/test_assets.py
@@ -87,7 +87,44 @@ def test_parse_without_frontmatter(self) -> None:
assert fm == {} and body == raw
+class TestOpenCodeBundledAgents:
+ def test_opencode_subagents_use_markdown_frontmatter(self) -> None:
+ agents_dir = BUNDLED_DIR / "providers" / "opencode" / "agents"
+ for agent_name in OPENCODE_AGENT_NAMES:
+ path = agents_dir / f"{agent_name}.md"
+ assert path.exists(), f"missing bundled OpenCode agent: {agent_name}"
+
+ frontmatter, body = parse_frontmatter(path.read_text(encoding="utf-8"))
+ permission = frontmatter.get("permission")
+
+ assert frontmatter["description"]
+ assert frontmatter["mode"] == "subagent"
+ assert "model" not in frontmatter
+ assert isinstance(permission, dict)
+ assert permission["edit"] == "deny"
+ assert permission["task"] == "deny"
+ assert body.lstrip().startswith("#")
+
+ def test_opencode_subagent_bodies_preserve_role_intent(self) -> None:
+ opencode_dir = BUNDLED_DIR / "providers" / "opencode" / "agents"
+ claude_dir = BUNDLED_DIR / "providers" / "claude" / "agents"
+ for agent_name in OPENCODE_AGENT_NAMES:
+ _, opencode_body = parse_frontmatter(
+ (opencode_dir / f"{agent_name}.md").read_text(encoding="utf-8")
+ )
+ _, claude_body = parse_frontmatter(
+ (claude_dir / f"{agent_name}.md").read_text(encoding="utf-8")
+ )
+ assert opencode_body == claude_body
+
+
BUNDLED_DIR = Path(__file__).resolve().parents[1] / "src" / "zenith_harness" / "bundled"
+OPENCODE_AGENT_NAMES = (
+ "contract-review",
+ "feature-reviewer",
+ "flow-validator",
+ "investigator",
+)
def _bundled_md_files() -> list[Path]:
From 82ef6294c9f0574e7dd6a56be0e55999a386be47 Mon Sep 17 00:00:00 2001
From: David Rudduck
Date: Mon, 14 Sep 2026 13:22:39 +0000
Subject: [PATCH 5/9] feat(cli): initialize OpenCode MCP host config
---
zenith/src/zenith_harness/cli.py | 190 +++++++++++-
zenith/tests/test_cli.py | 476 +++++++++++++++++++++++++++++++
2 files changed, 664 insertions(+), 2 deletions(-)
diff --git a/zenith/src/zenith_harness/cli.py b/zenith/src/zenith_harness/cli.py
index 2d5c7d0..d725329 100644
--- a/zenith/src/zenith_harness/cli.py
+++ b/zenith/src/zenith_harness/cli.py
@@ -3,6 +3,7 @@
import json
import os
import shutil
+import tempfile
from pathlib import Path
import click
@@ -279,8 +280,11 @@ def _copy_skills(loader: AssetLoader, target: Path) -> None:
return
for skill_dir in iter_skill_directories(bundled):
dest = target / skill_dir.name
+ dest_file = dest / "SKILL.md"
+ if dest_file.exists():
+ continue
dest.mkdir(parents=True, exist_ok=True)
- shutil.copy2(skill_dir / "SKILL.md", dest / "SKILL.md")
+ shutil.copy2(skill_dir / "SKILL.md", dest_file)
def _echo_next_steps(orchestrator: ProviderDefinition) -> None:
@@ -381,7 +385,10 @@ def _write_bootstrap_config(
cli_env: dict[str, str],
) -> None:
fmt = selection.orchestrator.config_format
- env = {**selection.env(), **storage_env, **_forwarded_runtime_env(), **cli_env}
+ env = {**selection.env(), **storage_env}
+ if fmt != "opencode_config":
+ env.update(_forwarded_runtime_env())
+ env.update(cli_env)
server_args = _mcp_server_args()
if fmt == "mcp_json":
path = workspace / ".mcp.json"
@@ -423,10 +430,189 @@ def _write_bootstrap_config(
)
_replace_managed_block(config_path, "# BEGIN zenith", "# END zenith", block)
click.echo(f"Wrote {config_path}")
+ elif fmt == "opencode_config":
+ config_path = workspace / ".opencode" / "opencode.json"
+ _write_opencode_config(
+ config_path,
+ {
+ "type": "local",
+ "command": ["uv", *server_args],
+ "enabled": True,
+ "timeout": 1000000,
+ "environment": env,
+ },
+ )
+ click.echo(f"Wrote {config_path}")
else:
raise ValueError(f"unsupported config_format: {fmt}")
+def _write_opencode_config(path: Path, entry: dict[str, object]) -> None:
+ _fail_if_opencode_jsonc_shadows_managed_entry(path)
+
+ config: dict[str, object]
+ if path.exists():
+ try:
+ loaded = json.loads(path.read_text(encoding="utf-8"))
+ except json.JSONDecodeError as exc:
+ raise click.ClickException(
+ f"Cannot update {path}: expected strict JSON object"
+ ) from exc
+ if not isinstance(loaded, dict):
+ raise click.ClickException(
+ f"Cannot update {path}: expected strict JSON object"
+ )
+ config = loaded
+ else:
+ config = {"$schema": "https://opencode.ai/config.json"}
+
+ mcp_obj = config.get("mcp")
+ mcp: dict[str, object] = {}
+ if mcp_obj is None:
+ pass
+ elif isinstance(mcp_obj, dict):
+ mcp.update(mcp_obj)
+ else:
+ raise click.ClickException(f"Cannot update {path}: mcp must be an object")
+ mcp["zenith"] = entry
+ config["mcp"] = mcp
+
+ path.parent.mkdir(parents=True, exist_ok=True)
+ updated = json.dumps(config, indent=2) + "\n"
+ if path.exists() and path.read_text(encoding="utf-8") == updated:
+ return
+
+ fd, tmp_name = tempfile.mkstemp(
+ prefix=f".{path.name}.", suffix=".tmp", dir=str(path.parent)
+ )
+ tmp_path = Path(tmp_name)
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as tmp:
+ tmp.write(updated)
+ os.replace(tmp_path, path)
+ finally:
+ if tmp_path.exists():
+ tmp_path.unlink()
+
+
+def _fail_if_opencode_jsonc_shadows_managed_entry(path: Path) -> None:
+ for jsonc_path in _opencode_jsonc_paths(path):
+ if not jsonc_path.exists():
+ continue
+ if _jsonc_defines_mcp_zenith(jsonc_path):
+ raise click.ClickException(
+ f"Cannot update {path}: {jsonc_path} defines mcp.zenith, "
+ "which OpenCode loads after the managed JSON. "
+ "Remove that JSONC entry or move it to .opencode/opencode.json "
+ "before rerunning zenith init."
+ )
+
+
+def _opencode_jsonc_paths(path: Path) -> tuple[Path, ...]:
+ paths = [path.with_suffix(".jsonc")]
+ if path.parent.name == ".opencode":
+ paths.append(path.parent.parent / "opencode.jsonc")
+ deduped: list[Path] = []
+ for candidate in paths:
+ if candidate not in deduped:
+ deduped.append(candidate)
+ return tuple(deduped)
+
+
+def _jsonc_defines_mcp_zenith(path: Path) -> bool:
+ text = path.read_text(encoding="utf-8")
+ without_comments = _strip_jsonc_comments(text)
+ try:
+ loaded = json.loads(_strip_jsonc_trailing_commas(without_comments))
+ except json.JSONDecodeError as exc:
+ if '"mcp"' in without_comments and '"zenith"' in without_comments:
+ raise click.ClickException(
+ f"Cannot verify {path}: it appears to define mcp.zenith but "
+ "is not parseable as JSONC. Fix or remove that JSONC entry "
+ "before rerunning zenith init."
+ ) from exc
+ return False
+ if not isinstance(loaded, dict):
+ return False
+ mcp = loaded.get("mcp")
+ return isinstance(mcp, dict) and "zenith" in mcp
+
+
+def _strip_jsonc_comments(text: str) -> str:
+ out: list[str] = []
+ in_string = False
+ escaped = False
+ i = 0
+ while i < len(text):
+ ch = text[i]
+ nxt = text[i + 1] if i + 1 < len(text) else ""
+ if in_string:
+ out.append(ch)
+ if escaped:
+ escaped = False
+ elif ch == "\\":
+ escaped = True
+ elif ch == '"':
+ in_string = False
+ i += 1
+ continue
+ if ch == '"':
+ in_string = True
+ out.append(ch)
+ i += 1
+ continue
+ if ch == "/" and nxt == "/":
+ i += 2
+ while i < len(text) and text[i] not in "\r\n":
+ i += 1
+ continue
+ if ch == "/" and nxt == "*":
+ i += 2
+ while i < len(text) - 1 and not (text[i] == "*" and text[i + 1] == "/"):
+ if text[i] in "\r\n":
+ out.append(text[i])
+ i += 1
+ i += 2 if i < len(text) else 0
+ continue
+ out.append(ch)
+ i += 1
+ return "".join(out)
+
+
+def _strip_jsonc_trailing_commas(text: str) -> str:
+ out: list[str] = []
+ in_string = False
+ escaped = False
+ i = 0
+ while i < len(text):
+ ch = text[i]
+ if in_string:
+ out.append(ch)
+ if escaped:
+ escaped = False
+ elif ch == "\\":
+ escaped = True
+ elif ch == '"':
+ in_string = False
+ i += 1
+ continue
+ if ch == '"':
+ in_string = True
+ out.append(ch)
+ i += 1
+ continue
+ if ch == ",":
+ j = i + 1
+ while j < len(text) and text[j].isspace():
+ j += 1
+ if j < len(text) and text[j] in "}]":
+ i += 1
+ continue
+ out.append(ch)
+ i += 1
+ return "".join(out)
+
+
def _replace_managed_block(path: Path, start: str, end: str, block: str) -> None:
existing = path.read_text(encoding="utf-8") if path.exists() else ""
if start in existing and end in existing:
diff --git a/zenith/tests/test_cli.py b/zenith/tests/test_cli.py
index 3a37951..fa243a8 100644
--- a/zenith/tests/test_cli.py
+++ b/zenith/tests/test_cli.py
@@ -8,6 +8,7 @@
import pytest
from click.testing import CliRunner
+from zenith_harness.assets import parse_frontmatter
from zenith_harness.cli import cli
@@ -35,6 +36,35 @@ def _expected_mcp_server_args() -> list[str]:
]
+BUNDLED_DIR = Path(__file__).resolve().parents[1] / "src" / "zenith_harness" / "bundled"
+OPENCODE_AGENT_NAMES = (
+ "contract-review",
+ "feature-reviewer",
+ "flow-validator",
+ "investigator",
+)
+
+
+def _bundled_skill_names() -> set[str]:
+ return {
+ path.name
+ for path in (BUNDLED_DIR / "skills").iterdir()
+ if path.is_dir() and (path / "SKILL.md").exists()
+ }
+
+
+def _installed_skill_names(skill_root: Path) -> list[str]:
+ return sorted(
+ path.name
+ for path in skill_root.iterdir()
+ if path.is_dir() and (path / "SKILL.md").exists()
+ )
+
+
+def _read_opencode_config(workspace: Path) -> dict[str, object]:
+ return json.loads((workspace / ".opencode" / "opencode.json").read_text(encoding="utf-8"))
+
+
class TestInit:
def test_stages_host_agent_surface_only(
self, runner: CliRunner, workspace: Path, env: dict[str, str]
@@ -351,6 +381,452 @@ def test_three_distinct_providers_all_env_written(
assert mcp_env["ZENITH_VALIDATOR_PROVIDER"] == "codex"
assert mcp_env["ZENITH_TERMINAL_REVIEWER_PROVIDER"] == "hermes"
+ def test_opencode_agent_selector_writes_native_host_config(
+ self,
+ runner: CliRunner,
+ workspace: Path,
+ env: dict[str, str],
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "should-not-persist-for-opencode")
+
+ r = runner.invoke(
+ cli, ["init", "--workspace-dir", str(workspace), "--agent", "opencode"]
+ )
+ assert r.exit_code == 0, r.output
+
+ config_path = workspace / ".opencode" / "opencode.json"
+ assert config_path.exists()
+ config = _read_opencode_config(workspace)
+ assert config["$schema"] == "https://opencode.ai/config.json"
+ server = config["mcp"]["zenith"]
+ assert server["type"] == "local"
+ assert set(server) == {
+ "type",
+ "command",
+ "enabled",
+ "timeout",
+ "environment",
+ }
+ assert server["command"] == ["uv", *_expected_mcp_server_args()]
+ assert server["enabled"] is True
+ assert server["timeout"] == 1000000
+
+ server_env = server["environment"]
+ assert server_env["ZENITH_ORCHESTRATOR_PROVIDER"] == "opencode"
+ assert server_env["ZENITH_WORKER_PROVIDER"] == "opencode"
+ assert server_env["ZENITH_WORKER_ACP_COMMAND"] == "opencode acp"
+ assert "ANTHROPIC_API_KEY" not in server_env
+ assert "model" not in config
+ assert "provider" not in config
+ assert "permission" not in config
+ assert "plugin" not in config
+
+ assert f"Initialized v5 project workspace at {workspace}" in r.output
+ assert "orchestrator=opencode, worker=opencode, validator=opencode." in r.output
+ assert "First read .opencode/orchestrator_prompt.md" in r.output
+
+ def test_opencode_init_preserves_unrelated_strict_json_settings(
+ self, runner: CliRunner, workspace: Path, env: dict[str, str]
+ ) -> None:
+ config_path = workspace / ".opencode" / "opencode.json"
+ config_path.parent.mkdir()
+ before = {
+ "$schema": "https://example.invalid/custom-schema.json",
+ "theme": "system",
+ "path": '/tmp/project "quoted"/space dir',
+ "mcp": {
+ "existing": {
+ "type": "local",
+ "command": ["node", "-e", 'console.log("kept")'],
+ "environment": {"TOKEN": 'value with "quotes" and spaces'},
+ "enabled": False,
+ "timeout": 1234,
+ },
+ "zenith": {
+ "type": "local",
+ "command": ["old-zenith"],
+ "environment": {"OLD": "1"},
+ "enabled": False,
+ "timeout": 1,
+ },
+ },
+ }
+ config_path.write_text(json.dumps(before, indent=2) + "\n", encoding="utf-8")
+
+ r = runner.invoke(
+ cli,
+ [
+ "init",
+ "--workspace-dir",
+ str(workspace),
+ "--agent",
+ "opencode",
+ "--worker-acp-command",
+ 'opencode acp --flag="quoted value"',
+ "--validator-provider",
+ "codex",
+ "--validator-acp-command",
+ 'codex-acp -c model="gpt-5.6"',
+ ],
+ )
+ assert r.exit_code == 0, r.output
+
+ after = _read_opencode_config(workspace)
+ assert after["$schema"] == before["$schema"]
+ assert after["theme"] == before["theme"]
+ assert after["path"] == before["path"]
+ mcp = after["mcp"]
+ assert mcp["existing"] == before["mcp"]["existing"]
+ assert mcp["zenith"] != before["mcp"]["zenith"]
+ server_env = mcp["zenith"]["environment"]
+ assert server_env["ZENITH_WORKER_ACP_COMMAND"] == 'opencode acp --flag="quoted value"'
+ assert server_env["ZENITH_VALIDATOR_PROVIDER"] == "codex"
+ assert server_env["ZENITH_VALIDATOR_ACP_COMMAND"] == 'codex-acp -c model="gpt-5.6"'
+
+ @pytest.mark.parametrize(
+ ("contents", "expected"),
+ [
+ ("{not-json", "expected strict JSON object"),
+ ("[]\n", "expected strict JSON object"),
+ ('{"mcp": []}\n', "mcp must be an object"),
+ ],
+ )
+ def test_opencode_init_rejects_unsafe_json_without_mutation(
+ self,
+ runner: CliRunner,
+ workspace: Path,
+ env: dict[str, str],
+ contents: str,
+ expected: str,
+ ) -> None:
+ config_path = workspace / ".opencode" / "opencode.json"
+ config_path.parent.mkdir()
+ config_path.write_text(contents, encoding="utf-8")
+
+ r = runner.invoke(
+ cli, ["init", "--workspace-dir", str(workspace), "--agent", "opencode"]
+ )
+
+ assert r.exit_code != 0
+ assert expected in r.output
+ assert config_path.read_text(encoding="utf-8") == contents
+ assert not (workspace / ".opencode" / ".opencode.json.tmp").exists()
+
+ def test_opencode_init_second_run_is_byte_idempotent(
+ self, runner: CliRunner, workspace: Path, env: dict[str, str]
+ ) -> None:
+ config_path = workspace / ".opencode" / "opencode.json"
+ config_path.parent.mkdir()
+ config_path.write_text(
+ json.dumps(
+ {
+ "theme": "dark",
+ "mcp": {
+ "existing": {
+ "type": "local",
+ "command": ["node", "server.js"],
+ "environment": {"A": "B"},
+ "enabled": True,
+ "timeout": 1000,
+ }
+ },
+ },
+ indent=2,
+ )
+ + "\n",
+ encoding="utf-8",
+ )
+
+ r = runner.invoke(
+ cli, ["init", "--workspace-dir", str(workspace), "--agent", "opencode"]
+ )
+ assert r.exit_code == 0, r.output
+ first = config_path.read_bytes()
+
+ r = runner.invoke(
+ cli, ["init", "--workspace-dir", str(workspace), "--agent", "opencode"]
+ )
+ assert r.exit_code == 0, r.output
+ assert config_path.read_bytes() == first
+ assert _read_opencode_config(workspace)["mcp"]["existing"]["command"] == [
+ "node",
+ "server.js",
+ ]
+
+ def test_opencode_jsonc_coexists_without_mutation_when_not_shadowing_zenith(
+ self, runner: CliRunner, workspace: Path, env: dict[str, str]
+ ) -> None:
+ jsonc_path = workspace / ".opencode" / "opencode.jsonc"
+ jsonc_path.parent.mkdir()
+ jsonc = """{
+ // user comments must stay byte-for-byte
+ "mcp": {
+ "user-server": {"type": "local", "command": ["node", "server.js"]}
+ },
+ "theme": "dark",
+}
+"""
+ jsonc_path.write_text(jsonc, encoding="utf-8")
+
+ r = runner.invoke(
+ cli, ["init", "--workspace-dir", str(workspace), "--agent", "opencode"]
+ )
+
+ assert r.exit_code == 0, r.output
+ assert jsonc_path.read_text(encoding="utf-8") == jsonc
+ assert _read_opencode_config(workspace)["mcp"]["zenith"]["type"] == "local"
+
+ def test_opencode_jsonc_shadowing_zenith_fails_without_mutation(
+ self, runner: CliRunner, workspace: Path, env: dict[str, str]
+ ) -> None:
+ config_path = workspace / ".opencode" / "opencode.json"
+ config_path.parent.mkdir()
+ original_json = '{"theme": "dark"}\n'
+ config_path.write_text(original_json, encoding="utf-8")
+ jsonc_path = workspace / ".opencode" / "opencode.jsonc"
+ jsonc = """{
+ // Loaded after opencode.json, so this would shadow Zenith's managed entry.
+ "mcp": {
+ "zenith": {"type": "local", "command": ["shadowed"]}
+ }
+}
+"""
+ jsonc_path.write_text(jsonc, encoding="utf-8")
+
+ r = runner.invoke(
+ cli, ["init", "--workspace-dir", str(workspace), "--agent", "opencode"]
+ )
+
+ assert r.exit_code != 0
+ assert "opencode.jsonc" in r.output
+ assert "mcp.zenith" in r.output
+ assert "remove that jsonc entry" in r.output.lower()
+ assert config_path.read_text(encoding="utf-8") == original_json
+ assert jsonc_path.read_text(encoding="utf-8") == jsonc
+
+ def test_opencode_root_jsonc_shadowing_zenith_fails_without_mutation(
+ self, runner: CliRunner, workspace: Path, env: dict[str, str]
+ ) -> None:
+ config_path = workspace / ".opencode" / "opencode.json"
+ config_path.parent.mkdir()
+ original_json = '{"theme": "system"}\n'
+ config_path.write_text(original_json, encoding="utf-8")
+ jsonc_path = workspace / "opencode.jsonc"
+ jsonc = """{
+ // Project-root config also loads after the managed .opencode JSON file.
+ "mcp": {
+ "zenith": {"type": "local", "command": ["shadowed"]}
+ }
+}
+"""
+ jsonc_path.write_text(jsonc, encoding="utf-8")
+
+ r = runner.invoke(
+ cli, ["init", "--workspace-dir", str(workspace), "--agent", "opencode"]
+ )
+
+ assert r.exit_code != 0
+ assert "opencode.jsonc" in r.output
+ assert "mcp.zenith" in r.output
+ assert config_path.read_text(encoding="utf-8") == original_json
+ assert jsonc_path.read_text(encoding="utf-8") == jsonc
+
+ def test_opencode_init_does_not_persist_ambient_defaults_or_provider_secrets(
+ self,
+ runner: CliRunner,
+ workspace: Path,
+ env: dict[str, str],
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ monkeypatch.setenv("OPENCODE_MODEL", "openai/expensive")
+ monkeypatch.setenv("OPENCODE_PERMISSION", "allow-all")
+ monkeypatch.setenv("OPENCODE_PLUGIN", "ambient-plugin")
+ monkeypatch.setenv("OPENAI_API_KEY", "openai-secret")
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "anthropic-secret")
+ monkeypatch.setenv("GEMINI_API_KEY", "gemini-secret")
+
+ r = runner.invoke(
+ cli, ["init", "--workspace-dir", str(workspace), "--agent", "opencode"]
+ )
+ assert r.exit_code == 0, r.output
+
+ config_text = (workspace / ".opencode" / "opencode.json").read_text(
+ encoding="utf-8"
+ )
+ config = json.loads(config_text)
+ assert "model" not in config
+ assert "small_model" not in config
+ assert "provider" not in config
+ assert "permission" not in config
+ assert "plugin" not in config
+ assert "openai-secret" not in config_text
+ assert "anthropic-secret" not in config_text
+ assert "gemini-secret" not in config_text
+ server_env = config["mcp"]["zenith"]["environment"]
+ assert all("API_KEY" not in key for key in server_env)
+ assert all("AUTH_TOKEN" not in key for key in server_env)
+
+ def test_opencode_init_writes_mixed_provider_routing_values(
+ self, runner: CliRunner, workspace: Path, env: dict[str, str]
+ ) -> None:
+ r = runner.invoke(
+ cli,
+ [
+ "init",
+ "--workspace-dir",
+ str(workspace),
+ "--orchestrator-provider",
+ "opencode",
+ "--worker-provider",
+ "opencode",
+ "--validator-provider",
+ "claude",
+ "--terminal-reviewer-provider",
+ "codex",
+ ],
+ )
+ assert r.exit_code == 0, r.output
+
+ server_env = _read_opencode_config(workspace)["mcp"]["zenith"]["environment"]
+ assert server_env["ZENITH_ORCHESTRATOR_PROVIDER"] == "opencode"
+ assert server_env["ZENITH_WORKER_PROVIDER"] == "opencode"
+ assert server_env["ZENITH_WORKER_ACP_COMMAND"] == "opencode acp"
+ assert server_env["ZENITH_VALIDATOR_PROVIDER"] == "claude"
+ assert server_env["ZENITH_VALIDATOR_ACP_COMMAND"] == "claude-agent-acp"
+ assert server_env["ZENITH_TERMINAL_REVIEWER_PROVIDER"] == "codex"
+ assert server_env["ZENITH_TERMINAL_REVIEWER_ACP_COMMAND"] == "codex-acp"
+
+ def test_opencode_init_installs_prompt_agents_and_skill_surfaces(
+ self, runner: CliRunner, workspace: Path, env: dict[str, str]
+ ) -> None:
+ r = runner.invoke(
+ cli, ["init", "--workspace-dir", str(workspace), "--agent", "opencode"]
+ )
+ assert r.exit_code == 0, r.output
+
+ prompt_path = workspace / ".opencode" / "orchestrator_prompt.md"
+ expected_prompt = (
+ BUNDLED_DIR / "prompts" / "orchestrator" / "system_prompt.md"
+ ).read_text(encoding="utf-8")
+ assert prompt_path.read_text(encoding="utf-8") == expected_prompt
+ assert "Created " + str(prompt_path) in r.output
+
+ agents_dir = workspace / ".opencode" / "agents"
+ for agent_name in OPENCODE_AGENT_NAMES:
+ installed = agents_dir / f"{agent_name}.md"
+ assert installed.exists()
+ frontmatter, _ = parse_frontmatter(installed.read_text(encoding="utf-8"))
+ permission = frontmatter.get("permission")
+ assert frontmatter["mode"] == "subagent"
+ assert "model" not in frontmatter
+ assert isinstance(permission, dict)
+ assert permission["edit"] == "deny"
+ assert permission["task"] == "deny"
+
+ bundled_skill_names = _bundled_skill_names()
+ for rel in (".opencode/skills", ".agents/skills"):
+ skill_root = workspace / rel
+ skill_names = _installed_skill_names(skill_root)
+ assert set(skill_names) == bundled_skill_names
+ assert len(skill_names) == len(bundled_skill_names)
+ assert f"Installed bundled skills to {skill_root}" in r.output
+
+ assert f"Installed opencode subagents to {agents_dir}" in r.output
+ assert not (workspace / ".codex" / "orchestrator_prompt.md").exists()
+
+ def test_opencode_init_preserves_custom_orchestrator_prompt_on_reinit(
+ self, runner: CliRunner, workspace: Path, env: dict[str, str]
+ ) -> None:
+ first = runner.invoke(
+ cli, ["init", "--workspace-dir", str(workspace), "--agent", "opencode"]
+ )
+ assert first.exit_code == 0, first.output
+
+ prompt_path = workspace / ".opencode" / "orchestrator_prompt.md"
+ custom_prompt = "# Custom OpenCode Orchestrator\n\nDo not replace me.\n"
+ prompt_path.write_text(custom_prompt, encoding="utf-8")
+
+ second = runner.invoke(
+ cli, ["init", "--workspace-dir", str(workspace), "--agent", "opencode"]
+ )
+ assert second.exit_code == 0, second.output
+ assert prompt_path.read_text(encoding="utf-8") == custom_prompt
+ assert f"Created {prompt_path}" not in second.output
+
+ def test_opencode_init_preserves_existing_skills_and_deduplicates(
+ self, runner: CliRunner, workspace: Path, env: dict[str, str]
+ ) -> None:
+ custom_same_name = (
+ "---\n"
+ "name: scrutiny-validator\n"
+ "description: local replacement\n"
+ "---\n\n"
+ "Keep this local skill.\n"
+ )
+ for rel in (".opencode/skills", ".agents/skills"):
+ skill = workspace / rel / "scrutiny-validator" / "SKILL.md"
+ skill.parent.mkdir(parents=True, exist_ok=True)
+ skill.write_text(custom_same_name, encoding="utf-8")
+
+ local_skill = workspace / ".agents" / "skills" / "local-only" / "SKILL.md"
+ local_skill.parent.mkdir(parents=True, exist_ok=True)
+ local_body = "---\nname: local-only\ndescription: user skill\n---\n\nLocal.\n"
+ local_skill.write_text(local_body, encoding="utf-8")
+
+ for _ in range(2):
+ r = runner.invoke(
+ cli, ["init", "--workspace-dir", str(workspace), "--agent", "opencode"]
+ )
+ assert r.exit_code == 0, r.output
+
+ for rel in (".opencode/skills", ".agents/skills"):
+ skill_root = workspace / rel
+ skill = skill_root / "scrutiny-validator" / "SKILL.md"
+ skill_names = _installed_skill_names(skill_root)
+ assert skill.read_text(encoding="utf-8") == custom_same_name
+ assert len(skill_names) == len(set(skill_names))
+ assert (skill_root / "engineering-mission-playbook" / "SKILL.md").exists()
+
+ assert local_skill.read_text(encoding="utf-8") == local_body
+
+ def test_codex_init_asset_paths_still_install_codex_and_shared_surfaces(
+ self, runner: CliRunner, workspace: Path, env: dict[str, str]
+ ) -> None:
+ r = runner.invoke(
+ cli, ["init", "--workspace-dir", str(workspace), "--agent", "codex"]
+ )
+ assert r.exit_code == 0, r.output
+
+ assert (workspace / ".codex" / "agents" / "investigator.toml").exists()
+ assert (workspace / ".codex" / "orchestrator_prompt.md").exists()
+ assert (workspace / ".codex" / "skills" / "scrutiny-validator" / "SKILL.md").exists()
+ assert (workspace / ".agents" / "skills" / "scrutiny-validator" / "SKILL.md").exists()
+ assert not (workspace / ".opencode").exists()
+
+ def test_opencode_explicit_provider_selectors_are_accepted(
+ self, runner: CliRunner, workspace: Path, env: dict[str, str]
+ ) -> None:
+ r = runner.invoke(
+ cli,
+ [
+ "init",
+ "--workspace-dir",
+ str(workspace),
+ "--orchestrator-provider",
+ "opencode",
+ "--worker-provider",
+ "opencode",
+ "--validator-provider",
+ "opencode",
+ "--terminal-reviewer-provider",
+ "opencode",
+ ],
+ )
+ assert r.exit_code == 0, r.output
+ assert (workspace / ".opencode" / "opencode.json").exists()
+
+
class TestListProjects:
def test_empty(self, runner: CliRunner, env: dict[str, str]) -> None:
From 55e2f16865b98122551b471dd93ccc1d1cbf6f21 Mon Sep 17 00:00:00 2001
From: David Rudduck
Date: Mon, 14 Sep 2026 14:02:28 +0000
Subject: [PATCH 6/9] fix(cli): print OpenCode init diagnostics
---
zenith/src/zenith_harness/cli.py | 48 +++++++++++++++++++++++++++++
zenith/tests/test_cli.py | 52 ++++++++++++++++++++++++++++++++
2 files changed, 100 insertions(+)
diff --git a/zenith/src/zenith_harness/cli.py b/zenith/src/zenith_harness/cli.py
index d725329..d9996da 100644
--- a/zenith/src/zenith_harness/cli.py
+++ b/zenith/src/zenith_harness/cli.py
@@ -2,6 +2,7 @@
import json
import os
+import re
import shutil
import tempfile
from pathlib import Path
@@ -145,6 +146,7 @@ def init(
f"worker={selection.worker.name}, "
f"validator={selection.resolved_validation_worker.name}."
)
+ _echo_opencode_diagnostics(workspace, selection)
click.echo(
"Bucket lives at $ZENITH_HOME/projects// — created on the first "
"`start_project(brief, workspace_dir)` call."
@@ -302,6 +304,52 @@ def _echo_next_steps(orchestrator: ProviderDefinition) -> None:
click.echo(" ")
+_SECRET_ASSIGNMENT_RE = re.compile(
+ r"(?i)\b([A-Z0-9_]*(?:API[_-]?KEY|AUTH[_-]?TOKEN|SECRET|PASSWORD)"
+ r"[A-Z0-9_]*)=([^ \t]+)"
+)
+_SECRET_FLAG_RE = re.compile(
+ r"(?i)(--(?:api[_-]?key|auth[_-]?token|token|secret|password)(?:=|\s+))"
+ r"([^ \t]+)"
+)
+_BEARER_TOKEN_RE = re.compile(r"(?i)\bBearer\s+([^ \t]+)")
+
+
+def _echo_opencode_diagnostics(workspace: Path, selection: ProviderSelection) -> None:
+ if selection.orchestrator.config_format != "opencode_config":
+ return
+
+ config_path = workspace / ".opencode" / "opencode.json"
+ click.echo("OpenCode diagnostics:")
+ click.echo(f" host: {selection.orchestrator.name} ({config_path})")
+ click.echo(
+ f" roles: orchestrator={selection.orchestrator.name}, "
+ f"worker={selection.worker.name}, "
+ f"validator={selection.resolved_validation_worker.name}, "
+ f"terminal reviewer={selection.resolved_terminal_reviewer.name}"
+ )
+ click.echo(
+ " ACP commands: "
+ f"worker={_diagnostic_command(selection.resolved_worker_acp_command)}, "
+ f"validator={_diagnostic_command(selection.resolved_validation_worker_acp_command)}, "
+ "terminal reviewer="
+ f"{_diagnostic_command(selection.resolved_terminal_reviewer_acp_command)}"
+ )
+ click.echo(
+ " model pins: worker=absent, validator=absent, "
+ "terminal reviewer=absent "
+ "(provider defaults preserved; no default model selected)"
+ )
+
+
+def _diagnostic_command(command: str | None) -> str:
+ if command is None:
+ return "absent"
+ redacted = _SECRET_ASSIGNMENT_RE.sub(r"\1=", command)
+ redacted = _SECRET_FLAG_RE.sub(r"\1", redacted)
+ return _BEARER_TOKEN_RE.sub("Bearer ", redacted)
+
+
def _resolve_selection(
*,
agent: str | None,
diff --git a/zenith/tests/test_cli.py b/zenith/tests/test_cli.py
index fa243a8..1aa3810 100644
--- a/zenith/tests/test_cli.py
+++ b/zenith/tests/test_cli.py
@@ -426,6 +426,41 @@ def test_opencode_agent_selector_writes_native_host_config(
assert "orchestrator=opencode, worker=opencode, validator=opencode." in r.output
assert "First read .opencode/orchestrator_prompt.md" in r.output
+ def test_opencode_init_stdout_includes_default_role_diagnostics(
+ self,
+ runner: CliRunner,
+ workspace: Path,
+ env: dict[str, str],
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ monkeypatch.setenv("OPENCODE_MODEL", "openai/ambient-expensive")
+ monkeypatch.setenv("OPENAI_API_KEY", "openai-secret")
+
+ r = runner.invoke(
+ cli, ["init", "--workspace-dir", str(workspace), "--agent", "opencode"]
+ )
+ assert r.exit_code == 0, r.output
+
+ config_path = workspace / ".opencode" / "opencode.json"
+ assert "OpenCode diagnostics:" in r.output
+ assert f"host: opencode ({config_path})" in r.output
+ assert (
+ "roles: orchestrator=opencode, worker=opencode, "
+ "validator=opencode, terminal reviewer=opencode"
+ ) in r.output
+ assert (
+ "ACP commands: worker=opencode acp, validator=opencode acp, "
+ "terminal reviewer=opencode acp"
+ ) in r.output
+ assert (
+ "model pins: worker=absent, validator=absent, "
+ "terminal reviewer=absent"
+ ) in r.output
+ assert "provider defaults preserved; no default model selected" in r.output
+ assert "openai/ambient-expensive" not in r.output
+ assert "openai-secret" not in r.output
+ assert "OPENAI_API_KEY" not in r.output
+
def test_opencode_init_preserves_unrelated_strict_json_settings(
self, runner: CliRunner, workspace: Path, env: dict[str, str]
) -> None:
@@ -697,6 +732,23 @@ def test_opencode_init_writes_mixed_provider_routing_values(
assert server_env["ZENITH_TERMINAL_REVIEWER_PROVIDER"] == "codex"
assert server_env["ZENITH_TERMINAL_REVIEWER_ACP_COMMAND"] == "codex-acp"
+ config_path = workspace / ".opencode" / "opencode.json"
+ assert "OpenCode diagnostics:" in r.output
+ assert f"host: opencode ({config_path})" in r.output
+ assert (
+ "roles: orchestrator=opencode, worker=opencode, "
+ "validator=claude, terminal reviewer=codex"
+ ) in r.output
+ assert (
+ "ACP commands: worker=opencode acp, validator=claude-agent-acp, "
+ "terminal reviewer=codex-acp"
+ ) in r.output
+ assert (
+ "model pins: worker=absent, validator=absent, "
+ "terminal reviewer=absent"
+ ) in r.output
+ assert "provider defaults preserved; no default model selected" in r.output
+
def test_opencode_init_installs_prompt_agents_and_skill_surfaces(
self, runner: CliRunner, workspace: Path, env: dict[str, str]
) -> None:
From 41abed4e59e9f182c6e43901dc220049fe930656 Mon Sep 17 00:00:00 2001
From: David Rudduck
Date: Mon, 14 Sep 2026 14:44:52 +0000
Subject: [PATCH 7/9] fix(cli): reject root OpenCode zenith conflicts
---
zenith/src/zenith_harness/cli.py | 35 ++++++++++++++++++++++++++++++
zenith/tests/test_cli.py | 37 ++++++++++++++++++++++++++++++++
2 files changed, 72 insertions(+)
diff --git a/zenith/src/zenith_harness/cli.py b/zenith/src/zenith_harness/cli.py
index d9996da..ad14604 100644
--- a/zenith/src/zenith_harness/cli.py
+++ b/zenith/src/zenith_harness/cli.py
@@ -497,6 +497,7 @@ def _write_bootstrap_config(
def _write_opencode_config(path: Path, entry: dict[str, object]) -> None:
_fail_if_opencode_jsonc_shadows_managed_entry(path)
+ _fail_if_opencode_root_strict_json_shadows_managed_entry(path)
config: dict[str, object]
if path.exists():
@@ -567,6 +568,40 @@ def _opencode_jsonc_paths(path: Path) -> tuple[Path, ...]:
return tuple(deduped)
+def _fail_if_opencode_root_strict_json_shadows_managed_entry(path: Path) -> None:
+ if path.parent.name != ".opencode":
+ return
+ root_json_path = path.parent.parent / path.name
+ if not root_json_path.exists():
+ return
+ if _strict_json_defines_mcp_zenith(root_json_path):
+ raise click.ClickException(
+ f"Cannot update {path}: {root_json_path} defines mcp.zenith, "
+ "which OpenCode loads alongside the managed .opencode JSON and "
+ "may merge into the effective registration. Remove that root "
+ "entry, rename the user MCP server, or keep Zenith's mcp.zenith "
+ "only in .opencode/opencode.json before rerunning zenith init."
+ )
+
+
+def _strict_json_defines_mcp_zenith(path: Path) -> bool:
+ text = path.read_text(encoding="utf-8")
+ try:
+ loaded = json.loads(text)
+ except json.JSONDecodeError as exc:
+ if '"mcp"' in text and '"zenith"' in text:
+ raise click.ClickException(
+ f"Cannot verify {path}: it appears to define mcp.zenith but "
+ "is not parseable as strict JSON. Fix or remove that root "
+ "entry before rerunning zenith init."
+ ) from exc
+ return False
+ if not isinstance(loaded, dict):
+ return False
+ mcp = loaded.get("mcp")
+ return isinstance(mcp, dict) and "zenith" in mcp
+
+
def _jsonc_defines_mcp_zenith(path: Path) -> bool:
text = path.read_text(encoding="utf-8")
without_comments = _strip_jsonc_comments(text)
diff --git a/zenith/tests/test_cli.py b/zenith/tests/test_cli.py
index 1aa3810..5109079 100644
--- a/zenith/tests/test_cli.py
+++ b/zenith/tests/test_cli.py
@@ -667,6 +667,43 @@ def test_opencode_root_jsonc_shadowing_zenith_fails_without_mutation(
assert config_path.read_text(encoding="utf-8") == original_json
assert jsonc_path.read_text(encoding="utf-8") == jsonc
+ def test_opencode_root_strict_json_shadowing_zenith_fails_without_mutation(
+ self, runner: CliRunner, workspace: Path, env: dict[str, str]
+ ) -> None:
+ config_path = workspace / ".opencode" / "opencode.json"
+ config_path.parent.mkdir()
+ original_managed = '{"theme": "system"}\n'
+ config_path.write_text(original_managed, encoding="utf-8")
+ root_config_path = workspace / "opencode.json"
+ root_config = json.dumps(
+ {
+ "theme": "root-user-config",
+ "mcp": {
+ "zenith": {
+ "type": "local",
+ "command": ["node", "shadowed.js"],
+ "environment": {"SHADOW": "root-strict-json"},
+ "enabled": True,
+ "timeout": 42,
+ }
+ },
+ },
+ indent=2,
+ ) + "\n"
+ root_config_path.write_text(root_config, encoding="utf-8")
+
+ r = runner.invoke(
+ cli, ["init", "--workspace-dir", str(workspace), "--agent", "opencode"]
+ )
+
+ assert r.exit_code != 0
+ assert "opencode.json" in r.output
+ assert "mcp.zenith" in r.output
+ assert "remove that root entry" in r.output.lower()
+ assert "SHADOW" not in r.output
+ assert config_path.read_text(encoding="utf-8") == original_managed
+ assert root_config_path.read_text(encoding="utf-8") == root_config
+
def test_opencode_init_does_not_persist_ambient_defaults_or_provider_secrets(
self,
runner: CliRunner,
From 8ba02fad7292d74b29359f284a4060f23af23048 Mon Sep 17 00:00:00 2001
From: David Rudduck
Date: Wed, 16 Sep 2026 20:40:35 +0000
Subject: [PATCH 8/9] docs: add OpenCode audience guides
---
CONTRIBUTING.md | 5 ++
README.md | 5 ++
docs/opencode-support/README.md | 17 ++++
docs/opencode-support/admin.md | 115 ++++++++++++++++++++++++
docs/opencode-support/developer.md | 136 +++++++++++++++++++++++++++++
docs/opencode-support/user.md | 132 ++++++++++++++++++++++++++++
zenith/README.md | 5 ++
7 files changed, 415 insertions(+)
create mode 100644 docs/opencode-support/README.md
create mode 100644 docs/opencode-support/admin.md
create mode 100644 docs/opencode-support/developer.md
create mode 100644 docs/opencode-support/user.md
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 82f89a9..4d38272 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -52,6 +52,11 @@ work. If you add future live OpenCode smoke tests, keep them opt-in and document
that normal worker and validator sessions use the credentials available to the
`opencode` process and therefore share the operator's billing trust boundary.
+Keep the audience-specific OpenCode docs in sync with code changes:
+[`docs/opencode-support/user.md`](docs/opencode-support/user.md),
+[`docs/opencode-support/admin.md`](docs/opencode-support/admin.md), and
+[`docs/opencode-support/developer.md`](docs/opencode-support/developer.md).
+
## License
By contributing, you agree that your contributions will be licensed under the [Apache License 2.0](LICENSE).
diff --git a/README.md b/README.md
index b50a6e8..da05003 100644
--- a/README.md
+++ b/README.md
@@ -160,6 +160,11 @@ use disposable local OpenCode configuration checks such as `opencode debug
config`; any live-provider smoke that can spend tokens must stay explicit and
opt-in.
+For audience-specific OpenCode guidance, see the
+[user](docs/opencode-support/user.md),
+[admin](docs/opencode-support/admin.md), and
+[developer](docs/opencode-support/developer.md) guides.
+
## How Zenith Works
diff --git a/docs/opencode-support/README.md b/docs/opencode-support/README.md
new file mode 100644
index 0000000..66ddb51
--- /dev/null
+++ b/docs/opencode-support/README.md
@@ -0,0 +1,17 @@
+# OpenCode Support Documentation
+
+OpenCode support is split by audience so setup, operations, and development
+guidance can stay focused:
+
+- [User guide](user.md): install OpenCode, initialize a project, and start a
+ Zenith mission from OpenCode.
+- [Admin guide](admin.md): understand generated configuration, preservation
+ rules, security boundaries, and operational checks.
+- [Developer guide](developer.md): maintain the PR-A implementation, tests,
+ assets, and future PR-B/PR-C boundaries.
+
+The original planning artifacts remain available for deeper design context:
+
+- [Product requirements](PRD.md)
+- [Technical specification](SPEC.md)
+- [Implementation plan](PLAN.md)
diff --git a/docs/opencode-support/admin.md b/docs/opencode-support/admin.md
new file mode 100644
index 0000000..a01da7b
--- /dev/null
+++ b/docs/opencode-support/admin.md
@@ -0,0 +1,115 @@
+---
+audience: admin
+component: opencode-support
+sources:
+ - README.md
+ - zenith/README.md
+ - zenith/src/zenith_harness/cli.py
+ - zenith/src/zenith_harness/providers.py
+ - zenith/tests/test_cli.py
+generated: 2026-09-16
+---
+
+# OpenCode Admin Guide
+
+This guide covers the operational and security boundaries of Zenith's
+project-scoped OpenCode support. Use it when reviewing what `zenith init
+--agent opencode` writes, what it refuses to write, and how to verify the
+generated host configuration.
+
+## Managed Surface
+
+OpenCode support is project-local. The managed configuration lives in
+`.opencode/opencode.json` under the single MCP server key `mcp.zenith`.
+
+The managed entry uses OpenCode's local MCP server shape:
+
+- `type: "local"`
+- `command`: an array beginning with `uv run --project `
+- `enabled: true`
+- `timeout: 1000000`
+- `environment`: Zenith routing values only
+
+The default OpenCode routing values are:
+
+- `ZENITH_ORCHESTRATOR_PROVIDER=opencode`
+- `ZENITH_WORKER_PROVIDER=opencode`
+- `ZENITH_WORKER_ACP_COMMAND=opencode acp`
+
+When a mixed-provider initialization is requested, the generated environment
+may also include validator or terminal-reviewer provider and ACP command keys.
+
+## Preservation And Conflict Policy
+
+Zenith preserves:
+
+- unrelated top-level strict JSON settings
+- unrelated entries under `mcp`
+- existing customized `.opencode/orchestrator_prompt.md`
+- existing skills that are not replaced by bundled Zenith skills
+
+Zenith fails closed instead of mutating or normalizing unsafe inputs:
+
+- malformed `.opencode/opencode.json`
+- non-object `.opencode/opencode.json`
+- non-object `mcp`
+- `.opencode/opencode.jsonc` defining `mcp.zenith`
+- project-root `opencode.jsonc` defining `mcp.zenith`
+- project-root strict `opencode.json` defining `mcp.zenith`
+
+The root strict JSON guard exists because OpenCode can load project-root config
+alongside `.opencode/opencode.json` and merge user-controlled `mcp.zenith` data
+into the effective server registration. Zenith refuses that situation unless
+the managed `.opencode/opencode.json` entry can remain the sole `mcp.zenith`
+source.
+
+## Security Boundary
+
+Zenith does not persist OpenCode provider credentials or host policy choices.
+The generated OpenCode config must not contain:
+
+- API keys or provider tokens
+- OpenCode default model or provider preferences
+- permission policy
+- plugin configuration
+- global OpenCode config
+- arbitrary provider secret environment variables
+
+Normal OpenCode worker and validator sessions use whatever credentials and
+billing access are available to the `opencode` process. Live provider checks can
+spend tokens and should remain explicitly opt-in. The default validation floor is
+hermetic tests plus disposable local OpenCode configuration checks.
+
+## Operational Verification
+
+Use a disposable workspace when verifying host configuration:
+
+```bash
+tmp="$(mktemp -d)"
+git -C "$tmp" init
+cd /path/to/zenith/zenith
+uv run zenith init --workspace-dir "$tmp" --agent opencode
+uv run zenith init --workspace-dir "$tmp" --agent opencode
+cd "$tmp"
+opencode debug config
+opencode mcp list
+```
+
+Expected results:
+
+- the second initialization leaves `.opencode/opencode.json` byte-identical
+- `opencode debug config` resolves `mcp.zenith`
+- `opencode mcp list` reports `zenith connected`
+- no credentials or ambient model/plugin/permission sentinels appear in stdout
+ or generated config
+
+## Troubleshooting
+
+If initialization reports that a root or JSONC file defines `mcp.zenith`, remove
+or rename that user-controlled server entry, then re-run initialization. Keep
+Zenith's managed `mcp.zenith` only in `.opencode/opencode.json`.
+
+If `opencode mcp list` does not connect, first inspect `opencode debug config`
+and confirm the generated command points to the expected Zenith checkout. Then
+run `uv run zenith-server --mode orchestrator` from that checkout to confirm the
+runtime can start.
diff --git a/docs/opencode-support/developer.md b/docs/opencode-support/developer.md
new file mode 100644
index 0000000..ef15703
--- /dev/null
+++ b/docs/opencode-support/developer.md
@@ -0,0 +1,136 @@
+---
+audience: developer
+component: opencode-support
+sources:
+ - zenith/pyproject.toml
+ - zenith/src/zenith_harness/providers.py
+ - zenith/src/zenith_harness/cli.py
+ - zenith/src/zenith_harness/acp_runner.py
+ - zenith/src/zenith_harness/bundled/providers/opencode/agents/contract-review.md
+ - zenith/src/zenith_harness/bundled/providers/opencode/agents/feature-reviewer.md
+ - zenith/src/zenith_harness/bundled/providers/opencode/agents/flow-validator.md
+ - zenith/src/zenith_harness/bundled/providers/opencode/agents/investigator.md
+ - zenith/tests/test_config.py
+ - zenith/tests/test_cli.py
+ - zenith/tests/test_assets.py
+ - zenith/tests/test_acp_runner.py
+generated: 2026-09-16
+---
+
+# OpenCode Developer Guide
+
+This guide describes the PR-A OpenCode implementation surface so future changes
+can keep provider behavior, generated assets, and validation boundaries aligned.
+
+## Component Summary
+
+OpenCode support is implemented inside the `zenith-harness` Python package. The
+package metadata declares `opencode` as a dependency, and the provider registry
+accepts `opencode` for orchestrator, worker, validator, and terminal-reviewer
+roles.
+
+The OpenCode provider definition uses:
+
+- `config_format="opencode_config"`
+- `default_worker_acp_command="opencode acp"`
+- `agent_output_dir=".opencode/agents"`
+- `orchestrator_prompt_output_path=".opencode/orchestrator_prompt.md"`
+- `skill_dirs=(".opencode/skills", ".agents/skills")`
+- `acp_runtime_mode="build"`
+- `acp_supports_system_prompt=False`
+
+## Initialization Flow
+
+`zenith init --agent opencode` resolves a `ProviderSelection`, writes OpenCode
+assets, and writes `.opencode/opencode.json` through the OpenCode-specific
+writer in `cli.py`.
+
+The OpenCode config writer must keep these properties:
+
+- strict JSON is parsed and preserved rather than regenerated from scratch
+- unrelated strict JSON settings and unrelated MCP servers survive
+- writes are atomic and avoid partial files on failure
+- a second identical initialization is byte-idempotent
+- JSONC files are never rewritten or normalized
+- root strict `opencode.json` and JSONC `mcp.zenith` conflicts fail clearly
+- OpenCode config does not receive forwarded runtime env secrets/defaults
+
+OpenCode diagnostics are emitted only for OpenCode host configuration. They
+print resolved host, roles, ACP commands, and absent model-pin status without
+dumping raw credential values.
+
+## ACP Runtime Behavior
+
+The OpenCode provider's `acp_runtime_mode` is `build`. During ACP session setup,
+the runner still uses the existing `session/set_mode` path for provider runtime
+mode. The Claude settings workaround is scoped to the Claude provider only, so
+OpenCode runtime mode must not create or modify `.claude/settings.json`.
+
+PR-A deliberately does not implement OpenCode ACP model or effort session
+options. Those remain PR-B work.
+
+## Bundled Assets
+
+OpenCode subagents are bundled as Markdown frontmatter files under
+`zenith/src/zenith_harness/bundled/providers/opencode/agents/`:
+
+- `investigator.md`
+- `contract-review.md`
+- `feature-reviewer.md`
+- `flow-validator.md`
+
+Their bodies preserve the role intent of the Claude agents while using
+OpenCode-compatible asset shape. Initialization installs these assets under the
+target workspace's `.opencode/agents/` directory and installs bundled skills
+under both `.opencode/skills/` and `.agents/skills/`.
+
+## Tests To Keep Current
+
+The PR-A behavior is covered across four focused test modules:
+
+- `tests/test_config.py`: provider registration, default ACP command, role
+ resolution, and provider switching.
+- `tests/test_cli.py`: strict JSON write/merge behavior, idempotency, JSONC and
+ root strict conflict failures, no ambient secret/default persistence,
+ diagnostics, mixed-provider routing, prompt/agent/skill installation, and
+ asset preservation.
+- `tests/test_assets.py`: OpenCode agent frontmatter and body parity.
+- `tests/test_acp_runner.py`: build-mode selection and the guard that prevents
+ OpenCode from writing Claude host settings.
+
+Before opening or updating an OpenCode support PR, run:
+
+```bash
+cd zenith
+uv run ruff check .
+uv run mypy src
+uv run pytest -q
+uv build
+```
+
+For real host-surface validation, also run disposable OpenCode checks:
+
+```bash
+tmp="$(mktemp -d)"
+git -C "$tmp" init
+uv run zenith init --workspace-dir "$tmp" --agent opencode
+uv run zenith init --workspace-dir "$tmp" --agent opencode
+cd "$tmp"
+opencode debug config
+opencode mcp list
+```
+
+## Future Boundaries
+
+Keep PR-A focused. Do not backfill these future surfaces into PR-A maintenance
+work unless a later design explicitly changes the boundary:
+
+- PR B: per-role OpenCode model fields, model/effort session options, live
+ OpenCode worker/validator smokes, and model-selection docs.
+- PR C: isolated OpenCode terminal review, hardening, `--pure`/isolated homes,
+ and canary fixtures.
+- Separate future work: user-scoped OpenCode setup and provider-neutral billing
+ grants.
+
+When adding future behavior, update the user, admin, and developer audience docs
+in this directory in the same PR as the code change.
diff --git a/docs/opencode-support/user.md b/docs/opencode-support/user.md
new file mode 100644
index 0000000..904bec8
--- /dev/null
+++ b/docs/opencode-support/user.md
@@ -0,0 +1,132 @@
+---
+audience: user
+component: opencode-support
+sources:
+ - zenith/README.md
+ - README.md
+ - zenith/src/zenith_harness/providers.py
+ - zenith/src/zenith_harness/cli.py
+ - zenith/tests/test_cli.py
+generated: 2026-09-16
+---
+
+# OpenCode User Guide
+
+OpenCode support lets you initialize a target project so OpenCode can connect to
+Zenith as the orchestrator host and run Zenith worker, validator, and terminal
+review roles through OpenCode's native ACP command. The PR-A implementation is
+project-scoped and experimental: it sets up the OpenCode host surface and local
+configuration, but it does not claim live paid OpenCode worker execution or
+OpenCode model/effort session controls.
+
+## Requirements
+
+Install the normal Zenith requirements first:
+
+- Python 3.11+
+- `uv`
+- Node.js 22+ and `npm`
+- OpenCode on `PATH`
+
+OpenCode does not need a third-party ACP adapter for Zenith. It uses the native
+`opencode acp` command registered in Zenith's provider table.
+
+```bash
+curl -fsSL https://opencode.ai/install | bash
+command -v opencode
+opencode --version
+```
+
+PR-A compatibility was validated against OpenCode `1.18.30`.
+
+## Initialize A Project
+
+Run initialization from the Zenith checkout, pointing `--workspace-dir` at the
+target project that Zenith should operate on:
+
+```bash
+cd /path/to/zenith/zenith
+uv run zenith init --workspace-dir /path/to/your-app --agent opencode
+```
+
+The command writes only project-local OpenCode files:
+
+- `.opencode/opencode.json`
+- `.opencode/orchestrator_prompt.md`
+- `.opencode/agents/`
+- `.opencode/skills/`
+- `.agents/skills/`
+
+It prints OpenCode diagnostics that include the generated host path, resolved
+roles, ACP commands, and the fact that model pins are absent. Secret-looking
+command fragments are redacted in diagnostics.
+
+## Start A Mission From OpenCode
+
+Start OpenCode from the initialized target project:
+
+```bash
+cd /path/to/your-app
+opencode
+```
+
+Then ask OpenCode to use the generated Zenith prompt:
+
+```text
+First read .opencode/orchestrator_prompt.md and treat it as your primary role, then use Zenith to run this mission.
+
+
+```
+
+## Generated Configuration
+
+`zenith init --agent opencode` manages the `mcp.zenith` entry in
+`.opencode/opencode.json`. The generated server is local and points back to the
+Zenith checkout:
+
+```json
+{
+ "mcp": {
+ "zenith": {
+ "type": "local",
+ "command": ["uv", "run", "--project", "/path/to/zenith", "zenith-server", "--mode", "orchestrator"],
+ "enabled": true,
+ "timeout": 1000000,
+ "environment": {
+ "ZENITH_ORCHESTRATOR_PROVIDER": "opencode",
+ "ZENITH_WORKER_PROVIDER": "opencode",
+ "ZENITH_WORKER_ACP_COMMAND": "opencode acp"
+ }
+ }
+ }
+}
+```
+
+The exact `--project` path depends on the Zenith checkout used to run
+initialization.
+
+## What Zenith Preserves
+
+Zenith preserves unrelated strict JSON settings and unrelated OpenCode MCP
+servers in `.opencode/opencode.json`. Re-running the same initialization is
+byte-idempotent once the managed entry already exists.
+
+Zenith never rewrites or normalizes JSONC. If a JSONC source or project-root
+strict `opencode.json` defines `mcp.zenith`, initialization fails with
+remediation instead of silently allowing OpenCode to shadow or merge into the
+managed server.
+
+## Current Limits
+
+PR-A does not select or persist an OpenCode model, provider credential,
+permission policy, plugin configuration, global OpenCode config, or arbitrary
+provider secret. Provider access and billing remain with the `opencode` process
+you run locally.
+
+The following are intentionally future work:
+
+- per-role OpenCode model and effort session options
+- verified live OpenCode worker and validator smoke tests
+- isolated OpenCode terminal review
+- user-scoped OpenCode setup
+- provider-neutral billing grants
diff --git a/zenith/README.md b/zenith/README.md
index a88e456..d801ca9 100644
--- a/zenith/README.md
+++ b/zenith/README.md
@@ -111,6 +111,11 @@ models, permission policy, plugin configuration, or global config.
Default checks are hermetic. Live OpenCode provider checks may spend tokens and
must remain explicit opt-in tests.
+Detailed OpenCode guidance is split by audience in the repository docs:
+[user guide](../docs/opencode-support/user.md),
+[admin guide](../docs/opencode-support/admin.md), and
+[developer guide](../docs/opencode-support/developer.md).
+
## Development
```bash
From aed7cb0cc5a7ff9bdb77e9ae99c14443edb565af Mon Sep 17 00:00:00 2001
From: David Rudduck
Date: Wed, 16 Sep 2026 20:49:45 +0000
Subject: [PATCH 9/9] test: expand OpenCode coverage
---
zenith/tests/test_assets.py | 62 ++++++++-
zenith/tests/test_cli.py | 253 +++++++++++++++++++++++++++++++++++-
2 files changed, 313 insertions(+), 2 deletions(-)
diff --git a/zenith/tests/test_assets.py b/zenith/tests/test_assets.py
index f355279..b5a5158 100644
--- a/zenith/tests/test_assets.py
+++ b/zenith/tests/test_assets.py
@@ -6,7 +6,7 @@
import pytest
-from zenith_harness.assets import AssetLoader, parse_frontmatter
+from zenith_harness.assets import AssetLoader, iter_skill_directories, parse_frontmatter
from zenith_harness.config import HarnessConfig
from zenith_harness.models import ASSERTION_ID_REGEX
@@ -34,6 +34,9 @@ def loader(config: HarnessConfig) -> AssetLoader:
class TestSkillResolution:
+ def test_missing_skill_directory_lists_empty(self, tmp_path: Path) -> None:
+ assert iter_skill_directories(tmp_path / "missing") == []
+
@pytest.mark.parametrize(
"skill_name", ["scrutiny-validator", "engineering-mission-playbook"]
)
@@ -73,6 +76,45 @@ def test_project_authored_worker_skill_loads(
assert s.source == "project"
assert "Project body" in s.body
+ def test_load_skill_missing_raises(self, loader: AssetLoader) -> None:
+ with pytest.raises(FileNotFoundError, match="Skill not found: no-such-skill"):
+ loader.load_skill("no-such-skill")
+
+ def test_list_skills_prefers_project_then_personal_then_bundled(
+ self,
+ loader: AssetLoader,
+ config: HarnessConfig,
+ ) -> None:
+ project_skill = config.zenith_dir("p-list") / "skills" / "project" / "SKILL.md"
+ project_skill.parent.mkdir(parents=True, exist_ok=True)
+ project_skill.write_text(
+ "---\n"
+ "name: shared-skill\n"
+ "description: project copy wins\n"
+ "---\n\n"
+ "Project body.\n",
+ encoding="utf-8",
+ )
+ personal_skill = config.harness_home / "skills" / "personal" / "SKILL.md"
+ personal_skill.parent.mkdir(parents=True, exist_ok=True)
+ personal_skill.write_text(
+ "---\n"
+ "name: shared-skill\n"
+ "description: personal copy loses\n"
+ "---\n\n"
+ "Personal body.\n",
+ encoding="utf-8",
+ )
+
+ with_project = loader.list_skills(project_id="p-list")
+ without_project = loader.list_skills()
+
+ shared = [skill for skill in with_project if skill.name == "shared-skill"]
+ assert len(shared) == 1
+ assert shared[0].source == "project"
+ assert shared[0].description == "project copy wins"
+ assert all(skill.source != "project" for skill in without_project)
+
class TestFrontmatter:
def test_parse_with_frontmatter(self) -> None:
@@ -86,6 +128,24 @@ def test_parse_without_frontmatter(self) -> None:
fm, body = parse_frontmatter(raw)
assert fm == {} and body == raw
+ def test_parse_incomplete_frontmatter_as_body(self) -> None:
+ raw = "---\nname: x\nbody without closing delimiter\n"
+ fm, body = parse_frontmatter(raw)
+ assert fm == {}
+ assert body == raw
+
+ def test_parse_non_mapping_frontmatter_as_empty(self) -> None:
+ raw = "---\n- not\n- a\n- mapping\n---\nbody here\n"
+ fm, body = parse_frontmatter(raw)
+ assert fm == {}
+ assert body == "body here\n"
+
+
+class TestPrompts:
+ def test_missing_prompt_file_raises(self, loader: AssetLoader) -> None:
+ with pytest.raises(FileNotFoundError, match="Prompt file not found"):
+ loader.load_prompt_file("worker", "missing.md")
+
class TestOpenCodeBundledAgents:
def test_opencode_subagents_use_markdown_frontmatter(self) -> None:
diff --git a/zenith/tests/test_cli.py b/zenith/tests/test_cli.py
index 5109079..d16d6fb 100644
--- a/zenith/tests/test_cli.py
+++ b/zenith/tests/test_cli.py
@@ -1,15 +1,31 @@
"""CLI integration tests — init / list-projects / show-project / install-skills."""
from __future__ import annotations
+from dataclasses import replace
import json
import tomllib
from pathlib import Path
+import click
import pytest
from click.testing import CliRunner
from zenith_harness.assets import parse_frontmatter
-from zenith_harness.cli import cli
+import zenith_harness.cli as cli_module
+from zenith_harness.cli import (
+ _diagnostic_command,
+ _jsonc_defines_mcp_zenith,
+ _replace_managed_block,
+ _resolve_selection,
+ _storage_env,
+ _strict_json_defines_mcp_zenith,
+ _strip_jsonc_comments,
+ _strip_jsonc_trailing_commas,
+ _write_bootstrap_config,
+ _write_opencode_config,
+ cli,
+)
+from zenith_harness.providers import ProviderSelection, get_provider
@pytest.fixture
@@ -916,6 +932,241 @@ def test_opencode_explicit_provider_selectors_are_accepted(
assert (workspace / ".opencode" / "opencode.json").exists()
+class TestOpenCodeConfigHelpers:
+ def test_diagnostic_command_redacts_sensitive_forms(self) -> None:
+ command = (
+ "OPENAI_API_KEY=super-secret opencode acp --token bearer-secret "
+ "--auth-token next-secret -H 'Authorization: Bearer raw-secret'"
+ )
+
+ redacted = _diagnostic_command(command)
+
+ assert _diagnostic_command(None) == "absent"
+ assert "super-secret" not in redacted
+ assert "bearer-secret" not in redacted
+ assert "next-secret" not in redacted
+ assert "raw-secret" not in redacted
+ assert "OPENAI_API_KEY=" in redacted
+ assert "--token " in redacted
+ assert "--auth-token " in redacted
+ assert "Bearer " in redacted
+
+ def test_resolve_selection_rejects_agent_orchestrator_conflict(self) -> None:
+ with pytest.raises(
+ click.UsageError,
+ match="--agent conflicts with --orchestrator-provider",
+ ):
+ _resolve_selection(
+ agent="opencode",
+ orchestrator="codex",
+ worker=None,
+ worker_acp_command=None,
+ validator=None,
+ validator_acp_command=None,
+ terminal_reviewer=None,
+ terminal_reviewer_acp_command=None,
+ )
+
+ def test_storage_env_resolves_explicit_zenith_home(self, tmp_path: Path) -> None:
+ selection = ProviderSelection(
+ orchestrator=get_provider("opencode"),
+ worker=get_provider("opencode"),
+ )
+ zenith_home = tmp_path / "home" / ".." / "zenith-home"
+
+ env = _storage_env(
+ zenith_home=str(zenith_home),
+ workspace=tmp_path,
+ selection=selection,
+ )
+
+ assert env == {"ZENITH_HOME": str(zenith_home.resolve())}
+
+ def test_write_bootstrap_config_rejects_unknown_config_format(
+ self,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ bad_orchestrator = replace(
+ get_provider("opencode"),
+ config_format="future_config",
+ )
+ selection = ProviderSelection(
+ orchestrator=bad_orchestrator,
+ worker=get_provider("opencode"),
+ )
+ monkeypatch.setattr(cli_module, "_mcp_server_args", lambda: ["server"])
+
+ with pytest.raises(ValueError, match="unsupported config_format: future_config"):
+ _write_bootstrap_config(tmp_path, selection, {}, {})
+
+ def test_write_opencode_config_cleans_temp_file_when_replace_fails(
+ self,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ config_path = tmp_path / ".opencode" / "opencode.json"
+
+ def fail_replace(src: Path, dst: Path) -> None:
+ raise RuntimeError(f"replace failed for {src} -> {dst}")
+
+ monkeypatch.setattr(cli_module.os, "replace", fail_replace)
+
+ with pytest.raises(RuntimeError, match="replace failed"):
+ _write_opencode_config(config_path, {"type": "local"})
+
+ assert not config_path.exists()
+ assert list(config_path.parent.glob(".opencode.json.*.tmp")) == []
+
+ @pytest.mark.parametrize(
+ "config_path",
+ [
+ Path("opencode.json"),
+ Path("nested/opencode.json"),
+ ],
+ )
+ def test_write_opencode_config_allows_absent_root_shadow_config(
+ self,
+ tmp_path: Path,
+ config_path: Path,
+ ) -> None:
+ path = tmp_path / config_path
+
+ _write_opencode_config(path, {"type": "local"})
+
+ assert json.loads(path.read_text(encoding="utf-8"))["mcp"]["zenith"] == {
+ "type": "local"
+ }
+
+ def test_strict_json_shadow_detection_handles_invalid_and_non_object(
+ self,
+ tmp_path: Path,
+ ) -> None:
+ invalid_shadow = tmp_path / "shadow.json"
+ invalid_shadow.write_text('{"mcp": {"zenith": ', encoding="utf-8")
+ invalid_irrelevant = tmp_path / "irrelevant.json"
+ invalid_irrelevant.write_text('{"theme": ', encoding="utf-8")
+ non_object = tmp_path / "array.json"
+ non_object.write_text('["mcp", "zenith"]', encoding="utf-8")
+ valid_shadow = tmp_path / "valid.json"
+ valid_shadow.write_text(
+ json.dumps({"mcp": {"zenith": {"type": "local"}}}),
+ encoding="utf-8",
+ )
+
+ with pytest.raises(click.ClickException, match="Cannot verify"):
+ _strict_json_defines_mcp_zenith(invalid_shadow)
+ assert _strict_json_defines_mcp_zenith(invalid_irrelevant) is False
+ assert _strict_json_defines_mcp_zenith(non_object) is False
+ assert _strict_json_defines_mcp_zenith(valid_shadow) is True
+
+ def test_jsonc_shadow_detection_handles_invalid_and_non_object(
+ self,
+ tmp_path: Path,
+ ) -> None:
+ invalid_shadow = tmp_path / "shadow.jsonc"
+ invalid_shadow.write_text(
+ '{\n // comment\n "mcp": {"zenith": \n',
+ encoding="utf-8",
+ )
+ invalid_irrelevant = tmp_path / "irrelevant.jsonc"
+ invalid_irrelevant.write_text('{"theme": ', encoding="utf-8")
+ non_object = tmp_path / "array.jsonc"
+ non_object.write_text('["mcp", "zenith",]', encoding="utf-8")
+ valid_shadow = tmp_path / "valid.jsonc"
+ valid_shadow.write_text(
+ '{\n "mcp": {"zenith": {"type": "local",},},\n}\n',
+ encoding="utf-8",
+ )
+
+ with pytest.raises(click.ClickException, match="Cannot verify"):
+ _jsonc_defines_mcp_zenith(invalid_shadow)
+ assert _jsonc_defines_mcp_zenith(invalid_irrelevant) is False
+ assert _jsonc_defines_mcp_zenith(non_object) is False
+ assert _jsonc_defines_mcp_zenith(valid_shadow) is True
+
+ def test_jsonc_strippers_preserve_string_literals(self) -> None:
+ jsonc = r'''{
+ "slash": "proto://value",
+ "block": "literal /* not comment */ value",
+ "quote": "escaped \" // not comment",
+ // remove this line comment
+ "list": [
+ "kept",
+ ],
+ /*
+ * remove this block comment but keep newlines
+ */
+ "mcp": {
+ "zenith": {"type": "local",},
+ },
+}
+'''
+
+ without_comments = _strip_jsonc_comments(jsonc)
+ without_commas = _strip_jsonc_trailing_commas(without_comments)
+ parsed = json.loads(without_commas)
+
+ assert parsed["slash"] == "proto://value"
+ assert parsed["block"] == "literal /* not comment */ value"
+ assert parsed["quote"] == 'escaped " // not comment'
+ assert parsed["list"] == ["kept"]
+ assert parsed["mcp"]["zenith"] == {"type": "local"}
+ assert "remove this line comment" not in without_comments
+ assert "remove this block comment" not in without_comments
+
+ def test_replace_managed_block_replaces_existing_block_and_preserves_suffix(
+ self,
+ tmp_path: Path,
+ ) -> None:
+ config_path = tmp_path / "config.toml"
+ config_path.write_text(
+ "prefix = true\n"
+ "\n"
+ "# BEGIN zenith\n"
+ "old = true\n"
+ "# END zenith\n"
+ "\n"
+ "suffix = true\n",
+ encoding="utf-8",
+ )
+
+ _replace_managed_block(
+ config_path,
+ "# BEGIN zenith",
+ "# END zenith",
+ "# BEGIN zenith\nnew = true\n# END zenith\n",
+ )
+
+ updated = config_path.read_text(encoding="utf-8")
+ assert "prefix = true" in updated
+ assert "new = true" in updated
+ assert "suffix = true" in updated
+ assert "old = true" not in updated
+
+ def test_replace_managed_block_appends_when_block_missing(
+ self,
+ tmp_path: Path,
+ ) -> None:
+ config_path = tmp_path / "config.toml"
+ config_path.write_text("prefix = true\n", encoding="utf-8")
+
+ _replace_managed_block(
+ config_path,
+ "# BEGIN zenith",
+ "# END zenith",
+ "# BEGIN zenith\nnew = true\n# END zenith\n",
+ )
+
+ assert config_path.read_text(encoding="utf-8") == (
+ "prefix = true\n"
+ "\n"
+ "# BEGIN zenith\n"
+ "new = true\n"
+ "# END zenith\n"
+ )
+
+
class TestListProjects:
def test_empty(self, runner: CliRunner, env: dict[str, str]) -> None: