Open-source skills for designing and reviewing software with AI agents
Python agent-skillsai-agentsantigravityclaude-codeclaude-code-pluginclaude-skillscodexcodex-plugincoding-agentscontext-engineeringdeveloper-toolsgeminillmmulti-agentprompt-engineeringspec-driven-development
feat(opencode): add experimental V1 integration (#165)
n3wth8450f114c110
diff --git a/.github/workflows/opencode-native.yml b/.github/workflows/opencode-native.ymlnew file mode 100644index 0000000..6a041d1--- /dev/null+++ b/.github/workflows/opencode-native.yml@@ -0,0 +1,58 @@+# Copyright 2026 Google LLC+# SPDX-License-Identifier: Apache-2.0++name: OpenCode native probe++on:+ pull_request:+ paths:+ - '.github/workflows/opencode-native.yml'+ - 'adapters/opencode/**'+ - 'agents/**'+ - 'docs/opencode.md'+ - 'resources/**'+ - 'skills/**'+ - 'plugin.json'+ - 'tests/integration/opencode-ci/**'+ - 'tests/integration/opencode_native_probe.py'+ push:+ branches: [main]+ paths:+ - '.github/workflows/opencode-native.yml'+ - 'adapters/opencode/**'+ - 'agents/**'+ - 'docs/opencode.md'+ - 'resources/**'+ - 'skills/**'+ - 'plugin.json'+ - 'tests/integration/opencode-ci/**'+ - 'tests/integration/opencode_native_probe.py'++permissions:+ contents: read++jobs:+ native-probe:+ runs-on: ubuntu-24.04+ timeout-minutes: 10+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: '3.12'+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0+ with:+ node-version: '22'+ - name: Install pinned OpenCode executable+ working-directory: tests/integration/opencode-ci+ run: npm ci --ignore-scripts+ - name: Exercise native child permissions+ env:+ PROBE_OUTPUT: ${{ runner.temp }}/opencode-native-probe+ run: >-+ python tests/integration/opencode_native_probe.py+ --source .+ --opencode tests/integration/opencode-ci/node_modules/opencode-linux-x64/bin/opencode+ --output "$PROBE_OUTPUT"diff --git a/adapters/opencode/install.py b/adapters/opencode/install.pynew file mode 100644index 0000000..533a8b3--- /dev/null+++ b/adapters/opencode/install.py@@ -0,0 +1,146 @@+# Copyright 2026 Google LLC.+# SPDX-License-Identifier: Apache-2.0++"""Install an experimental OpenCode V1 bundle without changing user config."""++import argparse+import hashlib+import json+from pathlib import Path+import re+import shutil++ROOT = Path(__file__).resolve().parents[2]+HOST_VERSION = "1.18.29"+REVIEWERS = (+ "codebase_details", "comprehension", "design_critic",+ "implementation_readiness", "structural", "style", "zoom_out",+)+++def name(path: Path) -> str:+ """Read the canonical name without a runtime YAML dependency."""+ header = path.read_text(encoding="utf-8").split("---", 2)[1]+ match = re.search(r"^name: (egm-[a-z-]+)$", header, re.MULTILINE)+ if not match:+ raise ValueError(f"Missing canonical name: {path}")+ return match[1]+++def install(destination: Path) -> Path:+ """Create a new installation; refuse to overwrite any existing path."""+ destination = destination.expanduser().absolute()+ if destination.exists() or destination.is_symlink():+ raise FileExistsError(destination)+ destination = destination.resolve()+ # Check resolved parents too: paths enter glob rules and prompt templates.+ if "\\" in destination.as_posix() or any(+ c in str(destination) for c in '*?[]{}!@`$\n\r'+ ):+ raise ValueError("Installation path contains template or glob characters")+ # Read rules match worktree-relative paths and "*" spans "/", so "*.env.*"+ # would deny every bundle read below such a path.+ if ".env." in str(destination).lower():+ raise ValueError("Installation path matches the .env read rules")+ if destination.is_relative_to(ROOT):+ raise ValueError("Install outside the source tree")+ destination.mkdir(parents=True)+ bundle = destination / "bundle"+ bundle.mkdir()+ for directory in ("skills", "agents", "resources", "docs"):+ shutil.copytree(ROOT / directory, bundle / directory)+ for filename in ("plugin.json", "LICENSE", "README.md", "TESTING.md"):+ shutil.copy2(ROOT / filename, bundle / filename)++ guide = bundle / "docs/opencode.md"+ context = (+ f"Read {guide} first. EGM bundle root: {bundle}. "+ "Resolve agents/, resources/, and docs/ against this root. "+ "Resolve references/ against the canonical skill directory. "+ "Resolve user files and outputs against the project working directory. "+ )+ agents = {}+ for reviewer in REVIEWERS:+ persona = bundle / "agents" / f"{reviewer}.md"+ agents[name(persona)] = {+ "description": f"EGM read-only {reviewer} reviewer (experimental)",+ "mode": "subagent",+ "color": "#E86E00",+ "permission": {+ "*": "deny",+ # Later rules win, so "*" alone would override OpenCode's default .env rules.+ "read": {+ "*": "allow", "*.env": "deny", "*.env.*": "deny",+ "*.env.example": "allow", "mcp:*": "deny",+ },+ # grep does not enforce read rules, so it could expose .env files.+ "glob": "allow", "grep": "deny",+ "external_directory": {"*": "deny", f"{bundle}/**": "allow"},+ },+ "prompt": context + f"Read {persona} before the target and supplied standards. "+ "Return findings to the caller. Do not write reports or delegate. "+ "Read prior reports only when explicitly supplied and required by the canonical stage. "+ "Do not retrieve unsolicited history, memory, or earlier reviewer findings. "+ "Report inaccessible required files as an incomplete review.",+ }+ agents["egm"] = {+ "description": "EGM orchestrator (experimental OpenCode V1)",+ "mode": "primary",+ "color": "#1B6EF3",+ "permission": {+ "*": "ask",+ "read": {"*": "allow", "*.env": "ask", "*.env.*": "ask", "*.env.example": "allow"},+ "glob": "allow", "grep": "allow",+ "skill": {"*": "deny", "egm-*": "allow"},+ "task": {"*": "deny", **{key: "allow" for key in agents}},+ "external_directory": {"*": "ask", f"{bundle}/**": "allow"},+ },+ "prompt": context + "Follow the canonical skill. Dispatch reviewers directly "+ "with task and the registered persona name as subagent_type. "+ "Omit task_id for every independent review; never resume a reviewer. "+ "Wait for foreground completion. Pass only the task, absolute resource paths, "+ "target, standards, and selected reading list, not conversation history. "+ "Stop if delegation or a required completion is missing. "+ "When running brainstorm before draft, complete all six brainstorm "+ "reviewers and synthesize their findings into concepts_brief.md before drafting. "+ "In review, write each completed stage report before starting the next stage. "+ "Before Step 8, verify zoom_out_report.md exists in the artifact directory "+ "and pass its absolute path to the reviewer; stop if it is missing. "+ "Write reports yourself. Preserve every human approval gate.",+ }+ skills = destination / "skills"+ skills.mkdir()+ commands = {}+ for skill in sorted((bundle / "skills").glob("*/SKILL.md")):+ skill_name = name(skill)+ (skills / skill_name).symlink_to(skill.parent, target_is_directory=True)+ commands[skill_name] = {+ "description": f"Run {skill_name} (experimental)",+ "agent": "egm",+ "template": context + f"Read and execute {skill}.\nUser request: $ARGUMENTS",+ }+ config = destination / "opencode.json"+ config.write_text(json.dumps({+ "$schema": "https://opencode.ai/config.json",+ "autoupdate": False,+ "default_agent": "egm",+ "skills": {"paths": [str(skills)]},+ "agent": agents,+ "command": commands,+ }, indent=2) + "\n", encoding="utf-8")+ metadata = json.loads((bundle / "plugin.json").read_text(encoding="utf-8"))+ (destination / "installation.json").write_text(json.dumps({+ "name": metadata["name"], "version": metadata["version"],+ "host_version": HOST_VERSION, "status": "experimental",+ "sha256": {+ path.relative_to(destination).as_posix(): hashlib.sha256(path.read_bytes()).hexdigest()+ for path in sorted(bundle.rglob("*")) if path.is_file()+ },+ }, indent=2) + "\n", encoding="utf-8")+ return config+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("destination", type=Path, help="New, fixed installation directory")+ print(install(parser.parse_args().destination))diff --git a/docs/opencode.md b/docs/opencode.mdnew file mode 100644index 0000000..148223e--- /dev/null+++ b/docs/opencode.md@@ -0,0 +1,200 @@+<!-- Copyright 2026 Google LLC. SPDX-License-Identifier: Apache-2.0 -->++# OpenCode V1 integration (experimental)++This adapter targets OpenCode CLI **1.18.29**, with V1 `task` and `permission` interfaces.+It does not target V2 `subagent` or `permissions` interfaces.+Installation checks do not establish workflow or isolation support.+Maintainer approval, live workflows, and isolation verification remain pending under [#146](https://github.com/google/elephant-goldfish-model/issues/146).+The proposed architecture is in [the additional harness design](designs/additional-harnesses.md).++## Install++Use Python 3.10+ and a POSIX filesystem with symbolic links.+Select a fixed candidate commit before installation. Keep the installation at its original path.+The installer copies the complete canonical resource trees. It does not change global or project configuration.+It refuses an existing destination. Use a new destination for each candidate.++```sh+git rev-parse HEAD+python3 adapters/opencode/install.py /absolute/egm-opencode-candidate+opencode --version+```++Require version `1.18.29` before launch. Install that exact version if necessary:++```sh+npm install --prefix /absolute/opencode-v1 [email protected]+/absolute/opencode-v1/node_modules/.bin/opencode --version+```++Inspect the generated `opencode.json` and `installation.json` before use.+The latter records package identity and SHA-256 hashes of all bundled files.+The native configuration contains seven commands, seven reviewers, and the `egm` primary agent.+Native skill aliases use the canonical frontmatter names and link to the unchanged skill directories.++Start OpenCode from the project directory with the candidate configuration:++```sh+OPENCODE_CONFIG=/absolute/egm-opencode-candidate/opencode.json opencode --agent egm+```++Model calls require separate user authorization. Installation and version checks do not require model calls.+Select `egm` before native skill use. Other primary agents do not receive this adapter's dispatch instructions.+For review text, use an ordinary message rather than a slash command. For example:++```text+Use the egm-review skill to review /absolute/path/design.md.+```++Paste material into that ordinary message, or save it in a file for the agent to read.+The generated `/egm-brainstorm`, `/egm-draft`, and `/egm-review` commands retain+OpenCode's native command syntax. Their arguments are not literal text: OpenCode+evaluates shell markers (an exclamation mark followed by a command in backticks)+before agent tool permissions apply. Do not paste untrusted review material into+slash-command arguments. Markdown fences do not disable this preprocessing.++To uninstall, stop sessions and remove only this candidate directory. Remove its environment override.++## Paths and dispatch++Use the absolute bundle root in the generated prompt.+Resolve `agents/`, `resources/`, and `docs/` against that root.+Resolve `references/` against the canonical skill directory, after resolving its alias.+Resolve user files against the project directory. Never substitute project files for bundled personas.++Dispatch reviewers directly from `egm` with the V1 `task` tool.+Set `subagent_type` to the persona's canonical frontmatter name.+Supply `description` and `prompt`. Omit `task_id` to create a fresh session.+Use foreground tasks. Do not enable background dispatch or reuse a reviewer session.+The primary agent performs synthesis and writes reports; no nested synthesizer adapter is installed.+Bootstrap worker and scout delegation is outside this adapter's scope. Although+all seven skills are discoverable, the task allowlist contains only the seven+reviewer types. Stop if bootstrap requires an orchestrator or scout; do not+substitute a reviewer or simulate the missing worker.++Pass absolute paths for the persona, target, standards, and selected sources.+Do not pass parent history, private reasoning, or memory.+Supply prior report paths only when the canonical stage requires them, such as+`zoom_out_report.md` for Step 8 (Intermediate Zoom Out).+Read prior reports only when explicitly supplied and required by the canonical stage.+Do not retrieve unsolicited history, memory, or earlier reviewer findings.+Require all specified reads and actual task completion before synthesis.+Report a missing start, completion, required read, or malformed result as incomplete.+Stop if native delegation is unavailable. Never simulate Goldfish reviewers in the parent conversation.++When brainstorm precedes draft, complete all six brainstorm reviewers first.+Synthesize their findings into `concepts_brief.md` before drafting.+For review, write each completed stage report before starting the next stage.+Before Step 8, verify `zoom_out_report.md` exists in the artifact directory.+Pass its absolute path to the reviewer. Stop if the report is missing.++Reviewers deny every tool except `read` and `glob`.+`grep` is denied because its searches bypass the host's per-file `read` rules,+including the `.env` exclusions. Use permitted file reads for review context.+V1 maps MCP resource reads and resource lists to the `read` permission.+The reviewer `read` rules allow local reads, then deny `mcp:*`.+This denies `mcp:<server>:<uri>` reads and `mcp:<server>:*` resource or template lists.+MCP resource tool names can remain visible. Their resource access is denied at the permission check.+The adapter's external-directory exception covers only the installed bundle.+OpenCode also adds access to its tool-output directory in the resolved agent configuration.+Shell commands, edits, network tools, MCP tools, skills, and delegation remain denied.+The primary agent requests permission for other tools, including writes.+For an external target, move a fixture into the project or review a narrow permission change separately.++Honor `EGM artifact directory: <path>` in the user's prompt or loaded instructions.+Resolve a relative output directory against the project directory. Otherwise retain the canonical output filenames and working-directory default.+Preserve each readiness, section, and stage approval gate. Ask one plain-text question when the native question tool is unavailable.+Wait for the user's answer. Missing tools and elapsed time do not constitute approval.++## Verification limits++OpenCode merges custom, global, project, and managed configuration.+Inspect the effective configuration before a run; later settings can override these permissions.+Use a clean profile and a disposable project for verification.+Inspect inherited instructions, plugins, MCP services, memory, and shared files separately.+Read-only tool configuration is not process or filesystem isolation.+A fresh child session alone does not prove Goldfish isolation.++Run the offline checks:++```sh+pytest tests/unit/test_opencode_adapter.py+pytest tests/unit+```++These tests check installation, resource identity, native configuration, and refusal to overwrite files.+They do not simulate host completion records or prove enforcement by the host.+No live model test runs in ordinary CI.++The scoped OpenCode native probe uses a scripted local model, not a live model.+It checks native child dispatch, one parent marker, and denial of a synthetic+`.env` read. It requires the pinned OpenCode 1.18.29 Linux x64 executable.++```sh+npm ci --ignore-scripts --prefix tests/integration/opencode-ci+python tests/integration/opencode_native_probe.py \+ --source . \+ --opencode tests/integration/opencode-ci/node_modules/opencode-linux-x64/bin/opencode \+ --output /tmp/egm-opencode-probe-new+```++Choose an output path that does not exist. A passing probe does not establish+live model behavior, full workflows, or general reviewer isolation.++On 2026-10-24, OpenCode `1.18.29` accepted the generated configuration through `debug config` and `debug agent egm-style`.+The historical reviewer toolset enabled `read`, `glob`, and `grep`. The current+candidate denies `grep` to preserve the `.env` read restriction.+The `debug skill` command discovered all seven skills from the installed candidate paths.+These commands made no model calls. This result does not prove task execution or runtime permission enforcement.+Separate XDG directories did not prevent discovery of home-directory skills. A clean verification profile must account for those locations too.+This historical note does not identify the tested EGM commit or installed bundle+checksum. Repeat discovery against the pinned candidate before relying on it for+that candidate.++Before a support claim, explicitly authorize and complete these checks:++1. Record the candidate SHA, installed hashes, host version, model identifier, surface, and date.+2. Run brainstorm, draft, and review with an actual human approval pause.+3. Retain native reviewer starts, completions, required reads, and produced artifacts.+4. Probe write denial against a disposable file and inspect the effective child permissions.+5. Place a random marker only in the parent conversation and inspect child context and output.+6. Report installation, workflow, and isolation outcomes separately. Mark missing evidence as unverified.++For OpenCode 1.18.29, the offline verifier checks one exported child session+against its parent JSONL trace. Supply each required absolute POSIX file path:++```sh+opencode export <child-session-id> > child.json+python tests/integration/opencode_trace_verifier.py \+ --parent-trace parent.jsonl --child-export child.json \+ --require /absolute/path/to/agents/zoom_out.md \+ --require /absolute/path/to/target.md \+ --require /absolute/path/to/standard.md+```++The verifier matches native child and parent session identities, the task+completion and time window, reviewer type, and each tool call's message and+session IDs. It requires a new task without `task_id`. It+requires a nonempty, successful file read for every supplied path before the+child's final response. It matches that response to the parent task result.+Missing, conflicting, malformed, or unsupported evidence+fails. Parent JSONL records are split on literal LF, not Unicode separators.+This does not verify every required path unless the caller supplies it. It does+not prove whole-file coverage, transcript authenticity, context isolation, or+that a running workflow stopped on missing evidence. Do not treat a parent+summary or an absent marker as sufficient isolation evidence.++## Interface sources++Reviewed on 2026-10-24. The versioned sources define this adapter's interface:++- [V1 agent configuration](https://github.com/anomalyco/opencode/blob/v1.18.29/packages/web/src/content/docs/agents.mdx)+- [V1 config and merge order](https://github.com/anomalyco/opencode/blob/v1.18.29/packages/web/src/content/docs/config.mdx)+- [V1 skill discovery](https://github.com/anomalyco/opencode/blob/v1.18.29/packages/web/src/content/docs/skills.mdx)+- [V1 command syntax](https://github.com/anomalyco/opencode/blob/v1.18.29/packages/web/src/content/docs/commands.mdx)+- [V1 command preprocessing](https://github.com/anomalyco/opencode/blob/v1.18.29/packages/opencode/src/session/prompt.ts)+- [V1 task implementation](https://github.com/anomalyco/opencode/blob/v1.18.29/packages/opencode/src/tool/task.ts)+- [V1 permission evaluator](https://github.com/anomalyco/opencode/blob/v1.18.29/packages/opencode/src/permission/index.ts)+- [V1 MCP resource permission paths](https://github.com/anomalyco/opencode/blob/v1.18.29/packages/opencode/src/session/tools.ts)+- [Current official agent guide](https://opencode.ai/docs/agents/)diff --git a/tests/integration/opencode-ci/.gitignore b/tests/integration/opencode-ci/.gitignorenew file mode 100644index 0000000..c2658d7--- /dev/null+++ b/tests/integration/opencode-ci/.gitignore@@ -0,0 +1 @@+node_modules/diff --git a/tests/integration/opencode-ci/package-lock.json b/tests/integration/opencode-ci/package-lock.jsonnew file mode 100644index 0000000..1d921aa--- /dev/null+++ b/tests/integration/opencode-ci/package-lock.json@@ -0,0 +1,23 @@+{+ "name": "egm-opencode-ci-lock",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "dependencies": {+ "opencode-linux-x64": "1.18.29"+ }+ },+ "node_modules/opencode-linux-x64": {+ "version": "1.18.29",+ "resolved": "https://registry.npmjs.org/opencode-linux-x64/-/opencode-linux-x64-1.18.29.tgz",+ "integrity": "sha512-X8/wS/8mzL7Ko0zYYF6RzKax39KkxXDRoimhmzXuo0gPrZX4DQjqBNpPAByBwUjFapk73ZGSVsjDGvoNapBa1Q==",+ "cpu": [+ "x64"+ ],+ "os": [+ "linux"+ ]+ }+ }+}diff --git a/tests/integration/opencode-ci/package.json b/tests/integration/opencode-ci/package.jsonnew file mode 100644index 0000000..1ec16f9--- /dev/null+++ b/tests/integration/opencode-ci/package.json@@ -0,0 +1,5 @@+{+ "dependencies": {+ "opencode-linux-x64": "1.18.29"+ }+}diff --git a/tests/integration/opencode_native_probe.py b/tests/integration/opencode_native_probe.pynew file mode 100644index 0000000..707e173--- /dev/null+++ b/tests/integration/opencode_native_probe.py@@ -0,0 +1,290 @@+# Copyright 2026 Google LLC.+# SPDX-License-Identifier: Apache-2.0++"""Exercise native OpenCode delegation with a scripted local model.++This checks transport and permission behavior, not model compliance or full+workflow execution. The only data sent to the mock is synthetic fixture data.+"""++import argparse+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+import json+import os+from pathlib import Path+import subprocess+import tempfile+import threading+from typing import Any++MARKER = 'EGM_PARENT_ONLY_SENTINEL'+SECRET = 'EGM_SYNTHETIC_SECRET'+REQUESTS: list[dict[str, Any]] = []+++class MockProvider(BaseHTTPRequestHandler):+ fixture = ''++ def log_message(self, _format: str, *_args: object) -> None:+ pass++ def do_POST(self) -> None:+ request = json.loads(+ self.rfile.read(int(self.headers['Content-Length']))+ )+ REQUESTS.append(request)+ tools = {tool['function']['name'] for tool in request.get('tools', [])}+ has_result = any(+ message.get('role') == 'tool' for message in request['messages']+ )+ delta = {'role': 'assistant', 'content': 'SCRIPTED_COMPLETION'}+ finish = 'stop'+ if not has_result and 'task' in tools:+ delta = self.call(+ 'task',+ {+ 'description': 'Probe child isolation',+ 'subagent_type': 'egm-zoom-out',+ 'prompt': 'Read the synthetic fixture .env file.',+ },+ )+ finish = 'tool_calls'+ elif not has_result and 'read' in tools:+ delta = self.call('read', {'filePath': self.fixture})+ finish = 'tool_calls'+ self.send_response(200)+ self.send_header('Content-Type', 'text/event-stream')+ self.end_headers()+ for payload in (delta, {}):+ event = {+ 'id': 'synthetic',+ 'object': 'chat.completion.chunk',+ 'created': 1,+ 'model': 'fixture',+ 'choices': [+ {+ 'index': 0,+ 'delta': payload,+ 'finish_reason': finish if not payload else None,+ }+ ],+ }+ self.wfile.write(('data: ' + json.dumps(event) + '\n\n').encode())+ self.wfile.write(b'data: [DONE]\n\n')++ @staticmethod+ def call(name: str, arguments: dict[str, str]) -> dict[str, Any]:+ return {+ 'role': 'assistant',+ 'tool_calls': [+ {+ 'index': 0,+ 'id': 'fixture-call',+ 'type': 'function',+ 'function': {+ 'name': name,+ 'arguments': json.dumps(arguments),+ },+ }+ ],+ }+++def main() -> None:+ parser = argparse.ArgumentParser()+ parser.add_argument('--source', type=Path, required=True)+ parser.add_argument('--opencode', type=Path, required=True)+ parser.add_argument('--output', type=Path, required=True)+ args = parser.parse_args()+ source, binary = args.source.resolve(), args.opencode.resolve()+ version = subprocess.check_output(+ [str(binary), '--version'], text=True+ ).strip()+ assert version == '1.18.29', f'Unexpected OpenCode version: {version}'+ sha = subprocess.check_output(+ ['git', '-C', str(source), 'rev-parse', 'HEAD'], text=True+ ).strip()+ status = subprocess.check_output(+ ['git', '-C', str(source), 'status', '--porcelain', '--untracked-files=all'],+ text=True,+ )+ assert not status, 'Source contains staged, unstaged, or untracked changes'+ args.output.mkdir(parents=True, exist_ok=False)+ server = ThreadingHTTPServer(('127.0.0.1', 0), MockProvider)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ with tempfile.TemporaryDirectory(prefix='egm-native-probe-') as root:+ root = Path(root)+ project, home, install = (+ root / 'project',+ root / 'home',+ root / 'install',+ )+ project.mkdir()+ home.mkdir()+ (project / '.env').write_text(SECRET + '\n')+ MockProvider.fixture = str(project / '.env')+ subprocess.run(+ [+ 'python3',+ str(source / 'adapters/opencode/install.py'),+ str(install),+ ],+ check=True,+ stdout=subprocess.DEVNULL,+ timeout=60,+ )+ config = json.loads((install / 'opencode.json').read_text())+ config['provider'] = {+ 'fixture': {+ 'npm': '@ai-sdk/openai-compatible',+ 'name': 'fixture',+ 'options': {+ 'baseURL': f'http://127.0.0.1:{server.server_port}/v1',+ 'apiKey': 'fixture',+ },+ 'models': {'fixture': {'name': 'fixture'}},+ }+ }+ config['model'] = 'fixture/fixture'+ config_path = root / 'config.json'+ config_path.write_text(json.dumps(config))+ env = {+ 'PATH': os.environ.get('PATH', '/usr/bin:/bin'),+ 'HOME': str(home),+ 'XDG_CONFIG_HOME': str(home / 'config'),+ 'XDG_DATA_HOME': str(home / 'data'),+ 'XDG_CACHE_HOME': str(home / 'cache'),+ 'OPENCODE_CONFIG': str(config_path),+ }+ result = subprocess.run(+ [+ str(binary),+ 'run',+ '--format',+ 'json',+ '--model',+ 'fixture/fixture',+ '--agent',+ 'egm',+ f'Parent-only marker: {MARKER}. Delegate without it.',+ ],+ cwd=project,+ env=env,+ text=True,+ capture_output=True,+ timeout=180,+ )+ (args.output / 'trace.jsonl').write_text(result.stdout)+ (args.output / 'stderr.txt').write_text(result.stderr)+ assert (+ result.returncode == 0+ ), f'OpenCode exited {result.returncode}; inspect stderr.txt'+ trace = [+ json.loads(line)+ for line in result.stdout.splitlines()+ if line.strip()+ ]+ tasks = [+ e+ for e in trace+ if e.get('type') == 'tool_use'+ and e['part'].get('tool') == 'task'+ ]+ assert (+ len(tasks) == 1+ and tasks[0]['part']['state']['status'] == 'completed'+ ), 'No completed native task'+ task = tasks[0]['part']['state']+ assert MARKER not in json.dumps(+ task['input']+ ), 'Parent marker passed to child'+ assert (+ task['metadata']['sessionId']+ != task['metadata']['parentSessionId']+ ), 'Child reused parent session'+ parent_requests = [+ r+ for r in REQUESTS+ if 'task'+ in {t['function']['name'] for t in r.get('tools', [])}+ ]+ assert any(+ MARKER in json.dumps(r) for r in parent_requests+ ), 'Parent marker did not reach provider'+ children = [+ r+ for r in REQUESTS+ if 'read'+ in {t['function']['name'] for t in r.get('tools', [])}+ and 'task'+ not in {t['function']['name'] for t in r.get('tools', [])}+ ]+ assert children, 'No native child provider request observed'+ assert all(+ task['input']['prompt'] in json.dumps(r) for r in children+ ), 'Child request does not match task prompt'+ assert all(+ MARKER not in json.dumps(r) for r in children+ ), 'Parent marker reached child'+ assert all(+ {t['function']['name'] for t in r['tools']}+ == {'read', 'glob'}+ for r in children+ ), 'Unexpected child tools'+ results = [+ json.dumps(m.get('content'))+ for r in children+ for m in r['messages']+ if m.get('role') == 'tool'+ ]+ assert results, 'No child tool result observed'+ observations = {+ 'parent_marker_seen_in_parent': True,+ 'native_task_input': task['input'],+ 'native_task_metadata': task['metadata'],+ 'child_tools': sorted(+ {t['function']['name'] for t in children[0]['tools']}+ ),+ 'child_marker_present': any(+ MARKER in json.dumps(r) for r in children+ ),+ 'child_tool_results': results,+ }+ (args.output / 'child-observations.json').write_text(+ json.dumps(observations, indent=2) + '\n'+ )+ assert all(+ SECRET not in r for r in results+ ), 'Synthetic secret reached child'+ assert any(+ 'prevents you from using this specific tool call' in r+ for r in results+ ), 'No native denial result'+ summary = {+ 'head': sha,+ 'opencode_version': version,+ 'model': 'scripted local mock',+ 'native_child_completed': True,+ 'child_tools': ['glob', 'read'],+ 'parent_marker_seen_in_parent': True,+ 'parent_marker_in_child': False,+ 'fixture_env_read': 'denied',+ 'scope': (+ 'One scripted delegation and one synthetic read; not full '+ 'workflow, model behavior, or general isolation'+ ),+ }+ (args.output / 'summary.json').write_text(+ json.dumps(summary, indent=2) + '\n'+ )+ print(json.dumps(summary, indent=2))+ finally:+ server.shutdown()+ server.server_close()+ thread.join(timeout=10)+++if __name__ == '__main__':+ main()diff --git a/tests/integration/opencode_trace_verifier.py b/tests/integration/opencode_trace_verifier.pynew file mode 100644index 0000000..c54b26f--- /dev/null+++ b/tests/integration/opencode_trace_verifier.py@@ -0,0 +1,219 @@+# Copyright 2026 Google LLC.+# SPDX-License-Identifier: Apache-2.0++"""Check required reads in an exported OpenCode 1.18.29 child session.++This is an offline evidence check. It does not control the running agent or+prove complete file coverage, context isolation, or transcript authenticity.+"""++import argparse+import json+from pathlib import Path, PurePosixPath+import re+import sys+from typing import Any+++class EvidenceError(ValueError):+ """Evidence is missing, inconsistent, or outside the supported format."""+++def _object(value: Any, label: str) -> dict[str, Any]:+ if not isinstance(value, dict):+ raise EvidenceError(f'{label} must be an object')+ return value+++def _identifier(value: Any, label: str) -> str:+ if not isinstance(value, str) or not value.strip():+ raise EvidenceError(f'{label} must be a nonempty string')+ return value+++def _path(value: Any) -> str:+ path = _identifier(value, 'read path')+ if '\x00' in path or not path.startswith('/') or str(PurePosixPath(path)) != path:+ raise EvidenceError(f'read path must be an absolute canonical POSIX path: {path!r}')+ if '..' in PurePosixPath(path).parts:+ raise EvidenceError(f'read path must not contain ..: {path!r}')+ return path+++def _nonempty_file_output(output: Any, expected_path: str) -> bool:+ if not isinstance(output, str):+ return False+ match = re.fullmatch(+ r'<path>([^\n]*)</path>\n<type>file</type>\n<content>\n(.*?)\n</content>'+ r'(?:\n\n<system-reminder>\n.*\n</system-reminder>)?',+ output, re.DOTALL,+ )+ if not match or match.group(1) != expected_path:+ return False+ lines = re.findall(r'^\d+: ?(.*)$', match.group(2), flags=re.MULTILINE)+ return any(line.strip() for line in lines)+++def _interval(value: Any, label: str) -> tuple[int, int]:+ times = _object(value, label)+ start, end = times.get('start'), times.get('end')+ if type(start) is not int or type(end) is not int or start < 0 or end < start:+ raise EvidenceError(f'{label} must have ordered integer timestamps')+ return start, end+++def verify(parent_events: list[Any], child_export: Any, required_paths: list[str]) -> None:+ """Raise EvidenceError unless every requested path has matched native evidence."""+ if not required_paths:+ raise EvidenceError('at least one required path is needed')+ required = {_path(path) for path in required_paths}+ if len(required) != len(required_paths):+ raise EvidenceError('duplicate required paths')++ child = _object(child_export, 'child export')+ info = _object(child.get('info'), 'child info')+ child_id = _identifier(info.get('id'), 'child session ID')+ parent_id = _identifier(info.get('parentID'), 'parent session ID')+ if child_id == parent_id or info.get('version') != '1.18.29':+ raise EvidenceError('child identity or OpenCode version is invalid')++ matching_tasks = []+ for raw in parent_events:+ event = _object(raw, 'parent event')+ if event.get('type') != 'tool_use':+ continue+ part = _object(event.get('part'), 'parent tool part')+ if part.get('tool') != 'task':+ continue+ state = _object(part.get('state'), 'task state')+ metadata = _object(state.get('metadata'), 'task metadata')+ if metadata.get('sessionId') == child_id:+ matching_tasks.append((event, part, state, metadata))+ if len(matching_tasks) != 1:+ raise EvidenceError('expected exactly one matching native child task')+ event, part, state, metadata = matching_tasks[0]+ _identifier(part.get('callID'), 'task call ID')+ _identifier(part.get('id'), 'parent task part ID')+ _identifier(part.get('messageID'), 'parent task message ID')+ task_input = _object(state.get('input'), 'task input')+ agent = _identifier(task_input.get('subagent_type'), 'task reviewer type')+ task_start, task_end = _interval(state.get('time'), 'parent task time')+ if (event.get('sessionID') != parent_id or part.get('sessionID') != parent_id+ or metadata.get('parentSessionId') != parent_id+ or info.get('agent') != agent+ or 'task_id' in task_input+ or state.get('status') != 'completed'+ or not isinstance(state.get('output'), str)+ or not state['output'].strip()):+ raise EvidenceError('native parent task identity or completion is invalid')++ messages = child.get('messages')+ if not isinstance(messages, list) or not messages:+ raise EvidenceError('child messages must be a nonempty list')+ seen_messages: set[str] = set()+ seen_parts: set[str] = set()+ seen_calls: set[str] = set()+ successful: set[str] = set()+ failed: set[str] = set()+ required_read_ends: list[int] = []+ final_message: dict[str, Any] | None = None+ for raw_message in messages:+ message = _object(raw_message, 'child message')+ message_info = _object(message.get('info'), 'message info')+ message_id = _identifier(message_info.get('id'), 'message ID')+ if message_id in seen_messages or message_info.get('sessionID') != child_id:+ raise EvidenceError('duplicate message or conflicting message session')+ seen_messages.add(message_id)+ role = message_info.get('role')+ if role not in ('user', 'assistant'):+ raise EvidenceError('unsupported child message role')+ parts = message.get('parts')+ if not isinstance(parts, list):+ raise EvidenceError('message parts must be a list')+ if role == 'assistant':+ final_message = message+ for raw_part in parts:+ child_part = _object(raw_part, 'child part')+ if child_part.get('type') != 'tool':+ continue+ if role != 'assistant':+ raise EvidenceError('tool part is not an assistant message')+ part_id = _identifier(child_part.get('id'), 'part ID')+ call_id = _identifier(child_part.get('callID'), 'tool call ID')+ if (part_id in seen_parts or call_id in seen_calls+ or child_part.get('sessionID') != child_id+ or child_part.get('messageID') != message_id):+ raise EvidenceError('duplicate or conflicting tool call identity')+ seen_parts.add(part_id)+ seen_calls.add(call_id)+ if child_part.get('tool') != 'read':+ continue+ read_state = _object(child_part.get('state'), 'read state')+ read_input = _object(read_state.get('input'), 'read input')+ read_path = _path(read_input.get('filePath'))+ status = read_state.get('status')+ if status not in ('completed', 'error'):+ raise EvidenceError('read did not finish')+ if read_path not in required:+ continue+ read_start, read_end = _interval(read_state.get('time'), 'required read time')+ if not task_start <= read_start <= read_end <= task_end:+ raise EvidenceError(f'required read occurred outside the parent task: {read_path}')+ required_read_ends.append(read_end)+ if status == 'error':+ failed.add(read_path)+ elif _nonempty_file_output(read_state.get('output'), read_path):+ successful.add(read_path)+ else:+ raise EvidenceError(f'malformed or empty native read result: {read_path}')++ if final_message is None:+ raise EvidenceError('missing child assistant completion')+ final_info = _object(final_message.get('info'), 'final message info')+ final_time = _object(final_info.get('time'), 'final message time')+ final_end = final_time.get('completed')+ text_parts = [+ part['text'] for part in final_message['parts']+ if isinstance(part, dict) and part.get('type') == 'text'+ and isinstance(part.get('text'), str)+ ]+ if (final_info.get('finish') != 'stop' or type(final_end) is not int+ or not task_start <= final_end <= task_end+ or not text_parts or not text_parts[-1].strip()):+ raise EvidenceError('missing completed child final text')+ if any(end > final_end for end in required_read_ends):+ raise EvidenceError('required read completed after the child final response')+ final_text = text_parts[-1]+ expected_output = (+ f'<task id="{child_id}" state="completed">\n<task_result>\n'+ f'{final_text}\n</task_result>\n</task>'+ )+ if state['output'] != expected_output:+ raise EvidenceError('parent task result does not match child final text')+ if required & failed:+ raise EvidenceError('required read has a failed or conflicting result')+ missing = required - successful+ if missing:+ raise EvidenceError('missing successful required reads: ' + ', '.join(sorted(missing)))+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--parent-trace', type=Path, required=True)+ parser.add_argument('--child-export', type=Path, required=True)+ parser.add_argument('--require', action='append', required=True, dest='required_paths')+ args = parser.parse_args()+ try:+ lines = args.parent_trace.read_text(encoding='utf-8').split('\n')+ parent = [json.loads(line) for line in lines if line.strip()]+ child = json.loads(args.child_export.read_text(encoding='utf-8'))+ verify(parent, child, args.required_paths)+ except (EvidenceError, OSError, UnicodeError, json.JSONDecodeError) as exc:+ print(f'INCOMPLETE: {exc}', file=sys.stderr)+ return 1+ print('Required native reads verified; this is not an isolation or coverage verdict.')+ return 0+++if __name__ == '__main__':+ sys.exit(main())diff --git a/tests/unit/test_opencode_adapter.py b/tests/unit/test_opencode_adapter.pynew file mode 100644index 0000000..67904b7--- /dev/null+++ b/tests/unit/test_opencode_adapter.py@@ -0,0 +1,189 @@+# Copyright 2026 Google LLC.+# SPDX-License-Identifier: Apache-2.0++"""Offline checks for the experimental OpenCode V1 installer."""++import hashlib+import json+import os+from pathlib import Path+import re+import runpy++import pytest++ROOT = Path(__file__).resolve().parents[2]+ADAPTER = runpy.run_path(str(ROOT / "adapters/opencode/install.py"))+++def test_install_preserves_resources_and_native_contract(tmp_path: Path) -> None:+ destination = tmp_path / "EGM candidate ü"+ config_path = ADAPTER["install"](destination)+ config = json.loads(config_path.read_text())+ identity = json.loads((destination / "installation.json").read_text())+ canonical = json.loads((ROOT / "plugin.json").read_text())+ assert (identity["name"], identity["version"]) == (canonical["name"], canonical["version"])+ assert identity["host_version"] == "1.18.29"+ for relative, digest in identity["sha256"].items():+ installed = destination / relative+ source = ROOT / installed.relative_to(destination / "bundle")+ assert installed.read_bytes() == source.read_bytes()+ assert hashlib.sha256(installed.read_bytes()).hexdigest() == digest+ for directory in ("skills", "agents", "resources", "docs"):+ for source in (ROOT / directory).rglob("*"):+ if source.is_file():+ assert (Path("bundle") / source.relative_to(ROOT)).as_posix() in identity["sha256"]++ assert config["default_agent"] == "egm"+ assert config["autoupdate"] is False+ assert "model" not in config+ assert len(config["command"]) == 7+ for skill in (ROOT / "skills").glob("*/SKILL.md"):+ key = ADAPTER["name"](skill)+ alias = Path(config["skills"]["paths"][0]) / key+ assert alias.resolve() == destination / "bundle/skills" / skill.parent.name+ assert (alias / "SKILL.md").read_bytes() == skill.read_bytes()+ command = config["command"][key]+ assert command["agent"] == "egm"+ assert str(alias.resolve() / "SKILL.md") in command["template"]+ assert "$ARGUMENTS" in command["template"]++ assert len(config["agent"]) == 8+ for filename in ADAPTER["REVIEWERS"]:+ persona = destination / "bundle/agents" / f"{filename}.md"+ agent = config["agent"][ADAPTER["name"](persona)]+ assert agent["mode"] == "subagent"+ assert agent["permission"] == {+ "*": "deny",+ "read": {+ "*": "allow", "*.env": "deny", "*.env.*": "deny",+ "*.env.example": "allow", "mcp:*": "deny",+ },+ "glob": "allow", "grep": "deny",+ "external_directory": {"*": "deny", f"{destination / 'bundle'}/**": "allow"},+ }+ # V1 maps resource reads and both list tools to read. Last match wins.+ assert list(agent["permission"]["read"].items()) == [+ ("*", "allow"), ("*.env", "deny"), ("*.env.*", "deny"),+ ("*.env.example", "allow"), ("mcp:*", "deny"),+ ]+ assert str(persona) in agent["prompt"]+ assert "Read-only Protocol" not in agent["prompt"]+ primary = config["agent"]["egm"]+ assert primary["permission"]["*"] == "ask"+ assert list(primary["permission"]["read"].items()) == [+ ("*", "allow"), ("*.env", "ask"), ("*.env.*", "ask"), ("*.env.example", "allow"),+ ]+ assert set(primary["permission"]["task"]) == {"*", *set(config["agent"]) - {"egm"}}+ assert "Omit task_id" in primary["prompt"]+ assert "foreground completion" in primary["prompt"]+++def test_stage_required_reports_preserve_context_boundary(tmp_path: Path) -> None:+ destination = tmp_path / "candidate"+ config = json.loads(ADAPTER["install"](destination).read_text())+ bundle = destination / "bundle"+ canonical = (bundle / "skills/egm-review/SKILL.md").read_text()+ assert "include `zoom_out_report.md` path in" in canonical+ guide = " ".join((bundle / "docs/opencode.md").read_text().split())+ prompt = config["agent"]["egm-zoom-out"]["prompt"]+ for instructions in (prompt, guide):+ assert (+ "Read prior reports only when explicitly supplied and required by the canonical stage."+ ) in instructions+ assert "Do not retrieve unsolicited history, memory, or earlier reviewer findings." in instructions+ assert "Do not pass parent history, private reasoning, or memory." in guide+++def test_existing_destination_is_untouched(tmp_path: Path) -> None:+ sentinel = tmp_path / "existing.txt"+ sentinel.write_text("other worker")+ with pytest.raises(FileExistsError):+ ADAPTER["install"](tmp_path)+ assert list(tmp_path.iterdir()) == [sentinel]+ assert sentinel.read_text() == "other worker"++[email protected]("suffix", ["bad*", "bad?", "bad[glob]", "{env:HOME}", "bad\npath", r"bad\path"])+def test_template_paths_are_rejected(tmp_path: Path, suffix: str) -> None:+ if "\\" in suffix and Path(suffix).name != suffix:+ pytest.skip("Requires a literal backslash in a POSIX filename")+ with pytest.raises(ValueError):+ ADAPTER["install"](tmp_path / suffix)+ assert not list(tmp_path.iterdir())+++def test_source_destination_is_rejected() -> None:+ with pytest.raises(ValueError, match="outside the source"):+ ADAPTER["install"](ROOT / "unused-opencode-test-destination")+++def test_command_interpolation_paths_are_rejected(tmp_path: Path) -> None:+ # V1 replaces positional placeholders and $ARGUMENTS across the template.+ for component in ("$ARGUMENTS", "$1"):+ with pytest.raises(ValueError, match="template or glob"):+ ADAPTER["install"](tmp_path / component / "candidate")+ assert not list(tmp_path.iterdir())+++def test_symlink_parent_cannot_bypass_path_validation(tmp_path: Path) -> None:+ target = tmp_path / "unsafe[glob]"+ target.mkdir()+ alias = tmp_path / "safe"+ alias.symlink_to(target, target_is_directory=True)+ with pytest.raises(ValueError):+ ADAPTER["install"](alias / "candidate")+ assert not list(target.iterdir())+++def test_dangling_destination_is_untouched(tmp_path: Path) -> None:+ destination = tmp_path / "candidate"+ destination.symlink_to(tmp_path / "absent")+ with pytest.raises(FileExistsError):+ ADAPTER["install"](destination)+ assert destination.is_symlink()+ assert not (tmp_path / "absent").exists()+++def v1_match(pattern: str, value: str) -> bool:+ """Port of V1 Wildcard.match (anomalyco/opencode@1674747): "*" spans "/"."""+ escaped = re.escape(pattern.replace("\\", "/")).replace(r"\*", ".*").replace(r"\?", ".")+ flags = re.S | (re.I if os.name == "nt" else 0)+ return re.fullmatch(escaped, value.replace("\\", "/"), flags) is not None+++def v1_read_effect(rules: dict, path: str) -> str | None:+ effect = None+ for pattern, action in rules.items():+ if v1_match(pattern, path):+ effect = action+ return effect+++def test_required_reads_pass_env_rules(tmp_path: Path) -> None:+ # V1 checks reads against the path relative to the worktree.+ worktree = tmp_path / "project"+ worktree.mkdir()+ destination = tmp_path / "candidate"+ config = json.loads(ADAPTER["install"](destination).read_text())+ bundle = destination / "bundle"+ required = [+ bundle / "docs/opencode.md",+ *(bundle / "agents").glob("*.md"),+ *(bundle / "resources").rglob("*.md"),+ ]+ for name, agent in config["agent"].items():+ rules = agent["permission"]["read"]+ for path in required:+ assert v1_read_effect(rules, os.path.relpath(path, worktree)) == "allow", (name, path)+ secret = "ask" if name == "egm" else "deny"+ for path in (".env", "app/.env", ".env.local", "app/.env.production", "prod.env"):+ assert v1_read_effect(rules, path) == secret, (name, path)+ assert v1_read_effect(rules, "app/.env.example") == "allow"++[email protected]("suffix", ["egm.env.candidate", "staging.ENV.d/candidate"])+def test_env_matching_destination_is_rejected(tmp_path: Path, suffix: str) -> None:+ with pytest.raises(ValueError, match="read rules"):+ ADAPTER["install"](tmp_path / suffix)+ assert not list(tmp_path.iterdir())diff --git a/tests/unit/test_opencode_trace_verifier.py b/tests/unit/test_opencode_trace_verifier.pynew file mode 100644index 0000000..95a7ae2--- /dev/null+++ b/tests/unit/test_opencode_trace_verifier.py@@ -0,0 +1,204 @@+# Copyright 2026 Google LLC.+# SPDX-License-Identifier: Apache-2.0++"""Adversarial evidence checks for exported native OpenCode child sessions."""++from copy import deepcopy+from pathlib import Path+import runpy++import pytest+++MODULE = runpy.run_path(str(+ Path(__file__).resolve().parents[2] / 'tests/integration/opencode_trace_verifier.py'+))+verify = MODULE['verify']+EvidenceError = MODULE['EvidenceError']+PERSONA = '/bundle/agents/zoom_out.md'+TARGET = '/project/design.md'+++def read_part(part_id: str, call_id: str, path: str) -> dict:+ return {+ 'type': 'tool', 'tool': 'read', 'id': part_id, 'callID': call_id,+ 'sessionID': 'child', 'messageID': 'assistant-1',+ 'state': {+ 'status': 'completed', 'input': {'filePath': path},+ 'time': {'start': 110, 'end': 120},+ 'output': (+ f'<path>{path}</path>\n<type>file</type>\n<content>\n'+ '1: content\n\n(End of file - total 1 lines)\n</content>'+ ),+ },+ }+++def evidence() -> tuple[list[dict], dict]:+ parent = [{+ 'type': 'tool_use', 'sessionID': 'parent',+ 'part': {+ 'type': 'tool', 'tool': 'task', 'callID': 'task-1', 'id': 'task-part',+ 'messageID': 'parent-message', 'sessionID': 'parent',+ 'state': {+ 'status': 'completed',+ 'output': (+ '<task id="child" state="completed">\n<task_result>\n'+ 'Completed\n</task_result>\n</task>'+ ),+ 'input': {'subagent_type': 'egm-zoom-out'},+ 'time': {'start': 100, 'end': 130},+ 'metadata': {'sessionId': 'child', 'parentSessionId': 'parent'},+ },+ },+ }]+ child = {+ 'info': {+ 'id': 'child', 'parentID': 'parent', 'version': '1.18.29',+ 'agent': 'egm-zoom-out',+ },+ 'messages': [+ {'info': {'id': 'user-1', 'sessionID': 'child', 'role': 'user'}, 'parts': []},+ {+ 'info': {'id': 'assistant-1', 'sessionID': 'child', 'role': 'assistant'},+ 'parts': [read_part('part-1', 'call-1', PERSONA),+ read_part('part-2', 'call-2', TARGET)],+ },+ {+ 'info': {'id': 'assistant-2', 'sessionID': 'child', 'role': 'assistant',+ 'finish': 'stop', 'time': {'completed': 123}},+ 'parts': [{'type': 'text', 'text': 'Completed'}],+ },+ ],+ }+ return parent, child+++def test_accepts_correlated_nonempty_read_results(evidence: tuple[list[dict], dict]) -> None:+ parent, child = evidence+ verify(parent, child, [PERSONA, TARGET])+++def test_accepts_last_text_part_from_multi_part_final_message(+ evidence: tuple[list[dict], dict],+) -> None:+ parent, child = evidence+ child['messages'][2]['parts'] = [+ {'type': 'text', 'text': 'First'},+ {'type': 'text', 'text': 'Completed'},+ ]+ verify(parent, child, [PERSONA, TARGET])+++def test_accepts_native_system_reminder_suffix(evidence: tuple[list[dict], dict]) -> None:+ parent, child = evidence+ part = child['messages'][1]['parts'][0]+ part['state']['output'] += '\n\n<system-reminder>\nApplicable instructions\n</system-reminder>'+ verify(parent, child, [PERSONA])+++def test_child_claim_cannot_substitute_for_a_missing_read(+ evidence: tuple[list[dict], dict],+) -> None:+ parent, child = evidence+ child['messages'][1]['parts'] = [read_part('part-2', 'call-2', TARGET)]+ child['messages'][2]['parts'][0]['text'] = f'I read {PERSONA}'+ parent[0]['part']['state']['output'] = (+ '<task id="child" state="completed">\n<task_result>\n'+ f'I read {PERSONA}\n</task_result>\n</task>'+ )+ with pytest.raises(EvidenceError, match='missing successful required reads'):+ verify(parent, child, [PERSONA, TARGET])++[email protected]('change', [+ 'error', 'empty', 'unrelated_output', 'wrong_message', 'wrong_session',+ 'duplicate_call', 'duplicate_part', 'wrong_parent', 'duplicate_task',+ 'missing_completion', 'wrong_version', 'relative_path', 'wrong_agent',+ 'read_outside_task', 'missing_read_time', 'resumed_task', 'read_after_final',+ 'mismatched_task_result', 'mismatched_task_result_id', 'zero_limit', 'arbitrary_suffix',+])+def test_rejects_unreliable_or_conflicting_evidence(+ evidence: tuple[list[dict], dict], change: str,+) -> None:+ parent, child = deepcopy(evidence)+ part = child['messages'][1]['parts'][0]+ if change == 'error':+ part['state'] = {'status': 'error', 'input': {'filePath': PERSONA},+ 'time': {'start': 110, 'end': 120}, 'error': 'denied'}+ elif change == 'empty':+ part['state']['output'] = (+ f'<path>{PERSONA}</path>\n<type>file</type>\n<content>\n'+ '1: \n\n(End of file - total 1 lines)\n</content>'+ )+ elif change == 'unrelated_output':+ part['state']['output'] = part['state']['output'].replace(PERSONA, TARGET)+ elif change == 'wrong_message':+ part['messageID'] = 'another-message'+ elif change == 'wrong_session':+ part['sessionID'] = 'another-session'+ elif change == 'duplicate_call':+ child['messages'][1]['parts'][1]['callID'] = part['callID']+ elif change == 'duplicate_part':+ child['messages'][1]['parts'][1]['id'] = part['id']+ elif change == 'wrong_parent':+ parent[0]['part']['state']['metadata']['parentSessionId'] = 'another-parent'+ elif change == 'duplicate_task':+ parent.append(deepcopy(parent[0]))+ elif change == 'missing_completion':+ child['messages'][2]['info']['finish'] = 'tool-calls'+ elif change == 'wrong_version':+ child['info']['version'] = '2.0.0'+ elif change == 'relative_path':+ part['state']['input']['filePath'] = 'agents/zoom_out.md'+ elif change == 'wrong_agent':+ child['info']['agent'] = 'egm-comprehension'+ elif change == 'read_outside_task':+ part['state']['time']['start'] = 99+ elif change == 'missing_read_time':+ del part['state']['time']+ elif change == 'resumed_task':+ parent[0]['part']['state']['input']['task_id'] = 'old-child'+ elif change == 'read_after_final':+ part['state']['time'] = {'start': 124, 'end': 125}+ elif change == 'mismatched_task_result':+ parent[0]['part']['state']['output'] = (+ parent[0]['part']['state']['output'].replace('Completed', 'Something else')+ )+ elif change == 'mismatched_task_result_id':+ parent[0]['part']['state']['output'] = (+ parent[0]['part']['state']['output'].replace('id="child"', 'id="old-child"')+ )+ elif change == 'zero_limit':+ part['state']['input']['limit'] = 0+ part['state']['output'] = (+ f'<path>{PERSONA}</path>\n<type>file</type>\n<content>\n\n\n'+ '(Showing lines 1-0 of 3. Use offset=1 to continue.)\n</content>'+ )+ elif change == 'arbitrary_suffix':+ part['state']['output'] += '\nUnrecognized suffix'+ with pytest.raises(EvidenceError):+ verify(parent, child, [PERSONA, TARGET])+++def test_rejects_conflicting_results_for_one_required_path(+ evidence: tuple[list[dict], dict],+) -> None:+ parent, child = evidence+ child['messages'][1]['parts'].append({+ **read_part('part-3', 'call-3', PERSONA),+ 'state': {'status': 'error', 'input': {'filePath': PERSONA},+ 'time': {'start': 110, 'end': 120}, 'error': 'denied'},+ })+ with pytest.raises(EvidenceError, match='failed or conflicting'):+ verify(parent, child, [PERSONA])+++def test_rejects_duplicate_or_noncanonical_required_paths(+ evidence: tuple[list[dict], dict],+) -> None:+ parent, child = evidence+ for required in ([PERSONA, PERSONA], ['/bundle/../agents/zoom_out.md'], []):+ with pytest.raises(EvidenceError):+ verify(parent, child, required)