You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@magpie.apache.org by po...@apache.org on 2026/07/03 01:48:48 UTC

(magpie) branch main updated: feat(harness): OpenCode support for permission-audit + sandbox-lint — harness 100% (#688)

This is an automated email from the ASF dual-hosted git repository.

potiuk pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/magpie.git


The following commit(s) were added to refs/heads/main by this push:
     new 1791c445 feat(harness): OpenCode support for permission-audit + sandbox-lint — harness 100% (#688)
1791c445 is described below

commit 1791c4456c57a42cdb6bfe9c56eb8a2dc6d24c07
Author: Jarek Potiuk <ja...@potiuk.com>
AuthorDate: Fri Jul 3 03:48:43 2026 +0200

    feat(harness): OpenCode support for permission-audit + sandbox-lint — harness 100% (#688)
    
    Closes the last two Claude-Code-coupled substrate tools on the
    agent-harness axis, each via a genuine OpenCode config auditor (not a
    label flip). The agent-harness score reaches 20/20 (100%); with the
    contract axis already at 10/10, every LLM-integration axis is now neutral.
    
    Both tools operate on Claude's `.claude/settings.json` schema; OpenCode
    models permissions entirely differently — `opencode.json` `permission` is
    a string or an object keyed by tool, and `permission.bash` maps glob
    command patterns to allow/ask/deny, evaluated last-matching-rule-wins
    with a `"*"` default (https://opencode.ai/docs/permissions/). So each
    tool gains a separate OpenCode classifier that enforces the same intent.
    
    permission-audit:
    - New `audit-opencode <opencode.json>` subcommand + `opencode.py` module.
      Flags over-permissioning: `blanket-allow` (`permission` == "allow"),
      `bash-allow-all` (bash defaults to allow), and `dangerous-allow` (a
      specific rule auto-approves git push / sudo / curl / rm -rf / cloud
      CLIs / kubectl / docker / ssh / interpreters / npx / uvx while the
      default is stricter). Read-only JSON output; the Claude-only `apply`
      has no OpenCode counterpart yet.
    
    sandbox-lint:
    - New `--opencode <opencode.json>` mode + `opencode.py` invariants.
      OpenCode has no sandbox.filesystem model (isolation is the OS-level
      sandbox), so there is no baseline to diff — the lint asserts permission
      invariants instead: not blanket-allow, bash default not allow, no
      dangerous family auto-approved (last-match-wins), and webfetch /
      external_directory not blanket-allow.
    
    Both: `**Harness:**` -> `Claude Code, OpenCode`; tests cover the rule
    engine (last-match-wins, dedup, safe configs) and the CLIs. Regenerated
    the score block (agent-harness 20/20). permission-audit `apply` and the
    `.claude/settings.json` baseline remain Claude-specific by design.
    
    Co-authored-by: Tester <t...@example.com>
---
 docs/vendor-neutrality.md                          |   8 +-
 tools/permission-audit/README.md                   |  27 +++-
 tools/permission-audit/src/permission_audit/cli.py |  41 ++++-
 .../src/permission_audit/opencode.py               | 176 +++++++++++++++++++++
 tools/permission-audit/tests/test_opencode.py      | 128 +++++++++++++++
 tools/sandbox-lint/README.md                       |  18 ++-
 tools/sandbox-lint/src/sandbox_lint/__init__.py    |  32 +++-
 tools/sandbox-lint/src/sandbox_lint/opencode.py    | 138 ++++++++++++++++
 tools/sandbox-lint/tests/test_opencode.py          |  98 ++++++++++++
 9 files changed, 658 insertions(+), 8 deletions(-)

diff --git a/docs/vendor-neutrality.md b/docs/vendor-neutrality.md
index 22443031..f89353da 100644
--- a/docs/vendor-neutrality.md
+++ b/docs/vendor-neutrality.md
@@ -571,22 +571,22 @@ Organization scope (declared, orthogonal to vendor): ASF = 14, agnostic = 49.
 
 **LLM / agent-integration neutrality**
 
-**Agent harness: 18/20 substrate tools run under any harness unchanged (90%).** Substrate tools are Magpie's own machinery; each declares the agent harness it integrates with (`**Harness:**`), or `agnostic`. A tool is neutral when it is harness-agnostic or supports two or more harnesses; *coupled* when it targets a single harness.
+**Agent harness: 20/20 substrate tools run under any harness unchanged (100%).** Substrate tools are Magpie's own machinery; each declares the agent harness it integrates with (`**Harness:**`), or `agnostic`. A tool is neutral when it is harness-agnostic or supports two or more harnesses; *coupled* when it targets a single harness.
 
 | Substrate tool | Substrate | Harness support | Verdict |
 |---|---|---|---|
-| `permission-audit` | sandbox | Claude Code | ❌ coupled |
-| `sandbox-lint` | sandbox | Claude Code | ❌ coupled |
 | `agent-guard` | action-guard | Claude Code, OpenCode | ✅ portable |
 | `agent-isolation` | sandbox | Claude Code, OpenCode | ✅ portable |
 | `dashboard-generator` | analytics | any | ✅ agnostic |
 | `dev` | framework-dev | any | ✅ agnostic |
 | `egress-gateway` | sandbox | any | ✅ agnostic |
+| `permission-audit` | sandbox | Claude Code, OpenCode | ✅ portable |
 | `pilot-report-validator` | framework-dev | any | ✅ agnostic |
 | `pr-management-stats` | analytics | any | ✅ agnostic |
 | `preflight-audit` | analytics | any | ✅ agnostic |
 | `privacy-llm` | privacy | any | ✅ agnostic |
 | `probe-templates` | sandbox | any | ✅ agnostic |
+| `sandbox-lint` | sandbox | Claude Code, OpenCode | ✅ portable |
 | `security-tracker-stats-dashboard` | analytics | any | ✅ agnostic |
 | `skill-and-tool-validator` | framework-dev | any | ✅ agnostic |
 | `skill-evals` | framework-dev | any | ✅ agnostic |
@@ -599,7 +599,7 @@ Organization scope (declared, orthogonal to vendor): ASF = 14, agnostic = 49.
 Harness → substrate tools it supports:
 
 - **Claude Code** (5): `agent-guard`, `agent-isolation`, `permission-audit`, `sandbox-lint`, `spec-loop`
-- **OpenCode** (3): `agent-guard`, `agent-isolation`, `spec-loop`
+- **OpenCode** (5): `agent-guard`, `agent-isolation`, `permission-audit`, `sandbox-lint`, `spec-loop`
 - **any harness** (15): `dashboard-generator`, `dev`, `egress-gateway`, `pilot-report-validator`, `pr-management-stats`, `preflight-audit`, `privacy-llm`, `probe-templates`, `security-tracker-stats-dashboard`, `skill-and-tool-validator`, `skill-evals`, `spec-status-index`, `spec-validator`, `symlink-lint`, `vendor-neutrality-score`
 
 **Model endpoint: neutral by construction — 4 default-approved endpoint classes across independent trust domains, plus adopter opt-in.** From the [`privacy-llm` registry](../tools/privacy-llm/models.md): the framework keys approval on *endpoint identity*, not on who hosts the model, so no single LLM vendor is privileged.
diff --git a/tools/permission-audit/README.md b/tools/permission-audit/README.md
index 5b05d05d..e140980e 100644
--- a/tools/permission-audit/README.md
+++ b/tools/permission-audit/README.md
@@ -23,7 +23,7 @@
 
 **Capability:** substrate:sandbox
 
-**Harness:** Claude Code
+**Harness:** Claude Code, OpenCode
 
 Audit + atomically edit Claude Code's `permissions.allow[]` entries
 in `<repo>/.claude/settings.json` and `<repo>/.claude/settings.local.json`.
@@ -32,6 +32,31 @@ Backs the `--apply-permission-audit` flag of
 [`/magpie-setup verify`](../../skills/setup/verify.md#8d-permission-allow-list-hygiene)
 (check 8d), and is also directly usable as a CLI.
 
+**OpenCode.** The same over-permissioning check applies to the other
+harness through `audit-opencode`, which reads an
+[`opencode.json`](https://opencode.ai/docs/permissions/) `permission`
+config instead of a Claude allow-list. OpenCode models permissions
+differently — `permission` is a string or an object keyed by tool, and
+`permission.bash` may map glob command patterns to `allow`/`ask`/`deny`
+(last-matching-rule-wins, with a `"*"` default) — so this is a separate
+classifier, but it enforces the same intent: **flag configuration that
+auto-approves dangerous shell execution.** It reports, in JSON:
+
+- `blanket-allow` — `permission` is the string `"allow"` (every tool
+  auto-approved);
+- `bash-allow-all` — the default `permission.bash` decision is `"allow"`;
+- `dangerous-allow` — a specific rule auto-approves a dangerous command
+  family (`git push`, `sudo`, `curl`/`wget`, `rm -rf`, cloud CLIs,
+  `kubectl`, `docker run`, `ssh`, interpreters/`npx`/`uvx`, …) while the
+  default is stricter.
+
+```bash
+uv run --project tools/permission-audit permission-audit audit-opencode opencode.json
+```
+
+The Claude-only `apply` subcommand (atomic allow-list edits) has no
+OpenCode counterpart yet; `audit-opencode` is read-only.
+
 ## Prerequisites
 
 - **Runtime:** Python 3.11+ run via `uv` (`uv sync` / `uv run`); the
diff --git a/tools/permission-audit/src/permission_audit/cli.py b/tools/permission-audit/src/permission_audit/cli.py
index 266e4c4c..8bb35ceb 100644
--- a/tools/permission-audit/src/permission_audit/cli.py
+++ b/tools/permission-audit/src/permission_audit/cli.py
@@ -40,6 +40,7 @@ from permission_audit.audit import (
     audit_settings,
 )
 from permission_audit.edit import apply_changes
+from permission_audit.opencode import audit_opencode
 
 
 def _read_allow(settings_path: Path) -> list[str]:
@@ -105,6 +106,36 @@ def _cmd_apply(args: argparse.Namespace) -> int:
     return 0
 
 
+def _read_opencode_config(config_path: Path) -> dict:
+    if not config_path.exists():
+        return {}
+    raw = config_path.read_text(encoding="utf-8")
+    if not raw.strip():
+        return {}
+    try:
+        data = json.loads(raw)
+    except json.JSONDecodeError as e:
+        sys.stderr.write(f"{config_path}: invalid JSON: {e}\n")
+        raise SystemExit(2) from e
+    return data if isinstance(data, dict) else {}
+
+
+def _cmd_audit_opencode(args: argparse.Namespace) -> int:
+    config_path = Path(args.config_path).resolve()
+    config = _read_opencode_config(config_path)
+    result = audit_opencode(config)
+
+    output = {
+        "config_path": str(config_path),
+        "file_exists": config_path.exists(),
+        "harness": "opencode",
+        "forbidden": [asdict(f) for f in result.forbidden],
+    }
+    json.dump(output, sys.stdout, indent=2)
+    sys.stdout.write("\n")
+    return 1 if result.forbidden else 0
+
+
 def _cmd_list_known(args: argparse.Namespace) -> int:
     output = {
         "forbidden_patterns": sorted(FORBIDDEN_PATTERNS),
@@ -120,7 +151,8 @@ def _build_parser() -> argparse.ArgumentParser:
         prog="permission-audit",
         description=(
             "Audit + atomically edit Claude Code permissions.allow[] entries "
-            "in .claude/settings.json / .claude/settings.local.json."
+            "in .claude/settings.json / .claude/settings.local.json; and "
+            "audit an OpenCode opencode.json permission config (audit-opencode)."
         ),
     )
     subparsers = parser.add_subparsers(dest="cmd", required=True)
@@ -155,6 +187,13 @@ def _build_parser() -> argparse.ArgumentParser:
     )
     p_apply.set_defaults(func=_cmd_apply)
 
+    p_audit_oc = subparsers.add_parser(
+        "audit-opencode",
+        help="Audit an OpenCode opencode.json permission config for over-permissioning.",
+    )
+    p_audit_oc.add_argument("config_path", help="Path to opencode.json.")
+    p_audit_oc.set_defaults(func=_cmd_audit_opencode)
+
     p_known = subparsers.add_parser(
         "list-known",
         help="Print the canonical forbidden + recommended-by-family lists.",
diff --git a/tools/permission-audit/src/permission_audit/opencode.py b/tools/permission-audit/src/permission_audit/opencode.py
new file mode 100644
index 00000000..01aa1cd7
--- /dev/null
+++ b/tools/permission-audit/src/permission_audit/opencode.py
@@ -0,0 +1,176 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Audit an OpenCode `permission` config for over-permissioning.
+
+OpenCode's permission model differs in shape from Claude Code's flat
+`permissions.allow[]` list, so the audit is a separate classifier — but the
+*intent* is the same one this tool applies to Claude: flag configuration that
+**auto-approves dangerous shell execution** (the OpenCode analog of the broad
+`FORBIDDEN_PATTERNS` wildcards the Claude audit removes).
+
+The `permission` value in `opencode.json` is either:
+
+- a string (`"allow"` / `"ask"` / `"deny"`) applied to every tool, or
+- an object keyed by tool (`bash`, `edit`, `webfetch`, …). The `bash` key may
+  itself be an object mapping glob command patterns to a decision, evaluated
+  **last-matching-rule-wins** with a `"*"` default
+  (per <https://opencode.ai/docs/permissions/>).
+
+Pure data + classification — no I/O. The CLI layer reads the file and renders.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from fnmatch import fnmatch
+
+DECISIONS = frozenset({"allow", "ask", "deny"})
+
+# Canonical dangerous commands. If a config's *effective* bash decision for any
+# of these resolves to "allow", it auto-approves arbitrary or high-blast-radius
+# execution. Kept representative (not exhaustive), the same posture as the
+# Claude `FORBIDDEN_PATTERNS` list.
+DANGEROUS_COMMANDS: tuple[tuple[str, str], ...] = (
+    ("git push origin main", "git push (publish to a remote)"),
+    ("sudo rm -rf /", "sudo (privilege escalation)"),
+    ("curl http://example.com/x", "curl (network fetch / exfiltration)"),
+    ("wget http://example.com/x", "wget (network fetch / exfiltration)"),
+    ("rm -rf /tmp/x", "rm -rf (destructive delete)"),
+    ("aws s3 ls", "aws (cloud credentials)"),
+    ("gcloud auth list", "gcloud (cloud credentials)"),
+    ("az login", "az (cloud credentials)"),
+    ("kubectl get pods", "kubectl (cluster access)"),
+    ("docker run alpine sh", "docker run (container-escape surface)"),
+    ("ssh host uptime", "ssh (remote shell)"),
+    ("eval something", "eval (arbitrary execution)"),
+    ("npx cowsay hi", "npx (arbitrary package execution)"),
+    ("uvx ruff check", "uvx (arbitrary package execution)"),
+    ("python -c print(1)", "python -c (arbitrary code)"),
+    ("bash -c echo", "bash -c (arbitrary code)"),
+)
+
+
+@dataclass(frozen=True)
+class OpenCodeFinding:
+    """A single OpenCode permission finding.
+
+    `kind` is one of ``blanket-allow`` (the whole `permission` is "allow"),
+    ``bash-allow-all`` (bash defaults to allow), or ``dangerous-allow`` (a
+    specific rule auto-approves a dangerous command family).
+    """
+
+    severity: str  # always "forbidden" today
+    kind: str
+    detail: str
+    json_pointer: str
+
+
+@dataclass
+class OpenCodeAuditResult:
+    forbidden: list[OpenCodeFinding] = field(default_factory=list)
+
+    @property
+    def has_findings(self) -> bool:
+        return bool(self.forbidden)
+
+
+def bash_default(bash_cfg: object) -> str | None:
+    """The decision applied to a bash command that matches no specific rule.
+
+    A string `bash` value is itself the default; an object's default is its
+    `"*"` entry (OpenCode's own built-in default when absent is "ask").
+    """
+    if isinstance(bash_cfg, str):
+        return bash_cfg if bash_cfg in DECISIONS else None
+    if isinstance(bash_cfg, dict):
+        value = bash_cfg.get("*")
+        return value if value in DECISIONS else None
+    return None
+
+
+def effective_bash_decision(bash_cfg: object, command: str) -> tuple[str | None, str | None]:
+    """Return ``(decision, matched_pattern)`` for `command`, last-match-wins."""
+    if isinstance(bash_cfg, str):
+        return (bash_cfg if bash_cfg in DECISIONS else None), ("*" if bash_cfg in DECISIONS else None)
+    if isinstance(bash_cfg, dict):
+        decision: str | None = None
+        matched: str | None = None
+        for pattern, value in bash_cfg.items():
+            if not isinstance(pattern, str) or value not in DECISIONS:
+                continue
+            if fnmatch(command, pattern):
+                decision, matched = value, pattern
+        return decision, matched
+    return None, None
+
+
+def audit_opencode(config: dict) -> OpenCodeAuditResult:
+    """Classify an ``opencode.json`` dict for dangerous auto-approval."""
+    result = OpenCodeAuditResult()
+    permission = config.get("permission")
+
+    # 1. The whole permission policy is a blanket "allow".
+    if permission == "allow":
+        result.forbidden.append(
+            OpenCodeFinding(
+                "forbidden",
+                "blanket-allow",
+                '`permission` is "allow" — every tool (bash included) is auto-approved with no gate. '
+                'Use an object policy that gates bash (e.g. {"bash": {"*": "ask"}}).',
+                ".permission",
+            )
+        )
+        return result
+
+    if not isinstance(permission, dict):
+        # Absent, or the safe "ask"/"deny" strings — nothing to flag.
+        return result
+
+    bash_cfg = permission.get("bash")
+    default = bash_default(bash_cfg)
+
+    # 2. bash defaults to allow (string "allow", or "*": "allow").
+    if default == "allow":
+        result.forbidden.append(
+            OpenCodeFinding(
+                "forbidden",
+                "bash-allow-all",
+                'the default `permission.bash` decision is "allow" — every shell command is '
+                'auto-approved. Set the default ("*") to "ask" or "deny".',
+                ".permission.bash",
+            )
+        )
+
+    # 3. Specific rules that auto-approve a dangerous family while the default
+    #    is stricter (when the default already allows all, #2 covers it).
+    if default != "allow":
+        seen: set[str] = set()
+        for command, label in DANGEROUS_COMMANDS:
+            decision, matched = effective_bash_decision(bash_cfg, command)
+            if decision == "allow" and matched is not None and matched != "*" and matched not in seen:
+                seen.add(matched)  # one finding per over-broad rule, not per sample command
+                result.forbidden.append(
+                    OpenCodeFinding(
+                        "forbidden",
+                        "dangerous-allow",
+                        f'{label} is auto-approved by rule {matched!r} = "allow".',
+                        f'.permission.bash["{matched}"]',
+                    )
+                )
+
+    return result
diff --git a/tools/permission-audit/tests/test_opencode.py b/tools/permission-audit/tests/test_opencode.py
new file mode 100644
index 00000000..c6e36410
--- /dev/null
+++ b/tools/permission-audit/tests/test_opencode.py
@@ -0,0 +1,128 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Tests for the OpenCode permission audit."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from permission_audit.cli import main
+from permission_audit.opencode import (
+    audit_opencode,
+    bash_default,
+    effective_bash_decision,
+)
+
+
+def _kinds(config: dict) -> list[str]:
+    return [f.kind for f in audit_opencode(config).forbidden]
+
+
+def test_empty_config_is_clean():
+    assert not audit_opencode({}).has_findings
+
+
+def test_ask_string_is_clean():
+    assert not audit_opencode({"permission": "ask"}).has_findings
+
+
+def test_deny_string_is_clean():
+    assert not audit_opencode({"permission": "deny"}).has_findings
+
+
+def test_blanket_allow_string_is_forbidden():
+    r = audit_opencode({"permission": "allow"})
+    assert [f.kind for f in r.forbidden] == ["blanket-allow"]
+    assert r.forbidden[0].json_pointer == ".permission"
+
+
+def test_bash_string_allow_is_forbidden():
+    assert _kinds({"permission": {"bash": "allow"}}) == ["bash-allow-all"]
+
+
+def test_bash_star_allow_is_forbidden():
+    assert _kinds({"permission": {"bash": {"*": "allow"}}}) == ["bash-allow-all"]
+
+
+def test_bash_star_ask_is_clean():
+    assert not audit_opencode({"permission": {"bash": {"*": "ask"}}}).has_findings
+
+
+def test_specific_dangerous_allow_while_default_asks():
+    # Default asks, but a specific rule opens `git *` → git push is auto-approved.
+    config = {"permission": {"bash": {"*": "ask", "git *": "allow"}}}
+    r = audit_opencode(config)
+    kinds = [f.kind for f in r.forbidden]
+    assert "dangerous-allow" in kinds
+    assert "bash-allow-all" not in kinds
+    assert any("git *" in f.json_pointer for f in r.forbidden)
+
+
+def test_default_allow_does_not_double_report_each_command():
+    # When the default is allow, report it once, not once per dangerous sample.
+    r = audit_opencode({"permission": {"bash": {"*": "allow"}}})
+    assert len(r.forbidden) == 1
+    assert r.forbidden[0].kind == "bash-allow-all"
+
+
+def test_last_match_wins_deny_overrides_earlier_allow():
+    # git * allow, then git push * deny → git push is denied, so no finding.
+    config = {"permission": {"bash": {"*": "ask", "git *": "allow", "git push *": "deny"}}}
+    r = audit_opencode(config)
+    # `git *` still allows other dangerous-ish git, but our sample "git push origin main"
+    # is denied by the later rule; no dangerous-allow for git push.
+    assert not any(f.json_pointer == '.permission.bash["git push *"]' for f in r.forbidden)
+
+
+def test_safe_narrow_allow_is_clean():
+    config = {"permission": {"bash": {"*": "ask", "lychee *": "allow", "ls *": "allow"}}}
+    assert not audit_opencode(config).has_findings
+
+
+def test_bash_default_helper():
+    assert bash_default("allow") == "allow"
+    assert bash_default({"*": "deny"}) == "deny"
+    assert bash_default({"git *": "allow"}) is None  # no explicit default
+    assert bash_default(None) is None
+
+
+def test_effective_decision_last_match_wins():
+    rules = {"*": "ask", "git *": "allow", "git push *": "deny"}
+    assert effective_bash_decision(rules, "git status") == ("allow", "git *")
+    assert effective_bash_decision(rules, "git push origin") == ("deny", "git push *")
+    assert effective_bash_decision(rules, "ls -la") == ("ask", "*")
+
+
+def test_cli_audit_opencode_denies_and_exits_1(tmp_path: Path, capsys):
+    cfg = tmp_path / "opencode.json"
+    cfg.write_text(json.dumps({"permission": {"bash": "allow"}}))
+    rc = main(["audit-opencode", str(cfg)])
+    assert rc == 1
+    out = json.loads(capsys.readouterr().out)
+    assert out["harness"] == "opencode"
+    assert out["forbidden"][0]["kind"] == "bash-allow-all"
+
+
+def test_cli_audit_opencode_clean_exits_0(tmp_path: Path, capsys):
+    cfg = tmp_path / "opencode.json"
+    cfg.write_text(json.dumps({"permission": {"bash": {"*": "ask"}}}))
+    rc = main(["audit-opencode", str(cfg)])
+    assert rc == 0
+    out = json.loads(capsys.readouterr().out)
+    assert out["forbidden"] == []
diff --git a/tools/sandbox-lint/README.md b/tools/sandbox-lint/README.md
index d7a376a8..2d60008b 100644
--- a/tools/sandbox-lint/README.md
+++ b/tools/sandbox-lint/README.md
@@ -19,7 +19,7 @@
 
 **Capability:** substrate:sandbox
 
-**Harness:** Claude Code
+**Harness:** Claude Code, OpenCode
 
 Lints `.claude/settings.json` against the shipped baseline at
 `tools/sandbox-lint/expected.json`, and against the security
@@ -28,6 +28,22 @@ invariants documented in `docs/security/threat-model.md`
 companion PR; the lint stands on its own and runs immediately on
 merge.
 
+**OpenCode.** `--opencode opencode.json` lints the other harness's
+security config. OpenCode has no `sandbox.filesystem` allow/deny model
+(its filesystem isolation comes from the OS-level sandbox of the
+secure-agent setup), so there is no baseline to diff — instead the lint
+asserts **invariants on the `permission` policy**
+([OpenCode permissions](https://opencode.ai/docs/permissions/)): the
+policy must not be a blanket `"allow"`, `permission.bash` must not default
+to `"allow"`, no rule may auto-approve a dangerous command family
+(`git push`, `sudo`, `curl`/`wget`, `rm -rf`, cloud CLIs, `kubectl`,
+`docker run`, `ssh`, interpreters, …) via last-match-wins evaluation, and
+`webfetch` / `external_directory` must not be blanket-`"allow"`.
+
+```bash
+uv run --project tools/sandbox-lint sandbox-lint --opencode opencode.json
+```
+
 ## Prerequisites
 
 - **Runtime:** Python 3.11+ run via `uv` (stdlib only, no third-party deps).
diff --git a/tools/sandbox-lint/src/sandbox_lint/__init__.py b/tools/sandbox-lint/src/sandbox_lint/__init__.py
index d7404624..635d2839 100644
--- a/tools/sandbox-lint/src/sandbox_lint/__init__.py
+++ b/tools/sandbox-lint/src/sandbox_lint/__init__.py
@@ -263,12 +263,28 @@ def _load_json(p: Path) -> dict[str, Any]:
     return data
 
 
+def _lint_opencode(config_path: Path) -> int:
+    """Lint an OpenCode opencode.json permission policy (invariants only)."""
+    from sandbox_lint.opencode import check_opencode_invariants
+
+    config = _load_json(config_path)
+    errors = check_opencode_invariants(config)
+    if not errors:
+        print(f"sandbox-lint: OK ({config_path} permission policy satisfies the OpenCode invariants)")
+        return 0
+    print(f"sandbox-lint: OpenCode permission-policy violations in {config_path}:", file=sys.stderr)
+    for e in errors:
+        print(f"  - {e}", file=sys.stderr)
+    return 1
+
+
 def main(argv: list[str] | None = None) -> int:
     parser = argparse.ArgumentParser(
         prog="sandbox-lint",
         description=(
             "Lint .claude/settings.json against the shipped baseline and the "
-            "security invariants from docs/security/threat-model.md (M.29)."
+            "security invariants from docs/security/threat-model.md (M.29); or, "
+            "with --opencode, lint an opencode.json permission policy."
         ),
     )
     parser.add_argument(
@@ -283,8 +299,22 @@ def main(argv: list[str] | None = None) -> int:
         default=DEFAULT_EXPECTED,
         help=f"Path to the canonical baseline (default: {DEFAULT_EXPECTED})",
     )
+    parser.add_argument(
+        "--opencode",
+        type=Path,
+        default=None,
+        metavar="OPENCODE_JSON",
+        help=(
+            "Lint an OpenCode opencode.json permission policy against the "
+            "OpenCode security invariants instead of the Claude Code sandbox "
+            "config (invariants only — no baseline diff)."
+        ),
+    )
     args = parser.parse_args(argv)
 
+    if args.opencode is not None:
+        return _lint_opencode(args.opencode)
+
     settings = _load_json(args.settings)
     expected = _load_json(args.expected)
 
diff --git a/tools/sandbox-lint/src/sandbox_lint/opencode.py b/tools/sandbox-lint/src/sandbox_lint/opencode.py
new file mode 100644
index 00000000..1b96a1d6
--- /dev/null
+++ b/tools/sandbox-lint/src/sandbox_lint/opencode.py
@@ -0,0 +1,138 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Security invariants for an OpenCode `opencode.json` permission config.
+
+The Claude Code lint compares `.claude/settings.json` against a shipped
+baseline *and* a set of hard invariants. OpenCode has no `sandbox.filesystem`
+allow/deny model — its filesystem isolation comes from the OS-level sandbox of
+the secure-agent setup, configured out of band — so there is nothing to diff
+against a baseline. What OpenCode *does* own is the `permission` policy, and
+that carries the security weight here. This module encodes the invariants that
+policy must satisfy: it must not auto-approve dangerous shell execution or
+blanket-allow exfiltration/scope-escape surfaces.
+
+Invariants only, no baseline — an adopter's `opencode.json` is their own, so
+the lint asserts safety properties rather than an exact shape.
+"""
+
+from __future__ import annotations
+
+from fnmatch import fnmatch
+from typing import Any
+
+DECISIONS = frozenset({"allow", "ask", "deny"})
+
+# Representative dangerous commands: if the effective bash decision for any
+# resolves to "allow", the policy auto-approves high-blast-radius execution.
+DANGEROUS_COMMANDS: tuple[tuple[str, str], ...] = (
+    ("git push origin main", "git push (publish to a remote)"),
+    ("sudo rm -rf /", "sudo (privilege escalation)"),
+    ("curl http://example.com/x", "curl (network fetch / exfiltration)"),
+    ("wget http://example.com/x", "wget (network fetch / exfiltration)"),
+    ("rm -rf /tmp/x", "rm -rf (destructive delete)"),
+    ("aws s3 ls", "aws (cloud credentials)"),
+    ("gcloud auth list", "gcloud (cloud credentials)"),
+    ("az login", "az (cloud credentials)"),
+    ("kubectl get pods", "kubectl (cluster access)"),
+    ("docker run alpine sh", "docker run (container-escape surface)"),
+    ("ssh host uptime", "ssh (remote shell)"),
+    ("eval something", "eval (arbitrary execution)"),
+    ("npx cowsay hi", "npx (arbitrary package execution)"),
+    ("uvx ruff check", "uvx (arbitrary package execution)"),
+    ("python -c print(1)", "python -c (arbitrary code)"),
+    ("bash -c echo", "bash -c (arbitrary code)"),
+)
+
+# Non-bash tools whose blanket "allow" is an exfiltration / scope-escape risk.
+FORBIDDEN_ALLOW_TOOLS: tuple[tuple[str, str], ...] = (
+    ("webfetch", "auto-approves fetching arbitrary URLs (exfiltration channel)"),
+    ("external_directory", "auto-approves access to paths outside the project"),
+)
+
+
+def _bash_default(bash_cfg: Any) -> str | None:
+    if isinstance(bash_cfg, str):
+        return bash_cfg if bash_cfg in DECISIONS else None
+    if isinstance(bash_cfg, dict):
+        value = bash_cfg.get("*")
+        return value if value in DECISIONS else None
+    return None
+
+
+def _effective_bash_decision(bash_cfg: Any, command: str) -> tuple[str | None, str | None]:
+    if isinstance(bash_cfg, str):
+        return (bash_cfg if bash_cfg in DECISIONS else None), ("*" if bash_cfg in DECISIONS else None)
+    if isinstance(bash_cfg, dict):
+        decision: str | None = None
+        matched: str | None = None
+        for pattern, value in bash_cfg.items():
+            if not isinstance(pattern, str) or value not in DECISIONS:
+                continue
+            if fnmatch(command, pattern):
+                decision, matched = value, pattern
+        return decision, matched
+    return None, None
+
+
+def check_opencode_invariants(config: dict[str, Any]) -> list[str]:
+    """Return a list of invariant violations; empty means the policy is safe."""
+    errors: list[str] = []
+
+    if "permission" not in config:
+        return [
+            "permission: missing — declare an explicit permission policy (do not rely on unstated defaults)"
+        ]
+
+    permission = config["permission"]
+
+    if permission == "allow":
+        return [
+            'permission: must not be the blanket string "allow" — every tool '
+            "(bash included) would be auto-approved with no gate"
+        ]
+
+    if isinstance(permission, str):
+        if permission in ("ask", "deny"):
+            return errors
+        return [f'permission: unexpected value {permission!r} (want an object, or "ask"/"deny")']
+
+    if not isinstance(permission, dict):
+        return [f'permission: must be an object or "ask"/"deny", got {type(permission).__name__}']
+
+    bash_cfg = permission.get("bash")
+
+    if _bash_default(bash_cfg) == "allow":
+        errors.append(
+            'permission.bash: the default decision (the "*" rule, or a string value) must not be '
+            '"allow" — set it to "ask" or "deny" so shell commands are gated'
+        )
+
+    seen: set[str] = set()
+    for command, label in DANGEROUS_COMMANDS:
+        decision, matched = _effective_bash_decision(bash_cfg, command)
+        if decision == "allow" and matched is not None and matched not in seen:
+            seen.add(matched)
+            errors.append(
+                f'permission.bash: must not auto-approve {label} (rule {matched!r} resolves to "allow")'
+            )
+
+    for tool, why in FORBIDDEN_ALLOW_TOOLS:
+        if permission.get(tool) == "allow":
+            errors.append(f'permission.{tool}: must not be "allow" — it {why}; use "ask" or "deny"')
+
+    return errors
diff --git a/tools/sandbox-lint/tests/test_opencode.py b/tools/sandbox-lint/tests/test_opencode.py
new file mode 100644
index 00000000..b2b0e4b5
--- /dev/null
+++ b/tools/sandbox-lint/tests/test_opencode.py
@@ -0,0 +1,98 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Tests for the OpenCode permission-policy invariants of sandbox-lint."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from sandbox_lint import main
+from sandbox_lint.opencode import check_opencode_invariants
+
+
+def test_missing_permission_flags() -> None:
+    errs = check_opencode_invariants({})
+    assert errs and "missing" in errs[0]
+
+
+def test_blanket_allow_flagged() -> None:
+    errs = check_opencode_invariants({"permission": "allow"})
+    assert len(errs) == 1
+    assert "blanket" in errs[0] or "allow" in errs[0]
+
+
+def test_ask_string_ok() -> None:
+    assert check_opencode_invariants({"permission": "ask"}) == []
+
+
+def test_bash_default_allow_flagged() -> None:
+    errs = check_opencode_invariants({"permission": {"bash": {"*": "allow"}}})
+    assert any("default decision" in e for e in errs)
+
+
+def test_bash_string_allow_flagged() -> None:
+    errs = check_opencode_invariants({"permission": {"bash": "allow"}})
+    assert any("allow" in e for e in errs)
+
+
+def test_safe_policy_ok() -> None:
+    config = {"permission": {"bash": {"*": "ask", "ls *": "allow", "lychee *": "allow"}}}
+    assert check_opencode_invariants(config) == []
+
+
+def test_specific_dangerous_allow_flagged() -> None:
+    config = {"permission": {"bash": {"*": "ask", "sudo *": "allow"}}}
+    errs = check_opencode_invariants(config)
+    assert any("sudo" in e for e in errs)
+
+
+def test_last_match_deny_wins_no_flag() -> None:
+    config = {"permission": {"bash": {"*": "ask", "git *": "allow", "git push *": "deny"}}}
+    errs = check_opencode_invariants(config)
+    assert not any("git push" in e for e in errs)
+
+
+def test_webfetch_allow_flagged() -> None:
+    config = {"permission": {"bash": {"*": "ask"}, "webfetch": "allow"}}
+    errs = check_opencode_invariants(config)
+    assert any("webfetch" in e for e in errs)
+
+
+def test_external_directory_allow_flagged() -> None:
+    config = {"permission": {"bash": {"*": "ask"}, "external_directory": "allow"}}
+    errs = check_opencode_invariants(config)
+    assert any("external_directory" in e for e in errs)
+
+
+def test_cli_opencode_clean(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
+    cfg = tmp_path / "opencode.json"
+    cfg.write_text(json.dumps({"permission": {"bash": {"*": "ask"}}}))
+    rc = main(["--opencode", str(cfg)])
+    assert rc == 0
+    assert "OK" in capsys.readouterr().out
+
+
+def test_cli_opencode_violation(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
+    cfg = tmp_path / "opencode.json"
+    cfg.write_text(json.dumps({"permission": "allow"}))
+    rc = main(["--opencode", str(cfg)])
+    assert rc == 1
+    assert "violations" in capsys.readouterr().err