Repository navigation
Description
Epic: M2 Blocked by: #992, #863 Tier: judgment Doc: docs/internal/graph-2026-09/PLAN.md §4, §5 I-1/I-3/I-8, §7 D2/D7 Graph node: 12
Summary
Add opencode (anomalyco/opencode, ~190k stars) as a third agent driver alongside Claude Code and Aider. Unlike Aider (which runs degraded 3–5-line phase prompts) and unlike the planned Codex driver #497 (which needs a skills mirror), opencode reads .claude/skills/SKILL.md natively — it is the first backend that can inherit sequant's full ~18k-line skill methodology rather than an aider-grade fallback.
Usage after implementation:
sequant run 123 --agent opencodeResearch basis: July 2026 investigation (three parallel deep-dives: sequant driver-layer map, Claude-surface inventory, opencode source/docs verification against anomalyco/opencode@dev). Full write-up: docs/investigations/multi-backend-2026-07.md.
Why opencode (and not more Aider investment)
Aider proves the AgentDriver seam works but is a working driver, not a working product: no skills, no subagents, no hooks, no resume, no structured errors. Bringing Aider to parity means sequant building its own agent runtime (multi-step workflow execution, subagent fan-out, pre-execution policy) — months of platform work, some of it impossible without forking Aider.
opencode is the only surveyed tool satisfying all four hard requirements simultaneously:
| Requirement | opencode support | Verified in |
|---|---|---|
Reads .claude/skills/ |
Native (.claude is a first-class external skill dir; walks up from cwd to the git worktree root — matches sequant's worktree phase model) |
packages/opencode/src/skill/index.ts |
| Headless + structured output | opencode run --command <name> <args> --format json --auto (NDJSON events: tool_use, step_start, step_finish, text, reasoning, error) |
packages/opencode/src/cli/cmd/run.ts |
| Subagents | Markdown defs in .opencode/agents/, Task-tool spawnable, mode: subagent, per-agent permissions |
opencode.ai/docs/agents |
| Blocking pre-tool hooks | Plugin tool.execute.before — blocks by throwing, can mutate args; permission.ask allows programmatic allow/deny |
packages/plugin/src/index.ts |
Bonus: 75+ providers (can keep driving Claude models through it), --auto respects explicit deny rules (safer than a blanket bypass), --fork session branching, opencode serve/--attach for warm-start across phases.
Design
D1 — Driver (src/lib/workflow/drivers/opencode.ts)
Subprocess driver following the Aider pattern, but resolvesSkills: true (skills preflight stays active — opencode reads the same .claude/skills/ tree the preflight checks):
opencode run --command <phase> <issue> --format json --auto --dir <worktree>
- Parse NDJSON: concatenate
textevents →output(feeds existingparseQaVerdict/parseQaSummaryunchanged);errorevents → structured failure. - Session resume:
--session <id>;ResumeHandle{driver: "opencode", token, originCwd}per the refactor: normalize agent-driver resume semantics (origin-cwd-bound ResumeHandle, driver-owned validation) #674 contract. SEQUANT_*env contract passes through spawn env unchanged.- Settings:
run.opencode?: { model?: string; variant?: string; extraArgs?: string[] }+--agent opencode(string plumbing already exists).
D2 — Command wrappers (phase entrypoints)
opencode skills are model-invoked tools, not slash commands — /qa 123 does not resolve. Each phase entrypoint needs a thin .opencode/commands/<phase>.md wrapper whose template instructs: load the <phase> skill via the skill tool and execute it against $ARGUMENTS. sequant init --agent opencode generates these (~9 small files). Generate from one source at init/build time — do not hand-mirror (we already carry drift risk across three skill dirs; hooks/post-tool.sh has already drifted from its siblings).
D3 — Hook shim (TS plugin wrapping the existing bash hooks)
opencode hooks are in-process TS plugins, not subprocess shell hooks. Rather than rewriting the 732-line pre-tool.sh security engine, ship a thin .opencode/plugins/sequant-hooks.ts shim: serialize the tool call to the hook's stdin JSON contract, pipe to pre-tool.sh via Bun $, translate exit 2 → throw (which blocks the tool call). Same pattern for post-tool.sh on tool.execute.after.
D4 — Subagent + frontmatter translation
Port the four .claude/agents/*.md defs to .opencode/agents/ (maxTurns→steps, tools→permission, add mode: subagent, hidden: true). opencode silently drops unknown skill frontmatter (allowed-tools), so tool restrictions move into opencode permission config generated by init.
D5 — Config plumbing
- MCP: translate to opencode's flat
mcpkey (type: local|remote,commandas array). OPENCODE_CONFIG_CONTENT(inline JSON env var) is the cleanest per-phase injection point for model/permission overrides — no files written into the user's repo.doctor/wizard: checkopencodebinary + minimum version whenrun.agent: "opencode".
Design critique / known risks (adversarial pass)
- Skill-invocation reliability is the load-bearing unknown. The whole value proposition rests on the model actually loading the skill when the command wrapper tells it to. Claude Code makes
/qaa protocol-level command; opencode makes it a polite request to call askilltool. If the model skips the skill and freelances, we get aider-grade output that looks like a skilled run — and QA verdict regexes may still match, silently laundering a low-fidelity review. Mitigation: dogfood gate (below) + a marker check: skills emit a known header; the driver should verify the marker appears in output before trusting phase-specific parsing, and fail the phase (distinct error) if the skill demonstrably never loaded. - Skill content is tuned on Claude Code tool names. 120
Grep, 41Glob, 29subagent_type, literalAgent(...)call syntax, 11AskUserQuestion. opencode's tools are lowercase and its Task syntax differs. Models adapt to prose, but theAgent(subagent_type="sequant-implementer", ...)blocks inexec/qaare executable syntax, not prose — expect degraded subagent fan-out until those sections get driver-conditional wording. Scoping decision: do not fork the skill tree; prefer small tool-name-neutral rewording in_sharedreferences where it measurably matters. - Hook shim gaps. (a) The bash hooks assume Claude Code's stdin JSON schema (
tool_name,tool_inputshapes) — the shim must map opencode's{tool, args}to that schema, and field mismatches fail open unless the shim defaults to deny-on-error. Make the shim fail closed. (b) Bun/TS plugin runtime means Windows users need bash present for the underlying scripts — same constraint the hooks already have today, but now two layers deep. (c)--pureor a user's global plugins can disable/reorder our plugin; doctor should verify the plugin is active. - No terminal result event. The NDJSON stream just ends on
session.idle— no cost/usage/duration record like the SDK'sresultmessage. Phase duration comes from the driver's own clock; token accounting needsopencode statsor the server API, or is simply absent at first (acceptable — Aider reports none either). - Platform velocity/churn risk. opencode moved orgs (
sst→anomalyco), ships 800+ releases, and several load-bearing features we'd depend on (--commandonrun, skill external dirs, plugin hook surface) are undocumented or ahead of docs. Pin a minimum version in doctor, keep the driver's flag surface minimal, and add a CI smoke test that runs a trivialopencode run --format jsonagainst the pinned version so upstream breakage is caught by us, not by users mid-phase. - Exit-code caveat when attaching.
--attachmode swallows session errors from the exit code. Don't useserve/--attachin v1 — spawn per phase (cold start is tolerable; warm-start is a later optimization). - Known drift trap in our own code: the ready-gate path (
ready-gate.ts:buildPhaseConfig) never plumbsagent/aiderSettingsand today silently runs the claude-code driver regardless ofrun.agent— tracked separately. That bug must be fixed before or with this work, or--ready-gateon an opencode run silently switches backends mid-run.
Real-world walk-through (sequant run 123 --agent opencode)
- Config resolution:
run.agent: "opencode"→getDriver("opencode"); doctor has verified binary + min version + plugin presence. - Worktree created;
.claude/settings.local.jsoncopy is a no-op for opencode; init has placed.opencode/commands/,.opencode/agents/,.opencode/plugins/sequant-hooks.ts(or they're resolved from global config). - Skills preflight passes —
.claude/skills/is present and is what opencode itself reads (preflight semantics carry over unchanged). - Spec phase: driver spawns
opencode run --command spec 123 --format json --auto --dir <worktree>; command template loads the spec skill;SEQUANT_*env flows to shell tools; hook shim guards force-push/commit rules. - QA phase: skill emits the
### Verdict:format; existingparseQaVerdictconsumes concatenatedtextevents; skill-marker check confirms the skill actually ran. - Failure modes to handle explicitly: opencode not installed (fail at preflight, not mid-run); skill never invoked (marker check → distinct
PhaseResult.error); NDJSON parse failure (treat aserror_during_executionequivalent); rate limits (opencode error events differ from SDKrate_limit_event— classify what we can, degrade to generic failure otherwise, do NOT reuse Claude-specific retry ladders blindly).
Scope (graph plan 2026-09)
- may touch:
src/lib/workflow/drivers/opencode.ts(new),src/lib/workflow/drivers/index.ts(one registry line),src/lib/settings.ts(run.opencode: { model, variant, extraArgs, reasoningMaxTokens }— the last field per spike(opencode): doesopencode run --command <phase>load the sequant skill? (#862 P0 precondition, resolves OQ-8/OQ-9) #992 (node 06) AC-3),src/lib/workflow/config-resolver.ts(pass-through only),src/commands/init.ts(+ one template source for.opencode/commands/<phase>.md),src/commands/doctor.ts, tests beside each,src/lib/workflow/drivers/opencode.live.integration.test.ts - not in scope: hook shim, subagent defs, MCP translation, error classification beyond NDJSON
errorevents, CI smoke (feat: opencode fidelity — hook shim (fail closed), subagent defs, MCP translation, error classes, CI smoke (#862 P1) #996 (node 15)); docs (GATE: opencode dogfood promotion decision (#862 P2, human gate) #997 (node 16) accept path);serve/--attach.
Acceptance criteria (graph plan 2026-09)
- AC-1: driver parses the recorded fixture — Verify:
npx vitest run src/lib/workflow/drivers/opencode.test.ts -t "862"→ passes; input issrc/lib/workflow/drivers/__fixtures__/opencode-run-qa.ndjsonfrom spike(opencode): doesopencode run --command <phase>load the sequant skill? (#862 P0 precondition, resolves OQ-8/OQ-9) #992 (node 06); asserts concatenatedtext→output,errorevents → structured failure,successonly when the skill marker is present (AC-4), abort → SIGTERM on a detached process group,config.envforwarded, RingBuffer tails populated. - AC-2: live SKIP-when-absent test — Verify: same command with
opencode.live.integration.test.ts: whenwhich opencodesucceeds and a provider key is present, spawnsopencode run --format json --auto --dir <tmp>with a trivial prompt and asserts ≥1textevent; otherwise reportsSKIPPED (opencode absent), never a pass. - AC-3: registry + settings + CLI — Verify:
node dist/bin/cli.js run 1 --agent opencode --dry-run(afternpm run build) prints the opencode driver in its plan without spawning;npx vitest run src/lib/workflow/drivers/index.test.ts -t "862"assertsgetDriver("opencode"). - AC-4: skill-marker verification — Verify:
-t "862 AC-4": a fixture stream with no skill marker yields a distinctPhaseResult.error(skill-not-loaded), not a parsed verdict. - AC-5: command wrappers from one source — Verify:
sequant init --agent opencodein a temp dir writes.opencode/commands/<phase>.mdfor every phase entrypoint from a single template (grep -rl 'opencode/commands' src/commands/init.ts templates | wc -l→ the template lives in exactly one place), anddiff <(ls .opencode/commands) <(expected phase list)is empty. - AC-6: resume honors refactor: normalize agent-driver resume semantics (origin-cwd-bound ResumeHandle, driver-owned validation) #674 — Verify:
npx vitest run src/lib/workflow/drivers/resume-semantics.test.ts -t "opencode"→ResumeHandle{driver:"opencode", token, originCwd}round-trips and is rejected from a different cwd. - AC-7: doctor — Verify:
npx vitest run src/commands/doctor.test.ts -t "opencode"→ withrun.agent: "opencode"doctor checks the binary and the pinned minimum version (1.18.27) and fails with the install hint when absent. - AC-8: spike(opencode): does
opencode run --command <phase>load the sequant skill? (#862 P0 precondition, resolves OQ-8/OQ-9) #992 (node 06) mitigations applied — Verify:-t "862 AC-8": the spawn passesOPENCODE_CONFIG_CONTENTcarrying the reasoning budget, the/tmp/$TMPDIRallow rule (or scratch relocation) from spike(opencode): doesopencode run --command <phase>load the sequant skill? (#862 P0 precondition, resolves OQ-8/OQ-9) #992 (node 06)'s table, anddetached: true. - AC-9: I-1 — Verify:
npx vitest run src/lib/workflow/execution-config-parity.test.ts→ passes with the newopencodeSettingsfield asserted equal across producers.
Done when (graph plan 2026-09)
sequant run <n> --agent opencode dispatches every phase through a driver whose parser was proven on recorded real output, fails distinctly when the skill did not load, and passes doctor and the parity test.
Original acceptance criteria (superseded by the graph-plan ACs above; kept for history)
P0 — Core driver
OpencodeDriverinsrc/lib/workflow/drivers/opencode.tsimplementingAgentDriverwithresolvesSkills: true: spawnsopencode run --command <phase> <issue> --format json --auto --dir <cwd>, parses NDJSON intoAgentPhaseResult, wires abort → SIGTERM, RingBuffer tails, forwardsconfig.env- Registry entry +
run.opencodesettings schema (model,variant,extraArgs) +--agent opencodeverified end to end frombin/cli.ts - Phase command wrappers:
sequant init --agent opencodegenerates.opencode/commands/<phase>.mdfor all phase entrypoints from a single template source (no hand-mirrored fourth tree) - Skill-marker verification: driver (or phase-executor) fails an opencode phase with a distinct error when the phase skill demonstrably never loaded
- Session resume via
--session <id>honoring the refactor: normalize agent-driver resume semantics (origin-cwd-bound ResumeHandle, driver-owned validation) #674ResumeHandlecontract (driver-tagged, originCwd-bound) doctorvalidates opencode binary + minimum pinned version when configured- Ready-gate
buildPhaseConfigplumbsagent/driver settings (or the separate bug for it is closed first)
P1 — Fidelity
- Hook shim plugin (
tool.execute.before/after→ bash hooks via stdin JSON; fail closed on schema mismatch); doctor verifies the plugin is active - Subagent defs ported to
.opencode/agents/with translated frontmatter;exec/qafan-out verified working (or driver-conditional sequential fallback documented) - MCP config translation for
sequant servein opencode'smcpformat - Error classification for opencode NDJSON
errorevents (distinct from exit-code-only failures); Claude-specific retry paths (MCP fallback, SDK rate-limit shapes) correctly bypassed - CI smoke test against the pinned opencode version
P2 — Dogfood gate (promotion criterion)
- Run ≥3 real issues end to end (spec→exec→qa) on this repo or a testbed with
--agent opencode; compare QA verdict quality against claude-code runs on the same issues; record results in the investigation doc - Docs: README multi-agent section +
docs/referencedriver page
Non-goals
- Aider parity work (explicitly rejected — see investigation doc)
serve/--attachwarm-start (exit-code caveat; later optimization)- Forking the skill tree per driver
- Codex driver (feat: add OpenAI Codex CLI agent driver #497 — separate issue; shares the command-wrapper and init patterns built here)
Related
- feat: add OpenAI Codex CLI agent driver #497 — Codex CLI driver (second backend target; OpenAI-locked, needs
.codex/skills/mirror) - refactor: normalize agent-driver resume semantics (origin-cwd-bound ResumeHandle, driver-owned validation) #674 — resume-handle contract this driver must honor
- feat(run): pre-flight the skills install — missing .claude/skills/ should fail fast, not flail for 30 minutes as a spec retry #813 — skills preflight (carries over unchanged for opencode)
- Strategic follow-up worth its own issue if multi-backend proceeds: mirror skills to
.agents/skills/— the emerging neutral path read by Codex, Gemini, Copilot, Amp, Factory, Kilo, and opencode
Activity
admarble commentedon Jul 29, 2026
#862 — feat: add opencode agent driver — first backend that can inherit the full skill methodology
Open · enhancement
────────────────────────────────────────────────────────────────
→ PROCEED — Design is specific and already adversarially critiqued; P0 depends on #863 landing first
Commands:
sequant run 862 -Q
spec → exec → qa · 14 ACs
Flags:
-Q a new driver touches the registry, settings schema, CLI plumbing and init generation
Considered:
--security-review the hook shim is the only security-adjacent surface and it sits in P1, not P0
--stacked the 863 → 862 chain is 2 issues, where stacked PRs are manifest-only and buy no incremental review
────────────────────────────────────────────────────────────────
⚠ Depends on #863 — run it after that lands, or chain with
sequant run 863 862 --chain -Q⚠ 14 ACs across P0/P1/P2 — one run will not land all three tiers; P0 is the shippable slice and P1/P2 belong in follow-ups
⚠ docs/investigations/multi-backend-2026-07.md cited by the body is not on main yet — it lands with open PR #864
────────────────────────────────────────────────────────────────
admarble commentedon Jul 29, 2026
#862 — feat: add opencode agent driver — first backend that can inherit the full skill methodology
Open · enhancement, backlog
────────────────────────────────────────────────────────────────
Supersedes prior assess from 2026-07-29 (PROCEED)
→ PARK — Backlogged by maintainer decision — multi-backend work deferred; design and research remain valid
Resume after: maintainer re-prioritizes multi-backend work; #863 (ready-gate driver plumbing) should land first regardless
────────────────────────────────────────────────────────────────
docs: multi-backend investigation (2026-07) (#864)
admarble commentedon Sep 6, 2026
Field evidence (2026-09-03 → 09-06, internal experiment on a separate non-sequant task): drove
openrouter/z-ai/glm-5.3-flashandanthropic/claude-sonnet-5through opencode 1.18.27 headless on an agentic build task (turn a ~170-line content brief into a static site in an otherwise-empty repo; output graded mechanically). What it tells this issue:Transport premise confirmed. opencode drove a non-Anthropic model with zero config beyond the env key — completion and tool-calling (file writes, shell, a local server, screenshots) all worked; Sonnet 5 through the same path also worked. Risk 1 (skill invocation) was not exercised — this task had no skills — but the layer under it is solid.
Three harness behaviors D1/D5 must handle, each observed and reproduced:
limit.output. Two consecutive runs died at exactly 32,000 completion tokens (step_finish reason=length) withlimit.output: 131072confirmed loaded fromopencode.jsonc(schema checked; no knob raises the per-step clamp). A reasoning model spent the whole step thinking (31.9K reasoning / ~100 output tokens), never called a tool — and opencode exited 0 with an empty workspace. What worked: per-modeloptions.reasoning.max_tokens: 20000via provider config, leaving ~12K/step for output. Implications:run.opencodeneeds a reasoning-budget field;OPENCODE_CONFIG_CONTENT(D5) is the right injection point; and the driver must treat "exit 0 + no diff" as failure — which is exactly theLOOP_NO_DIFFsignal feat(run): model escalation ladder on capability-bound non-convergence #971 keys on, so the ladder trigger already covers this class./tmp) and a GLM follow-up run (vendoring a library through/tmp) were both auto-rejected — not prompted, ended. Sequant's skills and hooks reference/tmpin 18 places (loopreads/tmp/claude-issue-<N>.log;assessandpost-tool.shuse${TMPDIR:-/tmp}). D1's--autoneeds explicit allow rules for those paths, or skill scratch moves under the worktree — otherwise phases die mid-run with a misleading exit.detached+ group-kill discipline from day one.Risk 4 (no terminal usage record) — softer than written: opencode's session store records per-step token counts (input/output/reasoning) in its part table, and per-request cost was reconstructable from the provider's generation records. Not a stream event, but not "simply absent."
Cost/quality datapoint (n=1, not a benchmark): the full GLM build cost ≈$0.03 including two dead attempts; once throttled it ran a genuine self-verification loop (syntax checks, quote-match script, local server, responsive screenshots) and handled a day-two change request with zero correction turns. Sonnet built first try and was killed by trap 2 during its own verification.
Net: the transport premise for this driver is de-risked; the remaining work is defaults and permission plumbing, not model capability. Still gated on #863 per P0's last AC.
admarble commentedon Sep 7, 2026
Graph plan 2026-09 — split. This issue now carries the P0 driver core (node 12). Moved out: skill-load spike → #992 (must report GO first), P1 fidelity → #996, P2 dogfood gate → #997. The ready-gate plumbing AC is #863. Blocked by #992 and #863. Plan:
docs/internal/graph-2026-09/PLAN.md.admarble commentedon Sep 7, 2026
Spike verdict: GO — #992 concluded
opencode run --command qa <issue> --format json --auto --dir <worktree>doesload
.claude/skills/qa/SKILL.mdand act on its deep content. Risk 1 is refutedas a blocker — but the run replaced it with a bigger one: the skill tool
truncates the body.
Full write-up:
docs/investigations/opencode-driver-spike.md.Recorded fixture:
src/lib/workflow/drivers/__fixtures__/opencode-run-qa.ndjson(93 events, 561 KB, real output, paths scrubbed). Both land in the #992 PR.
Environment: opencode
1.18.27, modelopenrouter/anthropic/claude-sonnet-5.Cost: $1.1216 total across 4 runs (cap was $5). Decisive run: 408 s, $1.1198.
Evidence (three independent signals, all positive on the first phrasing)
grep -cE 'SEQUANT_QA_VERDICT|### Verdict'on the fixturetool_useevent,part.tool == "skill", input{"name":"qa"}qa/SKILL.md, absent from the wrapperThe canary was planted as an instruction to emit an integrity token. The model
read it, recognised it as a prompt injection and refused, citing the qa skill's
own §6f Trust-Boundary Check. That is a second-order proof: it read char 150,308
and applied a rule from elsewhere in the same file. It also applied the skill's
deep
SEQUANT_WORKTREE_ISSUE_MISMATCHguard.Which P0 ACs change
skill-not-loaded→skill-truncated. The skill tool delivered51,145 of 174,981 chars in-band and set
metadata.truncated: true, pointingat an
outputPath. The run only worked because the model noticed and issuedfive follow-up
readcalls to page through the rest. A weaker model thataccepts the 51 KB gets ~29% of the skill — Risk 1's silent low-fidelity review,
arriving by another route. Assert on
metadata.truncated, not on the presenceof the
skilltool call. Every sequant skill trips this (~43K tokens each).run.opencode. Per-modeloptions.reasoning.max_tokens(+limit.context/limit.output) is the32K-clamp mitigation and must be expressible in sequant config.
OPENCODE_CONFIG_CONTENTandOPENCODE_CONFIGboth merge with the user's global~/.config/opencode/opencode.jsonc;--puredisables plugins, not config.Only an
XDG_CONFIG_HOMEredirect is hermetic. Write the AC as "these keys areset", never "only these keys are set".
--autoauto-approves everything notexplicitly denied, and the qa skill's tail posts comments and edits labels.
permission.bashdeny rules are the only layer that works —permission.external_directorydoes not govern the--dirtree (a blanket"*":"deny"still permitted a read inside the run root)./tmp" requirement unless separatelyre-justified. Two control runs showed
/tmpis not blocked on 1.18.27, withor without allow rules. The prior field observation is real but its cause is
unidentified — it is not opencode's permission system.
perl -e 'setpgrp(0,0)') +group kill; NDJSON to a file, never a pipe. The group-kill path executed for
real and reaped the tree without killing the harness.
readsplits them and reports phantom parse failures — a proper parse gives93/93 valid). Tool name is
part.tool, not.name.step_finish.part.costisper step — sum it.
.gitas afile). That untested assumption is confirmed. Discovery was proven at $0 via
opencode debug skill; only invocation needed paying for.Not proven
One model, one wrapper phrasing, one small diff (PR #983, +1/−1). Cheap-model
degradation is unmeasured — given the truncation finding, that is the highest
value follow-up. The qa skill's
gh-dependent tail never ran (denied by design),so the phase contract past the verdict text is unproven. The 32K clamp was not
re-triggered (its control run hit the wall-clock bound first).
admarble commentedon Sep 7, 2026
Correction to the #992 spike verdict (above)
Adversarial QA of the spike found two errors in my previous comment. The GO
verdict and the truncation finding both stand — these are corrections to the
contract details the driver would be built against, and one of them would have
produced a silently-dead guard.
1. The truncation flag is at a different path than I stated.
I wrote
part.metadata.truncated. The real location is:part.metadata.truncatedresolves toundefined, and becauseundefinedisfalsy, a
skill-truncatedguard written against it would never fire — theexact silent-failure class the spike exists to prevent. Verify against the
committed fixture:
2. I claimed the
permission.bashdeny rules "worked". They were never exercised.The fixture shows all 28 tool calls completed, zero denials, and no
gh issue comment/edit/pr,git push, orgit commitwas ever attempted.The model found
gh auth status→ "not logged into any GitHub hosts" and$GH_TOKENempty, and treated GitHub as read-only from then on. It stopped forlack of credentials, not because the permission layer denied it.
Worse, a follow-up check found
permission.webfetch: "deny"was set on that runand the model still made 6 successful
curlcalls toapi.github.comthroughbash. Revised sandboxing picture on 1.18.27:permission.external_directory--dirtreepermission.webfetch: "deny"curlfrombashpermission.bashdeny rulesSo P0 item 4 changes from "deny rules are the only layer that works" to "treat
opencode's permission layer as unproven; verify it with an authenticated-
ghcontrol run before any AC claims a sandbox."
3. Trap reproduction is weaker than implied. Three further controls failed to
re-trigger the 32K clamp (one completed normally at 7,321 output tokens — below
the cap; one opened 3 steps, closed none, and was killed at its bound). Only
process-group killwas actually reproduced. The ~32K figure is not measuredhere.
Cost-accounting corollary: the hung control consumed 420 s of real tokens but
sums to $0.00 under the
step_finishmethod, because nostep_finishwasemitted. A driver budgeting purely from
step_finish.costunder-reports exactlythe runs that hang. Pair it with a wall-clock check.
Total spend $1.1281 (cap $5). Full corrected write-up in PR #1005 →
docs/investigations/opencode-driver-spike.md.docs(plan): 2026-09 backlog graph (16 nodes, /graph-run ready) (#998)
admarble commentedon Sep 8, 2026
Runner context — wave 2 launch (2026-09-08, main at ecea618). All wave-1 PRs are merged (#999 #1000 #1001 #1002 #1003 #1004 #1005) plus the plan PR #998 and #1006, so read the plan and your node file from
main:docs/internal/graph-2026-09/PLAN.md(§5 invariants, §7 decisions D16–D22, §8 conventions) anddocs/internal/graph-2026-09/issues/<NN>-*.md. Launch discipline learned in wave 1: the launcher kills any phase that is silent for 30 minutes and the shutdown cleanup deletes an uncommitted worktree — commit a WIP every ~10 minutes and before any long test run; run tests in the foreground only (never backgroundnpm test); prefer the node file's targeted-tcommands over the full suite (the full suite takes ~6 min). A phase that reports "Out of credits" at ~30 min was a timeout, not a wallet problem. Consent mode is stop-at-PR: open the PR, do not merge.Node file:
issues/12-862P0-opencode-driver-core.md. Blockers are merged: node 06's spike (PR #1005, verdict GO) recorded the NDJSON fixture atsrc/lib/workflow/drivers/__fixtures__/and its findings indocs/investigations/(opencode spike doc) — build the parser against the fixture, never the README. Two findings amend how you read the ACs: (1) AC-8's/tmpallow-rule clause is non-load-bearing — the spike refuted the/tmppermission kill on 1.18.27 and could not provoke the 32K clamp in three controls (OQ-19, amended and accepted by the owner); satisfy AC-8 by passing the reasoning budget viaOPENCODE_CONFIG_CONTENTanddetached: true, and have the AC-8 test assert that no/tmprule is injected, citing the spike doc — do not add a deny/allow rule for a trap that does not reproduce. (2) The spike found opencode's skill tool truncates a long SKILL.md body (about 51K of 175K chars read) and that onlyXDG_CONFIG_HOMEisolation is hermetic (a globalopencode.jsonccontaminates runs) — the driver's spawn must setXDG_CONFIG_HOMEto a per-run directory, and AC-4's skill-marker check must not assume the whole skill body reached the model. Provider key: the live test (AC-2) must SKIP, never pass, when no key or binary is present; a run that does spawn opencode must stay under $5 total.admarble commentedon Sep 8, 2026
Complexity: Complex (9 ACs, 6 directories)
AC Quality Check
lintAcceptanceCriteriaon the 9 graph-plan ACs: 1/9 flagged.integration_testwas inferred from keywords, not declared." Every other AC carries a runnableVerify:command; AC-2's is prose-embedded (same command with opencode.live.integration.test.ts). Recommend reading it asEvidence: npx vitest run src/lib/workflow/drivers/opencode.live.integration.test.ts -t "862"and asserting the SKIP path, not just the spawn path.Rule-touchpoint detector: fired on AC-2 only (
never+skip); all touchpoints resolve tosrc/lib/__fixtures__/ac-parser/*.md, i.e. no production rule site. Section omitted.AC amendments already accepted on this issue (apply them, do not re-litigate):
tool_usewherepart.tool === "skill"), and it must not assume the whole skill body reached the model.part.state.metadata.truncated—part.metadatais provider metadata and resolves toundefined, which is falsy, so a guard written there never fires./tmpallow-rule clause is non-load-bearing (OQ-19). Satisfy it with the reasoning budget viaOPENCODE_CONFIG_CONTENT+detached: true, and have the test assert that no/tmprule is injected, citing the spike doc.XDG_CONFIG_HOMEredirect isolates from the user's globalopencode.jsonc;OPENCODE_CONFIG_CONTENTandOPENCODE_CONFIGboth leak (spike Finding 1).Scope Assessment
Non-Goals: ✅ 4 declared (aider parity,
serve/--attach, forking the skill tree, Codex #497).Verdict: ❌ SCOPE_SPLIT_RECOMMENDED — overridden with reason. The split already happened: this issue is the P0 slice (P1 → #996, P2 → #997, ready-gate → #863 merged, spike → #992 merged). The analyzer's suggested splits (
config/ui/test) are keyword artifacts of theVerify:clauses, not real seams — all 9 ACs land on one driver plus its registration surface. Quality loop auto-enables; keep it (-Q).Acceptance Criteria
AC-1: driver parses the recorded fixture
Verification: Unit Test —
npx vitest run src/lib/workflow/drivers/opencode.test.ts -t "862"Scenario: Given
__fixtures__/opencode-run-qa.ndjson(93 events, 561 KB) → When the parser consumes it → Then the 7textparts concatenate tooutputending in### Verdict: READY_FOR_MERGE,errorevents map to structured failure,successrequires the AC-4 marker, abort sends SIGTERM to the process group,config.envis forwarded, and both RingBuffer tails populate.Assumptions: The fixture contains only
step_start/step_finish/text/tool_use— there is no recordederrorevent, so that branch needs a synthetic line and its shape is unverified.AC-2: live SKIP-when-absent test
Verification: Integration Test —
opencode.live.integration.test.tsScenario: Given no
opencodebinary or no provider key → When the suite runs → Then it reportsSKIPPED (opencode absent), never a pass. Given both present → spawns a trivial prompt and asserts ≥1textevent.Assumptions: The
.integration.infix is required for the vitest project's longer timeout (a missing infix gets the 5s default). Total live spend stays under $5.AC-3: registry + settings + CLI
Verification: Integration Test (CLI) + Unit Test (registry)⚠️ The dry-run path prints no driver name today —
Scenario: Given
npm run build→ Whennode dist/bin/cli.js run 1 --agent opencode --dry-run→ Then the plan names the opencode driver and nothing spawns;getDriver("opencode")returns it.Assumptions:
phase-executor.ts:1141returns beforegetDriverand only echoes the prompt under--verbose. AC-3 requires adding that line (see Phase 1).AC-4: skill-marker verification
Verification: Unit Test —
-t "862 AC-4"Scenario: Given a stream with no
skilltool call for the phase → Then a distinctPhaseResult.error(skill-not-loaded), not a parsed verdict.Assumptions: Marker =
tool_usewithpart.tool === "skill"andpart.state.metadata.name === <phase>. Truncation is a separate condition (see Open Question 1).AC-5: command wrappers from one source
Verification: Integration Test —⚠️
sequant init --agent opencodein a temp dirScenario: Given a temp project → When init runs → Then
.opencode/commands/<phase>.mdexists for all 9 registered phases, rendered from one template.Assumptions:
sequant inithas no--agentflag today — it needs a.option()inbin/cli.tsplusInitOptions(the classic silent-no-op trap).AC-6: resume honors #674
Verification: Unit Test —
resume-semantics.test.ts -t "opencode"Scenario: Given a
ResumeHandle{driver:"opencode", token, originCwd}→ WhencanResumeis asked from a different cwd or with a foreigndrivertag → Then false; same cwd → true and the spawn gains--session <token>.Assumptions:
sessionIDis on the envelope of all 93 fixture events, so the token is available even on a failed run.opencode run -s/--session <id>is confirmed present on 1.18.27.AC-7: doctor
Verification: Unit Test —
doctor.test.ts -t "opencode"Scenario: Given
run.agent: "opencode"→ When doctor runs → Then it checks the binary and the pinned floor1.18.27and fails with an install hint when absent. Mirrors the existing aider block atdoctor.ts:426.AC-8: #992 mitigations applied
Verification: Unit Test —
-t "862 AC-8"Scenario: Given
run.opencode: { model, reasoningMaxTokens }→ When the spawn is built → ThenOPENCODE_CONFIG_CONTENTcarries the per-model reasoning budget,XDG_CONFIG_HOMEpoints at a per-run dir,detached: trueis set, and no/tmppermission rule is injected (OQ-19).Assumptions: The budget key is per-model (
provider.<p>.models.<m>.options.reasoning.max_tokens), so it can only be emitted whenrun.opencode.modelis set — assert that conditionality, not an unconditional payload.AC-9: I-1 producer parity
Verification: Unit Test —
execution-config-parity.test.tsScenario: Given
opencodeSettingsadded toExecutionConfig→ When the resolver andbuildPhaseConfigare compared over the key union → Then equal (the gate spreadsopts.configpost-#863, so this holds without a new allowlist entry).Implementation Plan
Wave-2 discipline applies: commit a WIP every ~10 min, foreground tests only, prefer the
-tfilters above over the ~6-min full suite.Phase 1 — Seams first (AC-3, AC-9)
settings.ts:OpencodeSettings { model?, variant?, extraArgs?, reasoningMaxTokens? }+OpencodeSettingsSchema+run.opencode. Sibling sites in this one file — all five must move together (this is therun.aiderpattern): interface (:117), Zod schema (:417),KNOWN_KEYS.run(:641), a newKNOWN_KEYS["run.opencode"],validateAiderSettings's twin, and the two generated doc tables (:1223agent values,:1233).types.ts:ExecutionConfig.opencodeSettings;config-resolver.ts:516: one pass-through line. Run AC-9's parity test — it should pass immediately.drivers/index.ts: registry line +DriverOptions.opencodeSettings.phase-executor.ts:1302passes it.skills-preflight.tsandrun-orchestrator.tsneed no change — they callgetDriveronly to readresolvesSkills, which is a statictrue.config.dryRunbranch (phase-executor.ts:1141), print the resolved driver name unconditionally (not gated on--verbose) so AC-3's command shows it.Phase 2 — Parser, fixture-driven (AC-1, AC-4)
opencode.tsskeleton with a chunk-safe NDJSON reader: accumulatestdoutchunks and split on\n— the three longest fixture lines are 100 KB / 96 KB / 70 KB, so any fixed-buffer or line-at-a-time reader corrupts them. Cap what reaches the RingBuffer tails (50 × 100 KB lines = 5 MB otherwise).type:"text"→part.textconcatenation;type:"step_finish"→ sumpart.cost(per-step, not cumulative);tool_use→part.tool(not.name); envelopesessionID→ resume token.part.state.metadata.{name,truncated}. Add a mutation-verified negative fixture (a stream with theskillevent stripped).Phase 3 — Spawn contract, resume, doctor (AC-6, AC-7, AC-8, AC-2)
buildArgs:run --command <phase> <prompt> --format json --auto --dir <cwd>+--model/--variant/--session/extraArgs.AgentExecutionConfigneeds aphasefield — the driver is handed only a prompt string today and cannot otherwise name the command (see Open Question 2). The full sequant prompt (AGENTS.md context +/loop'sPROMPT_CONTEXTblock) rides in as$ARGUMENTS, so no prompt content is lost.detached: true; kill withprocess.kill(-pid, "SIGTERM")and swallowESRCH; per-runXDG_CONFIG_HOME(neverXDG_DATA_HOME— auth and tool-output live there).canResume: driver-tag equality + byte-equaloriginCwd. Convert theit.skipslot pattern used for feat: add OpenAI Codex CLI agent driver #497.doctor.ts:426, with the1.18.27floor.Phase 4 — Init wrappers (AC-5)
templates/opencode/command.md(one phase-parameterized source;copyTemplatescopies only named subdirs, so it will not leak into every project) + a writer ininit.tsloopinggetPhaseNames(). Keep the literal.opencode/commandsstring in exactly one file so AC-5'sgrep -rl … | wc -l→ 1.bin/cli.ts:init --agent <name>option +InitOptions.agent.Design Review
AgentDriverseam. The one leak outside it isAgentExecutionConfig.phase— an additive, optional field the claude-code and aider drivers ignore.AiderDriver's spawn/RingBuffer/abort shape, with claude-code'sresumeHandle/structuredErrorshape for the result. Rejected: an inlinedriverOverrides.opencodeprompt template that skips wrappers entirely — cheaper, but the wrapper path is the one the spike actually proved, and AC-5 mandates it.AiderDriverfor process lifecycle;ClaudeCodeDriver.buildResumeHandlefor refactor: normalize agent-driver resume semantics (origin-cwd-bound ResumeHandle, driver-owned validation) #674;doctor.ts's aider block;run.aider's five-site settings pattern.--autoacceptable?" It is not, on its own — see OQ-4.Feature Quality Planning
settings.ts) —run.aiderappears at 5+ sites in that one file plus 2 generated doc tables. Addingrun.opencodeat 4 of 5 leaves a silent unknown-key warning or an undocumented field. Enumerated in Phase 1.1 as a checklist, not prose.errorevent branch has no recorded instance. Treat exit≠0 with nostep_finish reason:"stop"as a failure signal too, so a malformed/absenterrorevent cannot pass as success.step_finish.costunder-reports exactly the hung runs (spike: 420 s of real spend summed to $0.00 because nostep_finishwas emitted). Pair with wall-clock.tokensUsedplumbing is 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's, not this issue's.Derived ACs
errorshapestep_finish reason:"stop"yields a failure, not a successoutputto a single-shot feedrun.opencodeproduces no unknown-key warning (KNOWN_KEYS+ nested set)Open Questions
truncated: truefatal? — Recommendation: no. Every sequant SKILL.md exceeds the 51 KB in-band cap, so a hard fail bricks the backend on day one. Fail only onskill-not-loaded(noskilltool call for the phase); emitskill-partially-loadedas a warning, escalating to a failure only whentruncated: trueand no subsequentreadtool call targets the skill'sdir/outputPath— which is precisely the discriminator the GO run exhibited (5 follow-up reads). Impact if wrong: a weak model silently reviews on 29% of the skill.agent-driver.ts(+phase, so--command <phase>is constructible),phase-executor.ts(populate it; print the dry-run driver line),types.ts(opencodeSettings, which AC-9 requires). Recommendation: proceed — all three are additive and forced by the ACs as written. Impact if wrong: AC-3 and AC-9 are unsatisfiable as literally specified.XDG_CONFIG_HOMEredirect discards the user's ownopencode.jsonc(models, MCP, plugins), not just the contaminating bits. Recommendation: keep the redirect per the runner instruction and write sequant's config into that dir rather than relying on the leaky merge; leaveextraArgsas the escape hatch and document the exclusion. Auth is unaffected (it lives underXDG_DATA_HOME). Impact if wrong: a user's configured provider stops resolving under sequant but works standalone.--autoposture. The spike refutedpermission.external_directory(does not govern the--dirtree) andpermission.webfetch: "deny"(6 successfulcurls to api.github.com frombash), and thepermission.bashdeny list was never exercised —ghwas unauthenticated. Recommendation: ship the deny list as the documented minimum, claim no sandbox in any AC or doc, and leave the authenticated control run to feat: opencode fidelity — hook shim (fail closed), subagent defs, MCP translation, error classes, CI smoke (#862 P1) #996. Impact if wrong: an--autophase with authenticatedghmutates live issues.grep -rl … | wc -lis layout-brittle. Recommendation: pin the layout in Phase 4.13 (templates/opencode/command.mdholds noopencode/commandsliteral;init.tsholds it once) so the count is 1 by construction rather than by luck.aiderSettings, nowopencodeSettings) acrossDriverOptions/ExecutionConfig/config-resolver/phase-executor. A third driver is the point where a genericdriverSettingsbag pays for itself. Recommend filing after merge rather than widening here.Recommended Workflow
Phases: exec → qa
Quality Loop: enabled
Reasoning: New driver touching the registry, settings schema, CLI plumbing and init generation; scope metrics are red and the prior
/assessalso landed on-Q. testgen deliberately skipped despite the Unit/Integration verification methods: all 9 ACs already prescribe exact test file paths and-tfilters, so generated stubs would duplicate names the ACs pin and risk untracked stub litter. Security-review skipped — the hook shim (the only security-adjacent surface) is #996, not this slice.Command:
sequant run 862 -QLabel Review
Current:
enhancement,backlog,graph-2026-09Recommended: drop
backlogReason: The label records the 2026-07 PARK decision, which the 2026-09 graph plan superseded — both blockers (#992, #863) are merged and this is a live wave-2 node. Leaving it on keeps
/assessreading a stale PARK signal.Quality Loop: auto-enables from SCOPE_SPLIT_RECOMMENDED regardless of flags.
→
gh issue edit 862 --remove-label backlogadmarble commentedon Sep 8, 2026
Runner context — exec was killed by the launcher's 30-minute no-progress ceiling at 05:02Z and the shutdown cleanup deleted the worktree. Your committed work is safe: branch
feature/862-feat-add-opencode-agent-driver-first-backend-that-has 8 commits ahead of main (last:4be710bc docs(#862): CHANGELOG entry for the opencode driver) and is now pushed to origin, so the re-dispatch reuses it. Only the uncommitted tail is lost — the transcript's last step was the full test suite in the foreground: run the node-12 targeted-t "862"commands first, commit, then the full suite only if time allows, then open the PR. The dead session's transcript is/Users/tony/.claude/projects/-Users-tony-Projects-worktrees-feature-862-feat-add-opencode-agent-driver-first-backend-that-/167a905a-e4c9-40fd-bd05-e1be88634700.jsonl; replay only what post-dates the last commit (jq -c 'select(.type=="assistant") | .message.content[]? | select(.type=="tool_use" and (.name=="Write" or .name=="Edit" or .name=="Bash")) | {name, input}'). Commit within the first 5 minutes and every ~10 minutes after; foreground targeted tests only; open the PR as soon as the ACs' verify commands pass — a phase silent for 30 minutes is killed again.2 remaining items
test(#862): fixture-driven opencode driver tests (AC-1, AC-1a/b, AC-4…
test(#862): registry, resume and producer-parity coverage (AC-3, AC-6…
feat(#862): doctor validates the opencode binary and pinned version f…
feat(#862): init --agent opencode writes per-phase command wrappers (…
test(#862): live opencode smoke that skips, never passes, when absent…
test(#862): executor phase wiring, dry-run driver line, and settings …
docs(#862): CHANGELOG entry for the opencode driver
test(#862): pin the live smoke's model so it tests the driver, not th…
chore(#862): reconcile pushed pre-rebase lineage (ours; tree unchanged)
admarble commentedon Sep 8, 2026
Runner verification — node 12 (PR #1011, QA verdict AC_MET_BUT_NOT_A_PLUS, iteration 1)
All nine verify commands from
issues/12-862P0-opencode-driver-core.mdwere executed verbatim in the worktree atc7b30367(tree identical to the QA'de60c7164, rebased onto post-#935main); the results table and the three gate-test mutation records are in the PR body.Driver: opencodeper phase without spawning, registry 3 passed · AC-4 6 passed · AC-5 9 wrappers from 1 template site · AC-6 5 passed · AC-7 5 passed · AC-8 5 passed (asserts no/tmprule, per OQ-19) · AC-9 parity 11 passed.Run history: the first exec was killed by the launcher's 30-minute no-progress ceiling (05:02Z) and its worktree deleted; its 8 commits were pushed and the re-dispatch finished in ~25 minutes. The exec never opened a PR (0
gh pr createattempts in the transcript), so QA's only non-A+ finding was the missing mutation record; the runner opened PR #1011 with that record. The post-QA rebase ontomainwas reconciled with the pushed lineage via an-s oursmerge rather than a force-push.Merging on the owner's standing instruction once CI is green.
feat(#862): opencode agent driver — fixture-proven NDJSON parser, ski…
fix(#1059): send codex the $<skill> invocation and persist run.agent …
fix(#1059): keep the skill-prompt lookup settings-aware and non-throwing
feat(#497): sequant init --agent codex — .agents/skills symlink, .cod…