Skip to content

feat: add opencode agent driver — first backend that can inherit the full skill methodology #862

Closed

Description

@admarble

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 opencode

Research 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>

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 mcp key (type: local|remote, command as 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: check opencode binary + minimum version when run.agent: "opencode".

Design critique / known risks (adversarial pass)

  1. 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 /qa a protocol-level command; opencode makes it a polite request to call a skill tool. 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.
  2. Skill content is tuned on Claude Code tool names. 120 Grep, 41 Glob, 29 subagent_type, literal Agent(...) call syntax, 11 AskUserQuestion. opencode's tools are lowercase and its Task syntax differs. Models adapt to prose, but the Agent(subagent_type="sequant-implementer", ...) blocks in exec/qa are 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 _shared references where it measurably matters.
  3. Hook shim gaps. (a) The bash hooks assume Claude Code's stdin JSON schema (tool_name, tool_input shapes) — 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) --pure or a user's global plugins can disable/reorder our plugin; doctor should verify the plugin is active.
  4. No terminal result event. The NDJSON stream just ends on session.idle — no cost/usage/duration record like the SDK's result message. Phase duration comes from the driver's own clock; token accounting needs opencode stats or the server API, or is simply absent at first (acceptable — Aider reports none either).
  5. Platform velocity/churn risk. opencode moved orgs (sst → anomalyco), ships 800+ releases, and several load-bearing features we'd depend on (--command on run, 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 trivial opencode run --format json against the pinned version so upstream breakage is caught by us, not by users mid-phase.
  6. Exit-code caveat when attaching. --attach mode swallows session errors from the exit code. Don't use serve/--attach in v1 — spawn per phase (cold start is tolerable; warm-start is a later optimization).
  7. Known drift trap in our own code: the ready-gate path (ready-gate.ts:buildPhaseConfig) never plumbs agent/aiderSettings and today silently runs the claude-code driver regardless of run.agent — tracked separately. That bug must be fixed before or with this work, or --ready-gate on an opencode run silently switches backends mid-run.

Real-world walk-through (sequant run 123 --agent opencode)

  1. Config resolution: run.agent: "opencode" → getDriver("opencode"); doctor has verified binary + min version + plugin presence.
  2. Worktree created; .claude/settings.local.json copy 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).
  3. Skills preflight passes — .claude/skills/ is present and is what opencode itself reads (preflight semantics carry over unchanged).
  4. 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.
  5. QA phase: skill emits the ### Verdict: format; existing parseQaVerdict consumes concatenated text events; skill-marker check confirms the skill actually ran.
  6. 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 as error_during_execution equivalent); rate limits (opencode error events differ from SDK rate_limit_event — classify what we can, degrade to generic failure otherwise, do NOT reuse Claude-specific retry ladders blindly).

Scope (graph plan 2026-09)

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 is src/lib/workflow/drivers/__fixtures__/opencode-run-qa.ndjson from spike(opencode): does opencode run --command <phase> load the sequant skill? (#862 P0 precondition, resolves OQ-8/OQ-9) #992 (node 06); asserts concatenated text → output, error events → structured failure, success only when the skill marker is present (AC-4), abort → SIGTERM on a detached process group, config.env forwarded, RingBuffer tails populated.
  • AC-2: live SKIP-when-absent test — Verify: same command with opencode.live.integration.test.ts: when which opencode succeeds and a provider key is present, spawns opencode run --format json --auto --dir <tmp> with a trivial prompt and asserts ≥1 text event; otherwise reports SKIPPED (opencode absent), never a pass.
  • AC-3: registry + settings + CLI — Verify: node dist/bin/cli.js run 1 --agent opencode --dry-run (after npm run build) prints the opencode driver in its plan without spawning; npx vitest run src/lib/workflow/drivers/index.test.ts -t "862" asserts getDriver("opencode").
  • AC-4: skill-marker verification — Verify: -t "862 AC-4": a fixture stream with no skill marker yields a distinct PhaseResult.error (skill-not-loaded), not a parsed verdict.
  • AC-5: command wrappers from one source — Verify: sequant init --agent opencode in a temp dir writes .opencode/commands/<phase>.md for 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), and diff <(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" → with run.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 passes OPENCODE_CONFIG_CONTENT carrying the reasoning budget, the /tmp/$TMPDIR allow rule (or scratch relocation) from spike(opencode): does opencode run --command <phase> load the sequant skill? (#862 P0 precondition, resolves OQ-8/OQ-9) #992 (node 06)'s table, and detached: true.
  • AC-9: I-1 — Verify: npx vitest run src/lib/workflow/execution-config-parity.test.ts → passes with the new opencodeSettings field 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

  • OpencodeDriver in src/lib/workflow/drivers/opencode.ts implementing AgentDriver with resolvesSkills: true: spawns opencode run --command <phase> <issue> --format json --auto --dir <cwd>, parses NDJSON into AgentPhaseResult, wires abort → SIGTERM, RingBuffer tails, forwards config.env
  • Registry entry + run.opencode settings schema (model, variant, extraArgs) + --agent opencode verified end to end from bin/cli.ts
  • Phase command wrappers: sequant init --agent opencode generates .opencode/commands/<phase>.md for 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) #674 ResumeHandle contract (driver-tagged, originCwd-bound)
  • doctor validates opencode binary + minimum pinned version when configured
  • Ready-gate buildPhaseConfig plumbs agent/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/qa fan-out verified working (or driver-conditional sequential fallback documented)
  • MCP config translation for sequant serve in opencode's mcp format
  • Error classification for opencode NDJSON error events (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/reference driver page

Non-goals

  • Aider parity work (explicitly rejected — see investigation doc)
  • serve/--attach warm-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

Activity

  1. added
    enhancement
    on Jul 29, 2026
  2. admarble commented on Jul 29, 2026

    @admarble
    ContributorAuthor

    #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
    ────────────────────────────────────────────────────────────────

  3. added
    backlog
    on Jul 29, 2026
  4. admarble commented on Jul 29, 2026

    @admarble
    ContributorAuthor

    #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
    ────────────────────────────────────────────────────────────────

  5. admarble commented on Sep 6, 2026

    @admarble
    ContributorAuthor

    Field evidence (2026-09-03 → 09-06, internal experiment on a separate non-sequant task): drove openrouter/z-ai/glm-5.3-flash and anthropic/claude-sonnet-5 through 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:

    1. Per-step completion clamp ≈32K, not raisable via limit.output. Two consecutive runs died at exactly 32,000 completion tokens (step_finish reason=length) with limit.output: 131072 confirmed loaded from opencode.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-model options.reasoning.max_tokens: 20000 via provider config, leaving ~12K/step for output. Implications: run.opencode needs 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 the LOOP_NO_DIFF signal feat(run): model escalation ladder on capability-bound non-convergence #971 keys on, so the ladder trigger already covers this class.
    2. Non-interactive permission gate terminates the run on writes outside the workspace. A Sonnet run (verification logs to /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 /tmp in 18 places (loop reads /tmp/claude-issue-<N>.log; assess and post-tool.sh use ${TMPDIR:-/tmp}). D1's --auto needs explicit allow rules for those paths, or skill scratch moves under the worktree — otherwise phases die mid-run with a misleading exit.
    3. Interrupt propagation. Ctrl+C in the orchestrating session took the backgrounded opencode run down with it. Same process-group class as Nested phase claude that hangs after its turn is killed at ~106s, taking down the parent sequant run #856/fix(containment): a phase agent killed its own orchestrator — no Bash signal guard, no process-group isolation, machine re-prompts read as human consent #934 — nothing new, but the subprocess driver needs 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.

  6. added
    graph-2026-09
    on Sep 7, 2026
  7. admarble commented on Sep 7, 2026

    @admarble
    ContributorAuthor

    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.

  8. admarble commented on Sep 7, 2026

    @admarble
    ContributorAuthor

    Spike verdict: GO — #992 concluded

    opencode run --command qa <issue> --format json --auto --dir <worktree> does
    load .claude/skills/qa/SKILL.md and act on its deep content. Risk 1 is refuted
    as 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, model openrouter/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)

    # Signal Result
    (i) grep -cE 'SEQUANT_QA_VERDICT|### Verdict' on the fixture 5
    (ii) tool_use event, part.tool == "skill", input {"name":"qa"} 1
    (iii) Canary planted at char 150,308 of qa/SKILL.md, absent from the wrapper 5

    The 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_MISMATCH guard.

    Which P0 ACs change

    1. AC-4's skill-not-loaded → skill-truncated. The skill tool delivered
      51,145 of 174,981 chars in-band and set metadata.truncated: true, pointing
      at an outputPath. The run only worked because the model noticed and issued
      five follow-up read calls to page through the rest. A weaker model that
      accepts 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 presence
      of the skill tool call.
      Every sequant skill trips this (~43K tokens each).
    2. Add a reasoning-budget field to run.opencode. Per-model
      options.reasoning.max_tokens (+ limit.context / limit.output) is the
      32K-clamp mitigation and must be expressible in sequant config.
    3. Config is a merge layer, not a contract. OPENCODE_CONFIG_CONTENT and
      OPENCODE_CONFIG both merge with the user's global
      ~/.config/opencode/opencode.jsonc; --pure disables plugins, not config.
      Only an XDG_CONFIG_HOME redirect is hermetic. Write the AC as "these keys are
      set", never "only these keys are set".
    4. Deny rules are P0, not hardening. --auto auto-approves everything not
      explicitly denied, and the qa skill's tail posts comments and edits labels.
      permission.bash deny rules are the only layer that works —
      permission.external_directory does not govern the --dir tree (a blanket
      "*":"deny" still permitted a read inside the run root).
    5. Drop the "keep the worktree out of /tmp" requirement unless separately
      re-justified. Two control runs showed /tmp is not blocked on 1.18.27, with
      or without allow rules. The prior field observation is real but its cause is
      unidentified — it is not opencode's permission system.
    6. Spawn contract confirmed: own process group (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.
    7. Parser must be fixture-driven. Single lines reach 100,151 bytes (shell
      read splits them and reports phantom parse failures — a proper parse gives
      93/93 valid). Tool name is part.tool, not .name. step_finish.part.cost is
      per step — sum it.
    8. No work needed: skills resolve correctly inside a git worktree (.git as a
      file). 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).

  9. admarble commented on Sep 7, 2026

    @admarble
    ContributorAuthor

    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.state.metadata  →  {name, dir, truncated: true, outputPath}   ← tool metadata
    part.metadata        →  {"openrouter": {reasoning_details: […]}}   ← provider metadata
    

    part.metadata.truncated resolves to undefined, and because undefined is
    falsy, a skill-truncated guard written against it would never fire — the
    exact silent-failure class the spike exists to prevent. Verify against the
    committed fixture:

    jq -r 'select(.part.tool=="skill")|.part.state.metadata.truncated' \
      src/lib/workflow/drivers/__fixtures__/opencode-run-qa.ndjson   # → true
    

    2. I claimed the permission.bash deny 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, or git commit was ever attempted.
    The model found gh auth status → "not logged into any GitHub hosts" and
    $GH_TOKEN empty, and treated GitHub as read-only from then on. It stopped for
    lack of credentials, not because the permission layer denied it.

    Worse, a follow-up check found permission.webfetch: "deny" was set on that run
    and the model still made 6 successful curl calls to api.github.com through
    bash. Revised sandboxing picture on 1.18.27:

    Control Status
    permission.external_directory Refuted — does not govern the --dir tree
    permission.webfetch: "deny" Refuted — does not stop curl from bash
    permission.bash deny rules Untested — never exercised

    So 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-gh
    control 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 kill was actually reproduced. The ~32K figure is not measured
    here
    .

    Cost-accounting corollary: the hung control consumed 420 s of real tokens but
    sums to $0.00 under the step_finish method, because no step_finish was
    emitted. A driver budgeting purely from step_finish.cost under-reports exactly
    the 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.

  10. admarble commented on Sep 8, 2026

    @admarble
    ContributorAuthor

    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) and docs/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 background npm test); prefer the node file's targeted -t commands 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 at src/lib/workflow/drivers/__fixtures__/ and its findings in docs/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 /tmp allow-rule clause is non-load-bearing — the spike refuted the /tmp permission 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 via OPENCODE_CONFIG_CONTENT and detached: true, and have the AC-8 test assert that no /tmp rule 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 only XDG_CONFIG_HOME isolation is hermetic (a global opencode.jsonc contaminates runs) — the driver's spawn must set XDG_CONFIG_HOME to 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.

  11. admarble commented on Sep 8, 2026

    @admarble
    ContributorAuthor

    Complexity: Complex (9 ACs, 6 directories)

    AC Quality Check

    lintAcceptanceCriteria on the 9 graph-plan ACs: 1/9 flagged.

    • ⚠️ AC-2 — "Incomplete: verification not named — method integration_test was inferred from keywords, not declared." Every other AC carries a runnable Verify: command; AC-2's is prose-embedded (same command with opencode.live.integration.test.ts). Recommend reading it as Evidence: npx vitest run src/lib/workflow/drivers/opencode.live.integration.test.ts -t "862" and asserting the SKIP path, not just the spawn path.
    • ✅ AC-1, AC-3, AC-4, AC-5, AC-6, AC-7, AC-8, AC-9: clear and testable.

    Rule-touchpoint detector: fired on AC-2 only (never + skip); all touchpoints resolve to src/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):

    1. AC-4 — the spike refuted Risk 1 and replaced it with truncation. The marker must be structural (tool_use where part.tool === "skill"), and it must not assume the whole skill body reached the model. ⚠️ Read part.state.metadata.truncated — part.metadata is provider metadata and resolves to undefined, which is falsy, so a guard written there never fires.
    2. AC-8 — the /tmp allow-rule clause is non-load-bearing (OQ-19). Satisfy it with the reasoning budget via OPENCODE_CONFIG_CONTENT + detached: true, and have the test assert that no /tmp rule is injected, citing the spike doc.
    3. Hermeticity — only an XDG_CONFIG_HOME redirect isolates from the user's global opencode.jsonc; OPENCODE_CONFIG_CONTENT and OPENCODE_CONFIG both leak (spike Finding 1).

    Scope Assessment

    Non-Goals: ✅ 4 declared (aider parity, serve/--attach, forking the skill tree, Codex #497).

    Metric Value Status
    Feature count 4 ❌
    AC items 9 ❌
    Directory spread 6 ❌

    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 the Verify: 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 7 text parts concatenate to output ending in ### Verdict: READY_FOR_MERGE, error events map to structured failure, success requires the AC-4 marker, abort sends SIGTERM to the process group, config.env is forwarded, and both RingBuffer tails populate.
    Assumptions: The fixture contains only step_start/step_finish/text/tool_use — there is no recorded error event, 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.ts
    Scenario: Given no opencode binary or no provider key → When the suite runs → Then it reports SKIPPED (opencode absent), never a pass. Given both present → spawns a trivial prompt and asserts ≥1 text event.
    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)
    Scenario: Given npm run build → When node 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: ⚠️ The dry-run path prints no driver name today — phase-executor.ts:1141 returns before getDriver and 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 skill tool call for the phase → Then a distinct PhaseResult.error (skill-not-loaded), not a parsed verdict.
    Assumptions: Marker = tool_use with part.tool === "skill" and part.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 opencode in a temp dir
    Scenario: Given a temp project → When init runs → Then .opencode/commands/<phase>.md exists for all 9 registered phases, rendered from one template.
    Assumptions: ⚠️ sequant init has no --agent flag today — it needs a .option() in bin/cli.ts plus InitOptions (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} → When canResume is asked from a different cwd or with a foreign driver tag → Then false; same cwd → true and the spawn gains --session <token>.
    Assumptions: sessionID is 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 floor 1.18.27 and fails with an install hint when absent. Mirrors the existing aider block at doctor.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 → Then OPENCODE_CONFIG_CONTENT carries the per-model reasoning budget, XDG_CONFIG_HOME points at a per-run dir, detached: true is set, and no /tmp permission 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 when run.opencode.model is set — assert that conditionality, not an unconditional payload.

    AC-9: I-1 producer parity

    Verification: Unit Test — execution-config-parity.test.ts
    Scenario: Given opencodeSettings added to ExecutionConfig → When the resolver and buildPhaseConfig are compared over the key union → Then equal (the gate spreads opts.config post-#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 -t filters above over the ~6-min full suite.

    Phase 1 — Seams first (AC-3, AC-9)

    1. settings.ts: OpencodeSettings { model?, variant?, extraArgs?, reasoningMaxTokens? } + OpencodeSettingsSchema + run.opencode. Sibling sites in this one file — all five must move together (this is the run.aider pattern): interface (:117), Zod schema (:417), KNOWN_KEYS.run (:641), a new KNOWN_KEYS["run.opencode"], validateAiderSettings's twin, and the two generated doc tables (:1223 agent values, :1233).
    2. types.ts: ExecutionConfig.opencodeSettings; config-resolver.ts:516: one pass-through line. Run AC-9's parity test — it should pass immediately.
    3. drivers/index.ts: registry line + DriverOptions.opencodeSettings. phase-executor.ts:1302 passes it. skills-preflight.ts and run-orchestrator.ts need no change — they call getDriver only to read resolvesSkills, which is a static true.
    4. Dry-run driver line: in the config.dryRun branch (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)

    1. opencode.ts skeleton with a chunk-safe NDJSON reader: accumulate stdout chunks 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).
    2. Extract: type:"text" → part.text concatenation; type:"step_finish" → sum part.cost (per-step, not cumulative); tool_use → part.tool (not .name); envelope sessionID → resume token.
    3. AC-4 marker + truncation guard, reading part.state.metadata.{name,truncated}. Add a mutation-verified negative fixture (a stream with the skill event stripped).

    Phase 3 — Spawn contract, resume, doctor (AC-6, AC-7, AC-8, AC-2)

    1. buildArgs: run --command <phase> <prompt> --format json --auto --dir <cwd> + --model / --variant / --session / extraArgs. AgentExecutionConfig needs a phase field — 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's PROMPT_CONTEXT block) rides in as $ARGUMENTS, so no prompt content is lost.
    2. Spawn detached: true; kill with process.kill(-pid, "SIGTERM") and swallow ESRCH; per-run XDG_CONFIG_HOME (never XDG_DATA_HOME — auth and tool-output live there).
    3. canResume: driver-tag equality + byte-equal originCwd. Convert the it.skip slot pattern used for feat: add OpenAI Codex CLI agent driver #497.
    4. Doctor block mirroring doctor.ts:426, with the 1.18.27 floor.
    5. Live integration test with the SKIP path asserted first.

    Phase 4 — Init wrappers (AC-5)

    1. templates/opencode/command.md (one phase-parameterized source; copyTemplates copies only named subdirs, so it will not leak into every project) + a writer in init.ts looping getPhaseNames(). Keep the literal .opencode/commands string in exactly one file so AC-5's grep -rl … | wc -l → 1.
    2. bin/cli.ts: init --agent <name> option + InitOptions.agent.

    Design Review

    1. Where does this logic belong? Entirely behind the AgentDriver seam. The one leak outside it is AgentExecutionConfig.phase — an additive, optional field the claude-code and aider drivers ignore.
    2. Simplest correct approach? Subprocess + NDJSON parse, mirroring AiderDriver's spawn/RingBuffer/abort shape, with claude-code's resumeHandle/structuredError shape for the result. Rejected: an inline driverOverrides.opencode prompt template that skips wrappers entirely — cheaper, but the wrapper path is the one the spike actually proved, and AC-5 mandates it.
    3. Existing pattern? AiderDriver for process lifecycle; ClaudeCodeDriver.buildResumeHandle for 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.
    4. What would a senior reviewer challenge? (a) "You made truncation non-fatal — isn't that the exact silent-degradation this issue exists to prevent?" See OQ-1: fatal-on-truncation fails every sequant skill (43K tokens vs a 51 KB in-band cap), so the discriminating signal has to be the follow-up reads, not the flag alone. (b) "Why is --auto acceptable?" It is not, on its own — see OQ-4.

    Feature Quality Planning

    Derived ACs

    Source Derived AC Priority
    Unobserved error shape AC-1a: exit≠0 with no terminal step_finish reason:"stop" yields a failure, not a success High
    Chunk-safety AC-1b: parser fed the fixture in 8 KB chunks yields byte-identical output to a single-shot feed High
    Settings surface AC-3a: run.opencode produces no unknown-key warning (KNOWN_KEYS + nested set) Medium

    Open Questions

    1. Is truncated: true fatal? — 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 on skill-not-loaded (no skill tool call for the phase); emit skill-partially-loaded as a warning, escalating to a failure only when truncated: true and no subsequent read tool call targets the skill's dir/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.
    2. Scope: three files outside the node's "may touch" list. — 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.
    3. XDG_CONFIG_HOME redirect discards the user's own opencode.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; leave extraArgs as the escape hatch and document the exclusion. Auth is unaffected (it lives under XDG_DATA_HOME). Impact if wrong: a user's configured provider stops resolving under sequant but works standalone.
    4. --auto posture. The spike refuted permission.external_directory (does not govern the --dir tree) and permission.webfetch: "deny" (6 successful curls to api.github.com from bash), and the permission.bash deny list was never exercised — gh was 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 --auto phase with authenticated gh mutates live issues.
    5. AC-5's grep -rl … | wc -l is layout-brittle. Recommendation: pin the layout in Phase 4.13 (templates/opencode/command.md holds no opencode/commands literal; init.ts holds it once) so the count is 1 by construction rather than by luck.
    6. Follow-up, not this PR: per-driver settings are threaded by name (aiderSettings, now opencodeSettings) across DriverOptions/ExecutionConfig/config-resolver/phase-executor. A third driver is the point where a generic driverSettings bag 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 /assess also landed on -Q. testgen deliberately skipped despite the Unit/Integration verification methods: all 9 ACs already prescribe exact test file paths and -t filters, 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 -Q


    Label Review

    Current: enhancement, backlog, graph-2026-09
    Recommended: drop backlog
    Reason: 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 /assess reading a stale PARK signal.
    Quality Loop: auto-enables from SCOPE_SPLIT_RECOMMENDED regardless of flags.

    → gh issue edit 862 --remove-label backlog

  12. added
    planned
    on Sep 8, 2026
  13. admarble commented on Sep 8, 2026

    @admarble
    ContributorAuthor

    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.

  14. 2 remaining items

  15. added 9 commits that reference this issue on Sep 8, 2026
  16. admarble commented on Sep 8, 2026

    @admarble
    ContributorAuthor

    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.md were executed verbatim in the worktree at c7b30367 (tree identical to the QA'd e60c7164, rebased onto post-#935 main); the results table and the three gate-test mutation records are in the PR body.

    • AC-1 29 passed · AC-2 skip contract exercised (1 passed, 2 skipped; real opencode 1.18.27 present here) · AC-3 dry-run prints Driver: opencode per 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 /tmp rule, 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 create attempts 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 onto main was reconciled with the pushed lineage via an -s ours merge rather than a force-push.

    Merging on the owner's standing instruction once CI is green.

  17. added a commit that references this issue on Sep 8, 2026
  18. added 3 commits that reference this issue on Sep 16, 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

    backlogenhancementgraph-2026-09planned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions