Skip to content

feat(#996): opencode fidelity — fail-closed hook shim, subagent defs, MCP translation, error classes, CI smoke - #1013

Merged
admarble merged 15 commits into
mainfrom
feature/996-feat-opencode-fidelity-hook-shim-fail-closed-subag
Sep 8, 2026
Merged

admarble merged 15 commits into
mainfrom
feature/996-feat-opencode-fidelity-hook-shim-fail-closed-subag

Conversation

@admarble

@admarble admarble commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Gives an opencode phase the same hook guards a Claude Code phase gets, and makes every unprovable path fail closed. Closes #996 (#862 P1).

  • The shim (templates/opencode/plugins/) translates opencode's tool.execute.before pair into the stdin envelope .claude/hooks/pre-tool.sh expects, spawns the real 1,576-line hook, and throws on exit 2.
  • Provisioning: sequant init --agent opencode writes three subagent defs, the plugin, and the MCP entry under opencode's flat mcp key.
  • Guards: doctor reports a missing shim and flags --pure; the driver fails closed when the shim is absent from the phase worktree or never announced itself at runtime.
  • CI: a $0 structural smoke job gates every PR against the pinned 1.18.27.

The security-review phase ran before implementation and its findings shaped the design — see "Security review findings addressed" below.

Pre-PR AC Verification

AC Source Description Status Evidence
AC-1 Original Shim maps {tool,args} → hook stdin, blocks on exit 2, fails closed on malformed args ✅ Implemented opencode-hooks.test.ts — 33 passed
AC-2 Original doctor verifies the plugin is active ✅ Implemented doctor.test.ts -t "opencode plugin" — 5 passed
AC-3 Original Subagent defs translated ✅ Implemented init.opencode.integration.test.ts — 11 passed; 3 defs (OQ-1). Fan-out clause now satisfied via the driver doc comment, gated by opencode.test.ts -t "996 AC-3" (2 tests, both mutation-verified).
AC-4 Original MCP translation, flat mcp key, type: local, array command ✅ Implemented mcp-config.test.ts -t "opencode mcp" — 3 passed
AC-5 Original Error classification; Claude-specific retry paths not entered ✅ Implemented opencode.test.ts -t "862 P1 errors" — 3 passed
AC-6 Original CI smoke against the pinned version ⚠️ Partial grep -c '1.18.27' → 6 ≥ 1 ✅. The $0 structural job is green on a8d275a2 (run) and gates every PR — but it runs opencode debug …, not opencode run --format json. The job matching that clause is model-backed, which is workflow_dispatch-only and gated on OPENCODE_SMOKE_API_KEY (not configured) — it has never run. See "AC-6, precisely" below.
Derived
AC-7 Worktree fail-closed Driver fails closed with hooks-not-installed ✅ Implemented opencode.test.ts -t "862 P1 hooks preflight" — 8 passed
— Provisioning UX Post-init hint to commit .opencode/ ✅ Implemented init.ts prints the hint after provisioning

Verify output

AC-1  Tests  33 passed (33)
AC-2  Tests  5 passed | 41 skipped (46)
AC-3  Tests  11 passed (11)
AC-4  Tests  3 passed | 47 skipped (50)
AC-5  Tests  3 passed | 37 skipped (40)
AC-7  Tests  8 passed | 32 skipped (40)
AC-6  .github/workflows/opencode-smoke.yml:6

Open-question resolutions (as recommended by /spec)

  • OQ-1 — AC-3 names four defs. Wrote three. sequant-explorer was deleted in fix(spec): the explorer fan-out prescription has a 0% execution rate over 169 runs — delete it or make it real #927; a fourth would have no Claude-side counterpart. The AC's grep -c 'mode: subagent' gate reads 3.
  • OQ-2 — AC-4's serve.test.ts doesn't exist. Implemented in src/lib/mcp-config.ts, gated at mcp-config.test.ts -t "opencode mcp".
  • OQ-3 — no --max-cost on 1.18.27. Two-job design: $0 structural job gates the PR; the model-backed job is secret-gated with timeout-minutes: 5.
  • OQ-4 — does a throw actually cancel the tool call? Still unproven, and deliberately so — it needs a real model-backed run. The smoke workflow's model-backed job prompts a git push --force and asserts HOOK_BLOCKED. Until that job runs green, the end-to-end guarantee rests on opencode's documented behaviour, not on evidence.
  • OQ-5 — post-tool.sh / tool.execute.after. Out of scope here, as recommended; worth a follow-up.

Verified against real opencode 1.18.27 ($0, no model calls)

sequant-implementer    mode=subagent  steps=25   denied=[plan_enter, plan_exit, question]
sequant-qa-checker     mode=subagent  steps=15   denied=[edit, plan_enter, plan_exit, question]
sequant-testgen        mode=subagent  steps=25   denied=[bash, edit, plan_enter, plan_exit, question]

mcp.sequant = {"type":"local","command":["npx","-y","[email protected]","serve"],"enabled":true}
shim sentinel on stderr: present  ✅

tools → permission derivation works as the spec predicted: writing the tools map alone produces the deny rules.

Corrected after QA re-ran this hermetically. An earlier revision of this table listed a write deny that opencode 1.18.27 does not emit — it derives permission denies for bash and edit, not write. The security outcome is unchanged, because the resolved tools map does carry write: false and that is the actual enablement mechanism; but the deny list above is now what opencode really returns. patch: false is dropped entirely from the resolved map (unknown tool id) — the shim covers it by omitting patch from PASSTHROUGH_TOOLS, so it throws as an unknown tool.

Security review findings addressed

The pre-exec security-review returned ISSUES_FOUND with two P0s. Both were gaps in the ACs, not implementation slips, and both are now closed and mutation-verified:

  1. Plugin load failure is silent. Verified: a plugin throwing at load gives exit 0, empty stderr, resolved tool map. File-presence checks (AC-2, AC-7 as written) cannot see it. → The shim announces itself on stderr and the driver fails the phase when that line is absent (hooks-not-active).

    This was not hypothetical — the first version of this shim hit it. It exported constants, and opencode rejects any scanned plugin file that exports a non-function ("Plugin export is not a function"), logging at ERROR and otherwise swallowing it. The shim is now split into a function-only entry plus lib/sequant-hooks-core.ts, since the plugin scan is non-recursive.

  2. filePath vs file_path. opencode's edit/write args are camelCase; pre-tool.sh:1495,1539 reads snake_case. Forwarding args verbatim leaves FILE_PATH empty, skips the worktree-boundary and file-lock guards, and falls through to exit 0. → The shim translates key-by-key; M1 below proves the suite catches a regression.

Also addressed: bash.workdir routed into the envelope cwd (#3); relative filePath resolved against opencode's own base (#4); CLAUDE_HOOKS_DISABLED/CLAUDE_HOOKS_FILE_LOCKING stripped from the hook env (#5); MCP built from the secret-free overload (#6); patch/apply_patch explicitly denied and barred from passthrough (#7); jq absence fails closed (#8).

Mutation verification

Per CLAUDE.md §Testing. Each mutation applied to a committed tree, verified, restored.

Mutation-verified: AC-1 — forwarded opencode args verbatim instead of mapping filePath→file_path; maps edit's filePath onto the file_path key pre-tool.sh reads + blocks an edit whose file_path escapes the worktree failed; restored.
Mutation-verified: AC-1 — removed the STRIPPED_ENV_VARS deletion loop from buildHookEnv; strips the guard-disabling vars before spawning the hook + still blocks a force push when CLAUDE_HOOKS_DISABLED is set ambiently failed; restored.
Mutation-verified: AC-1 — made an unrecognised tool pass through instead of throwing; blocks an unrecognised tool rather than passing it through failed; restored.
Mutation-verified: AC-1 — deleted the SHIM_LOADED_SENTINEL stderr write; writes the sentinel to stderr when the plugin loads failed; restored.
Mutation-verified: AC-1 — made decideFromHook allow undocumented exit codes; blocks on the undocumented exit 3/127/255/null failed (4 cases); restored.
Mutation-verified: AC-2 — disabled doctor's shim-presence check; 996 AC-2 fails with guidance when the opencode plugin is absent failed; restored.
Mutation-verified: AC-2 — disabled doctor's --pure check; 996 AC-2 fails when --pure is configured, which disables plugins failed; restored.
Mutation-verified: AC-3 — emitted maxSteps: instead of steps:; translates maxTurns into steps failed; restored.
Mutation-verified: AC-3 — stopped denying unlisted mutating tools; denies unlisted mutating tools rather than leaving them unset failed; restored.
Mutation-verified: AC-4 — spread the base MCP config so env carried through; never emits an env key, so no provider secret can reach a committed file failed; restored.
Mutation-verified: AC-5 — set OpencodeDriver.usesSdkMcp = true; declares that it does not use the SDK's MCP plumbing failed; restored.
Mutation-verified: AC-5 — set ClaudeCodeDriver.usesSdkMcp = false; 5 phase-executor.test.ts MCP-fallback tests failed, proving the new gate does not silently disable the fallback for claude-code; restored.
Mutation-verified: AC-7 — disabled the findShimIn preflight; fails closed with hooks-not-installed when the shim is absent + does not spawn opencode at all when the shim is missing failed; restored.
Mutation-verified: AC-7 — disabled the requireShimHandshake check; fails a run whose shim never announced itself, even on a clean exit failed; restored.
Mutation-verified: AC-3 — deleted the ## Sub-agent fan-out section from the driver header comment; both 996 AC-3 gate tests failed; restored.
Mutation-verified: AC-3 — rewrote the honest prose into a claim that the driver "transparently switches to a sequential fallback"; 996 AC-3 does not claim an implemented driver-conditional fallback failed while the other gate test still passed; restored.
Mutation-verified: AC-6 — pushed --permission bash:/tmp/**=allow into the opencode argv; 862 AC-8 injects no /tmp or $TMPDIR permission rule failed; restored.

One mutation that did not fail, reported honestly

Swapping getSequantMcpConfig() → getSequantMcpConfig({clientType: "claude-desktop"}) did not break the AC-4 secret test. The builder whitelists command/args rather than spreading the base object, so env cannot survive regardless of clientType. That is defense in depth, but it means the test gates "the entry never carries env", not "the clientType-free overload was called". M10b (spreading the base) is the mutation that does fail, and is the one recorded above.

Checks

Check Result
npm run build ✅ pass
npm run lint ✅ pass (0 warnings)
Targeted AC suites ✅ 63 passed
src/lib/workflow/drivers/ ✅ 172 passed, 4 skipped
src/lib/workflow/phase-executor* ✅ 197 passed
src/commands/init*, doctor, mcp-config ✅ pass

Per the runner's launch discipline, the full suite was not run inside the phase — CI is the gate for it.

Test coverage

Changed file Tier Tests
templates/opencode/plugins/** Critical (security) opencode-hooks.test.ts (33)
src/lib/workflow/drivers/opencode.ts Critical opencode.test.ts (40)
src/commands/doctor.ts Standard doctor.test.ts
src/commands/init.ts Standard init.opencode.integration.test.ts
src/lib/mcp-config.ts Critical (secrets) mcp-config.test.ts
src/lib/workflow/phase-executor.ts Critical phase-executor.test.ts (fallback gate mutation-verified)
src/lib/workflow/drivers/agent-driver.ts Optional (interface) asserted on all 3 implementers + registry

CI repairs (commit a8d275a2)

The first CI run turned two of this PR's own gates red. Neither was a defect in
the shipped behaviour; both were defects in the gates.

1. The AC-6 secret scan matched itself. It ran git grep across the whole
repo, so it hit a docs placeholder and — self-defeatingly — the mcp-config
tests that assert a key is not serialized. The gate failed loudest exactly
when the protection was working. It is now scoped to the generated
.opencode/ tree plus .github/workflows, and the pattern uses bracket
classes so the scan cannot match its own source line. Verified locally in both
directions: no false positive on a clean tree, and a planted sk-ant- /
sk-or-v1- key is still caught.

2. 862 AC-8 injects no /tmp or $TMPDIR permission rule broke on Linux.
Commit 36addff7 repointed the driver fixture at a shim-provisioned mkdtemp
cwd. --dir <cwd> then legitimately carried /tmp/..., and the blanket
args.join(" ") assertion read that as an injected rule. It stayed green on
macOS only because tmpdir() there is /var/folders, which is why the failure
first appeared in CI. The assertion now drops that one value, so a /tmp rule
injected anywhere else in the argv still fails it — mutation-verified above.

Reproduced locally by running the suite under TMPDIR=/tmp/....

AC-6, precisely (owner decision needed)

QA caught me overstating this, so here is the exact state.

AC-6 has three clauses:

Clause State
grep -c '1.18.27' .github/workflows/*.yml ≥ 1 ✅ 6
a job runs opencode run --format json on a trivial prompt with a budget ⚠️ the job exists (model-backed, timeout-minutes: 5) but has never executed
one green run URL in the PR body ⚠️ present, but it is the structural job, which never invokes opencode run

model-backed is if: github.event_name == 'workflow_dispatch' and gated on secrets.OPENCODE_SMOKE_API_KEY, which is not configured on this repo. Dispatching it today would hit its own "Skip when unconfigured" branch and skip again.

I also tried to settle this for $0, without a model or a key, via opencode debug agent <name> --tool bash --params '{"command":"git push --force origin main"}'. The force push was not blocked — but that is a false alarm, and the reason matters: instrumenting the fixture's plugin copy with a hook-entry probe showed tool.execute.before is never invoked on the debug --tool path. The plugin's load sentinel appears; the hook does not fire. So that path bypasses the shim and cannot serve as evidence either way. It is now recorded in the driver's doc comment as a real (if narrow) unguarded surface.

This is a decision for you, not something /loop should decide:

I have not done either: (a) spends money and adds a repo secret, and (b) edits the acceptance criteria — both are owner calls. AC-6 is marked ⚠️ Partial until one of them happens.

Known gaps

  1. AC-6 is partially met, and the green run does not close it. The structural job is green on a8d275a2, but it never invokes opencode run --format json; the job that does is workflow_dispatch-only and gated on an unconfigured secret, so it has never executed. Owner decision needed — see "AC-6, precisely" below.
  2. OQ-4 is still unproven. No test here can close it — it needs a live model-backed run. Documented above rather than papered over.
  3. templates/ is excluded from tsconfig.json and npm run lint, so the shim ships untypechecked; vitest catches syntax errors only. Accepted gap, flagged as the spec asked.
  4. tsconfig.json excludes **/*.test.ts, so mock AgentDriver literals were not typechecked against the new usesSdkMcp field. Covered behaviourally by the M14 mutation instead.

Test plan

  • Force push blocked through the shim, against the real pre-tool.sh
  • Conventional commit allowed (fixture is a real repo with staged work)
  • Malformed args blocked before any hook spawn
  • Edit outside the worktree blocked; inside allowed
  • Ambient CLAUDE_HOOKS_DISABLED does not disable the guards
  • Three subagent defs resolve under real opencode with correct mode/steps/permission
  • MCP entry resolves under opencode debug config
  • Shim load handshake observed on real opencode stderr
  • Model-backed run proves a throw cancels the tool call (OQ-4) — needs the secret-gated job

Closes #996

🤖 Generated with Claude Code

…on (AC-3, AC-4)

Entire-Checkpoint: 69e0723c0252
…ht (AC-2, AC-5, AC-7)

Entire-Checkpoint: 0f1cbefe2003
…xport only functions)

Entire-Checkpoint: f215c75ab1d5
…ssertion)

Both failures were in gates this PR added, not in the shipped behaviour.

The AC-6 secret scan ran `git grep` over the whole repo, so it matched a
docs placeholder and — self-defeatingly — the `mcp-config` tests that
assert a key is NOT serialized. It failed loudest exactly when the
protection worked. Scoped to the generated `.opencode/` tree plus the
workflow directory, with bracket classes in the pattern so the scan
cannot match its own source line. Verified both ways locally: no false
positive on a clean tree, and a planted `sk-ant-`/`sk-or-v1-` key is
still caught.

`862 AC-8 injects no /tmp or $TMPDIR permission rule` began failing on
Linux CI after 36addff pointed the fixture at a shim-provisioned
mkdtemp cwd. `--dir <cwd>` then legitimately carried `/tmp/...`, which
the blanket `args.join(" ")` assertion read as an injected rule. It
passed on macOS only because tmpdir() there is /var/folders. The
assertion now drops that one value, so a /tmp rule injected anywhere
else in the argv still fails it.

Entire-Checkpoint: b6d61bf23ae1
AC-3 offers two ways to settle sub-agent fan-out: a verified dogfood table
on #997, or documenting the fallback in the driver's doc comment. #997 has
no such table, and the driver's doc comment had zero matches for
fan-out/parallel/sequential/subagent — so neither satisfier was taken. QA
caught it.

Documents what actually happens rather than inventing a fallback. There is
no driver-conditional branch anywhere in the driver or the exec skill, so
claiming an implemented "sequential fallback" would have been false. The
honest disposition: provisioning works (a hermetic `opencode debug agent`
resolves mode/steps/permission on all three defs), fan-out itself is
unverified, and the de facto behaviour is sequential inline execution
arrived at by absence rather than design.

Also records a boundary found while probing this: `opencode debug agent
<name> --tool <id>` executes a tool WITHOUT invoking `tool.execute.before`,
so the hook shim never runs on that path. Verified on 1.18.27 — the
plugin's load sentinel appears but an instrumented hook-entry probe does
not. It is a debug harness rather than the phase path, but anything run
through it is unguarded, and it is the reason OQ-4 cannot be settled for
free that way.

The two gate tests are scoped to the leading block comment (everything
before the first import) per CLAUDE.md, so an unrelated inline comment
elsewhere in the file cannot satisfy them.

Entire-Checkpoint: 8773b696557e
…code-fidelity-hook-shim-fail-closed-subag

# Conflicts:
#	CHANGELOG.md
@admarble
admarble merged commit 2efe220 into main Sep 8, 2026
8 checks passed
@admarble
admarble deleted the feature/996-feat-opencode-fidelity-hook-shim-fail-closed-subag branch September 8, 2026 15:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: opencode fidelity — hook shim (fail closed), subagent defs, MCP translation, error classes, CI smoke (#862 P1)

1 participant