From 9d06036a416351be5fe2901190e4537e03b4cef2 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 10:31:12 +0100 Subject: [PATCH 1/2] Replace Codex/Copilot support with an OpenCode adapter (plugin 2.4.0) Removes the 2.3.0 host-specific code (openai.yaml, guard deny mode, Copilot context key, their checks and CI installs); core/bin is identical to 2.2.1. Adds adapters/opencode/index.ts, a thin OpenCode plugin over core/: it runs dev-brain-context for the main session only, runs dev-brain-guard through the permission hook (ask), registers core/skills with workflows hidden, and builds the reviewer from core/agents/reviewer.md with read-only permissions plus explicit denies for redirections, which OpenCode's shell matcher ignores. Offline check: 20 checks (11 Claude Code, 9 OpenCode 2.3.2); six adapter mutations each fail the intended check. TUI and OpenCode 2.4.0 are NOT RUN. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Sm3JtGSXFLR6CZYVJXGHtU --- .dev-brain/STATE.md | 11 +- .github/workflows/offline-check.yml | 21 +-- AGENTS.md | 14 +- MANUALE.md | 68 ++++---- README.md | 50 +++--- adapters/opencode/index.ts | 121 ++++++++++++++ core/.claude-plugin/plugin.json | 2 +- core/bin/dev-brain-context | 13 +- core/bin/dev-brain-guard | 14 +- core/skills/handoff/agents/openai.yaml | 2 - core/skills/impact/agents/openai.yaml | 2 - core/skills/learn/agents/openai.yaml | 2 - core/skills/resume/agents/openai.yaml | 2 - core/skills/review/agents/openai.yaml | 2 - core/skills/start/agents/openai.yaml | 2 - evals/offline/check.py | 220 +++++++++++-------------- evals/offline/mock_model.py | 36 ++-- evals/results.md | 20 ++- 18 files changed, 352 insertions(+), 250 deletions(-) create mode 100644 adapters/opencode/index.ts delete mode 100644 core/skills/handoff/agents/openai.yaml delete mode 100644 core/skills/impact/agents/openai.yaml delete mode 100644 core/skills/learn/agents/openai.yaml delete mode 100644 core/skills/resume/agents/openai.yaml delete mode 100644 core/skills/review/agents/openai.yaml delete mode 100644 core/skills/start/agents/openai.yaml diff --git a/.dev-brain/STATE.md b/.dev-brain/STATE.md index 4b3c190..8a5fcb0 100644 --- a/.dev-brain/STATE.md +++ b/.dev-brain/STATE.md @@ -1,26 +1,25 @@ # State — agents-platform -Updated: 2026-11-20 +Updated: 2026-11-23 ## Goal -Plugin (Claude Code; Codex CLI and Copilot read it too) for readable, maintainable code at the lowest context cost — acceptance: installs from GitHub with two commands, every claim backed by `evals/` evidence, measured benefit on real tasks. +Plugin (Claude Code, plus an OpenCode adapter) for readable, maintainable code at the lowest context cost — acceptance: installs from GitHub with two commands, every claim backed by `evals/` evidence, measured benefit on real tasks. ## Done (latest first, max 5) -- Plugin 2.3.0 merged (PR #7): Codex 0.171.0 and Copilot CLI 1.0.114 support (six `agents/openai.yaml`, guard denies on Codex, Copilot context key) — evidence: `python3 evals/offline/check.py` ALL PASS (24 checks, local), six mutations each FAIL the intended check; PR #7 CI success, manual run of both jobs success (newest: Claude Code 2.1.329, Codex 0.171.0, Copilot CLI 1.0.114); install from GitHub run as written on Codex and Copilot +- Plugin 2.4.0 on branch `feat/opencode-adapter`, PR open and not merged: Codex and Copilot support removed (user decision), OpenCode adapter `adapters/opencode/index.ts` added — evidence: `python3 evals/offline/check.py` ALL PASS (20 checks: 11 Claude Code 2.1.325, 9 OpenCode 2.3.2), six adapter mutations each FAIL the intended check - Plugin 2.2.1 merged (PR #6): `handoff` stops writing branch/HEAD/commit status, CI pin 2.1.325 plus a newest-release job — evidence: CI success on both jobs; weekly schedule NOT RUN until it first fires - Offline check on GitHub Actions for every PR — evidence: PR #5 run `offline-check` success, ALL PASS on a clean runner - Plugin 2.2.0 merged (PR #4): minimal `start`, review passes the Goal line, reviewer checks weakened tests — evidence: `python3 evals/offline/check.py` ALL PASS on a clean clone of main (0d01d2b) -- No commit without the user, enforced: `PreToolUse` git guard (2.1.0) — evidence: `python3 evals/offline/check.py` ALL PASS; mutation without the hook FAILs ## In progress / blockers - Benefit of the rules on real code — status: NOT RUN; `claude plugin eval` (with/without plugin) would measure it but needs the user's credentials and tokens - Minimal `start` with a real model — status: partly seen on Presidio (deny rules and Stop hook adopted, `AGENTS.md` kept, not trimmed); its deletion-candidate list not seen - Opus 5.5 system card read only through secondary reports (PDF unreachable here) -- VS Code Copilot, interactive Copilot prompts and the Codex `/hooks` trust screen — status: NOT RUN (cannot be driven here) +- OpenCode TUI (the interactive ask prompt, `@start`) and OpenCode 2.4.0 — status: NOT RUN (the TUI cannot be driven here; the 2.4.0 package would not download) ## Known pre-existing failures - none ## Next (max 3) -1. User: try 2.3.0 in VS Code Copilot (do the rules arrive? do the workflows list?) and in Codex (`/hooks` trust), then `claude plugin marketplace update dev-brain`; review hph PR #10; delete remote branch `improve/state-and-ci-2-2-1` (the proxy blocks it here). +1. User: review the PR; after merging, add `adapters/opencode` to `plugins` in `opencode.json`, run `opencode debug agents` (must list `reviewer`), then try `@start` and a commit in the TUI. 2. User decision: draft a `claude plugin eval` suite (authorization, weakened tests, `start` size) and run it with `--max-cost-usd`. 3. Collect Presidio feedback: `/context all` from a fresh session, the `start` candidate list; change only what repeats twice. diff --git a/.github/workflows/offline-check.yml b/.github/workflows/offline-check.yml index b0815d9..20fbd94 100644 --- a/.github/workflows/offline-check.yml +++ b/.github/workflows/offline-check.yml @@ -1,7 +1,7 @@ name: offline-check -# Runs evals/offline/check.py: the real Claude Code, Codex CLI and Copilot CLI -# binaries against a local mock model. No secrets, no tokens, no network beyond the +# Runs evals/offline/check.py: the real Claude Code and OpenCode binaries +# against a local mock model. No secrets, no tokens, no network beyond the # package registry. Pull requests test the pinned versions. Pushes to main, the # weekly schedule and manual runs also test the newest releases, to see a change early. on: @@ -21,7 +21,7 @@ concurrency: jobs: pinned: - name: Pinned versions (Claude Code 2.1.325, Codex 0.171.0, Copilot CLI 1.0.114) + name: Pinned versions (Claude Code 2.1.325, OpenCode 2.3.2) runs-on: ubuntu-latest timeout-minutes: 10 steps: @@ -34,12 +34,11 @@ jobs: # The versions the check was last tested against. Bump them deliberately, # together with the "provato su" line in MANUALE.md. - name: Install the agents - run: npm install --global @anthropic-ai/claude-code@2.1.325 @openai/codex@0.171.0 @github/copilot@1.0.114 - # CODEX and COPILOT make those checks required: a missing binary fails the job. + run: npm install --global @anthropic-ai/claude-code@2.1.325 @opencode/cli@2.3.2 + # OPENCODE makes that check required: a missing binary fails the job. - name: Offline check env: - CODEX: codex - COPILOT: copilot + OPENCODE: opencode run: python3 evals/offline/check.py latest: @@ -55,14 +54,12 @@ jobs: with: node-version: 22 - name: Install the newest agents - run: npm install --global @anthropic-ai/claude-code@latest @openai/codex@latest @github/copilot@latest + run: npm install --global @anthropic-ai/claude-code@latest @opencode/cli@latest - name: Show the versions under test run: | claude --version - codex --version - copilot --version + opencode --version - name: Offline check env: - CODEX: codex - COPILOT: copilot + OPENCODE: opencode run: python3 evals/offline/check.py diff --git a/AGENTS.md b/AGENTS.md index 91cdb1a..13a9237 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # Maintaining dev-brain -This repository is a plugin marketplace with one plugin, `dev-brain`, in `core/`, built for Claude Code. Codex CLI and Copilot read the same marketplace and plugin unchanged; the few host differences are listed below. It is not an application. +This repository is a plugin marketplace with one plugin, `dev-brain`, in `core/`, built for Claude Code, with an adapter for OpenCode in `adapters/opencode/`. It is not an application. Its primary goal is readable, maintainable code across languages and frameworks. Workflows and saved state support that goal. ## What belongs where @@ -8,11 +8,11 @@ Its primary goal is readable, maintainable code across languages and frameworks. - `core/AGENTS.md` — the global rules, injected into every session by the `SessionStart` hook. Keep it short: only instructions that change default behavior. - `core/skills/` — Agent Skills. User-invoked workflows (`start`, `resume`, `handoff`, `impact`, `learn`, `review`) set `disable-model-invocation: true`, so they cost no context until invoked; `debugging`, `engineering-risk`, `review-feedback` are loaded by the model when relevant. - `core/agents/reviewer.md` — the read-only reviewer; its `tools` line is the enforcement. -- `core/hooks/hooks.json` + `core/bin/dev-brain-context` — inject rules and the project state (3000-character budget). Copilot CLI also needs a top-level `additionalContext`, which Codex rejects, so the script adds it only when `COPILOT_PLUGIN_ROOT` is set. -- `core/bin/dev-brain-guard` — `PreToolUse` hook that answers "ask" for git commands changing history, branches or the remote; keep its list in sync with the Authorization rules in `core/AGENTS.md`. Codex cannot ask (an "ask" fails the hook and the command runs), so there it answers "deny". -- `core/skills//agents/openai.yaml` — Codex ignores `disable-model-invocation`; this file (`allow_implicit_invocation: false`) keeps the six workflows out of its skill listing. Add one to every new workflow skill. +- `core/hooks/hooks.json` + `core/bin/dev-brain-context` — inject rules and the project state (3000-character budget). +- `core/bin/dev-brain-guard` — `PreToolUse` hook that answers "ask" for git commands changing history, branches or the remote; keep its list in sync with the Authorization rules in `core/AGENTS.md`. +- `adapters/opencode/index.ts` — OpenCode has no plugin marketplace, so this one file runs `dev-brain-context` and `dev-brain-guard`, registers `core/skills` and builds the reviewer from `core/agents/reviewer.md`. It holds no rule of its own: change the rule in `core/`, not here. Its one extra line of policy is the reviewer's denial of redirections, which OpenCode's shell matcher does not parse. - `core/.claude-plugin/plugin.json` — bump `version` on every change so installed copies refresh. `.claude-plugin/marketplace.json` at the root lists the plugin. -- `evals/` — scenarios, measured results, and `offline/check.py` with `offline/mock_model.py`, a zero-token check against the real Claude Code, Codex CLI and Copilot CLI binaries. VS Code cannot run here, so it is untested. +- `evals/` — scenarios, measured results, and `offline/check.py` with `offline/mock_model.py`, a zero-token check against the real Claude Code and OpenCode binaries. The OpenCode TUI cannot run here, so it is untested. ## Changing the harness @@ -27,7 +27,7 @@ Never add rules by intuition alone. A rule that the model already follows is pur ## Constraints - All kit content is English. Exception: `MANUALE.md` is the Italian user manual. -- Runtime dependencies: Claude Code, `python3`, `git`. -- Skills and rules stay in standard formats (`AGENTS.md`, `SKILL.md`) with no absolute paths, so another agent is supported with an adapter instead of a rewrite. Host-specific code stays limited to the items above. +- Runtime dependencies: Claude Code or OpenCode, `python3`, `git`. +- Skills and rules stay in standard formats (`AGENTS.md`, `SKILL.md`) with no absolute paths, so another agent is supported with an adapter instead of a rewrite. Host-specific code stays limited to `adapters/`. - Do not duplicate a rule or template across files: `core/` holds each once. - Do not copy project facts (stack, commands, state) from a destination repository into this source repository. diff --git a/MANUALE.md b/MANUALE.md index 6b97fbf..8f5772c 100644 --- a/MANUALE.md +++ b/MANUALE.md @@ -1,6 +1,6 @@ # dev-brain — Manuale d'uso -> Manuale utente in italiano; il resto del kit è in inglese. Versione 2026-11-20, plugin 2.3.0, provato su Claude Code 2.1.325, Codex CLI 0.171.0 e Copilot CLI 1.0.114. Indipendente dal provider del modello. +> Manuale utente in italiano; il resto del kit è in inglese. Versione 2026-11-23, plugin 2.4.0, provato su Claude Code 2.1.325 e OpenCode 2.3.2. Indipendente dal provider del modello. ## Avvio rapido @@ -21,7 +21,7 @@ Da lì: `resume` a inizio sessione → lavoro → `review` → `handoff` a fine ## 1. Cos'è -Un plugin per Claude Code, installabile anche in Codex CLI e GitHub Copilot (sezione 12). Fa tre cose: +Un plugin per Claude Code, con un adattatore per OpenCode (sezione 12). Fa tre cose: 1. **Regole globali** in ogni sessione: soluzione più semplice e completa, idiomi del progetto, una sola fonte per ogni regola di business, errori mai nascosti, niente commit senza la tua decisione, controlli riportati come PASS / FAIL / NOT RUN. 2. **Continuità**: lo stato del progetto (`.dev-brain/STATE.md`) arriva in ogni sessione, anche dopo `/clear` e dopo la compattazione. @@ -33,7 +33,7 @@ Non decide quando committare, non sostituisce test né la tua revisione, e non g ## 2. Installazione -Prerequisiti: Claude Code (o Codex / Copilot, sezione 12), `python3`, `git`. +Prerequisiti: Claude Code (o OpenCode, sezione 12), `python3`, `git`. ```bash claude plugin marketplace add Stcant/agents-platform @@ -43,7 +43,7 @@ claude plugin install dev-brain@dev-brain - **Aggiornamento:** `claude plugin marketplace update dev-brain`. - **Sviluppo locale:** `claude plugin marketplace add /percorso/agents-platform`. Il plugin viene letto sul posto: le modifiche valgono dalla sessione successiva. - **Disinstallazione:** `claude plugin uninstall dev-brain@dev-brain`. I file nelle repository restano. -- **Codex e Copilot:** installazione, aggiornamento e rimozione sono nella sezione 12. +- **OpenCode:** installazione, aggiornamento e rimozione sono nella sezione 12. Il plugin non tocca `CLAUDE.md` né le tue impostazioni: regole e stato arrivano da un hook `SessionStart`. @@ -112,7 +112,7 @@ La regola globale vieta commit, push, cambi di branch e comandi git distruttivi Vale anche dentro comandi concatenati (`git add -A && git commit …`), con opzioni globali (`git -C dir commit`), e anche se nelle tue impostazioni hai permesso git: la richiesta arriva comunque. I comandi in sola lettura (`status`, `diff`, `log`, `show`, `stash`, `reset `) passano senza chiedere. -Se rispondi sì, il commit avviene: la decisione resta tua, ed è il punto. Su Codex non c'è la domanda: il comando viene rifiutato e lo esegui tu (sezione 12). +Se rispondi sì, il commit avviene: la decisione resta tua, ed è il punto. Su OpenCode la richiesta compare nel TUI (la richiesta interattiva non è stata provata) e `opencode run` rifiuta (sezione 12). --- @@ -120,7 +120,7 @@ Se rispondi sì, il commit avviene: la decisione resta tua, ed è il punto. Su C Subagente `dev-brain:reviewer`, in sola lettura **imposta**. Può usare Read, Grep, Glob e `git diff/log/show/status`; ogni comando che crea, modifica o cancella file chiede la tua approvazione. Rispondi no. -Su Codex non viene caricato, su Copilot non ha git (sezione 12). Riporta difetti di correttezza, sicurezza, integrità dei dati o requisiti, separati dai problemi concreti di manutenibilità. Per ogni finding: `file:line`, trigger o scenario, impatto, correzione minima, confidenza. Niente preferenze cosmetiche. Non esegue test o build: li riporta come `NOT RUN`. +Riporta difetti di correttezza, sicurezza, integrità dei dati o requisiti, separati dai problemi concreti di manutenibilità. Per ogni finding: `file:line`, trigger o scenario, impatto, correzione minima, confidenza. Niente preferenze cosmetiche. Non esegue test o build: li riporta come `NOT RUN`. --- @@ -189,11 +189,11 @@ Il **controllo offline** installa il plugin in una home temporanea e sostituisce - reviewer che legge il diff ma non scrive; - commit e push che chiedono conferma anche con git permesso nelle impostazioni. -Se trova `codex` o `copilot` nel PATH (o nelle variabili `CODEX` e `COPILOT`, che in quel caso li rendono obbligatori) ripete su ciascuno i controlli che hanno senso: regole e stato, workflow fuori dall'elenco, commit e push fermati, reviewer senza shell su Copilot. +Se trova `opencode` nel PATH (o nella variabile `OPENCODE`, che in quel caso lo rende obbligatorio) ripete su di esso gli stessi controlli attraverso l'adattatore, più uno: regole e stato non devono arrivare al subagente. -Non valuta la qualità delle risposte. Su GitHub Actions gira a ogni pull request sulle versioni fissate (Claude Code 2.1.325, Codex 0.171.0, Copilot CLI 1.0.114); a ogni push su `main`, ogni lunedì e su richiesta gira anche sulle ultime versioni, per accorgersi presto di un cambiamento. +Non valuta la qualità delle risposte. Su GitHub Actions gira a ogni pull request sulle versioni fissate (Claude Code 2.1.325, OpenCode 2.3.2); a ogni push su `main`, ogni lunedì e su richiesta gira anche sulle ultime versioni, per accorgersi presto di un cambiamento. -`core/AGENTS.md` e le skill restano in formati standard. Codex e Copilot si supportano con tre adattamenti (sezione 12); un nuovo workflow richiede anche il suo `agents/openai.yaml` (due righe, `allow_implicit_invocation: false`), altrimenti Codex lo elenca e ne paga il contesto. Un altro agente richiede un adattatore, non una riscrittura. +`core/AGENTS.md` e le skill restano in formati standard. OpenCode si supporta con un adattatore (`adapters/opencode/index.ts`, sezione 12) che non copia nessuna regola; un altro agente richiede un altro adattatore, non una riscrittura. --- @@ -207,10 +207,8 @@ Non valuta la qualità delle risposte. Su GitHub Actions gira a ogni pull reques | Il reviewer chiede di eseguire un comando che scrive | Rispondi no | | Claude Code chiede conferma per un `git commit` | È il guard di dev-brain: conferma solo se hai deciso tu di committare | | Ho dati sensibili nello stato | Rimuovili subito; non committare | -| Codex: regole e stato non arrivano, il commit non viene fermato | Gli hook non sono approvati: apri `/hooks` e approva quelli di dev-brain; `codex exec` non avvisa | -| Codex rifiuta un `git commit` | È voluto: Codex non può chiedere conferma, lo esegui tu | -| Codex: `review` dice che non c'è un reviewer | Atteso: Codex non carica gli agenti del plugin | -| Copilot: il reviewer non trova le modifiche | Non ha git: legge solo i file elencati; per un diff completo incollalo tu | +| OpenCode: regole e stato non arrivano | Controlla che `plugins` contenga il percorso assoluto di `adapters/opencode`, che `python3` sia installato e che `opencode debug agents` elenchi `reviewer` | +| OpenCode rifiuta un `git commit` in `opencode run` | È voluto: `run` non può chiedere conferma; esegui il commit tu o usa il TUI | --- @@ -220,30 +218,38 @@ Non valuta la qualità delle risposte. Su GitHub Actions gira a ogni pull reques - Il controllo offline verifica cosa il kit invia e permette, non le risposte. - Il reviewer chiede approvazione per le scritture: se approvi, scrive. - Le regole costano circa 1200 token per sessione; se rendano non è ancora dimostrato. -- Codex e Copilot sono provati solo con il modello finto e con i loro programmi a riga di comando; VS Code non è stato eseguito (sezione 12). +- OpenCode è provato solo con il modello finto e con `opencode run`; il TUI non è stato eseguito (sezione 12). --- -## 12. Codex e GitHub Copilot +## 12. OpenCode -Lo stesso marketplace e lo stesso plugin si installano senza modifiche. Provato con i programmi reali contro il modello finto, non con un modello vero. +OpenCode non ha un marketplace di plugin: un solo file, `adapters/opencode/index.ts`, lo collega allo stesso `core/`. Lancia gli script `dev-brain-context` e `dev-brain-guard` del plugin e costruisce il reviewer da `core/agents/reviewer.md`: nessuna regola è copiata. Provato con il programma reale contro il modello finto, non con un modello vero. -| | Codex CLI | Copilot CLI | -| --- | --- | --- | -| Installazione | `codex plugin marketplace add Stcant/agents-platform`, poi `codex plugin add dev-brain@dev-brain` | `copilot plugin marketplace add Stcant/agents-platform`, poi `copilot plugin install dev-brain@dev-brain` | -| Aggiornamento | `codex plugin marketplace upgrade dev-brain`; se aggiorni anche la copia installata NON è stato provato: se la versione non cambia, ripeti `codex plugin add dev-brain@dev-brain` | `copilot plugin marketplace update`, poi `copilot plugin update dev-brain` | -| Rimozione | `codex plugin remove dev-brain@dev-brain` | `copilot plugin uninstall dev-brain` | -| Regole e stato | Sì, ma solo dopo che approvi gli hook del plugin con `/hooks`: finché non lo fai regole, stato e guardia git sono spenti senza alcun avviso | Sì | -| Workflow | `$dev-brain:start`; non costano contesto (file `agents/openai.yaml` in ogni workflow) | Elencati da `copilot skill list`, non costano contesto; la chiamata in sessione interattiva non è stata provata | -| Commit, push, cambio di branch | **Rifiutati**: gli hook di Codex non sanno chiedere conferma, quindi il comando lo esegui tu | Chiede conferma (la richiesta interattiva non è stata provata; in `-p`, che non può chiedere, rifiuta) | -| Reviewer | Non viene caricato: `review` lo dice e si ferma | Caricato, in sola lettura ma senza shell: non può lanciare git e legge i file elencati | +**Installazione** + +```bash +git clone https://github.com/Stcant/agents-platform /percorso/agents-platform +``` -Versioni provate: Codex 0.171.0 e Copilot CLI 1.0.114 (Claude Code 2.1.325, in CI anche 2.1.329). La versione minima che funziona non è nota; le più vecchie NON sono state provate. Ho eseguito i comandi di installazione così come scritti, da GitHub: entrambi installano la 2.3.0. I nomi dei workflow in questo manuale sono quelli di Claude Code (`/dev-brain:`): su Codex scrivi `$dev-brain:`. +Poi in `~/.config/opencode/opencode.json` (o nell'`opencode.json` di un progetto), con percorso assoluto: -**VS Code (Copilot in modalità agente): NON PROVATO**, non si può eseguire qui. La documentazione dice che i plugin agente leggono il formato Claude: aggiungi `Stcant/agents-platform` dall'editor delle personalizzazioni (Configure Marketplaces) o con l'impostazione `chat.plugins.marketplaces`, poi installa `dev-brain`. Come VS Code carichi hook e agenti di un plugin non è documentato: verifica che le regole arrivino; se non arrivano, incolla `core/AGENTS.md` nelle istruzioni di Copilot. +```json +{ "plugins": ["/percorso/agents-platform/adapters/opencode"] } +``` + +- **Verifica:** `opencode debug agents` deve elencare `reviewer`. +- **Aggiornamento:** `git -C /percorso/agents-platform pull`. +- **Rimozione:** togli la voce da `plugins`. + +| | Claude Code | OpenCode | +| --- | --- | --- | +| Regole e stato | ogni sessione | solo sessione principale, non i subagenti | +| Workflow | `/dev-brain:start` | `@start` nel prompt, oppure chiedi di caricare la skill `start` (la skill si carica per id: provato; la forma `@` segue la documentazione di OpenCode e NON è provata, serve il TUI) | +| Costo di contesto dei workflow | nullo | nullo: non compaiono nell'elenco delle skill | +| Commit, push, cambio di branch | chiede conferma | chiede conferma (la richiesta interattiva NON è stata provata); `opencode run` non può chiedere e rifiuta; `opencode run --auto` approva | +| Reviewer | sola lettura, legge il diff con git | sola lettura, legge il diff con git; redirezioni e `--output` sono negati per nome perché il filtro dei comandi di OpenCode non le interpreta | -Cosa è stato aggiunto per far funzionare tutto (solo ciò che i programmi reali hanno mostrato rotto): +**`--auto` annulla la guardia.** `opencode run --auto` approva ogni richiesta, comprese quelle di dev-brain: usalo solo dove accetti commit e push senza controllo. -- 6 file `agents/openai.yaml` (Codex ignora `disable-model-invocation`: senza, i 6 workflow comparivano nell'elenco, circa 1100 caratteri a sessione); -- la guardia git risponde "deny" invece di "ask" quando gira su Codex (Codex segna l'hook come fallito e il comando parte lo stesso); -- l'hook di contesto aggiunge la chiave `additionalContext` che Copilot CLI legge al posto di `hookSpecificOutput`, solo quando è Copilot a eseguirlo (Codex la rifiuta). +Versione provata: OpenCode 2.3.2, con la sua API plugin V2; OpenCode 1.x NON è stato provato. La 2.4.0 NON è stata provata (il pacchetto non si poteva scaricare qui; la CI prova l'ultima versione). I nomi dei workflow in questo manuale sono quelli di Claude Code (`/dev-brain:`): su OpenCode usa il nome nudo (`@start`). diff --git a/README.md b/README.md index f1e70d4..17dffdf 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # dev-brain -A plugin for Claude Code (also installable in Codex CLI and GitHub Copilot, see below) that steers ordinary coding requests toward readable, maintainable code, keeps each project's state across sessions, and spends as little context as possible. Works with any model the host can use. +A Claude Code plugin, with an adapter for OpenCode, that steers ordinary coding requests toward readable, maintainable code, keeps each project's state across sessions, and spends as little context as possible. Works with any model the agent can use. It provides: - global engineering rules, injected into every session; @@ -8,7 +8,7 @@ It provides: - user-invoked workflows: `start`, `resume`, `handoff`, `impact`, `learn`, `review` (no context cost until invoked); - three skills the model loads when relevant: `debugging`, `engineering-risk`, `review-feedback`; - a read-only reviewer subagent; -- a guard that makes the host ask you before any commit, push or destructive git command (Codex refuses instead, see below). +- a guard that makes the agent ask you before any commit, push or destructive git command. > Manuale utente in italiano: [MANUALE.md](MANUALE.md). @@ -21,28 +21,35 @@ claude plugin install dev-brain@dev-brain Requires `python3` and `git`. Update with `claude plugin marketplace update dev-brain`. For local development, add the cloned folder instead: `claude plugin marketplace add /path/to/agents-platform` (read in place). -## Codex and GitHub Copilot +## OpenCode -The same marketplace and plugin install unchanged; nothing is copied or forked. Checked with the real binaries against a mock model (`python3 evals/offline/check.py`), not with a real model. +OpenCode has no plugin marketplace, so one file, `adapters/opencode/index.ts`, connects it to the same `core/`: it runs the plugin's own `dev-brain-context` and `dev-brain-guard` scripts and builds the reviewer from `core/agents/reviewer.md`. No rule is copied. Checked with the real binary against a mock model (`python3 evals/offline/check.py`), not with a real model. -| | Claude Code | Codex CLI | Copilot CLI | -| --- | --- | --- | --- | -| Install | `claude plugin marketplace add Stcant/agents-platform`, then `claude plugin install dev-brain@dev-brain` | `codex plugin marketplace add Stcant/agents-platform`, then `codex plugin add dev-brain@dev-brain` | `copilot plugin marketplace add Stcant/agents-platform`, then `copilot plugin install dev-brain@dev-brain` | -| Rules and state | yes | yes, once you trust the plugin's hooks with `/hooks`; until then they are silently off, and so is the git guard | yes | -| Workflow call | `/dev-brain:start` | `$dev-brain:start` | listed by `copilot skill list`; calling them in an interactive session is NOT RUN | -| Workflows cost no context | yes | yes, through `agents/openai.yaml` in each workflow | yes | -| Update | `claude plugin marketplace update dev-brain` | `codex plugin marketplace upgrade dev-brain`; whether it also refreshes the installed copy is NOT RUN, so `codex plugin add dev-brain@dev-brain` again if the version does not change | `copilot plugin marketplace update`, then `copilot plugin update dev-brain` | -| Remove | `claude plugin uninstall dev-brain@dev-brain` | `codex plugin remove dev-brain@dev-brain` | `copilot plugin uninstall dev-brain` | -| Commit, push, branch change | asks you | refused: Codex hooks cannot ask, so you run the command | asks you (the interactive prompt is NOT RUN; `-p` mode cannot ask and refuses) | -| Reviewer | read-only, reads the diff with git | not loaded: `review` says so and stops | read-only, but without a shell: it cannot run git and reads the listed files | +```bash +git clone https://github.com/Stcant/agents-platform /path/to/agents-platform +``` -Tested versions: Claude Code 2.1.325 (CI also ran 2.1.329), Codex CLI 0.171.0, Copilot CLI 1.0.114. The oldest version that works is unknown; older releases are NOT RUN. The install commands above were run as written from GitHub (`Stcant/agents-platform`): both Codex and Copilot CLI installed 2.3.0. The workflow names below are written for Claude Code (`/dev-brain:`); on Codex write `$dev-brain:`. +Then add the adapter to `plugins` in `~/.config/opencode/opencode.json` (or in a project's `opencode.json`), with an absolute path: + +```json +{ "plugins": ["/path/to/agents-platform/adapters/opencode"] } +``` + +Requires `python3` and `git`; without `python3` the adapter asks before every shell command. Update with `git -C /path/to/agents-platform pull`; remove by deleting the entry. Check the install with `opencode debug agents`: it must list `reviewer`. + +| | Claude Code | OpenCode | +| --- | --- | --- | +| Rules and saved state | every session | main session only, not subagents | +| Workflow call | `/dev-brain:start` | `@start` in the prompt, or ask the agent to load the skill `start` (the skill tool loads it by id: tested; the `@` form follows the OpenCode docs and is NOT RUN, since it needs the TUI) | +| Workflows cost no context | yes | yes: not in the skill listing | +| Commit, push, branch change | asks you | asks you (the interactive prompt is NOT RUN); `opencode run` cannot ask and refuses; `opencode run --auto` approves it | +| Reviewer | read-only, reads the diff with git | read-only, reads the diff with git; redirections and `--output` are denied by name because OpenCode's shell matcher does not parse them | -VS Code (Copilot agent mode) is NOT RUN: it cannot be executed here. Its documentation says agent plugins read the Claude format: add `Stcant/agents-platform` in the Customizations editor (Configure Marketplaces) or in the `chat.plugins.marketplaces` setting, then install `dev-brain`. How VS Code loads a plugin's hooks and agents is not documented, so check that the rules arrive; if they do not, paste `core/AGENTS.md` into your Copilot instructions. +Tested version: OpenCode 2.3.2, through its V2 plugin API; OpenCode 1.x is NOT RUN. 2.4.0 is NOT RUN: its package could not be downloaded here, and CI tests the newest release. The workflow names below are written for Claude Code (`/dev-brain:`); in OpenCode use the bare name (`@start`). ## First step in every repository: `/dev-brain:start` -Run it once in each repository, from its root. Everything else builds on the two files it creates: `resume` and `handoff` read and rewrite the state, every session gets it automatically, and Claude Code reads the project facts natively (Codex and Copilot document the same for `AGENTS.md`; not tested here). +Run it once in each repository, from its root. Everything else builds on the two files it creates: `resume` and `handoff` read and rewrite the state, every session gets it automatically, and Claude Code and OpenCode read the project facts natively. 1. Inspects the real repository: stack, commands, conventions, traps. It does not open data directories (`input/`, `output/`, `.env`). 2. Writes or merges the root `AGENTS.md` as a draft, under 40 lines and only what the code does not show: exact commands, project tooling, decisions that differ from defaults, gotchas. No purpose line, stack list or architecture tour: studies find that such overviews add cost without helping the agent. It also creates or reconciles `.dev-brain/STATE.md` (goal, done with evidence, blockers, next actions, under 3000 characters). @@ -72,24 +79,25 @@ For planning use Claude Code's native plan mode (Shift+Tab): it is read-only by ## What is enforced, what is instructed -- **No commit without you: enforced.** A `PreToolUse` hook answers "ask" (on Codex, which cannot ask: "deny") for `git commit` (including `--amend`), `push`, `merge`, `rebase`, `cherry-pick`, `revert`, `checkout`/`switch`, history-moving `reset`, `clean -f`, `branch -d/-m/-f`, `stash drop/pop/clear` and tag deletion, even inside chained commands and even when your settings allow git. Read-only git runs normally. -- **Reviewer read-only: enforced on Claude Code and Copilot CLI** (not loaded on Codex). Its tool list allows Read, Grep, Glob and `git diff/log/show/status`; any command that creates, changes or removes files needs your approval. +- **No commit without you: enforced.** A `PreToolUse` hook (on OpenCode, the adapter) answers "ask" for `git commit` (including `--amend`), `push`, `merge`, `rebase`, `cherry-pick`, `revert`, `checkout`/`switch`, history-moving `reset`, `clean -f`, `branch -d/-m/-f`, `stash drop/pop/clear` and tag deletion, even inside chained commands and even when your settings allow git. Read-only git runs normally. +- **Reviewer read-only: enforced.** Its tool list allows Read, Grep, Glob and `git diff/log/show/status`; any command that creates, changes or removes files needs your approval. - **State budget: enforced.** Over 3000 characters only a notice is injected, telling the model to read the file and suggest `handoff`. - **Everything else is instructed:** rules guide the model; they do not guarantee good code. ## Evaluation ```bash -python3 evals/offline/check.py # CLAUDE / CODEX / COPILOT= if not on PATH +python3 evals/offline/check.py # CLAUDE / OPENCODE= if not on PATH ``` -Installs the plugin into a throwaway home, replaces the model with a local mock that records every request, and checks in about 20 seconds, at zero token cost. Claude Code (required): rules and state reach the session, oversized state becomes a notice, workflows expand and stay out of the skill listing, the reviewer reads the diff but cannot write, and commit and push need you even when your settings allow git. Codex CLI and Copilot CLI (run when found; an explicit `CODEX` or `COPILOT` variable makes them required): rules and state arrive, workflows stay out of the skill listing, commit and push are stopped, and Copilot's reviewer has no shell. GitHub Actions runs it on every pull request (`.github/workflows/offline-check.yml`, Claude Code 2.1.325, Codex 0.171.0, Copilot CLI 1.0.114, no secrets); pushes to `main`, a weekly run and manual runs also test the newest releases. It does not judge model behavior; `evals/scenarios/` describes the real-model scenarios and `evals/results.md` records decisions and evidence. +Installs the plugin into a throwaway home, replaces the model with a local mock that records every request, and checks in about 20 seconds, at zero token cost. Claude Code (required): rules and state reach the session, oversized state becomes a notice, workflows expand and stay out of the skill listing, the reviewer reads the diff but cannot write, and commit and push need you even when your settings allow git. OpenCode (run when found; an explicit `OPENCODE` variable makes it required): the same, through the adapter, plus rules and state staying out of the subagent. GitHub Actions runs it on every pull request (`.github/workflows/offline-check.yml`, Claude Code 2.1.325 and OpenCode 2.3.2, no secrets); pushes to `main`, a weekly run and manual runs also test the newest releases. It does not judge model behavior; `evals/scenarios/` describes the real-model scenarios and `evals/results.md` records decisions and evidence. ## Layout ``` .claude-plugin/marketplace.json marketplace listing the plugin core/ the plugin: AGENTS.md rules, skills/, agents/, hooks/, bin/ (context and git guard) +adapters/opencode/ OpenCode adapter over core/ evals/ scenarios, fixtures, results, offline check MANUALE.md Italian user manual ``` diff --git a/adapters/opencode/index.ts b/adapters/opencode/index.ts new file mode 100644 index 0000000..c4f01de --- /dev/null +++ b/adapters/opencode/index.ts @@ -0,0 +1,121 @@ +// OpenCode adapter for dev-brain: a thin layer over core/, with no rule of its own. +// - rules + saved state: runs core/bin/dev-brain-context for the main session +// - git guard: runs core/bin/dev-brain-guard on every shell command +// - skills: registers core/skills (workflows are not offered to the model) +// - reviewer: built from core/agents/reviewer.md (prompt and read-only tool list) +// Install: add this directory to `plugins` in opencode.json (see README). +import type { Plugin } from "@opencode/plugin" +import { execFileSync } from "node:child_process" +import { readFileSync, readdirSync } from "node:fs" +import { join } from "node:path" +import { fileURLToPath } from "node:url" + +const CORE = fileURLToPath(new URL("../../core/", import.meta.url)) + +// Frontmatter as flat `key: value` lines, which is all the kit's files use. +function readMarkdown(file: string): { meta: Record; body: string } { + const match = readFileSync(file, "utf8").match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/) + const meta: Record = {} + for (const line of (match?.[1] ?? "").split("\n")) { + const at = line.indexOf(":") + if (at > 0) meta[line.slice(0, at).trim()] = line.slice(at + 1).trim() + } + return { meta, body: (match?.[2] ?? "").trim() } +} + +function runScript(name: string, args: string[], input: string | undefined, cwd: string): string { + return execFileSync("python3", [join(CORE, "bin", name), ...args], { cwd, input, encoding: "utf8", timeout: 5000 }).trim() +} + +// Claude's `tools: Read, Grep, Glob, Bash(git diff:*)` as OpenCode permissions: everything is denied +// except what the list names, and the base policy's "ask" rules (such as .env files) stay. +type Rule = { action: string; resource: string; effect: "allow" | "deny" | "ask" } + +function permissionsFor(tools: string, base: Rule[]): Rule[] { + const allow = (action: string, resource = "*"): Rule => ({ action, resource, effect: "allow" }) + const names: Record = { Read: "read", Grep: "grep", Glob: "glob" } + const rules = tools.split(/,\s*(?![^()]*\))/).flatMap((tool) => { + const bash = tool.trim().match(/^Bash\((.+?):\*\)$/) + if (bash) return [allow("shell", `${bash[1]} *`)] + return names[tool.trim()] ? [allow(names[tool.trim()])] : [] + }) + // The shell matcher checks each chained command but not redirections, so those are denied by name. + const writes = ["* --output*", "*>*"].map((resource): Rule => ({ action: "shell", resource, effect: "deny" })) + return [{ action: "*", resource: "*", effect: "deny" }, ...rules, ...base.filter((rule) => rule.effect === "ask"), ...writes] +} + +const plugin: Plugin.Plugin = { + id: "dev-brain", + async setup(ctx) { + const project = ctx.location.directory + + // Subagents get a focused prompt from their parent; the rules and state are for the main session + // (Claude Code's SessionStart hook does not run for them either). + const subagent = new Map() + async function isSubagent(sessionID: string) { + if (!subagent.has(sessionID)) { + const session = await ctx.session.get({ sessionID }).catch(() => undefined) + subagent.set(sessionID, session?.parentID !== undefined) + } + return subagent.get(sessionID) + } + + await ctx.session.hook("context", async (event) => { + if (await isSubagent(event.sessionID)) return + let text = "" + try { + text = runScript("dev-brain-context", ["--text"], undefined, project) + } catch { + text = "dev-brain could not load its rules and saved state (is python3 installed?). Tell the user." + } + event.system.push({ type: "text", text }) + }) + + // The permission policy cannot see inside a git command, so the shared guard decides; "ask" is the + // same answer it gives Claude Code. An explicit deny in the user's config is final and never gets here. + await ctx.permission.hook("evaluate", (event) => { + if (event.action !== "shell" || event.effect === "deny") return + for (const command of event.resources) { + let reason: string | undefined + try { + const answer = runScript("dev-brain-guard", [], JSON.stringify({ tool_input: { command } }), project) + reason = answer ? JSON.parse(answer).hookSpecificOutput.permissionDecisionReason : undefined + } catch { + reason = "dev-brain could not check this command (is python3 installed?)" + } + if (reason) { + event.effect = "ask" + event.message = reason + return + } + } + }) + + await ctx.skill.transform((editor) => { + for (const dir of readdirSync(join(CORE, "skills"))) { + const path = join(CORE, "skills", dir, "SKILL.md") + const { meta, body } = readMarkdown(path) + editor.add({ + id: meta.name, + name: meta.name, + description: meta.description, + autoinvoke: meta["disable-model-invocation"] !== "true", + path, + content: body, + } as never) + } + }) + + await ctx.agent.transform((editor) => { + const { meta, body } = readMarkdown(join(CORE, "agents", "reviewer.md")) + editor.update(meta.name, (agent) => { + agent.mode = "subagent" + agent.description = meta.description + agent.system = body + agent.permissions = permissionsFor(meta.tools, agent.permissions) + }) + }) + }, +} + +export default plugin diff --git a/core/.claude-plugin/plugin.json b/core/.claude-plugin/plugin.json index 94d98f4..f4afec1 100644 --- a/core/.claude-plugin/plugin.json +++ b/core/.claude-plugin/plugin.json @@ -1,5 +1,5 @@ { "name": "dev-brain", - "version": "2.3.0", + "version": "2.4.0", "description": "Readable, maintainable code at low context cost: global rules, project state, workflows, skills and a read-only reviewer." } diff --git a/core/bin/dev-brain-context b/core/bin/dev-brain-context index 6dfdf8a..88ee6ef 100755 --- a/core/bin/dev-brain-context +++ b/core/bin/dev-brain-context @@ -2,11 +2,9 @@ """SessionStart hook: give the agent the global rules and the project's saved state. Claude Code runs it at startup, resume, /clear and after compaction, and adds the -printed `additionalContext` to the session; Codex does the same with the same output. -Copilot CLI ignores the `hookSpecificOutput` form and reads a top-level -`additionalContext` instead (Codex rejects that key, so only Copilot gets it). The -project is found from the hook's JSON on stdin (`cwd`), else from the current -directory. `--text` prints the plain context instead, for checking it by hand. +printed `additionalContext` to the session. The project is found from the hook's +JSON on stdin (`cwd`), else from the current directory. `--text` prints the plain +context instead, for checking it by hand. """ import json import os @@ -75,10 +73,7 @@ def main(): if "--text" in sys.argv: print(context) else: - output = {"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": context}} - if os.environ.get("COPILOT_PLUGIN_ROOT"): - output["additionalContext"] = context - print(json.dumps(output)) + print(json.dumps({"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": context}})) if __name__ == "__main__": diff --git a/core/bin/dev-brain-guard b/core/bin/dev-brain-guard index 7281e03..e94d7df 100755 --- a/core/bin/dev-brain-guard +++ b/core/bin/dev-brain-guard @@ -4,20 +4,13 @@ The global rules say no commit, push, branch change or destructive git command without the user's explicit decision. This hook enforces it: for such a command it answers "ask", so Claude Code requests confirmation whatever the model decided or -the permission settings allow (Copilot CLI asks too). Codex cannot ask: an "ask" fails -the hook and the command still runs, so there the answer is "deny" and the user runs -the command. Everything else passes untouched (no output). +the permission settings allow. Everything else passes untouched (no output). """ import json -import os import re import shlex import sys -# Codex sets PLUGIN_ROOT for plugin hooks; Copilot CLI sets it too, plus COPILOT_PLUGIN_ROOT; -# Claude Code sets only CLAUDE_PLUGIN_ROOT. -CANNOT_ASK = bool(os.environ.get("PLUGIN_ROOT")) and not os.environ.get("COPILOT_PLUGIN_ROOT") - # git global options that take a separate value: `git -C dir commit` is still a commit. OPTIONS_WITH_VALUE = {"-c", "-C", "--git-dir", "--work-tree", "--namespace", "--exec-path"} @@ -69,11 +62,10 @@ def main(): for segment in re.split(r"&&|\|\||[;|\n]|\$\(|`", command): reason = git_reason(segment.strip().lstrip("(")) if reason: - suffix = "; this host cannot ask, so the user must run it" if CANNOT_ASK else "" print(json.dumps({"hookSpecificOutput": { "hookEventName": "PreToolUse", - "permissionDecision": "deny" if CANNOT_ASK else "ask", - "permissionDecisionReason": f"dev-brain: {reason}; it needs your explicit decision{suffix}.", + "permissionDecision": "ask", + "permissionDecisionReason": f"dev-brain: {reason}; it needs your explicit decision.", }})) return diff --git a/core/skills/handoff/agents/openai.yaml b/core/skills/handoff/agents/openai.yaml deleted file mode 100644 index 5b1f887..0000000 --- a/core/skills/handoff/agents/openai.yaml +++ /dev/null @@ -1,2 +0,0 @@ -policy: - allow_implicit_invocation: false diff --git a/core/skills/impact/agents/openai.yaml b/core/skills/impact/agents/openai.yaml deleted file mode 100644 index 5b1f887..0000000 --- a/core/skills/impact/agents/openai.yaml +++ /dev/null @@ -1,2 +0,0 @@ -policy: - allow_implicit_invocation: false diff --git a/core/skills/learn/agents/openai.yaml b/core/skills/learn/agents/openai.yaml deleted file mode 100644 index 5b1f887..0000000 --- a/core/skills/learn/agents/openai.yaml +++ /dev/null @@ -1,2 +0,0 @@ -policy: - allow_implicit_invocation: false diff --git a/core/skills/resume/agents/openai.yaml b/core/skills/resume/agents/openai.yaml deleted file mode 100644 index 5b1f887..0000000 --- a/core/skills/resume/agents/openai.yaml +++ /dev/null @@ -1,2 +0,0 @@ -policy: - allow_implicit_invocation: false diff --git a/core/skills/review/agents/openai.yaml b/core/skills/review/agents/openai.yaml deleted file mode 100644 index 5b1f887..0000000 --- a/core/skills/review/agents/openai.yaml +++ /dev/null @@ -1,2 +0,0 @@ -policy: - allow_implicit_invocation: false diff --git a/core/skills/start/agents/openai.yaml b/core/skills/start/agents/openai.yaml deleted file mode 100644 index 5b1f887..0000000 --- a/core/skills/start/agents/openai.yaml +++ /dev/null @@ -1,2 +0,0 @@ -policy: - allow_implicit_invocation: false diff --git a/evals/offline/check.py b/evals/offline/check.py index d11ac98..6f2b989 100644 --- a/evals/offline/check.py +++ b/evals/offline/check.py @@ -9,15 +9,15 @@ state becomes a notice, workflows expand and stay out of the skill listing, the reviewer reads the diff with git but cannot write, and commit and push need the user even when the user's settings allow git. -Codex CLI and Copilot CLI (when found on PATH; an explicit CODEX / COPILOT variable -makes them required): the same plugin installs unchanged; rules and state arrive, -workflows stay out of the skill listing, and git commit is stopped. Copilot's reviewer -must also have no shell. VS Code is not covered: it cannot run here. +OpenCode (when found on PATH; an explicit OPENCODE variable makes it required): the +adapter in adapters/opencode loads; rules and state reach the main session and not the +subagent, workflows stay out of the skill listing, commit and push need the user, and +the reviewer reads the diff but cannot write. It does not judge model behavior; use evals/scenarios/ for that. usage: python3 evals/offline/check.py - (CLAUDE / CODEX / COPILOT= if not on PATH) + (CLAUDE / OPENCODE= if not on PATH) """ import json import os @@ -96,6 +96,17 @@ def commit_count(repo): return subprocess.run(["git", "rev-list", "--count", "HEAD"], cwd=repo, capture_output=True, text=True).stdout.strip() +def run_agent(cmd, env, repo, mock, steps): + """Run an agent CLI once against the mock model; returns the agent-loop requests it sent.""" + mock.script(steps) + subprocess.run(cmd, cwd=repo, env={**env, "PWD": str(repo)}, stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=240) + bodies = mock.agent_calls() + if not bodies: + check(f"{Path(cmd[0]).name} sent a request to the mock model", False) + return bodies + + class Sandbox: """Throwaway home with the plugin installed, and a fixture repository with a pending change.""" @@ -119,124 +130,94 @@ def write_state(self, text): (self.repo / ".dev-brain" / "STATE.md").write_text(text) def run(self, prompt, steps, *extra): - self.mock.script(steps) - subprocess.run([self.claude, "-p", prompt, "--model", "mock-model", *extra], cwd=self.repo, - env={**self.env, "PWD": str(self.repo)}, stdin=subprocess.DEVNULL, - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=240) - bodies = self.mock.agent_calls() - if not bodies: - check("claude sent a request to the mock model", False) - return bodies - - -def function_outputs(bodies): - """Tool outputs fed back to a Responses-API agent (Codex), once per call id.""" - results = {} - for body in bodies: - for item in body.get("input", []): - if isinstance(item, dict) and item.get("type") == "function_call_output": - results.setdefault(item.get("call_id"), json.dumps(item.get("output"))) - return list(results.values()) - - -def host_setup(prefix, **extra): - """A clean environment in a throwaway home, for an agent CLI other than Claude Code.""" - root = Path(tempfile.mkdtemp(prefix=prefix)) - home = root / "home" - home.mkdir() - identity = {"GIT_AUTHOR_NAME": "check", "GIT_COMMITTER_NAME": "check", - "GIT_AUTHOR_EMAIL": "check@example.invalid", "GIT_COMMITTER_EMAIL": "check@example.invalid"} - env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "HOME": str(home), "LANG": "C.UTF-8", "TERM": "dumb", - "NO_PROXY": "127.0.0.1,localhost", **identity, **extra} - return root, env - - -def host_install(binary, env, *commands): - for args in commands: - result = subprocess.run([binary, *args], env=env, capture_output=True, text=True) - if result.returncode: - raise SystemExit(f"FAIL {Path(binary).name} {' '.join(args)}: {result.stdout}{result.stderr}") - - -def host_run(cmd, env, repo, mock, steps): - mock.script(steps) - subprocess.run(cmd, cwd=repo, env={**env, "PWD": str(repo)}, stdin=subprocess.DEVNULL, - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=240) - bodies = mock.agent_calls() - if not bodies: - check(f"{Path(cmd[0]).name} sent a request to the mock model", False) - return bodies + cmd = [self.claude, "-p", prompt, "--model", "mock-model", *extra] + return run_agent(cmd, self.env, self.repo, self.mock, steps) GIT_COMMANDS = ["git status --short", "git commit -am wip", "git push origin main"] -def check_codex(codex, mock): - root, env = host_setup("dev-brain-offline-codex-", MOCK_KEY="offline-check") - try: - host_install(codex, env, ["plugin", "marketplace", "add", str(KIT)], ["plugin", "add", "dev-brain@dev-brain"]) - repo = make_repo(root) - provider = (f'model_providers.mock={{ name = "mock", base_url = "{mock.url}/v1", ' - 'wire_api = "responses", env_key = "MOCK_KEY" }') - - def run(prompt, steps, *extra): - cmd = [codex, "exec", "--skip-git-repo-check", "-c", 'model_provider="mock"', "-c", 'model="mock"', - "-c", provider, *extra, prompt] - return host_run(cmd, env, repo, mock, steps) - - # Plugin hooks run only after the user trusts them; the check bypasses that inside its own sandbox. - trust = "--dangerously-bypass-hook-trust" - check("codex: hooks wait for the user's trust", RULES not in json.dumps(run("hello", [{"text": "done"}]))) - text = json.dumps(run("hello", [{"text": "done"}], trust)) - check("codex: global rules and saved state arrive once trusted", RULES in text and STATE_MARK in text) - check("codex: workflows stay out of the skill listing", - "dev-brain:debugging" in text and "dev-brain:handoff" not in text) - for name, marker in WORKFLOWS.items(): - bodies = run(f"$dev-brain:{name}", [{"text": "done"}], trust) - check(f"codex: $dev-brain:{name} expands the workflow", marker in json.dumps(bodies)) - # Without the sandbox the commit would succeed, so only the guard can stop it. - steps = [{"tool": "exec_command", "args": {"cmd": cmd}} for cmd in GIT_COMMANDS] + [{"text": "done"}] - before = commit_count(repo) - results = function_outputs(run("save my work", steps, trust, "-s", "danger-full-access")) - check("codex: read-only git runs", any("app.txt" in r for r in results)) - guarded = sum("needs your explicit decision" in r for r in results) - check("codex: commit and push are refused", guarded == 2 and commit_count(repo) == before, f"{guarded}/2 refused") - finally: - shutil.rmtree(root, ignore_errors=True) +def chat_results(bodies): + """Tool outputs fed back to a chat-completions agent (OpenCode), once per call id.""" + results = {} + for body in bodies: + for message in body.get("messages", []): + if message.get("role") == "tool": + content = message.get("content") + results.setdefault(message.get("tool_call_id"), content if isinstance(content, str) else json.dumps(content)) + return list(results.values()) -def check_copilot(copilot, mock): - root, env = host_setup("dev-brain-offline-copilot-", NO_COLOR="1", COPILOT_OFFLINE="true", - COPILOT_PROVIDER_BASE_URL=mock.url, COPILOT_PROVIDER_TYPE="anthropic", - COPILOT_PROVIDER_API_KEY="sk-offline-check", COPILOT_MODEL="mock-model", - COPILOT_PROVIDER_MODEL_ID="claude-sonnet-4.5", COPILOT_PROVIDER_WIRE_MODEL="mock-model") - env["COPILOT_HOME"] = str(Path(env["HOME"]) / ".copilot") - Path(env["COPILOT_HOME"]).mkdir() +def check_opencode(opencode, mock): + root = Path(tempfile.mkdtemp(prefix="dev-brain-offline-opencode-")) + home = root / "home" + config = home / ".config" / "opencode" + config.mkdir(parents=True) + # Only the adapter is configured: it brings the skills, the guard and the reviewer with it. + (config / "opencode.json").write_text(json.dumps({ + "model": "mock/mock", "plugins": [str(KIT / "adapters" / "opencode")], + "providers": {"mock": { + "name": "Mock", "package": "@opencode/ai/providers/openai-compatible", + "settings": {"baseURL": mock.url + "/v1"}, + "models": {"mock": {"name": "Mock", "capabilities": {"tools": True, "input": ["text"], "output": ["text"]}, + "limit": {"context": 200000, "output": 8000}}}}}})) + env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "HOME": str(home), "LANG": "C.UTF-8", "TERM": "dumb", + "NO_PROXY": "127.0.0.1,localhost", "XDG_CONFIG_HOME": str(home / ".config"), + "XDG_DATA_HOME": str(home / ".local/share"), "XDG_STATE_HOME": str(home / ".local/state"), + "XDG_CACHE_HOME": str(home / ".cache"), "OPENCODE_DISABLE_MODELS_FETCH": "1", + "OPENCODE_DISABLE_FREE_MODELS": "1", "GIT_AUTHOR_NAME": "check", "GIT_COMMITTER_NAME": "check", + "GIT_AUTHOR_EMAIL": "check@example.invalid", "GIT_COMMITTER_EMAIL": "check@example.invalid"} try: - host_install(copilot, env, ["plugin", "marketplace", "add", str(KIT)], ["plugin", "install", "dev-brain@dev-brain"]) repo = make_repo(root) - def run(prompt, steps, *extra): - return host_run([copilot, "-p", prompt, *extra], env, repo, mock, steps) - - text = json.dumps(run("hello", [{"text": "done"}])) - check("copilot: global rules and saved state arrive", RULES in text and STATE_MARK in text) - check("copilot: workflows stay out of the skill listing", - "debugging" in text and "handoff" not in text) - steps = [{"tool": "bash", "args": {"command": cmd, "description": "git", "mode": "sync", "initial_wait": 30}} - for cmd in GIT_COMMANDS] + [{"text": "done"}] + def run(prompt, steps): + return run_agent([opencode, "run", "--standalone", "-m", "mock/mock", prompt], env, repo, mock, steps) + + def is_main(body): + return any(tool["function"]["name"] == "edit" for tool in body["tools"]) + + # The reviewer runs in the background, so each step says which session it belongs to. + mine, theirs = {"unless": "independent reviewer"}, {"when": "independent reviewer"} + steps = [{"tool": "subagent", "args": {"agent": "reviewer", "description": "review", "prompt": "Review all changes."}, **mine}, + {"tool": "shell", "args": {"command": "git diff HEAD"}, **theirs}, + {"tool": "shell", "args": {"command": "git diff HEAD > leak.txt"}, **theirs}, + {"tool": "shell", "args": {"command": "git diff HEAD --output=leak.txt"}, **theirs}, + {"tool": "shell", "args": {"command": "git status; rm app.txt"}, **theirs}, + {"tool": "shell", "args": {"command": "git diff HEAD $(touch touched.txt)"}, **theirs}, + {"tool": "shell", "args": {"command": "git diff HEAD `touch touched.txt`"}, **theirs}, + {"text": "no findings", **theirs}, {"text": "done", **mine}] + bodies = run("check", steps) + main = [b for b in bodies if is_main(b)] + child = [b for b in bodies if not is_main(b)] + results = chat_results(bodies) + check("opencode: global rules and saved state reach the main session", + bool(main) and all(RULES in system_text(b) and STATE_MARK in system_text(b) for b in main)) + check("opencode: rules and state stay out of the subagent", + bool(child) and not any(RULES in system_text(b) or STATE_MARK in system_text(b) for b in child)) + text = json.dumps(main[0]) if main else "" + check("opencode: workflows stay out of the skill listing", + "debugging" in text and "handoff" not in text) + check("opencode: reviewer reads the diff with git", any("hello, world" in r for r in results)) + rejected = sum(any(word in r for word in ("rejected", "denied", "not allowed")) for r in results) + check("opencode: reviewer cannot write (>, --output, rm, substitution)", + rejected == 5 and not any((repo / name).exists() for name in ("leak.txt", "touched.txt")) + and (repo / "app.txt").exists(), f"{rejected}/5 rejected") + + bodies = run("start the harness", [{"tool": "skill", "args": {"id": "start"}}, {"text": "done"}]) + check("opencode: a workflow loads by id", any(WORKFLOWS["start"] in r for r in chat_results(bodies))) + + # The fixture has a git identity, so only the guard can keep the commit from happening. + steps = [{"tool": "shell", "args": {"command": cmd}} for cmd in GIT_COMMANDS] + [{"text": "done"}] before = commit_count(repo) - results = tool_results(run("save my work", steps, "--allow-all-tools")) - check("copilot: read-only git runs", any("app.txt" in r for r in results)) - guarded = sum("needs your explicit decision" in r for r in results) - check("copilot: commit and push are stopped", guarded == 2 and commit_count(repo) == before, f"{guarded}/2 stopped") - steps = [{"tool": "task", "args": {"description": "review changes", "prompt": "Review all changes.", - "agent_type": "dev-brain:reviewer", "name": "rev", "mode": "sync"}}, - {"text": "no findings"}, {"text": "done"}] - bodies = run("check the changes", steps) - tools = {tool["name"] for body in bodies if "independent reviewer" in json.dumps(body.get("system")) - for tool in body["tools"]} - check("copilot: the reviewer has read tools only", bool(tools) and tools <= {"view", "grep", "glob"}, str(sorted(tools))) + results = chat_results(run("save my work", steps)) + check("opencode: read-only git runs", any("app.txt" in r for r in results)) + guarded = sum("cannot ask the user" in r for r in results) + check("opencode: commit and push need the user", guarded == 2 and commit_count(repo) == before, f"{guarded}/2 guarded") + + (repo / ".dev-brain" / "STATE.md").write_text(STATE + "- stale line\n" * 300) + bodies = run("hello", [{"text": "done"}]) + system = system_text(bodies[0]) if bodies else "" + check("opencode: oversized state becomes a notice", NOTICE in system and "stale line" not in system) finally: shutil.rmtree(root, ignore_errors=True) @@ -297,14 +278,13 @@ def main(): system = system_text(bodies[0]) if bodies else "" check("oversized state becomes a notice", NOTICE in system and "stale line" not in system) - for name, variable, check_host in (("codex", "CODEX", check_codex), ("copilot", "COPILOT", check_copilot)): - binary = shutil.which(os.environ.get(variable) or name) - if binary: - check_host(binary, mock) - elif os.environ.get(variable): - check(f"{name} found", False, f"{variable}={os.environ[variable]}") - else: - print(f"SKIP {name}: not on PATH (set {variable}= to require it)") + binary = shutil.which(os.environ.get("OPENCODE") or "opencode") + if binary: + check_opencode(binary, mock) + elif os.environ.get("OPENCODE"): + check("opencode found", False, f"OPENCODE={os.environ['OPENCODE']}") + else: + print("SKIP opencode: not on PATH (set OPENCODE= to require it)") finally: mock.server.shutdown() shutil.rmtree(sandbox.root, ignore_errors=True) diff --git a/evals/offline/mock_model.py b/evals/offline/mock_model.py index 49eb546..ea6079a 100644 --- a/evals/offline/mock_model.py +++ b/evals/offline/mock_model.py @@ -1,7 +1,7 @@ """Local model endpoint that records requests and replays scripted replies. -Speaks two wire formats: Anthropic Messages (Claude Code, and Copilot CLI configured -with its Anthropic provider) and OpenAI Responses (Codex CLI, `/responses`). +Speaks two wire formats: Anthropic Messages (Claude Code) and OpenAI chat completions +(OpenCode, `/chat/completions`). Requests that offer tools are agent-loop calls: each one pops the first scripted step whose optional "when" / "unless" text matches the request, either @@ -35,7 +35,7 @@ def do_POST(self): with mock.lock: mock.requests.append(body) step = mock.next_step(body) - (self._responses if path.endswith("/responses") else self._reply)(body, step) + (self._chat if path.endswith("/chat/completions") else self._reply)(body, step) def _json(self, payload): data = json.dumps(payload).encode() @@ -51,29 +51,27 @@ def _sse(self, events): self.send_header("connection", "close") self.end_headers() for name, data in events: - self.wfile.write(f"event: {name}\ndata: {json.dumps(data)}\n\n".encode()) + prefix = f"event: {name}\n" if name else "" + self.wfile.write(f"{prefix}data: {json.dumps(data)}\n\n".encode()) self.wfile.flush() self.close_connection = True - def _responses(self, body, step): - n = len(mock.requests) + def _chat(self, body, step): + call_id = f"call_{len(mock.requests)}" if "tool" in step: - item = {"type": "function_call", "id": f"fc_{n}", "call_id": f"call_{n}", "name": step["tool"], - "arguments": json.dumps(step["args"]), "status": "completed"} + delta = {"role": "assistant", "tool_calls": [{"index": 0, "id": call_id, "type": "function", + "function": {"name": step["tool"], "arguments": json.dumps(step["args"])}}]} + finish = "tool_calls" else: - item = {"type": "message", "id": f"msg_{n}", "role": "assistant", "status": "completed", - "content": [{"type": "output_text", "text": step["text"], "annotations": []}]} - usage = {"input_tokens": 1, "input_tokens_details": {"cached_tokens": 0}, "output_tokens": 1, - "output_tokens_details": {"reasoning_tokens": 0}, "total_tokens": 2} - response = {"id": f"resp_{n}", "object": "response", "status": "in_progress", "model": "mock", "output": []} + delta, finish = {"role": "assistant", "content": step["text"]}, "stop" + base = {"id": "c", "object": "chat.completion.chunk", "created": 0, "model": "mock"} self._sse([ - ("response.created", {"type": "response.created", "response": response}), - ("response.output_item.added", {"type": "response.output_item.added", "output_index": 0, - "item": dict(item, status="in_progress")}), - ("response.output_item.done", {"type": "response.output_item.done", "output_index": 0, "item": item}), - ("response.completed", {"type": "response.completed", - "response": dict(response, status="completed", output=[item], usage=usage)}), + (None, {**base, "choices": [{"index": 0, "delta": delta, "finish_reason": None}]}), + (None, {**base, "choices": [{"index": 0, "delta": {}, "finish_reason": finish}], + "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}}), ]) + self.wfile.write(b"data: [DONE]\n\n") + self.wfile.flush() def _reply(self, body, step): if "tool" in step: diff --git a/evals/results.md b/evals/results.md index d124599..cee39a8 100644 --- a/evals/results.md +++ b/evals/results.md @@ -6,7 +6,25 @@ A log of decisions and the evidence behind them, newest first. Full run details Not measured. Real-model evidence so far: one model per scenario, one run, small synthetic Python fixtures; the no-kit baseline already solved every task. The one measured gain is the review policy (below). Next: the same real tasks with and without the plugin, same model; compare tokens per task, fix iterations, review findings, time to resume after a break. Keep what moves the numbers. -## 2026-11-20 — Codex CLI and Copilot (CLI) support, plugin 2.3.0 +## 2026-11-23 — Codex and Copilot support removed; OpenCode adapter, plugin 2.4.0 + +The user dropped Codex and GitHub Copilot and asked for the harness to work well in OpenCode. This supersedes the 2026-11-20 entry below (kept as history). Removed: the six `agents/openai.yaml`, the guard's "deny" mode, the context hook's Copilot key, the Codex and Copilot checks, their mock handler and the CI installs; `core/bin/*` are byte-identical to 2.2.1. Kept from that change: the `make_repo` and `commit_count` helpers of the check. + +Read: OpenCode's skills page and the plugin server API page; the 2.3.2 plugin type declarations. Run: OpenCode 2.3.2 (`@opencode/cli`; 2.4.0 is listed but its package did not download here). OpenCode has no marketplace and does not read Claude plugins, so a plugin file is the adapter; one probe plugin logged each hook's event. + +Worked without a change: OpenCode reads the project `AGENTS.md`; `disable-model-invocation: true` hides a skill from the listing and the `skill` tool still loads it by id. + +Needed an adapter (`adapters/opencode/index.ts`, no rule of its own): +1. Rules and state: the `context` hook runs `core/bin/dev-brain-context --text` for the main session. A subagent is told apart by `parentID` of its session (observed: set for `explore`, absent for the main session) and gets neither, as on Claude Code. +2. Git guard: the `permission` `evaluate` hook runs `core/bin/dev-brain-guard` on each shell command and sets the effect to "ask" for its answer; an explicit deny in the user's config never reaches the hook. If the script cannot run (checked with a failing `python3`), every shell command is asked, not allowed. +3. Skills: `skill.transform` adds `core/skills/*/SKILL.md` with `autoinvoke` taken from `disable-model-invocation`; the loaded skill keeps its base directory and `references/` files. +4. Reviewer: `agent.transform` creates it (`update` on an unknown id creates the agent) from the body of `core/agents/reviewer.md` as the system prompt and its `tools` line as permissions: deny everything, allow `read`, `grep`, `glob` and the `git diff/log/show/status` shell commands, keep the base "ask" rules for `.env`. OpenCode's shell matcher splits chained commands and sees `$(...)` and backticks, but not redirections: `git diff HEAD > f` and `git diff --output=f` were allowed until two explicit denies (`* --output*`, `*>*`) were added; the same gap was recorded for OpenCode 2.1 in the 2026-10-25 "Review and state token cost" entry. + +Evidence: `python3 evals/offline/check.py` ALL PASS, 20 checks (11 Claude Code 2.1.325, 9 OpenCode 2.3.2), about 26 s: rules and state reach the main session and not the subagent, workflows are out of the skill listing and load by id, the reviewer reads the diff and 5 write attempts (`>`, `--output`, `rm`, `$(...)`, backticks) are rejected, `git status` runs while commit and push are refused with a git identity present, and an oversized state becomes a notice. Six mutations each failed the intended check: no context hook, context for subagents, no guard, no redirection denies (3/5 rejected), workflows offered, no reviewer. The adapter type-checks against the 2.3.2 plugin types. + +Limits: the TUI is NOT RUN, so the interactive "ask" prompt and the `@start` mention are untested (in `opencode run` an ask is rejected and `@start` is not expanded). `opencode run --auto` approves the guard's ask (observed: the commit ran); it is the equivalent of Claude Code's bypass mode. OpenCode 1.x and 2.4.0 are NOT RUN. The hook shapes come from 2.3.2 behavior and type declarations, not a stability promise: CI pins 2.3.2 on pull requests and runs `@latest` weekly to see a change. No real model was used. Install is by path (`plugins` in `opencode.json`), because the adapter lives in a repository that is not an npm package; `opencode plugin add` takes npm or git packages and was not used. + +## 2026-11-20 — Codex CLI and Copilot (CLI) support, plugin 2.3.0 (removed on 2026-11-23, see above) The user asked to use the plugin in Codex and GitHub Copilot (VS Code). This reverses the 2026-10-25 "Claude Code only" decision; the adapters removed then are not restored. Principle: install the unchanged plugin first and change only what the real binaries show broken. From 53c1557147b24c273e68b9fd1b380c007b1e2cbb Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 10:33:22 +0100 Subject: [PATCH 2/2] Record OpenCode 2.4.0 CI result and PR number A manual run of the branch resolved @latest to Claude Code 2.1.330 and OpenCode 2.4.0 and passed all 20 checks, so 2.4.0 is no longer NOT RUN. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Sm3JtGSXFLR6CZYVJXGHtU --- .dev-brain/STATE.md | 4 ++-- MANUALE.md | 2 +- README.md | 2 +- evals/results.md | 6 +++--- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.dev-brain/STATE.md b/.dev-brain/STATE.md index 8a5fcb0..8f9159b 100644 --- a/.dev-brain/STATE.md +++ b/.dev-brain/STATE.md @@ -5,7 +5,7 @@ Updated: 2026-11-23 Plugin (Claude Code, plus an OpenCode adapter) for readable, maintainable code at the lowest context cost — acceptance: installs from GitHub with two commands, every claim backed by `evals/` evidence, measured benefit on real tasks. ## Done (latest first, max 5) -- Plugin 2.4.0 on branch `feat/opencode-adapter`, PR open and not merged: Codex and Copilot support removed (user decision), OpenCode adapter `adapters/opencode/index.ts` added — evidence: `python3 evals/offline/check.py` ALL PASS (20 checks: 11 Claude Code 2.1.325, 9 OpenCode 2.3.2), six adapter mutations each FAIL the intended check +- Plugin 2.4.0 on branch `feat/opencode-adapter`, PR #9 open and not merged: Codex and Copilot support removed (user decision), OpenCode adapter `adapters/opencode/index.ts` added — evidence: `python3 evals/offline/check.py` ALL PASS (20 checks: 11 Claude Code 2.1.325, 9 OpenCode 2.3.2), six adapter mutations each FAIL the intended check; PR #9 CI success on both jobs (newest: Claude Code 2.1.330, OpenCode 2.4.0) - Plugin 2.2.1 merged (PR #6): `handoff` stops writing branch/HEAD/commit status, CI pin 2.1.325 plus a newest-release job — evidence: CI success on both jobs; weekly schedule NOT RUN until it first fires - Offline check on GitHub Actions for every PR — evidence: PR #5 run `offline-check` success, ALL PASS on a clean runner - Plugin 2.2.0 merged (PR #4): minimal `start`, review passes the Goal line, reviewer checks weakened tests — evidence: `python3 evals/offline/check.py` ALL PASS on a clean clone of main (0d01d2b) @@ -14,7 +14,7 @@ Plugin (Claude Code, plus an OpenCode adapter) for readable, maintainable code a - Benefit of the rules on real code — status: NOT RUN; `claude plugin eval` (with/without plugin) would measure it but needs the user's credentials and tokens - Minimal `start` with a real model — status: partly seen on Presidio (deny rules and Stop hook adopted, `AGENTS.md` kept, not trimmed); its deletion-candidate list not seen - Opus 5.5 system card read only through secondary reports (PDF unreachable here) -- OpenCode TUI (the interactive ask prompt, `@start`) and OpenCode 2.4.0 — status: NOT RUN (the TUI cannot be driven here; the 2.4.0 package would not download) +- OpenCode TUI (the interactive ask prompt, `@start`) and OpenCode 1.x — status: NOT RUN (the TUI cannot be driven here) ## Known pre-existing failures - none diff --git a/MANUALE.md b/MANUALE.md index 8f5772c..9444e3c 100644 --- a/MANUALE.md +++ b/MANUALE.md @@ -252,4 +252,4 @@ Poi in `~/.config/opencode/opencode.json` (o nell'`opencode.json` di un progetto **`--auto` annulla la guardia.** `opencode run --auto` approva ogni richiesta, comprese quelle di dev-brain: usalo solo dove accetti commit e push senza controllo. -Versione provata: OpenCode 2.3.2, con la sua API plugin V2; OpenCode 1.x NON è stato provato. La 2.4.0 NON è stata provata (il pacchetto non si poteva scaricare qui; la CI prova l'ultima versione). I nomi dei workflow in questo manuale sono quelli di Claude Code (`/dev-brain:`): su OpenCode usa il nome nudo (`@start`). +Versioni provate: OpenCode 2.3.2 (qui e in CI) e 2.4.0 (in CI, l'ultima al momento della scrittura), con la loro API plugin V2; OpenCode 1.x NON è stato provato. I nomi dei workflow in questo manuale sono quelli di Claude Code (`/dev-brain:`): su OpenCode usa il nome nudo (`@start`). diff --git a/README.md b/README.md index 17dffdf..67afc7e 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ Requires `python3` and `git`; without `python3` the adapter asks before every sh | Commit, push, branch change | asks you | asks you (the interactive prompt is NOT RUN); `opencode run` cannot ask and refuses; `opencode run --auto` approves it | | Reviewer | read-only, reads the diff with git | read-only, reads the diff with git; redirections and `--output` are denied by name because OpenCode's shell matcher does not parse them | -Tested version: OpenCode 2.3.2, through its V2 plugin API; OpenCode 1.x is NOT RUN. 2.4.0 is NOT RUN: its package could not be downloaded here, and CI tests the newest release. The workflow names below are written for Claude Code (`/dev-brain:`); in OpenCode use the bare name (`@start`). +Tested versions: OpenCode 2.3.2 here and in CI, and 2.4.0 in CI (the newest release when written), through the V2 plugin API; OpenCode 1.x is NOT RUN. The workflow names below are written for Claude Code (`/dev-brain:`); in OpenCode use the bare name (`@start`). ## First step in every repository: `/dev-brain:start` diff --git a/evals/results.md b/evals/results.md index cee39a8..0f47e87 100644 --- a/evals/results.md +++ b/evals/results.md @@ -10,7 +10,7 @@ Not measured. Real-model evidence so far: one model per scenario, one run, small The user dropped Codex and GitHub Copilot and asked for the harness to work well in OpenCode. This supersedes the 2026-11-20 entry below (kept as history). Removed: the six `agents/openai.yaml`, the guard's "deny" mode, the context hook's Copilot key, the Codex and Copilot checks, their mock handler and the CI installs; `core/bin/*` are byte-identical to 2.2.1. Kept from that change: the `make_repo` and `commit_count` helpers of the check. -Read: OpenCode's skills page and the plugin server API page; the 2.3.2 plugin type declarations. Run: OpenCode 2.3.2 (`@opencode/cli`; 2.4.0 is listed but its package did not download here). OpenCode has no marketplace and does not read Claude plugins, so a plugin file is the adapter; one probe plugin logged each hook's event. +Read: OpenCode's skills page and the plugin server API page; the 2.3.2 plugin type declarations. Run: OpenCode 2.3.2 (`@opencode/cli`; 2.4.0's package did not download here, so it was tested only in CI). OpenCode has no marketplace and does not read Claude plugins, so a plugin file is the adapter; one probe plugin logged each hook's event. Worked without a change: OpenCode reads the project `AGENTS.md`; `disable-model-invocation: true` hides a skill from the listing and the `skill` tool still loads it by id. @@ -20,9 +20,9 @@ Needed an adapter (`adapters/opencode/index.ts`, no rule of its own): 3. Skills: `skill.transform` adds `core/skills/*/SKILL.md` with `autoinvoke` taken from `disable-model-invocation`; the loaded skill keeps its base directory and `references/` files. 4. Reviewer: `agent.transform` creates it (`update` on an unknown id creates the agent) from the body of `core/agents/reviewer.md` as the system prompt and its `tools` line as permissions: deny everything, allow `read`, `grep`, `glob` and the `git diff/log/show/status` shell commands, keep the base "ask" rules for `.env`. OpenCode's shell matcher splits chained commands and sees `$(...)` and backticks, but not redirections: `git diff HEAD > f` and `git diff --output=f` were allowed until two explicit denies (`* --output*`, `*>*`) were added; the same gap was recorded for OpenCode 2.1 in the 2026-10-25 "Review and state token cost" entry. -Evidence: `python3 evals/offline/check.py` ALL PASS, 20 checks (11 Claude Code 2.1.325, 9 OpenCode 2.3.2), about 26 s: rules and state reach the main session and not the subagent, workflows are out of the skill listing and load by id, the reviewer reads the diff and 5 write attempts (`>`, `--output`, `rm`, `$(...)`, backticks) are rejected, `git status` runs while commit and push are refused with a git identity present, and an oversized state becomes a notice. Six mutations each failed the intended check: no context hook, context for subagents, no guard, no redirection denies (3/5 rejected), workflows offered, no reviewer. The adapter type-checks against the 2.3.2 plugin types. +Evidence: `python3 evals/offline/check.py` ALL PASS, 20 checks (11 Claude Code 2.1.325, 9 OpenCode 2.3.2), about 26 s: rules and state reach the main session and not the subagent, workflows are out of the skill listing and load by id, the reviewer reads the diff and 5 write attempts (`>`, `--output`, `rm`, `$(...)`, backticks) are rejected, `git status` runs while commit and push are refused with a git identity present, and an oversized state becomes a notice. Six mutations each failed the intended check: no context hook, context for subagents, no guard, no redirection denies (3/5 rejected), workflows offered, no reviewer. The adapter type-checks against the 2.3.2 plugin types. On GitHub Actions (pull request #9): pinned job success; manual run of the branch, both jobs success, and `latest` resolved to Claude Code 2.1.330 and OpenCode 2.4.0, so 2.4.0 also passes all 20 checks. -Limits: the TUI is NOT RUN, so the interactive "ask" prompt and the `@start` mention are untested (in `opencode run` an ask is rejected and `@start` is not expanded). `opencode run --auto` approves the guard's ask (observed: the commit ran); it is the equivalent of Claude Code's bypass mode. OpenCode 1.x and 2.4.0 are NOT RUN. The hook shapes come from 2.3.2 behavior and type declarations, not a stability promise: CI pins 2.3.2 on pull requests and runs `@latest` weekly to see a change. No real model was used. Install is by path (`plugins` in `opencode.json`), because the adapter lives in a repository that is not an npm package; `opencode plugin add` takes npm or git packages and was not used. +Limits: the TUI is NOT RUN, so the interactive "ask" prompt and the `@start` mention are untested (in `opencode run` an ask is rejected and `@start` is not expanded). `opencode run --auto` approves the guard's ask (observed: the commit ran); it is the equivalent of Claude Code's bypass mode. OpenCode 1.x is NOT RUN. The hook shapes come from 2.3.2 behavior and type declarations, not a stability promise: CI pins 2.3.2 on pull requests and runs `@latest` weekly to see a change. No real model was used. Install is by path (`plugins` in `opencode.json`), because the adapter lives in a repository that is not an npm package; `opencode plugin add` takes npm or git packages and was not used. ## 2026-11-20 — Codex CLI and Copilot (CLI) support, plugin 2.3.0 (removed on 2026-11-23, see above)