From 11ea81ba46eb441f6014858a7950230e70b50a04 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 25 Oct 2026 14:21:52 +0100 Subject: [PATCH 1/4] Make the kit agent-independent: one core, adapters per agent core/ is now the only source, in the formats the agents share: AGENTS.md for rules and Agent Skills for workflows and skills. install.py links or translates it for OpenCode, Claude Code, Codex CLI and Cursor; Claude Code and Codex get a local plugin marketplace built in build/. The injected state comes from one script, core/bin/dev-brain-context, used by every adapter, and the rules tell the agent to read the state when no hook can. The read-only reviewer is enforced where the agent allows it: OpenCode permissions, Claude Code tool list; on Codex 0.164 the role's sandbox_mode is not applied to spawned agents, so it is an instruction there, and Cursor is untested. evals/offline/check.py now checks every agent CLI it finds against a mock model that speaks the chat, messages and responses formats; results and limits are in evals/results.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Sm3JtGSXFLR6CZYVJXGHtU --- .dev-brain/STATE.md | 18 +- .gitignore | 2 + AGENTS.md | 20 +- MANUALE.md | 832 ++++++------------ README.md | 110 +-- adapters/opencode/plugin/index.ts | 75 ++ {global => core}/AGENTS.md | 6 +- {global => core}/agents/reviewer.md | 17 +- core/bin/dev-brain-context | 100 +++ {global => core}/skills/debugging/SKILL.md | 0 .../skills/engineering-risk/SKILL.md | 0 .../engineering-risk/references/data.md | 0 .../references/performance.md | 0 .../engineering-risk/references/security.md | 0 .../skills/review-feedback/SKILL.md | 0 .../templates}/PROJECT_AGENTS.md | 0 {templates => core/templates}/STATE.md | 0 .../workflows/handoff/SKILL.md | 13 +- .../workflows/impact/SKILL.md | 6 +- .../learn.md => core/workflows/learn/SKILL.md | 8 +- .../plan.md => core/workflows/plan/SKILL.md | 7 +- .../workflows/resume/SKILL.md | 11 +- core/workflows/review/SKILL.md | 18 + .../start.md => core/workflows/start/SKILL.md | 12 +- evals/offline/check.py | 367 +++++--- evals/offline/mock_model.py | 173 ++++ evals/results.md | 32 + global/commands/review.md | 20 - install.py | 322 +++++++ install.sh | 77 +- plugin/dev-brain/index.ts | 83 -- 31 files changed, 1305 insertions(+), 1024 deletions(-) create mode 100644 .gitignore create mode 100644 adapters/opencode/plugin/index.ts rename {global => core}/AGENTS.md (91%) rename {global => core}/agents/reviewer.md (58%) create mode 100755 core/bin/dev-brain-context rename {global => core}/skills/debugging/SKILL.md (100%) rename {global => core}/skills/engineering-risk/SKILL.md (100%) rename {global => core}/skills/engineering-risk/references/data.md (100%) rename {global => core}/skills/engineering-risk/references/performance.md (100%) rename {global => core}/skills/engineering-risk/references/security.md (100%) rename {global => core}/skills/review-feedback/SKILL.md (100%) rename {templates => core/templates}/PROJECT_AGENTS.md (100%) rename {templates => core/templates}/STATE.md (100%) rename global/commands/handoff.md => core/workflows/handoff/SKILL.md (69%) rename global/commands/impact.md => core/workflows/impact/SKILL.md (76%) rename global/commands/learn.md => core/workflows/learn/SKILL.md (75%) rename global/commands/plan.md => core/workflows/plan/SKILL.md (81%) rename global/commands/resume.md => core/workflows/resume/SKILL.md (75%) create mode 100644 core/workflows/review/SKILL.md rename global/commands/start.md => core/workflows/start/SKILL.md (83%) create mode 100644 evals/offline/mock_model.py delete mode 100644 global/commands/review.md create mode 100644 install.py delete mode 100644 plugin/dev-brain/index.ts diff --git a/.dev-brain/STATE.md b/.dev-brain/STATE.md index 51044a1..eeed0b1 100644 --- a/.dev-brain/STATE.md +++ b/.dev-brain/STATE.md @@ -2,22 +2,22 @@ Updated: 2026-10-25 · Branch: improve/token-budget-and-review ## Goal -Personal OpenCode harness for readable, maintainable code at the lowest context cost — acceptance: always-on design rules installed, review covers real defects and maintenance costs, every claim backed by `evals/` evidence. +Agent-independent harness (OpenCode, Claude Code, Codex CLI, Cursor; any model provider) for readable, maintainable code at the lowest context cost — acceptance: one `core/` source, `install.py` per agent, every claim backed by `evals/` evidence. ## Done (latest first, max 5) -- `/review` delegates the diff to the reviewer (read-only git allowlist); covers staged, unstaged and untracked; plugin skips subagents and enforces a 3000-char state budget; `/resume` stack-agnostic; `/start` migrates `harness/` — evidence: `python3 evals/offline/check.py` PASS (mock model, OpenCode 2.1.4); `evals/results.md` 2026-10-25 -- hph adopted by following `/start` (patch, not pushed) — evidence: plugin injected the 1.3 KB state; `git apply --check` PASS on hph `d6ee299` -- Maintainability scenario: review policy reports duplicated business rules — evidence: `evals/results.md` 2026-10-22 (Python only) +- `core/` + `install.py` adapters for 4 agents; Claude Code and Codex via a local plugin marketplace in `build/`; state via one script `core/bin/dev-brain-context` — evidence: `python3 evals/offline/check.py` ALL PASS (OpenCode 2.1.4, Claude Code 2.1.310, Codex 0.164, mock model); Cursor files only +- `/review` delegates the diff to the reviewer; plugin skips subagents; 3000-char state budget — evidence: `evals/results.md` 2026-10-25 +- hph adoption patch (`AGENTS.md` + 1.3 KB state) — evidence: state and resume workflow reached Claude Code and Codex on the hph copy; not pushed ## In progress / blockers -- Real-model behavior of the new `/review`, `/resume` and plugin — status: NOT RUN; providers unreachable from the test environment -- Cross-language generation scenario — status: NOT RUN -- hph `harness/` deletion and patch commit — status: waiting for the owner +- Codex reviewer read-only — status: blocked upstream; `sandbox_mode` not applied to spawned agents in 0.164, instruction only +- Cursor — status: NOT RUN; no CLI in the test environment; `sessionStart` context dropped by an open Cursor bug +- Real-model and TUI behavior of all workflows — status: NOT RUN ## Known pre-existing failures - `opencode run "/command"` does not expand slash commands (CLI limitation) ## Next (max 3) -1. Run `python3 evals/offline/check.py` locally, then `/review` on a real diff with a real model in the TUI. -2. Apply the hph patch, review it, delete `harness/` and fix the README link to it. +1. Run `./install.sh` and `python3 evals/offline/check.py` locally; approve the Codex hook; try `review` and `resume` in each agent's TUI with a real model. +2. Apply the hph patch, delete `harness/`, fix hph README's link to it. 3. Add a non-Python maintainability scenario before changing design rules again. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3d43339 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +build/ +__pycache__/ diff --git a/AGENTS.md b/AGENTS.md index b446c83..d4ca5b1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,21 +1,20 @@ # Maintaining dev-brain -This repository is the source of the personal OpenCode harness. It is not an application. -Its primary goal is readable, maintainable code across languages and frameworks. Workflow commands and saved state support that goal. +This repository is the source of a personal harness for coding agents (OpenCode, Claude Code, Codex CLI, Cursor). 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 -- `global/AGENTS.md` — always-loaded personal rules. Keep it short: only instructions that change the model's default behavior. -- `global/commands/`, `global/agents/`, `global/skills/` — installed into `~/.config/opencode/` by `install.sh`. -- `plugin/dev-brain/` — the V2 plugin injecting project state; registered in the global `opencode.json`. -- `templates/` — files written into destination projects. -- `evals/` — scenarios, measured results and `offline/check.py`, a zero-token check against a mock model. +- `core/` — the only source. `AGENTS.md` is the always-loaded rule set: keep it short, only instructions that change default behavior. `workflows/` (user-invoked, `disable-model-invocation: true`) and `skills/` use the Agent Skills format; `agents/reviewer.md` has neutral frontmatter; `bin/dev-brain-context` produces the injected state for every adapter; `templates/` are written into projects. +- `adapters/` — only what cannot be expressed as files (the OpenCode plugin). +- `install.py` — links `core/` or translates frontmatter per agent. It must not contain rules or prose for the model beyond frontmatter; if an adapter needs a rule, it belongs in `core/`. +- `evals/` — scenarios, measured results, and `offline/check.py` with `offline/mock_model.py`, a zero-token check against the real agent binaries. ## Changing the harness 1. Run the relevant scenarios in `evals/scenarios/` against the current version and record the baseline. 2. Make the smallest change that addresses an observed failure. -3. Re-run the same scenarios with the change. After touching the plugin, agents or `install.sh`, also run `python3 evals/offline/check.py`. +3. Re-run the same scenarios with the change. After touching `core/`, an adapter or `install.py`, also run `python3 evals/offline/check.py`. 4. Keep the change only if it improves a scenario or removes a real cost. Delete instructions that do not change behavior. 5. Record the result in `evals/results.md` with the date and the evidence. @@ -24,6 +23,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. -- No runtime dependency beyond the OpenCode binary itself; the plugin uses only `@opencode/plugin` and Node built-ins. -- Commands, agents and skills must be portable: no absolute paths inside their content. +- Runtime dependencies: the agent itself, `python3` and `git`. The OpenCode plugin uses only `@opencode/plugin` and Node built-ins. +- Workflows, skills and the reviewer must be portable: no absolute paths, no agent-specific syntax (`$ARGUMENTS`, `!` command expansion) in `core/`. +- Claude Code and Codex install the plugin from `build/` (generated, git-ignored); Codex copies it and drops symlinks, so the build uses real copies. - 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 f2d10ee..274df01 100644 --- a/MANUALE.md +++ b/MANUALE.md @@ -1,220 +1,187 @@ # dev-brain — Manuale d'uso -> Manuale utente in italiano. Il codice, i comandi e le skill del kit sono in inglese; questo file è l'unica eccezione documentale. -> Versione: 2026-10-25. Richiede OpenCode V2 (provato su 2.1.4). +> Manuale utente in italiano. Il codice, i workflow e le skill del kit sono in inglese; questo file è l'unica eccezione. +> Versione: 2026-10-25. Funziona con OpenCode (provato su 2.1.4), Claude Code (2.1.310), Codex CLI (0.164) e Cursor (non provato: nessuna CLI disponibile nell'ambiente di test). Indipendente dal provider del modello. ## Indice - Avvio rapido - 1. Cos'è -- 2. Installazione e verifica -- 3. Prima adozione di una repository -- 4. Lavoro quotidiano -- 5. I comandi in dettaglio -- 6. I due file di progetto -- 7. Il plugin -- 8. Regole, permessi e sicurezza -- 9. Le skill -- 10. Il reviewer -- 11. Flussi di lavoro tipici +- 2. Come è costruito +- 3. Installazione e verifica +- 4. Prima adozione di una repository +- 5. Lavoro quotidiano +- 6. I workflow in dettaglio +- 7. I due file di progetto +- 8. Lo stato nel contesto dell'agente +- 9. Regole, permessi e sicurezza +- 10. Le skill +- 11. Il reviewer - 12. Manutenzione del kit -- 13. Migrazione dal vecchio dev-brain -- 14. Problemi e domande frequenti -- 15. Limiti noti -- 16. Checklist -- Riferimenti +- 13. Problemi e domande frequenti +- 14. Limiti noti +- 15. Checklist + +--- ## Avvio rapido ```bash -# 1. dalla cartella del kit +# dalla cartella del kit: installa per ogni agente trovato sulla macchina ./install.sh - -# 2. apri una nuova sessione OpenCode e verifica -opencode plugin list -opencode api GET /api/command -``` - -Dopo l'installazione puoi già fare una normale richiesta di codice, per esempio: - -```text -Aggiungi la spedizione express al calcolo del totale, mantenendo invariata -la spedizione standard e compatibili le chiamate esistenti. +# oppure solo quelli che vuoi +./install.sh opencode claude-code codex cursor ``` -Le regole di leggibilità e manutenibilità sono già attive: non devi aggiungere “scrivilo bene”, invocare una skill o creare prima lo stato. Il kit segue il linguaggio e le convenzioni del progetto, non impone Python. - -Se vuoi anche salvare i fatti e lo stato della repository, adottala con: - -```text -/start -``` +Poi fai una normale richiesta di codice. Le regole di leggibilità e manutenibilità sono già attive: non devi scrivere “fallo bene”, né invocare una skill. -Per riprendere una sessione usando lo stato salvato: +I workflow si invocano con la sintassi del tuo agente: -```text -/resume -``` - -Per aggiornare lo stato alla fine del lavoro: - -```text -/handoff -``` +| Agente | Esempio | +| --- | --- | +| OpenCode | `/review` | +| Claude Code | `/dev-brain:review` | +| Codex CLI | `$dev-brain:review` | +| Cursor | `/review` | -I comandi sono strumenti di supporto, non una sequenza obbligatoria per ottenere codice curato. Usa `/plan`, `/impact`, `/learn` e `/review` quando servono. Le spiegazioni dettagliate restano su richiesta e nessun commit è autorizzato da questi comandi. +Sequenza tipica per un progetto adottato: `start` la prima volta, poi `resume` → lavoro → `review` → `handoff`. --- ## 1. Cos'è -dev-brain è un harness personale per OpenCode V2. Non è un'applicazione e non è un agente autonomo: è un insieme di istruzioni, comandi, skill e un piccolo plugin che rende il lavoro con OpenCode più prevedibile e continuo tra sessioni e repository. +dev-brain è un harness personale per agenti di coding. Non è un'applicazione e non è un agente autonomo: è un insieme di regole, workflow, skill, un reviewer e un meccanismo di stato. Rende il lavoro più prevedibile e continuo tra sessioni, repository e strumenti. -Il suo obiettivo principale è aiutarti a produrre **codice leggibile, manutenibile e facile da modificare**; gestione dello stato, comandi e skill servono a sostenere questo obiettivo. Le regole di progettazione valgono anche per una normale richiesta di codice: non devi ricordarti di lanciare `/plan` o una skill. Sono indipendenti dal linguaggio: Python va bene, ma il kit si adatta anche agli altri linguaggi e framework del progetto. +L'obiettivo principale è **codice leggibile, manutenibile e facile da modificare**. Stato e workflow servono a sostenerlo. Fornisce: - regole sempre attive, volutamente poche; -- sette comandi per il flusso ricorrente; -- tre skill caricate solo quando servono; +- sette workflow invocati da te: `start`, `resume`, `handoff`, `plan`, `impact`, `learn`, `review`; +- tre skill che il modello carica quando servono: `debugging`, `review-feedback`, `engineering-risk`; - un reviewer indipendente in sola lettura; -- un plugin che inietta lo stato del progetto nel contesto del modello; -- un metodo di valutazione per capire se una regola funziona davvero. +- lo stato del progetto iniettato nel contesto, con un budget di dimensione; +- un controllo offline a costo zero e un metodo di valutazione per capire se una regola funziona davvero. Non fa queste cose: -- non avvia modifiche autonomamente: è l'agente OpenCode a implementare ciò che chiedi, entro l'ambito autorizzato; - non decide quando committare; -- non sostituisce git, i test o la revisione umana; -- non garantisce che il modello segua le regole: le regole sono contesto, non un sistema di permessi. +- non sostituisce git, i test o la tua revisione; +- non garantisce che il modello segua le regole: le regole sono contesto. Dove l'agente lo permette (permessi, sandbox), alcune cose sono anche imposte; vedi sezione 2. -### Cosa cambia in OpenCode +--- -| Componente | Effetto | -| --- | --- | -| `~/.config/opencode/AGENTS.md` | Regole personali caricate in ogni sessione | -| `~/.config/opencode/commands/` | Comandi slash disponibili nella TUI | -| `~/.config/opencode/agents/reviewer.md` | Subagente di review in sola lettura | -| `~/.config/opencode/skills/` | Skill disponibili su richiesta | -| `~/.config/opencode/opencode.json` | Registrazione del plugin `dev-brain` | -| `.dev-brain/STATE.md` in ogni repo | Stato del progetto iniettato dal plugin | +## 2. Come è costruito + +**`core/` è l'unica fonte.** Usa i due formati che tutti gli agenti condividono: + +- `AGENTS.md` per le regole; +- Agent Skills (`SKILL.md`) per workflow e skill. + +`install.py` collega o traduce `core/` in ciò che ogni agente legge. Nessuna regola vive negli adattatori: se cambi una regola in `core/`, cambia per tutti. + +| | OpenCode | Claude Code | Codex CLI | Cursor | +| --- | --- | --- | --- | --- | +| Regole globali | `AGENTS.md` (link) | `CLAUDE.md` importa `core/AGENTS.md` | `AGENTS.md` (link) | `rules/dev-brain.mdc` (copia) | +| Workflow | comandi `/review` | plugin, `/dev-brain:review` | plugin, `$dev-brain:review` | skill, `/review` | +| Skill | `skills/` (link) | plugin | plugin | `skills/` (link) | +| Reviewer in sola lettura | **imposto**: solo `git diff/log/show/status`, `>` e `--output` bloccati | **imposto**: altri comandi chiedono la tua approvazione | **solo istruzione**: `sandbox_mode` non vale per i subagenti (Codex 0.164) | `readonly: true` (non provato) | +| Stato nel contesto | plugin, a ogni chiamata della sessione principale | hook `SessionStart` | hook `SessionStart`, dopo che lo approvi una volta | hook `sessionStart` (bug di Cursor) + regola di riserva | + +**Regola di riserva:** se l'agente non riesce a iniettare lo stato, le regole globali gli dicono di leggere `.dev-brain/STATE.md` prima di continuare un lavoro iniziato. Funziona con qualsiasi agente che legge `AGENTS.md`, ma costa una lettura e dipende dal modello. + +**Perché Claude Code e Codex usano un plugin:** è l'unico canale che porta skill, workflow e hook senza toccare le loro impostazioni a mano, ed è namespaced (`dev-brain:`), quindi non collide con i comandi integrati come `/review`. L'installer costruisce un marketplace locale in `build/` e lo installa con la CLI dell'agente. Codex copia il plugin e ignora i link simbolici, per questo il build contiene copie vere. --- -## 2. Installazione e verifica +## 3. Installazione e verifica ### Prerequisiti -- OpenCode V2 installato e funzionante (`opencode --version`); -- `bash`; -- `git`; -- `python3` — serve solo all'installer per aggiornare `opencode.json`, non a runtime. +- almeno uno tra OpenCode V2, Claude Code, Codex CLI, Cursor; +- `python3` e `git`. ### Installazione ```bash cd -./install.sh +./install.sh # agenti trovati: CLI nel PATH o cartella di configurazione presente +./install.sh opencode codex # solo questi ``` Lo script: -1. crea i collegamenti simbolici da `global/` a `~/.config/opencode/`; -2. registra il percorso assoluto del plugin in `~/.config/opencode/opencode.json`; -3. se trova un file già esistente e non gestito dal kit, lo sposta in `*.bak.` invece di cancellarlo; -4. è idempotente: eseguirlo di nuovo non duplica nulla. +1. collega le regole o le traduce nel formato dell'agente; +2. genera comandi, agenti e hook dove servono; +3. per Claude Code e Codex costruisce e installa il plugin `dev-brain`; +4. se trova un file non gestito dal kit, lo sposta in `*.bak.` invece di cancellarlo; +5. è idempotente: rieseguirlo non duplica nulla. -Non riavvia il server e non modifica le tue permission. +Passi manuali, una volta sola: -### Verifica +- **OpenCode:** `opencode service restart` quando non hai sessioni attive, altrimenti il server usa i template in cache. +- **Codex:** approva l'hook `SessionStart` nella TUI. Codex non esegue hook nuovi finché non li hai rivisti. +- **Cursor:** se l'agente ignora le regole, incolla `core/AGENTS.md` in Settings > Rules. Le regole globali su file non sempre vengono caricate (bug noto di Cursor). -```bash -opencode plugin list -opencode debug agents -opencode api GET /api/command -``` - -Risultati attesi: - -- `dev-brain` compare tra i plugin, con sorgente `local`; -- `reviewer` compare tra gli agenti, in modalità `subagent`; -- i sette comandi compaiono nell'elenco, oltre ai comandi integrati di OpenCode. - -Se i comandi non compaiono nella TUI: +### Verifica ```bash -# quando non hai sessioni attive -opencode service restart +python3 evals/offline/check.py ``` -Poi apri una nuova sessione. +Deve stampare `ALL PASS`. Verifica ogni agente installato senza spendere token (sezione 12). ### Aggiornamento ```bash -cd git pull ./install.sh ``` -Le modifiche ai file già collegati (regole, comandi, skill, reviewer) passano dai symlink. Se aggiungi un nuovo comando, agente o skill, riesegui `install.sh` per creare il nuovo collegamento. Se modifichi il plugin o un comando, riavvia il server: il server in esecuzione può usare il template in cache e la modifica non avrebbe effetto. +Rieseguire l'installer serve sempre: Codex e Cursor ricevono copie, e il plugin cambia versione quando cambia il contenuto. ### Disinstallazione -Non c'è uno script di disinstallazione. Per rimuovere il kit: +Non c'è uno script. In breve: -```bash -rm ~/.config/opencode/AGENTS.md -rm ~/.config/opencode/commands/{start,resume,handoff,plan,impact,learn,review}.md -rm ~/.config/opencode/agents/reviewer.md -rm -r ~/.config/opencode/skills/{debugging,review-feedback,engineering-risk} -``` +- OpenCode: rimuovi `AGENTS.md`, `commands/{start,resume,handoff,plan,impact,learn,review}.md`, `agents/reviewer.md`, `skills/{debugging,review-feedback,engineering-risk}` da `~/.config/opencode/` e il percorso del plugin da `opencode.json`; +- Claude Code: `claude plugin uninstall dev-brain@dev-brain` e togli la riga `@.../core/AGENTS.md` da `~/.claude/CLAUDE.md`; +- Codex: `codex plugin remove dev-brain@dev-brain`, rimuovi `~/.codex/AGENTS.md`, `~/.codex/agents/reviewer.toml` e la voce `dev-brain-context` da `~/.codex/hooks.json`; +- Cursor: rimuovi `~/.cursor/rules/dev-brain.mdc`, `~/.cursor/agents/reviewer.md`, i link in `~/.cursor/skills/` e la voce `dev-brain-context` da `~/.cursor/hooks.json`. -Poi togli il percorso del plugin da `~/.config/opencode/opencode.json`. Se l'installer aveva creato dei backup `*.bak.`, ripristinali manualmente. I file dentro i repository (`.dev-brain/STATE.md` e le sezioni dev-brain di `AGENTS.md`) restano: rimuovili solo se vuoi disadottare quei repository. +Ripristina eventuali backup `*.bak.`. I file nei repository (`AGENTS.md`, `.dev-brain/STATE.md`) restano. --- -## 3. Prima adozione di una repository +## 4. Prima adozione di una repository -Nella repository, dalla radice: - -```text -/start -``` - -Il comando è pensato per l'adozione iniziale. Ispeziona il repository e crea o aggiorna due file: +Lancia il workflow `start` nella radice della repository. Crea o aggiorna due file: ```text / ├── AGENTS.md fatti del progetto, meno di 60 righe └── .dev-brain/ - └── STATE.md obiettivo, fatto, blocchi, prossime azioni + └── STATE.md obiettivo, fatto, blocchi, prossime azioni, meno di 3000 caratteri ``` Cosa fa: - legge codice, configurazione, README e comandi reali; -- se `AGENTS.md` esiste, lo integra preservando le istruzioni già presenti; +- se `AGENTS.md` esiste, lo integra preservando le istruzioni presenti; - se `.dev-brain/STATE.md` esiste, lo riconcilia invece di sovrascriverlo; -- se trova file del vecchio kit (`harness/PROJECT_STATE.md`, `harness/PROJECT_MAP.md`, `NOW.md`, `RULES.md`), li usa come fonte: porta i fatti ancora veri in `AGENTS.md` e solo obiettivo, ultima evidenza e prossima azione nello stato. Non li cancella: te li elenca; -- tiene lo stato sotto i 3000 caratteri, perché il plugin lo inietta in ogni chiamata al modello; -- riporta fatti osservati, incognite, file legacy da eliminare e problemi trovati; -- non modifica codice, dipendenze, configurazione o storia git. - -Cosa non fa: +- se trova file del vecchio kit (`harness/PROJECT_STATE.md`, `harness/PROJECT_MAP.md`, `NOW.md`, `RULES.md`), li usa come fonte e te li elenca da eliminare, senza cancellarli; +- riporta fatti osservati, incognite, file legacy e problemi trovati; +- non modifica codice, dipendenze, configurazione o storia git, non installa nulla, non committa. -- non installa dipendenze; -- non esegue l'applicazione, migrazioni o conversioni; -- non committa; -- non decide al posto tuo se un problema va corretto. +**Esempio reale:** in hph i 21 KB di `harness/` sono diventati un `AGENTS.md` di 3,1 KB e uno stato di 1,3 KB. ### Privacy -Non aprire e non elencare directory che possono contenere dati personali, clinici o segreti, per esempio `input/`, `output/`, `.env`. Usa README e configurazione. Non copiare mai questi dati in `AGENTS.md`, in `STATE.md` o nella chat. +Non aprire e non elencare directory che possono contenere dati personali, clinici o segreti (`input/`, `output/`, `.env`). Usa README e configurazione. Non copiare mai questi dati in `AGENTS.md`, nello stato o nella chat: lo stato viene inviato al provider del modello. -### Dopo `/start` +### Dopo `start` -Leggi i due file generati e correggi ciò che non è vero. Sono pensati per essere versionati; se e quando decidi tu di committarli, puoi farlo separatamente dal codice. Questi sono comandi manuali, non un'autorizzazione automatica all'agente: +Leggi i due file e correggi ciò che non è vero. Sono pensati per essere versionati; se e quando decidi tu, committali separatamente dal codice: ```bash git diff -- AGENTS.md .dev-brain/STATE.md @@ -222,244 +189,116 @@ git add AGENTS.md .dev-brain/STATE.md git commit -m "Adopt dev-brain project instructions and state" ``` -Se hai lavoro non committato, `/start` non lo tocca. Un albero pulito rende però più chiara l'evidenza nello stato. - --- -## 4. Lavoro quotidiano +## 5. Lavoro quotidiano -Il lavoro principale resta una normale richiesta di implementazione o correzione, con il risultato atteso e gli eventuali vincoli. L'agente deve applicare le regole di progettazione sempre attive e rileggere il codice modificato prima di consegnarlo. Non è necessario lanciare tutti i comandi qui sotto. +Il lavoro principale resta una normale richiesta di implementazione o correzione, con risultato atteso e vincoli. I workflow sono strumenti di supporto, non una sequenza obbligatoria. -| Momento | Comando | Cosa ottieni | +| Momento | Workflow | Cosa ottieni | | --- | --- | --- | -| Prima volta in una repo | `/start` | `AGENTS.md` + `.dev-brain/STATE.md` | -| Inizio sessione | `/resume` | Stato riconciliato con git e codice | -| Modifica non banale | `/plan ` | Piano in massimo 5 passi, con verifiche | -| Prima di toccare codice condiviso | `/impact ` | Consumatori, contratti, test, incognite | -| Capire un flusso | `/learn ` | Spiegazione basata sul codice reale | -| Prima di committare | `/review [scope]` | Review indipendente del diff | -| Fine lavoro | `/handoff` | Stato aggiornato con evidenza fresca | - -Per un progetto adottato, una sequenza utile per la continuità è: - -```text -/resume → lavora → /handoff -``` - -### Un flusso tipico - -1. `/resume` — leggi obiettivo, ultimo risultato verificato, blocchi e prossima azione. -2. Se la modifica è non banale, `/plan` e poi `/impact`. +| Prima volta in una repo | `start` | `AGENTS.md` + `.dev-brain/STATE.md` | +| Inizio sessione | `resume` | Stato riconciliato con git e codice | +| Modifica non banale | `plan` | Piano in massimo 5 passi, con verifiche | +| Prima di toccare codice condiviso | `impact` | Consumatori, contratti, test, incognite | +| Capire un flusso | `learn` | Spiegazione basata sul codice reale | +| Prima di committare | `review` | Review indipendente delle modifiche | +| Fine lavoro | `handoff` | Stato aggiornato con evidenza fresca | + +Un flusso tipico: + +1. `resume`: obiettivo, ultimo risultato verificato, blocchi, prossima azione. +2. Se la modifica è non banale, `plan` e poi `impact`. 3. Implementa. -4. Fai eseguire i test o i controlli all'agente principale, oppure eseguili tu; il subagente reviewer non può lanciarli. -5. `/review` sul diff. -6. `/handoff` per chiudere lo stato. +4. Fai eseguire test e controlli all'agente principale, o eseguili tu: il reviewer non li lancia. +5. `review`. +6. `handoff`. 7. Committa solo se hai deciso di farlo. --- -## 5. I comandi in dettaglio - -### `/start` - -**Quando:** prima adozione di una repository, o quando vuoi riallineare i fatti del progetto. +## 6. I workflow in dettaglio -**Cosa produce:** root `AGENTS.md` e `.dev-brain/STATE.md`. +Ogni workflow è una skill in `core/workflows//SKILL.md` con `disable-model-invocation: true`: parte solo quando lo chiedi tu. Il testo che scrivi dopo il nome del workflow è l'argomento (obiettivo, area, scope). -**Scrive:** sì, solo quei due file (o li aggiorna). +### `start` -**Non fa:** modifiche al codice, installazioni, conversioni, commit. +Prima adozione, o riallineamento dei fatti del progetto. **Scrive:** solo `AGENTS.md` e `.dev-brain/STATE.md`. Dettagli nella sezione 4. -**Consiglio:** controlla che i comandi nel file siano quelli veri, che non ci siano path assoluti e che lo stato non contenga dati sensibili. - ---- - -### `/resume` +### `resume` **Quando:** all'inizio di una sessione, soprattutto dopo una pausa. -**Cosa fa:** - -- legge `.dev-brain/STATE.md` e `AGENTS.md`; -- confronta lo stato con `git status`, gli ultimi commit e i file reali; +- legge stato e `AGENTS.md`, esegue `git status` e `git log`; - se lo stato è vecchio, lo dice prima di proseguire; -- esegue un controllo registrato solo se è sicuro e in sola lettura; +- esegue un controllo registrato solo se è veloce e in sola lettura. Riporta come `NOT RUN`, senza eseguirlo, ciò che installa, scarica, compila o crea ambienti (`uv sync`, `pip install`, `npm install`, `uv run` senza `.venv`, `cargo test`, build complete); - riporta obiettivo, ultimo risultato verificato, blocchi e una prossima azione. -**Scrive:** no. - -**Non fa:** non implementa e non aggiorna lo stato; per quello c'è `/handoff`. +**Scrive:** no. È un'istruzione al modello, non un blocco tecnico. -**Nota:** i risultati vecchi non vengono presentati come appena eseguiti. +### `handoff` -Il comando esegue solo controlli veloci e in sola lettura. Riporta come `NOT RUN`, senza eseguirlo, tutto ciò che installa, scarica, compila o crea ambienti e cache: `uv sync`, `pip install`, `npm install`, `uv run` senza `.venv`, `cargo test`/`cargo build`, build complete. Vale per ogni stack, non solo Python. È un'istruzione al modello, non un blocco tecnico. +**Quando:** alla fine di un lavoro significativo. ---- - -### `/handoff` - -**Quando:** alla fine di un lavoro significativo, prima di chiudere la sessione o cambiare contesto. - -**Cosa fa:** - -- legge lo stato attuale; - ricostruisce cosa è successo davvero da diff, controlli e conversazione; -- riscrive `.dev-brain/STATE.md`: obiettivo, fatto con evidenza, blocchi, prossime azioni; -- aggiorna `AGENTS.md` solo se è cambiato un fatto stabile (stack, comandi, architettura, gotcha); -- riporta cosa ha cambiato e cosa non è verificato. - -**Scrive:** sì, lo stato (e raramente `AGENTS.md`). +- riscrive lo stato: obiettivo, fatto con evidenza (massimo 5), blocchi, prossime azioni (massimo 3), meno di 3000 caratteri; +- aggiorna `AGENTS.md` solo se è cambiato un fatto stabile. -**Non fa:** non committa e non modifica il codice. +**Scrive:** lo stato. Non committa. Lo stato non è un diario: sostituisci le righe vecchie. -**Regola:** massimo 5 voci in “Fatto”, massimo 3 in “Prossime azioni”, meno di 3000 caratteri in tutto. Lo stato non è un diario: sostituisci le righe vecchie. +### `plan` ---- +**Quando:** una modifica non banale, prima di scrivere codice. Produce un piano-contratto in sola lettura, massimo 5 passi. Ogni passo è un risultato concreto con file o simboli, input → output, dipendenze e un controllo che può fallire. Le decisioni che cambiano comportamento o dati ti vengono chieste prima. -### `/plan ` +Non cambia agente: dopo il piano puoi chiedere subito di implementare. Prima, in OpenCode, la sessione restava bloccata in modalità `plan`. -**Quando:** una modifica non banale, prima di scrivere codice. +### `impact` -**Cosa fa:** gira con l'agente `plan`, in sola lettura, e produce un piano-contratto con al massimo 5 passi. Ogni passo è un risultato concreto, non un'attività generica, e include: +**Quando:** prima di cambiare un contratto, un formato, un dato persistito o codice condiviso. Analisi in sola lettura di consumatori, contratti a rischio, test e configurazione, file da modificare e da rivedere, controlli esistenti, incognite. Etichette `OBSERVED`, `INFERRED`, `UNKNOWN`. -- file o simboli coinvolti; -- input → output; -- dipendenze; -- controllo che può fallire e risultato atteso. - -**Scrive:** no. - -**Consiglio:** indica obiettivo, vincoli e criteri di accettazione. Se una decisione cambia comportamento o dati, il piano deve chiedertela prima. - -**Nota:** dopo `/plan` la sessione resta sull'agente `plan` (verificato su OpenCode 2.1.4): se chiedi di implementare, rifiuta. Riseleziona `build` prima di implementare. - ---- +### `learn` -### `/impact ` - -**Quando:** prima di cambiare un contratto, un formato, un dato persistito o codice condiviso. - -**Cosa fa:** analisi in sola lettura di: - -- consumatori diretti: chiamanti, import, endpoint, eventi, query, formati; -- contratti a rischio: firme, errori, effetti collaterali, invarianti, configurazione, schema; -- test, fixture e configurazione che descrivono il comportamento attuale; -- file da modificare e file da rivedere; -- controlli esistenti, senza eseguirli; -- incognite e il più piccolo esperimento per risolverle. - -**Scrive:** no. - -**Etichette:** `OBSERVED` (visto nel codice), `INFERRED` (dedotto), `UNKNOWN`. Una dipendenza dichiarata non prova un collegamento attivo. - ---- - -### `/learn ` - -**Quando:** devi capire un flusso, un componente o uno stack che non conosci. - -**Cosa fa:** legge il codice reale e procede per strati: - -1. ambito e responsabilità; -2. inventario di file e simboli; -3. connessioni reali; -4. un flusso concreto, passo per passo; -5. ordine di lettura. - -**Scrive:** no. - -**Formato delle connessioni:** +**Quando:** devi capire un flusso, un componente o uno stack nuovo. Procede per strati: ambito, inventario, connessioni reali, un flusso concreto, ordine di lettura. Formato: ```text Flow: -> : -> : ``` -**Etichette:** `OBSERVED`, `INFERRED`, `UNKNOWN`. Non è un tutorial generico: se una cosa non è stata verificata, lo dice. - ---- - -### `/review [scope]` +### `review` **Quando:** prima di committare o aprire una PR. -**Cosa fa:** - -- cattura solo `git status` e `git diff HEAD --stat`: nomi dei file e conteggi, non il contenuto; -- delega la review al subagente `reviewer`, che è indipendente e in sola lettura, e legge da solo le modifiche con git; +- l'agente principale esegue `git status` e `git diff HEAD --stat`: nomi e conteggi, non il contenuto; +- delega al reviewer, che legge da solo le modifiche con git; - riporta i risultati senza ammorbidirli. -Senza scope copre tutte le modifiche non committate: in staging, non in staging e file nuovi non tracciati. Con uno scope (per esempio “ultimo commit”) il reviewer usa `git show` o `git log`. - -**Perché così:** prima il diff completo entrava nel contesto principale, il modello lo ricopiava come output nel prompt del subagente e il reviewer lo rileggeva. Il diff si pagava tre volte. Su un diff di 5,9 KB in hph il messaggio di `/review` è passato da 7005 a 1101 caratteri, e la copia in output è sparita. - -**Scrive:** no. - -**Non fa:** non modifica file, non committa e non esegue test. - -**Cosa cerca il reviewer:** - -- difetti di correttezza, sicurezza, integrità dei dati o requisiti dichiarati, separati da problemi concreti di manutenibilità; -- `file:line`, trigger concreto o scenario di manutenzione, impatto, correzione minima; -- difetti confermati separati da sospetti che richiedono contesto; -- test che provano davvero il comportamento e fallirebbero sul difetto originale. +Senza scope copre tutto ciò che non è committato: in staging, non in staging e file nuovi. Con uno scope (per esempio “ultimo commit”) il reviewer usa `git show` o `git log`. -**Permessi del reviewer:** niente modifiche ai file. La shell accetta solo `git diff`, `git log`, `git show` e `git status`. Sono bloccati `>`, `--output` e qualsiasi comando concatenato (`;`, `&&`, `|`, `$()`) che contenga altro. Verificato su OpenCode 2.1.4: OpenCode non blocca da solo la redirezione `>`, per questo c'è una regola esplicita. - -**Limiti importanti:** - -- il reviewer non può eseguire test o build: li esegue l'agente principale o li lanci tu; -- i file ignorati da git non entrano automaticamente nella review; -- il comportamento con un modello reale non è stato rimisurato dopo questa modifica: il flusso è verificato con un modello finto (`evals/offline/check.py`), non la qualità dei finding. +**Perché così:** prima il diff completo entrava nel contesto principale, veniva ricopiato come output nel prompt del subagente e riletto dal reviewer: si pagava tre volte. Su un diff di 5,9 KB in hph il messaggio di review è sceso da 7005 a 1101 caratteri. --- -## 6. I due file di progetto +## 7. I due file di progetto ### `AGENTS.md` -È il file dei fatti stabili del progetto. OpenCode lo carica come istruzioni. Deve restare sotto le 60 righe. - -Contenuto consigliato: +Tutti e quattro gli agenti lo leggono nella radice del progetto. Contiene solo fatti che l'agente non può dedurre in fretta: ```markdown # - ## Stack -- - -## Comandi -- Install: `` (dalla directory `<...>`) -- Test: `` -- Lint / type check: `` -- Build: `` - +## Comandi (con directory ed effetti collaterali) ## Struttura -- `` — - ## Convenzioni e gotcha -- -- - ## Da non fare -- ``` -Regole: - -- niente consigli generici: le regole globali ci sono già; -- comandi esatti, con directory di lavoro ed effetti collaterali; -- niente path assoluti della tua macchina; -- niente segreti, PHI o dati personali; -- aggiornalo solo quando cambia un fatto stabile, non a ogni modifica. +Meno di 60 righe. Niente consigli generici (stanno nelle regole globali), niente path assoluti della tua macchina. ### `.dev-brain/STATE.md` -È lo stato di lavoro del progetto. Va nella radice della repository ed è pensato per essere versionato; il commit resta una tua decisione esplicita, mai una conseguenza automatica di `/start` o `/handoff`. - -Template: - ```markdown # State — Updated: · Branch: @@ -471,7 +310,7 @@ Updated: · Branch: - — evidence: PASS|FAIL|NOT RUN ## In progress / blockers -- — status: implemented|verified|blocked — +- — status: implemented|verified|blocked — ## Known pre-existing failures - — — since @@ -480,42 +319,33 @@ Updated: · Branch: 1. ``` -Regole: - -- il plugin lo inietta solo se resta sotto i 3000 caratteri: oltre arriva un avviso al posto del contenuto; -- “Fatto” massimo 5 voci, “Prossime azioni” massimo 3; -- ogni voce “Fatto” ha un comando e un esito reale; -- `PASS` significa eseguito e passato; `NOT RUN` significa non eseguito; non usare “implementato” come se fosse “verificato”; -- sostituisci le righe vecchie, non aggiungerne di nuove in coda; -- non inserire dati sensibili: lo stato viene inviato al provider del modello e finisce nel repository; -- una sola sessione alla volta dovrebbe fare `/handoff`, per evitare sovrascritture. - -Lo stato è contesto, non prova e non autorizzazione: l'agente deve sempre verificare con git e con il codice. +Regole: meno di 3000 caratteri (oltre viene iniettato solo un avviso); ogni voce “Done” ha un comando e un esito reale; `PASS` significa eseguito e passato; sostituisci le righe vecchie; niente dati sensibili; una sola sessione alla volta fa `handoff`. --- -## 7. Il plugin +## 8. Lo stato nel contesto dell'agente + +Uno script unico, `core/bin/dev-brain-context`, produce il testo per tutti gli agenti: -Il plugin `plugin/dev-brain/index.ts` fa quattro cose. +- con uno stato valido: un blocco `` con l'avviso che è contesto, non prova né permesso; +- oltre i 3000 caratteri: una riga che dice al modello di leggerlo quando serve e di proporti `handoff` per compattarlo. Non viene troncato, perché il taglio eliminerebbe proprio “Next”, che sta in fondo; +- in una repo git senza stato: una riga che suggerisce `start`, senza creare nulla; +- fuori da una repo: niente. -1. **Iniezione dello stato.** A ogni chiamata al modello della sessione principale legge `.dev-brain/STATE.md` nella radice del progetto e lo aggiunge al contesto di sistema. L'iniezione è transitoria: non modifica il file e non serve ripetere lo stato nella chat. I subagenti (reviewer, explore, general) non lo ricevono: lavorano sul compito che il chiamante gli passa, e lo stato costerebbe token a ogni loro chiamata. -2. **Budget.** Se lo stato supera i 3000 caratteri non viene iniettato: al suo posto arriva una riga che dice al modello di leggerlo quando serve e di proporti `/handoff` per compattarlo. Non viene troncato, perché il taglio eliminerebbe proprio “Next”, che sta in fondo. -3. **Repository senza stato.** Se la repository è git e il file non esiste, aggiunge una sola riga che suggerisce `/start`. Non crea il file da solo. -4. **Compaction.** Quando la sessione viene compattata, chiede al riassunto di conservare obiettivo, evidenza verificata, blocchi e prossima azione. Lo stato viene comunque reiniettato alla chiamata successiva. +Come arriva all'agente: -Dettagli: +- **OpenCode:** il plugin lo aggiunge a ogni chiamata della sessione principale; i subagenti non lo ricevono. Rilegge il file solo quando cambia. In compattazione chiede al riassunto di conservare obiettivo, evidenza, blocchi e prossima azione. +- **Claude Code:** hook `SessionStart` all'avvio, al resume, dopo `/clear` e dopo la compattazione. +- **Codex:** stesso hook, dopo la tua approvazione nella TUI. +- **Cursor:** hook `sessionStart`. Cursor ha un bug aperto che scarta questo contesto, quindi vale la regola di riserva. -- il file va nella radice del repository, non in una sottocartella; -- oltre i 3000 caratteri viene iniettato solo l'avviso, non il contenuto; -- il plugin non fa chiamate di rete proprie, ma lo stato entra nella richiesta al provider del modello: non metterci segreti o PHI; -- i subagenti ricevono le regole globali e l'`AGENTS.md` del progetto, ma non lo stato; -- per disattivare l'iniezione in una repository, rimuovi o rinomina `.dev-brain/STATE.md`. Le regole globali restano attive e, se la repo è git, il plugin continuerà a suggerire `/start` finché il file manca. +Per disattivarlo in una repository, rinomina `.dev-brain/STATE.md`. --- -## 8. Regole, permessi e sicurezza +## 9. Regole, permessi e sicurezza -Le regole globali vivono in `global/AGENTS.md` e vengono installate come `~/.config/opencode/AGENTS.md`. +Le regole globali vivono in `core/AGENTS.md`. ### Precedenza @@ -525,335 +355,163 @@ correttezza > sicurezza e integrità dei dati > compatibilità col progetto > ma ### Qualità del codice, sempre attiva -Quando chiedi di scrivere o modificare codice, l'agente deve: - -- scegliere la soluzione più semplice che soddisfa davvero i requisiti, non quella con meno righe; niente funzionalità o punti di estensione ipotetici; -- seguire gli idiomi del linguaggio e le convenzioni del progetto, senza imporre classi, framework o livelli architetturali; -- usare nomi che esprimono l'intento, responsabilità coese, dipendenze ed effetti collaterali espliciti; dividere per responsabilità, non per limiti arbitrari di righe; -- mantenere in un solo punto le stesse regole di business, ma non accoppiare concetti diversi solo perché il codice si assomiglia; -- preservare contratti e gestione degli errori, senza nascondere fallimenti dietro fallback silenziosi; commentare motivazioni e vincoli non ovvi, non la sintassi; -- rileggere il codice modificato prima di consegnarlo, cercando complessità inutile, duplicazioni, nomi fuorvianti, effetti nascosti e debug dimenticato, senza avviare un refactor estraneo alla richiesta. - -Questo controllo sul codice non comporta una spiegazione lunga in output: il walkthrough resta su richiesta. Le regole guidano il modello, non garantiscono da sole un risultato migliore. Test funzionali e valutazione della manutenibilità restano due verifiche diverse. +- la soluzione più semplice che soddisfa davvero i requisiti, non quella con meno righe; niente funzionalità ipotetiche; +- idiomi del linguaggio e convenzioni del progetto, senza imporre classi o livelli; +- nomi che esprimono l'intento, responsabilità coese, effetti espliciti; divisione per responsabilità; +- una sola fonte per la stessa regola di business, senza accoppiare concetti diversi solo perché il codice si assomiglia; +- contratti e gestione degli errori preservati, niente fallback silenziosi; +- rilettura del codice modificato prima della consegna, senza refactor estranei. ### Autorizzazione - leggere o adottare una repository non autorizza modifiche; -- non creare, emendare o pushare un commit se non hai deciso tu esplicitamente di committare; implementare, correggere, testare, fare review o handoff non è un permesso di commit; -- nessun cambio di branch, operazione distruttiva, migrazione, deploy o pubblicazione senza un permesso esplicito per quell'azione; -- `/handoff` aggiorna lo stato, non autorizza un commit; -- preserva il lavoro non committato; niente pulizie o riformattazioni non richieste; -- non leggere e non elencare file che possono contenere segreti, dati personali o clinici senza necessità: usa documentazione e configurazione. - -### Test e debug - -- per un bug o un comportamento nuovo, se esiste un harness di test, prima guarda fallire un test mirato per il motivo giusto; -- un errore di setup non è evidenza del difetto; -- annota i fallimenti preesistenti e non attribuirli alla tua modifica; -- dopo 3 tentativi materialmente equivalenti falliti, fermati e riporta cosa hai imparato; -- per un bug non banale carica la skill `debugging`; per sicurezza, persistenza, concorrenza o prestazioni carica `engineering-risk`. +- nessun commit, amend o push se non lo decidi tu; implementare, testare, fare review o handoff non è un permesso di commit; +- nessun cambio di branch, operazione distruttiva, migrazione, deploy o pubblicazione senza un permesso esplicito; +- il lavoro non committato si preserva; niente pulizie non richieste; +- niente letture di segreti, dati personali o clinici senza necessità. -### Reporting +### Test, debug e reporting -- ogni controllo va riportato come `PASS`, `FAIL`, `NOT RUN` o `N/A`, con il comando reale; -- una build non è comportamento; un mock non è verifica dal vivo; -- “implementato” non significa “verificato”; -- chiudi con ciò che non hai controllato. - -### Spiegazione delle modifiche - -Non viene aggiunta automaticamente: consuma token di output. L'agente la produce solo se la chiedi esplicitamente (per esempio “spiega la modifica”, “walkthrough”, “Flow/Why/Checks/Read next”). In caso contrario riporta in modo conciso cosa ha cambiato, i controlli eseguiti e cosa non ha controllato. - -Quando la chiedi, il formato è: - -```text -Flow: -> : -> : -Why: -Checks: - ; prova , non -Read next: - -``` - -### Continuità - -- a fine lavoro aggiorna `.dev-brain/STATE.md` o chiedi `/handoff`; -- aggiorna `AGENTS.md` solo per fatti stabili; -- non importare evidenza, permessi o lavoro attivo da un'altra repository. +- per un bug o un comportamento nuovo, prima un test mirato che fallisce per il motivo giusto; +- dopo 3 tentativi equivalenti falliti, fermarsi e riportare; +- ogni controllo come `PASS`, `FAIL`, `NOT RUN` o `N/A`, con il comando reale; “implementato” non è “verificato”; +- la spiegazione dettagliata (Flow / Why / Checks / Read next) solo se la chiedi: consuma token. ### Cosa significa “permesso” -Significa che hai chiesto esplicitamente quell'azione. Non basta che l'azione sia utile o coerente con l'obiettivo. `--auto` elimina le richieste di conferma: usalo solo su fixture usa e getta, mai su dati reali. - -Il kit non modifica le permission globali di OpenCode. Il reviewer ha shell ed edit negati dalla sua configurazione; gli altri agenti seguono le tue impostazioni. +Che hai chiesto esplicitamente quell'azione. Non basta che sia utile. Il kit non modifica le permission globali dei tuoi agenti: impone restrizioni solo al reviewer. --- -## 9. Le skill +## 10. Le skill -Le skill sono istruzioni specializzate che il modello carica quando il compito corrisponde alla descrizione. Non hanno comandi slash propri. +Il modello le carica quando il compito corrisponde alla descrizione; puoi anche chiederle per nome. -| Skill | Quando si carica | Cosa impone | +| Skill | Quando | Cosa impone | | --- | --- | --- | | `debugging` | Bug, test che fallisce, comportamento inatteso | Riprodurre, localizzare, ipotizzare, testare, correggere la causa, verificare | -| `review-feedback` | Commenti di review, feedback PR, findings di un altro agente | Classificare ogni commento prima di implementarlo | -| `engineering-risk` | Auth, input utente, segreti, dati persistiti, migrazioni, concorrenza, servizi esterni, prestazioni | Leggere solo il riferimento pertinente: sicurezza, dati, prestazioni | - -Per richiamarle esplicitamente puoi scrivere, per esempio: - -```text -Carica la skill debugging e usa il suo metodo. -``` - -`review-feedback` classifica ogni osservazione in: - -- `SUPPORTED` — il codice o il requisito confermano il problema: correggi con un controllo; -- `UNSUPPORTED` — il codice contraddice la tesi: rispondi con l'evidenza, non cambiare; -- `NEEDS CONTEXT` — manca l'intento: fai la domanda specifica; -- `OUT OF SCOPE` — valido ma estraneo: registralo e proponilo a parte. - ---- - -## 10. Il reviewer - -Il reviewer è un subagente indipendente, in sola lettura. Non ha shell e non può modificare file. - -Riporta difetti di correttezza, sicurezza, integrità dei dati o requisiti dichiarati e problemi concreti di manutenibilità. Tiene separate le due categorie: un costo futuro di manutenzione non è automaticamente un bug presente. Per ogni finding: - -- `file:line` e simbolo; -- trigger concreto: input, stato o sequenza che produce il problema, oppure la modifica o attività di debug resa più difficile; -- impatto; -- correzione minima; -- confidenza: confermato dal codice o sospetto che richiede contesto. - -Per la manutenibilità cerca regole di business duplicate, indirezioni non necessarie, responsabilità non correlate accoppiate o flussi che nascondono il contratto. Deve indicare il costo concreto e la semplificazione minima, non proporre un redesign. Non segnala preferenze cosmetiche su stile o nomi, né chiede di astrarre ogni somiglianza. Se non trova nulla che superi la soglia, dice “No correctness or maintainability findings”. +| `review-feedback` | Commenti di review o findings di un altro agente | Classificare ogni commento prima di implementarlo | +| `engineering-risk` | Auth, input, segreti, dati persistiti, migrazioni, concorrenza, servizi esterni, prestazioni | Leggere solo il riferimento pertinente | -Limiti: - -- non esegue test; -- il diff non contiene i file non tracciati; il comando ne passa anche i nomi e il reviewer li legge se sono nello scope, ma i file ignorati restano esclusi; -- non conosce l'intento se non è nel diff o nello scope; -- la sua review non sostituisce i tuoi controlli. +`review-feedback` classifica in `SUPPORTED` (correggi con un controllo), `UNSUPPORTED` (rispondi con l'evidenza), `NEEDS CONTEXT` (fai la domanda), `OUT OF SCOPE` (registra e proponi a parte). --- -## 11. Flussi di lavoro tipici - -### Repository nuova - -```text -/start -# leggi AGENTS.md e .dev-brain/STATE.md -# committa i due file separatamente solo se lo decidi tu -/resume -``` - -### Sessione quotidiana - -```text -/resume -# lavora -/handoff -``` - -### Modifica non banale - -```text -/plan -/impact -# implementa -# esegui i test -/review -/handoff -# commit manuale, se decidi -``` +## 11. Il reviewer -### Bug +Subagente indipendente, in sola lettura. Riporta difetti di correttezza, sicurezza, integrità dei dati o requisiti, separati dai problemi concreti di manutenibilità. Per ogni finding: `file:line`, trigger o scenario di manutenzione, impatto, correzione minima, confidenza. Niente preferenze cosmetiche. Se non trova nulla, lo dice. -```text -# descrivi sintomo e comando di riproduzione -# carica la skill debugging -# riproduci il fallimento -# test mirato che fallisce per il motivo giusto -# correggi la causa -# verifica -/handoff -``` +Quanto è davvero “in sola lettura” dipende dall'agente (verificato nel controllo offline): -### Feedback di review +- **OpenCode:** imposto. Sono permessi solo `git diff`, `git log`, `git show`, `git status`. Bloccati `>`, `--output` e i comandi concatenati che contengono altro. OpenCode non blocca da solo la redirezione `>`, per questo c'è una regola esplicita. +- **Claude Code:** imposto con una lista di strumenti. Ogni comando che crea o modifica file chiede la tua approvazione: rispondi no. +- **Codex:** solo istruzione. Il file del reviewer dichiara `sandbox_mode = "read-only"`, ma Codex 0.164 non lo applica ai subagenti generati: con il genitore in `workspace-write` il reviewer ha scritto un file nel test. +- **Cursor:** `readonly: true`, che secondo la documentazione blocca modifiche e comandi che cambiano lo stato. Non provato. -```text -# incolla o descrivi i commenti -# carica la skill review-feedback -# classifica ogni punto -# implementa solo i SUPPORTED -# riesegui i controlli -``` - -### Capire un flusso - -```text -/learn -# leggi l'ordine di lettura suggerito -# fai domande sulle parti UNKNOWN -``` +Non esegue test o build e non conosce l'intento se non è nello scope. --- ## 12. Manutenzione del kit -### Struttura del repository del kit +### Struttura ```text -global/ regole sempre attive, comandi, agenti, skill -plugin/ plugin OpenCode V2 -templates/ template di STATE.md e AGENTS.md -evals/ scenari, fixture, risultati misurati +core/ unica fonte: AGENTS.md, workflows/, skills/, agents/reviewer.md, bin/, templates/ +adapters/ codice specifico che non si può esprimere come file (plugin OpenCode) +install.py collega o traduce core/ per ogni agente; install.sh è un wrapper +evals/ scenari, fixture, risultati, controllo offline MANUALE.md questo manuale ``` ### Modificare il kit -1. Apri una modifica piccola e mirata. +1. Una modifica piccola e mirata, in `core/` se riguarda il comportamento del modello. 2. Se cambia il comportamento, esegui gli scenari in `evals/scenarios/` e registra il baseline. -3. Applica la modifica. -4. Riesegui gli stessi scenari. -5. Tieni la modifica solo se migliora uno scenario o rimuove un costo reale. -6. Registra l'esito in `evals/results.md` con data ed evidenza. - -Non aggiungere regole per intuizione. Una regola che il modello già segue è solo costo di contesto. - -### Evals +3. Applica la modifica e riesegui gli stessi scenari. +4. Esegui `python3 evals/offline/check.py`. +5. Tieni la modifica solo se migliora uno scenario o rimuove un costo reale; registra l'esito in `evals/results.md`. -```bash -# Solo dopo aver autorizzato i commit locali delle fixture: -./evals/setup.sh -# copia le fixture in /tmp/opencode/dev-brain-evals e ricrea la storia git -cd /tmp/opencode/dev-brain-evals/bugfix -opencode run --standalone -m "The discount test fails. Fix the code." -``` - -I comandi slash si provano dalla TUI, non con `opencode run`. Negli script chiudi lo stdin (`< /dev/null`): `opencode run` legge lo stdin quando non è un terminale e resta in attesa. +Non aggiungere regole per intuizione: una regola che il modello già segue è solo costo di contesto. Niente sintassi specifica di un agente in `core/` (`$ARGUMENTS`, espansioni `!`). ### Controllo offline, a costo zero ```bash -python3 evals/offline/check.py # OPENCODE= se non è nel PATH +python3 evals/offline/check.py # OPENCODE / CLAUDE / CODEX= se non sono nel PATH ``` -Installa il kit in una configurazione temporanea, sostituisce il modello con un finto server locale che registra ogni richiesta e verifica in circa 5 secondi, senza spendere token: +Per ogni CLI trovata installa il kit in una home temporanea e sostituisce il modello con un server locale finto che registra ogni richiesta. In circa 10 secondi, senza spendere token, verifica: -- lo stato arriva alla sessione principale e non ai subagenti; -- uno stato oltre il budget viene sostituito dall'avviso; -- il reviewer legge il diff con git ma non può scrivere (`>`, `--output`, `rm` concatenato). +- regole globali caricate; +- stato nella sessione principale (e non nei subagenti, in OpenCode); +- stato troppo lungo sostituito dall'avviso; +- workflow che si espandono; +- reviewer che legge il diff ma non scrive. -Non valuta la qualità delle risposte del modello: per quella restano gli scenari. Lancialo dopo ogni modifica a plugin, agenti o installer. +Per Cursor controlla solo i file generati. Non valuta la qualità delle risposte: per quella restano gli scenari. -`evals/setup.sh` ricrea la cartella di test e crea commit locali per gli scenari che richiedono una storia git. Lo scenario di manutenibilità (`evals/scenarios/maintainability.md`) può essere eseguito su copie nuove senza storia git e senza commit. Non eseguire il setup per il solo aggiornamento della documentazione. +### Scenari con un modello reale -### Lingua +```bash +# Solo dopo aver autorizzato i commit locali delle fixture: +./evals/setup.sh +cd /tmp/opencode/dev-brain-evals/bugfix +opencode run --standalone -m "The discount test fails. Fix the code." < /dev/null +``` -Tutto il contenuto del kit è in inglese, tranne questo manuale utente. +Negli script chiudi lo stdin (`< /dev/null`): `opencode run` legge lo stdin quando non è un terminale e resta in attesa. -### Backup e aggiornamenti +### Backup - i file non gestiti vengono salvati come `*.bak.`; -- se l'installer sposta un tuo `AGENTS.md`, unisci le tue regole in `global/AGENTS.md` o in un `AGENTS.md` di progetto; -- il plugin è registrato con un percorso assoluto: se sposti la cartella del kit, riesegui `install.sh`; -- non copiare fatti di progetto (stack, comandi, stato) nel repository del kit. - ---- - -## 13. Migrazione dal vecchio dev-brain - -La vecchia cartella visibile `dev-brain/` non esiste più in questo repository; il contenuto resta nella storia git al commit `08baebc`. - -Per ogni repository che aveva una copia: - -1. confronta il suo `RULES.md` con `global/AGENTS.md` e conserva solo le regole specifiche del progetto o realmente utili; -2. sposta i fatti stabili nel root `AGENTS.md`; -3. converti `NOW.md`, `PROJECT_STATE.md` e `PROJECT_MAP.md` in `.dev-brain/STATE.md` e nelle sezioni di `AGENTS.md`; -4. rimuovi i file del vecchio kit; -5. verifica che non ci siano istruzioni contraddittorie: le regole globali nuove si applicano comunque. - -Se una repository ha una cartella `harness/` con i vecchi `PROJECT_MAP.md` e `PROJECT_STATE.md`, quei file vanno trattati come il vecchio kit. `/start` li usa come fonte e te li elenca; li rimuovi tu, dopo aver controllato i due file nuovi. Esempio reale: in hph i 21 KB di `harness/` sono diventati un `AGENTS.md` di 3,1 KB e uno stato di 1,3 KB. - -Per recuperare il vecchio contenuto: - -```bash -git show 08baebc:dev-brain/RULES.md -git archive 08baebc dev-brain | tar -x -C /tmp -``` +- il kit è referenziato con percorso assoluto: se sposti la cartella, riesegui l'installer; +- non copiare fatti di progetto nel repository del kit. --- -## 14. Problemi e domande frequenti +## 13. Problemi e domande frequenti | Sintomo | Causa e soluzione | | --- | --- | -| I comandi non compaiono nella TUI, o una modifica a un comando non ha effetto | Apri una nuova sessione; se il server era già attivo, `opencode service restart` quando non hai sessioni attive | -| `opencode run "/resume"` non espande il comando | Limite della CLI: manda il testo letterale. Usa la TUI | -| `opencode run` in uno script resta fermo | Legge lo stdin quando non è un terminale: aggiungi `< /dev/null` | -| Il plugin non compare | Controlla `opencode.json`, il percorso assoluto e `opencode plugin list`; riavvia il server | -| Lo stato non viene iniettato | Verifica `.dev-brain/STATE.md` nella radice, non vuoto, sotto i 3000 caratteri (oltre arriva solo l'avviso); i subagenti non lo ricevono per scelta; apri una nuova sessione | -| L'installer ha spostato il mio `AGENTS.md` | Cerca `AGENTS.md.bak.` e unisci le tue regole | -| `opencode.json` non viene aggiornato | Probabilmente contiene commenti JSONC non gestiti: aggiungi a mano `"plugins": ["/plugin/dev-brain"]` | -| Edit o shell negati | La tua configurazione OpenCode o il reviewer possono negarli; il reviewer nega edit e ogni shell tranne `git diff/log/show/status`. `--auto` solo su fixture usa e getta | -| `/review` non trova il file nuovo | I file non tracciati compaiono in `git status`; il reviewer li legge se sono nello scope. Controlla che il server usi il template aggiornato e la copertura dichiarata dal reviewer | -| Dopo `/plan` l'agente resta `plan` | Comportamento atteso di OpenCode: riseleziona `build` prima di implementare | -| Lo stato cresce troppo | Il plugin smette di iniettarlo e lo segnala: compattalo con `/handoff` (5 voci fatte, 3 prossime azioni, meno di 3000 caratteri) | -| Due sessioni si sovrascrivono lo stato | Fai `/handoff` da una sola sessione alla volta | -| Il modello ignora lo stato | Lo stato è contesto, non enforcement: usa `/resume`, verifica con git e chiedi esplicitamente | -| Una sessione API non esegue un comando | Imposta `agent` e `model` alla creazione della sessione; è un limite del test via API, non della TUI | -| Ho dati clinici o segreti in `STATE.md` | Rimuovili subito, valuta la rotazione delle credenziali e non committare; lo stato viene inviato al provider | +| OpenCode: i comandi non compaiono o una modifica non ha effetto | `opencode service restart` quando non hai sessioni attive; apri una nuova sessione | +| OpenCode: `opencode run "/resume"` non espande il comando | Limite della CLI: usa la TUI | +| Uno script con `opencode run` resta fermo | Aggiungi `< /dev/null` | +| Claude Code: `/review` apre la review integrata | Usa `/dev-brain:review`: i comandi integrati hanno la precedenza | +| Codex: lo stato non arriva | Approva l'hook `SessionStart` nella TUI; nel frattempo vale la regola di riserva | +| Codex: dopo un aggiornamento vedo la versione vecchia | Riesegui `./install.sh codex`: Codex usa una copia del plugin | +| Cursor: le regole non vengono applicate | Incolla `core/AGENTS.md` in Settings > Rules | +| Lo stato non viene iniettato | Controlla che `.dev-brain/STATE.md` sia nella radice, non vuoto, sotto i 3000 caratteri; i subagenti non lo ricevono per scelta | +| Lo stato cresce troppo | Arriva solo l'avviso: compattalo con `handoff` | +| Il reviewer chiede di eseguire un comando che scrive | Rispondi no: il reviewer è in sola lettura | +| L'installer ha spostato un mio file | Cerca `.bak.` e unisci il contenuto | +| Un file JSON non viene aggiornato | Contiene commenti o non è JSON valido: l'installer non lo tocca e lo segnala; aggiungi la voce a mano | +| Ho dati clinici o segreti nello stato | Rimuovili subito, valuta la rotazione delle credenziali, non committare: lo stato viene inviato al provider | --- -## 15. Limiti noti - -- Le prove usano fixture piccole e pochi run; i risultati dipendono dal modello e non sono una garanzia per ogni progetto. Il dettaglio delle esecuzioni e dei modelli è in `evals/results.md`. -- Nella nuova prova di generazione il codice era già leggibile prima della modifica alle regole e lo è rimasto dopo: non è stato dimostrato un guadagno generale nella qualità del codice prodotto. -- La policy di review ora riconosce una regola di business duplicata come problema di manutenzione, senza proporre di unire politiche indipendenti. La prova era diretta sulla policy. Il percorso di delega di `/review` (comando → subagente → git) è verificato via API con un modello finto, non dalla TUI e non con un modello reale. -- Le regole sono indipendenti dal linguaggio, ma la nuova fixture di manutenibilità è solo Python: la generazione in altri linguaggi non è stata verificata in quella prova. -- Le regole sono contesto: il modello può non seguirle. I comandi e le skill mirano a ridurre la variabilità, non a eliminarla. -- `opencode run` non espande i comandi slash; il percorso previsto è la TUI. L'espansione è stata verificata via API, non pilotando la TUI automaticamente. -- Il reviewer non esegue test né build. Legge da solo diff e file non tracciati; i file ignorati da git restano fuori. -- `/resume` dipende dal rispetto delle istruzioni di sola lettura: la regola “niente install, download o compilazione” è un'istruzione al modello, non un blocco tecnico. La versione generica non è ancora stata provata con un modello reale. -- L'hook di compaction è verificato via API con un modello finto: il testo arriva alla richiesta di riassunto. La qualità del riassunto con un modello reale non è stata misurata. -- Lo stato può diventare vecchio: `/resume` lo riconcilia, ma non è una verità automatica. -- Nessun commit automatico: l'agente non crea, emenda o pusha commit senza la tua decisione esplicita. -- Lo stato viene iniettato a ogni chiamata della sessione principale: oltre i 3000 caratteri arriva solo un avviso. -- La spiegazione dettagliata è su richiesta: di default le risposte restano brevi. +## 14. Limiti noti + +- Le prove con modelli reali usano fixture piccole e pochi run; i risultati dipendono dal modello. Dettagli in `evals/results.md`. +- Il controllo offline verifica cosa il kit invia e permette, non la qualità delle risposte. +- La nuova architettura multi-agente non è ancora stata provata con un modello reale, né nelle TUI. +- Cursor non è stato eseguito: i suoi file sono generati secondo la documentazione e controllati solo per presenza. +- Codex: il reviewer in sola lettura è solo un'istruzione (`sandbox_mode` non applicato ai subagenti in 0.164). +- Le regole sono contesto: il modello può non seguirle. Workflow e skill riducono la variabilità, non la eliminano. +- `resume` dipende dal rispetto delle istruzioni di sola lettura. +- Codex elenca anche i workflow tra le skill (non rispetta `disable-model-invocation`): circa 1200 caratteri (~300 token) in più nel prompt di sistema. - Una sola sessione dovrebbe aggiornare lo stato alla volta. - Non c'è uno script di disinstallazione. -- Il percorso del plugin è assoluto: se sposti il kit, reinstalla. -- Richiede OpenCode V2; non è testato su V1. --- -## 16. Checklist +## 15. Checklist - [ ] `./install.sh` eseguito senza errori -- [ ] `opencode plugin list` mostra `dev-brain` -- [ ] `opencode debug agents` mostra `reviewer` -- [ ] `opencode api GET /api/command` elenca i sette comandi - [ ] `python3 evals/offline/check.py` stampa `ALL PASS` -- [ ] Le regole di progettazione sono presenti in `~/.config/opencode/AGENTS.md`; non servono comandi speciali per applicarle -- [ ] `/start` eseguito su almeno una repository +- [ ] OpenCode: server riavviato; Codex: hook approvato; Cursor: regole visibili in Settings +- [ ] `start` eseguito su almeno una repository - [ ] `AGENTS.md` sotto 60 righe, senza path assoluti né dati sensibili - [ ] `.dev-brain/STATE.md` sotto 3000 caratteri, con evidenza reale -- [ ] I due file di progetto revisionati; eventuale commit separato dal codice solo per tua decisione -- [ ] Nessun commit, amend o push eseguito dall'agente senza una tua decisione esplicita -- [ ] `/resume` e `/handoff` provati in una sessione reale -- [ ] `/review` provato sullo scope desiderato, controllando anche la copertura dei file nuovi -- [ ] Backup `*.bak.*` controllati dopo l'installazione +- [ ] I due file di progetto revisionati; eventuale commit separato, solo per tua decisione +- [ ] `resume`, `review` e `handoff` provati in una sessione reale con ogni agente che usi - [ ] Nessun dato clinico, personale o segreto in stato, istruzioni o chat - ---- - -## Riferimenti - -- `README.md` — installazione e panoramica in inglese -- `global/AGENTS.md` — regole sempre attive -- `global/commands/` — codice dei sette comandi -- `global/skills/` — skill e riferimenti -- `plugin/dev-brain/index.ts` — plugin -- `evals/results.md` — cosa è stato misurato e cosa no diff --git a/README.md b/README.md index 33751d4..3ae9be3 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,15 @@ # dev-brain -Personal engineering harness for OpenCode V2. One install, used across every repository. +Personal engineering harness for coding agents: **OpenCode, Claude Code, Codex CLI and Cursor**, with any model provider. One install, used across every repository. -Its primary goal is to guide normal coding requests toward readable, maintainable code, adapted to each project's language and conventions. Commands and saved state are supporting tools, not the purpose of the kit. +Its primary goal is to guide normal coding requests toward readable, maintainable code, adapted to each project's language and conventions. Workflows and saved state are supporting tools, not the purpose of the kit. It provides: - rules that are always loaded, kept short and limited to behavior the model would not follow by default; -- commands for the recurring workflow: start, resume, handoff, plan, impact, learn, review; +- user-invoked workflows: start, resume, handoff, plan, impact, learn, review; - an independent read-only reviewer; - three on-demand skills: debugging, review feedback, engineering risk; -- a small plugin that injects each project's saved state into the main session's model calls, within a size budget. +- the project's saved state injected into the agent's context, within a size budget. Project facts stay in each repository. Nothing from one project is reused in another. @@ -17,55 +17,57 @@ Project facts stay in each repository. Nothing from one project is reused in ano ## Code quality by default -The global rules apply to ordinary coding requests; no special command is required. They favor complete but simple solutions, cohesive responsibilities, explicit effects, intention-revealing names and a single source for shared business rules. They reject speculative abstractions, forced layering and silent error handling. Before delivery the agent checks its changed code for these problems without adding an unsolicited explanation. +The global rules apply to ordinary coding requests; no special workflow is required. They favor complete but simple solutions, cohesive responsibilities, explicit effects, intention-revealing names and a single source for shared business rules. They reject speculative abstractions, forced layering and silent error handling. Before delivery the agent checks its changed code for these problems without adding an unsolicited explanation. -These are language-independent criteria, not a Python style guide. The agent discovers the stack and follows its idioms. `/review` adds an independent check for defects and concrete maintenance costs, not cosmetic preferences. - -Describe the feature or bug, its constraints and the expected behavior. You do not need to repeat "write maintainable code", invoke a skill, or create a state file before these rules apply. +These are language-independent criteria, not a Python style guide. The agent discovers the stack and follows its idioms. The review workflow adds an independent check for defects and concrete maintenance costs, not cosmetic preferences. | Always active | Used when helpful | Requires your explicit decision | | --- | --- | --- | | Code-design guidance and self-review of changed code | Planning, impact analysis, independent review and session continuity | Commits, amendments and pushes; unrelated refactors, new dependencies or architecture changes must be proposed first | -Detailed change walkthroughs are on request only. A normal answer stays concise: what changed, checks actually run, and material limits. See [`global/AGENTS.md`](global/AGENTS.md) for the full rules. +Detailed change walkthroughs are on request only. See [`core/AGENTS.md`](core/AGENTS.md) for the full rules. Instructions guide the model; they do not guarantee good code. + +## How it is built + +`core/` is the only source. It uses the formats the agents share: `AGENTS.md` for rules and Agent Skills (`SKILL.md`) for workflows and skills. `install.py` links or translates it into what each agent reads; no rule lives in an adapter. + +| | OpenCode | Claude Code | Codex CLI | Cursor | +| --- | --- | --- | --- | --- | +| Global rules | `AGENTS.md` (link) | `CLAUDE.md` imports `core/AGENTS.md` | `AGENTS.md` (link) | `rules/dev-brain.mdc` (copy) | +| Workflows | commands `/review` | plugin `/dev-brain:review` | plugin skills `$dev-brain:review` | skills `/review` | +| Skills | `skills/` (links) | plugin | plugin | `skills/` (links) | +| Read-only reviewer | permissions: only `git diff/log/show/status`; `>` and `--output` denied | tools: Read, Grep, Glob, read-only git; other commands need your approval | `sandbox_mode = "read-only"`, **not enforced on spawned agents** (Codex 0.164): instruction only | `readonly: true` | +| Saved state | plugin, every main-session call | `SessionStart` hook | `SessionStart` hook, after you approve it once | `sessionStart` hook (Cursor bug drops it) + rule fallback | -Instructions guide the model; they do not guarantee good code. Behavioral tests and maintenance scenarios are evaluated separately in `evals/`. +When an agent cannot inject the state, the global rules tell it to read `.dev-brain/STATE.md` before continuing earlier work. The state text and its 3000-character budget come from one script, `core/bin/dev-brain-context`, used by every adapter. ## Install ```bash -./install.sh +./install.sh # every agent found on this machine +./install.sh opencode claude-code # or name them: opencode claude-code codex cursor ``` -The script symlinks the kit into `~/.config/opencode` and registers the plugin in `~/.config/opencode/opencode.json`: +Requires `python3` and `git`. Re-run it after pulling changes. Existing files that are not managed by this kit are moved to `*.bak.`, never deleted. -| Source | Destination | -| --- | --- | -| `global/AGENTS.md` | `~/.config/opencode/AGENTS.md` | -| `global/commands/*.md` | `~/.config/opencode/commands/` | -| `global/agents/*.md` | `~/.config/opencode/agents/` | -| `global/skills/*` | `~/.config/opencode/skills/` | -| `plugin/dev-brain` | registered in `opencode.json` | - -Existing files that are not managed by this kit are moved to `*.bak.`, never deleted. The script is idempotent. - -After installing, start a new session. If the background server was already running, restart it when no session is active (`opencode service restart`) so commands are reloaded. +- **OpenCode**: restart the background server when no session is active (`opencode service restart`). +- **Claude Code / Codex**: the installer builds a local plugin marketplace in `build/` and installs `dev-brain` from it with the agent's own CLI. +- **Codex**: approve the `SessionStart` hook once in the TUI; new hooks need review before they run. +- **Cursor**: if the agent ignores the rules, paste `core/AGENTS.md` into Settings > Rules (file-based global rules are not always loaded). ## Daily use -Ask OpenCode to implement or fix what you need, using the project's existing language and tools. The commands below support that work; they are not a mandatory sequence or a switch that enables code quality. +Ask the agent to implement or fix what you need. The workflows support that work; they are not a mandatory sequence or a switch that enables code quality. Invoke them with the agent's syntax from the table above (`/review`, `/dev-brain:review`, `$dev-brain:review`). -| Command | When | +| Workflow | When | | --- | --- | -| `/start` | First adoption of a repository: writes project facts in the root `AGENTS.md` and creates `.dev-brain/STATE.md`; migrates files from the previous kit (`harness/`) without deleting them | -| `/resume` | Start of a session: reconciles the saved state with the real repository | -| `/handoff` | End of meaningful work: rewrites the state with verified results and next actions | -| `/plan ` | Non-trivial change: plan-contract with at most five steps | -| `/impact ` | Before editing: callers, contracts, tests and unknowns | -| `/learn ` | Explain a real flow or an unfamiliar stack | -| `/review [scope]` | Review all uncommitted changes (staged, unstaged, untracked) through the read-only reviewer, which reads the diff itself with git | - -When present, the plugin injects `.dev-brain/STATE.md` automatically, making the saved goal available at session start. Saved notes may be stale: `/resume` reconciles them with `git status` and recent commits. Neither `/start` nor a state file is required for the global design rules to apply. +| `start` | First adoption of a repository: writes project facts in the root `AGENTS.md` and creates `.dev-brain/STATE.md`; migrates files from the previous kit (`harness/`) without deleting them | +| `resume` | Start of a session: reconciles the saved state with the real repository | +| `handoff` | End of meaningful work: rewrites the state with verified results and next actions | +| `plan` | Non-trivial change: read-only plan-contract with at most five steps | +| `impact` | Before editing: callers, contracts, tests and unknowns | +| `learn` | Explain a real flow or an unfamiliar stack | +| `review` | Review all uncommitted changes (staged, unstaged, untracked) through the read-only reviewer, which reads the diff itself with git | ## What lives in a project @@ -76,28 +78,17 @@ When present, the plugin injects `.dev-brain/STATE.md` automatically, making the └── STATE.md goal, done with evidence, blockers, max 3 next actions (under 3000 characters) ``` -Create them with `/start` when adopting the project. Both files are intended for version control, but committing them always requires your explicit decision. The state is a working document, not a diary: replace stale content at every handoff. - -## Plugin - -`plugin/dev-brain/index.ts` uses only `@opencode/plugin` and Node built-ins: - -- `session.hook("context")` appends `.dev-brain/STATE.md` to the system context of every model call in the main session. Subagent sessions (reviewer, explore, general) do not get it: they work from the prompt their caller writes. The injection is transient, so it survives compaction. -- Budget: a state over 3000 characters is not injected; a one-line notice tells the model to read it when needed and to suggest `/handoff` to compact it. It is not truncated, because truncation would drop the `Next` section at the end. -- If the repository has no state file, it adds one line suggesting `/start`; it never creates the file by itself. -- `session.hook("compaction")` asks the summary to preserve goal, evidence, blockers and next action. +All four agents read the project `AGENTS.md`. Both files are intended for version control, but committing them always requires your explicit decision. The state is a working document, not a diary. ## Evaluation -`evals/offline/check.py` installs the kit into a temporary configuration, replaces the model with a local mock that records every request, and checks in about five seconds, at zero token cost, what the kit controls: state injection scope and budget, and the reviewer's read-only git permissions. Run it after changing the plugin, agents or installer: +`evals/offline/check.py` installs the kit into a throwaway home for every agent CLI it finds, replaces the model with a local mock that records every request (`evals/offline/mock_model.py`), and checks in about ten seconds, at zero token cost, what the kit controls: rules and state reach the agent, oversized state becomes a notice, workflows expand, the reviewer reads the diff but cannot write. Cursor is checked only for its generated files. Run it after changing `core/`, an adapter or the installer: ```bash -python3 evals/offline/check.py # set OPENCODE= if opencode is not on PATH +python3 evals/offline/check.py # OPENCODE / CLAUDE / CODEX= if not on PATH ``` -`evals/scenarios/` describes realistic tasks and the expected behavior. `evals/results.md` records the measured results and limitations. Every change to rules, commands or skills should be justified by a scenario; instructions that do not change behavior are removed. - -The maintainability scenario found an improvement in **review policy**: it now reports duplicated business knowledge as a maintenance problem without merging unrelated policies. Generated code was already readable in the baseline and remained so afterward; that run does not demonstrate a generation-quality gain. The new fixture is Python-only: language-independent rules do not mean cross-language results have been verified. The `/review` delegation path is verified through the server API with a mock model, not through the TUI or a real model. +`evals/scenarios/` describes realistic tasks and the expected model behavior; `evals/results.md` records measured results and limits. Every change to rules, workflows or skills should be justified by a scenario. Run a scenario manually in a fixture: @@ -105,30 +96,21 @@ Run a scenario manually in a fixture: # Only after explicitly authorizing local fixture commits: ./evals/setup.sh # copies fixtures to /tmp/opencode/dev-brain-evals and recreates git history cd /tmp/opencode/dev-brain-evals/bugfix -opencode run --standalone -m "The discount test fails. Fix the code." +opencode run --standalone -m "The discount test fails. Fix the code." < /dev/null ``` -For commands, use the TUI or the server command API; `opencode run` sends slash commands as literal text. In scripts, close stdin (`< /dev/null`): `opencode run` reads non-terminal stdin and waits for EOF. - -`evals/setup.sh` replaces its disposable output directory and creates commits in the history-based fixtures. The maintainability scenario can instead run on fresh copies without git history or commits; see [`evals/scenarios/maintainability.md`](evals/scenarios/maintainability.md). +In scripts, close stdin: `opencode run` waits for EOF on non-terminal stdin. ## Migration from the previous kit -The previous visible `dev-brain/` folder has been removed. Its content remains in git history at commit `08baebc`; inspect it with `git show 08baebc:dev-brain/RULES.md` or extract it with `git archive 08baebc dev-brain | tar -x -C /tmp`. - -For each repository that received a copy: - -1. Diff its `RULES.md` against `global/AGENTS.md` and keep any project-specific or genuinely useful rule. -2. Move stable project facts into the root `AGENTS.md`. -3. Convert `NOW.md`, `PROJECT_STATE.md` and `PROJECT_MAP.md` into `.dev-brain/STATE.md` plus the project `AGENTS.md`. -4. Remove the copied kit files. +Content of the old visible `dev-brain/` folder remains in git history at commit `08baebc`. For a repository that received a copy (`RULES.md`, `NOW.md`, `harness/PROJECT_STATE.md`, `harness/PROJECT_MAP.md`), run the `start` workflow: it carries still-true facts into `AGENTS.md` and `.dev-brain/STATE.md` and lists the old files for you to delete. ## Layout ``` -global/ always-loaded rules, commands, agents, skills -plugin/ OpenCode V2 plugin -templates/ STATE.md and project AGENTS.md templates +core/ the only source: AGENTS.md rules, workflows/, skills/, agents/reviewer.md, bin/, templates/ +adapters/ agent-specific code that cannot be expressed as files (OpenCode plugin) +install.py links or translates core/ for each agent; install.sh is a wrapper evals/ scenarios, fixtures, results, offline mock check MANUALE.md Italian user manual ``` diff --git a/adapters/opencode/plugin/index.ts b/adapters/opencode/plugin/index.ts new file mode 100644 index 0000000..06ceb5d --- /dev/null +++ b/adapters/opencode/plugin/index.ts @@ -0,0 +1,75 @@ +import { Plugin } from "@opencode/plugin" +import { execFileSync } from "node:child_process" +import { statSync } from "node:fs" +import { join } from "node:path" +import { fileURLToPath } from "node:url" + +// The state text and its size budget come from the shared core script, so every +// agent adapter injects exactly the same thing. +const CONTEXT_SCRIPT = fileURLToPath(new URL("../../../core/bin/dev-brain-context", import.meta.url)) +const STATE_PATH = ".dev-brain/STATE.md" + +function stateVersion(root: string): string { + try { + const stat = statSync(join(root, STATE_PATH)) + return `${stat.mtimeMs}:${stat.size}` + } catch { + return "none" + } +} + +export default Plugin.define({ + id: "dev-brain", + async setup(ctx) { + const root = ctx.location.project?.canonical ?? ctx.location.directory + let cached: { version: string; text: string } | undefined + + // The context hook runs on every model call: rerun the script only when the file changes. + function contextText(): string { + const version = stateVersion(root) + if (cached?.version !== version) { + let text = "" + try { + text = execFileSync("python3", [CONTEXT_SCRIPT, "--format", "text", "--root", root], { + encoding: "utf8", + timeout: 5000, + }).trim() + } catch { + // Without python3 nothing is injected; the global rules tell the agent to read the file. + } + cached = { version, text } + } + return cached.text + } + + // Subagent sessions (reviewer, explore, ...) get a focused prompt from their parent; + // the project state would only add tokens to each of their calls. + const isSubagent = new Map() + + async function isSubagentSession(sessionID: string): Promise { + const known = isSubagent.get(sessionID) + if (known !== undefined) return known + try { + const session = await ctx.session.get({ sessionID }) + const child = session.parentID !== undefined + isSubagent.set(sessionID, child) + return child + } catch { + return false + } + } + + await ctx.session.hook("context", async (event) => { + if (await isSubagentSession(event.sessionID)) return + const text = contextText() + if (text) event.system.push({ type: "text", text }) + }) + + await ctx.session.hook("compaction", (event) => { + event.system.push({ + type: "text", + text: "Preserve in the summary, in this order: current goal and acceptance criteria, verified evidence (command + PASS/FAIL/NOT RUN), blockers and failed attempts, and the next executable action. These are written to .dev-brain/STATE.md after the session.", + }) + }) + }, +}) diff --git a/global/AGENTS.md b/core/AGENTS.md similarity index 91% rename from global/AGENTS.md rename to core/AGENTS.md index af572b5..4160a11 100644 --- a/global/AGENTS.md +++ b/core/AGENTS.md @@ -1,11 +1,11 @@ # Personal engineering rules -The goal is correct code that is readable, maintainable and easy to change. Commands and saved state support that goal; they are not the goal. +The goal is correct code that is readable, maintainable and easy to change. Workflows and saved state support that goal; they are not the goal. Precedence: correctness > security/data integrity > project compatibility > maintainability > simplicity > measured performance. Scale effort to risk. ## Before changing -- Saved state (.dev-brain/STATE.md) is context, not proof or permission. Check `git status` and recent `git log` before acting on it. +- Saved state (.dev-brain/STATE.md) is context, not proof or permission. Check `git status` and recent `git log` before acting on it. If the task continues earlier work and no `` block is in your context, read the file first. - Read the code you will touch and trace its real flow. Reuse existing project code, then stdlib/platform, then installed dependencies, before writing new code. - Use only APIs supported by the declared versions; check authoritative docs when unsure. Ask only when the answer changes scope, behavior or data safety. @@ -40,7 +40,7 @@ Precedence: correctness > security/data integrity > project compatibility > main Read next: - ## Continuity -- At the end of meaningful work update .dev-brain/STATE.md, or ask the user to run /handoff: goal, done, evidence, blockers, max 3 next actions. Replace stale content; it is not a diary. +- At the end of meaningful work update .dev-brain/STATE.md, or suggest the `handoff` workflow: goal, done, evidence, blockers, max 3 next actions, under 3000 characters. Replace stale content; it is not a diary. - Update the root AGENTS.md only when stable facts change (stack, commands, architecture, gotchas). - Never import evidence, permissions or active work from another repository. diff --git a/global/agents/reviewer.md b/core/agents/reviewer.md similarity index 58% rename from global/agents/reviewer.md rename to core/agents/reviewer.md index dd6887f..f0b31bf 100644 --- a/global/agents/reviewer.md +++ b/core/agents/reviewer.md @@ -1,24 +1,11 @@ --- +name: reviewer description: Read-only reviewer for correctness, security, data integrity and concrete maintenance problems -mode: subagent -# Last matching rule wins. Shell is read-only git: the reviewer fetches the diff -# itself, so /review never copies it through the main session. Chained commands -# (; && | $()) are split and each part is checked; redirection and --output are -# not, so they are denied explicitly. Verified on OpenCode 2.1.4 (evals/results.md). -permissions: - - { action: edit, resource: "*", effect: deny } - - { action: shell, resource: "*", effect: deny } - - { action: shell, resource: "git diff *", effect: allow } - - { action: shell, resource: "git log *", effect: allow } - - { action: shell, resource: "git show *", effect: allow } - - { action: shell, resource: "git status *", effect: allow } - - { action: shell, resource: "* --output*", effect: deny } - - { action: shell, resource: "*>*", effect: deny } --- You are an independent reviewer. You did not write this code; be skeptical. -Read the changes yourself with git; the shell allows only `git diff`, `git log`, `git show` and `git status`. Uncommitted work: `git diff HEAD` (before the first commit: `git diff --cached` and `git diff`). Read untracked files in scope directly. You cannot run tests or builds; report them as NOT RUN. +You are read-only. Read the changes yourself with git: uncommitted work with `git diff HEAD` (before the first commit: `git diff --cached` and `git diff`), commits with `git show` or `git log`. Read untracked files in scope directly. Do not modify files or run tests or builds; report them as NOT RUN. Report correctness, security, data-integrity and stated-requirement defects, plus concrete maintenance problems in the changed code. Ignore subjective style, cosmetic naming, formatting and speculative redesigns. diff --git a/core/bin/dev-brain-context b/core/bin/dev-brain-context new file mode 100755 index 0000000..62be177 --- /dev/null +++ b/core/bin/dev-brain-context @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""Print the saved project state for an agent's context, within a size budget. + +One implementation for every adapter: + --format text raw text (OpenCode plugin) + --format hook SessionStart hook JSON for Claude Code and Codex + --format cursor sessionStart hook JSON for Cursor + +The project is found from the hook's JSON on stdin (`cwd`, or Cursor's +`workspace_roots`), else from --root, else from the current directory. +Prints nothing when there is nothing useful to add. +""" +import argparse +import json +import os +import sys + +STATE_PATH = os.path.join(".dev-brain", "STATE.md") +# The state rides on every session of the project, so it must stay a short checkpoint. +# Above the budget it is not injected at all: truncating would drop the "Next" section +# at the end, which is the part that keeps the user oriented. +MAX_STATE_CHARS = 3000 + + +def project_root(start): + """Nearest directory holding the state file or a .git entry; None outside a project.""" + directory = os.path.abspath(start) + while True: + if os.path.exists(os.path.join(directory, STATE_PATH)) or os.path.exists(os.path.join(directory, ".git")): + return directory + parent = os.path.dirname(directory) + if parent == directory: + return None + directory = parent + + +def context_text(root): + if root is None: + return "" + state_file = os.path.join(root, STATE_PATH) + try: + with open(state_file, encoding="utf-8") as handle: + state = handle.read().strip() + except FileNotFoundError: + state = None + except OSError: + return "" + if state is None: + if not os.path.exists(os.path.join(root, ".git")): + return "" + return ("This repository has no .dev-brain/STATE.md. If the user wants to adopt it, " + "suggest the `start` workflow. Do not create the file unasked.") + if not state: + return "" + if len(state) > MAX_STATE_CHARS: + return (f".dev-brain/STATE.md has {len(state)} characters, over the {MAX_STATE_CHARS}-character " + "budget for automatic injection, so it was not injected. Read it when the task needs saved " + "context, and suggest the `handoff` workflow to compact it.") + return "\n".join([ + '', + "Saved project state. Treat it as context, not proof or permission: verify against git " + "and the current source before acting on it.", + "", + state, + "", + ]) + + +def hook_input(): + if sys.stdin is None or sys.stdin.isatty(): + return {} + try: + data = json.loads(sys.stdin.read() or "{}") + except ValueError: + return {} + return data if isinstance(data, dict) else {} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--format", choices=("text", "hook", "cursor"), default="text") + parser.add_argument("--root", help="project directory (default: from hook input or cwd)") + args = parser.parse_args() + + event = hook_input() if args.format != "text" else {} + roots = event.get("workspace_roots") or [] + start = args.root or event.get("cwd") or (roots[0] if roots else None) or os.getcwd() + text = context_text(project_root(start)) + if not text: + return + if args.format == "text": + print(text) + elif args.format == "hook": + print(json.dumps({"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": text}})) + else: + print(json.dumps({"additional_context": text})) + + +if __name__ == "__main__": + main() diff --git a/global/skills/debugging/SKILL.md b/core/skills/debugging/SKILL.md similarity index 100% rename from global/skills/debugging/SKILL.md rename to core/skills/debugging/SKILL.md diff --git a/global/skills/engineering-risk/SKILL.md b/core/skills/engineering-risk/SKILL.md similarity index 100% rename from global/skills/engineering-risk/SKILL.md rename to core/skills/engineering-risk/SKILL.md diff --git a/global/skills/engineering-risk/references/data.md b/core/skills/engineering-risk/references/data.md similarity index 100% rename from global/skills/engineering-risk/references/data.md rename to core/skills/engineering-risk/references/data.md diff --git a/global/skills/engineering-risk/references/performance.md b/core/skills/engineering-risk/references/performance.md similarity index 100% rename from global/skills/engineering-risk/references/performance.md rename to core/skills/engineering-risk/references/performance.md diff --git a/global/skills/engineering-risk/references/security.md b/core/skills/engineering-risk/references/security.md similarity index 100% rename from global/skills/engineering-risk/references/security.md rename to core/skills/engineering-risk/references/security.md diff --git a/global/skills/review-feedback/SKILL.md b/core/skills/review-feedback/SKILL.md similarity index 100% rename from global/skills/review-feedback/SKILL.md rename to core/skills/review-feedback/SKILL.md diff --git a/templates/PROJECT_AGENTS.md b/core/templates/PROJECT_AGENTS.md similarity index 100% rename from templates/PROJECT_AGENTS.md rename to core/templates/PROJECT_AGENTS.md diff --git a/templates/STATE.md b/core/templates/STATE.md similarity index 100% rename from templates/STATE.md rename to core/templates/STATE.md diff --git a/global/commands/handoff.md b/core/workflows/handoff/SKILL.md similarity index 69% rename from global/commands/handoff.md rename to core/workflows/handoff/SKILL.md index 5486be8..b5fb04f 100644 --- a/global/commands/handoff.md +++ b/core/workflows/handoff/SKILL.md @@ -1,17 +1,14 @@ --- -description: Reconcile .dev-brain/STATE.md with the work actually done +name: handoff +description: Close a work session by rewriting .dev-brain/STATE.md with verified results and next actions. Run only when the user asks for it. +disable-model-invocation: true --- Close the current work session by updating the saved state. -Repository snapshot: -!`git status --short --branch` -Recent commits: -!`git log --oneline -10` - Steps: -1. Read the current `.dev-brain/STATE.md`. +1. Read the current `.dev-brain/STATE.md`, and run `git status --short --branch` and `git log --oneline -10`. 2. Establish what actually happened from the diff, the checks run in this session, and the conversation. Do not invent evidence and do not copy old results as new. 3. Rewrite `.dev-brain/STATE.md` using the existing structure: - goal and acceptance criteria, only if they changed; @@ -19,7 +16,7 @@ Steps: - in progress / blockers: mark each item implemented, verified or blocked; - known pre-existing failures, if newly discovered; - next: at most three executable actions, most important first. - Replace stale lines instead of appending. Keep it under 3000 characters: the plugin injects it into every model call and skips larger files. The transcript is not the state. + Replace stale lines instead of appending. Keep it under 3000 characters: it is injected into the agent's context and larger files are skipped. The transcript is not the state. 4. Update the root `AGENTS.md` only if a stable fact changed: stack, commands, architecture, gotchas. 5. Report what changed in the two files, and list anything not verified. diff --git a/global/commands/impact.md b/core/workflows/impact/SKILL.md similarity index 76% rename from global/commands/impact.md rename to core/workflows/impact/SKILL.md index 0b495d8..1339700 100644 --- a/global/commands/impact.md +++ b/core/workflows/impact/SKILL.md @@ -1,8 +1,10 @@ --- -description: Read-only impact analysis for a proposed change +name: impact +description: Read-only impact analysis of a proposed change - consumers, contracts, tests and unknowns. Run only when the user asks for it. +disable-model-invocation: true --- -Analyze the impact of this change: $ARGUMENTS +Analyze the impact of the change the user described with this request. Read-only: do not modify files, generate patches or run checks. diff --git a/global/commands/learn.md b/core/workflows/learn/SKILL.md similarity index 75% rename from global/commands/learn.md rename to core/workflows/learn/SKILL.md index c25db02..4ebb790 100644 --- a/global/commands/learn.md +++ b/core/workflows/learn/SKILL.md @@ -1,10 +1,10 @@ --- -description: Explain a flow, component or unfamiliar stack using the real code +name: learn +description: Explain a flow, component or unfamiliar stack from the real code, with a reading order. Run only when the user asks for it. +disable-model-invocation: true --- -Explain this for me: $ARGUMENTS - -If the argument is empty, explain the main request flow of this project. +Explain the area the user named with this request. If they named none, explain the main request flow of this project. Read-only. Inspect the actual source before writing anything. Do not produce a generic tutorial. diff --git a/global/commands/plan.md b/core/workflows/plan/SKILL.md similarity index 81% rename from global/commands/plan.md rename to core/workflows/plan/SKILL.md index a75c082..df48609 100644 --- a/global/commands/plan.md +++ b/core/workflows/plan/SKILL.md @@ -1,9 +1,10 @@ --- -description: Produce a plan-contract for a change (read-only, max 5 steps) -agent: plan +name: plan +description: Produce a read-only plan-contract of at most 5 steps for a non-trivial change. Run only when the user asks for it. +disable-model-invocation: true --- -Plan this work: $ARGUMENTS +Plan the work the user described with this request. This is read-only: do not edit files, install dependencies or change git state. diff --git a/global/commands/resume.md b/core/workflows/resume/SKILL.md similarity index 75% rename from global/commands/resume.md rename to core/workflows/resume/SKILL.md index 753e3f3..4699cd4 100644 --- a/global/commands/resume.md +++ b/core/workflows/resume/SKILL.md @@ -1,17 +1,14 @@ --- -description: Resume work from saved state, reconciled with the real repository +name: resume +description: Resume work from .dev-brain/STATE.md, reconciled with the real repository. Run only when the user asks for it. +disable-model-invocation: true --- Resume work in this repository. -Repository snapshot: -!`git status --short --branch` -Recent commits: -!`git log --oneline -15` - Steps: -1. Read `.dev-brain/STATE.md` and the root `AGENTS.md`. +1. Read `.dev-brain/STATE.md` and the root `AGENTS.md`, and run `git status --short --branch` and `git log --oneline -15`. 2. Reconcile the saved state with reality: branch, working-tree changes, recent commits, and the files named in the state. Saved notes are context, not proof. If something no longer matches, say so before continuing. 3. If the state records a quick verification command, run it only when it is read-only and fast, and report the actual result. Never present an old check as freshly run. Report as NOT RUN, without running, anything that would install, download, compile or create an environment or cache: `uv sync`, `pip install`, `npm install`, `uv run` without an existing `.venv`, `cargo test`/`cargo build`, full builds. 4. Report in a few lines: goal, last verified outcome, current blockers, and the single next action. Ask before starting work that changes behavior, data or git state. diff --git a/core/workflows/review/SKILL.md b/core/workflows/review/SKILL.md new file mode 100644 index 0000000..6721279 --- /dev/null +++ b/core/workflows/review/SKILL.md @@ -0,0 +1,18 @@ +--- +name: review +description: Review correctness and maintainability of the current changes through the read-only reviewer subagent. Run only when the user asks for it. +disable-model-invocation: true +--- + +Review the current changes by delegating to the read-only `reviewer` subagent. + +Scope: the text the user gave with this request. If none, every uncommitted change: staged, unstaged and untracked files. + +Steps: + +1. Run `git status --short --branch` and `git diff HEAD --stat` (before the first commit: `git diff --cached --stat`). If the scope is empty and nothing is modified, staged or untracked, say so and stop. +2. Delegate once to the `reviewer` subagent. Give it the scope and the changed-file list. Do not paste the diff or file contents: the reviewer reads them itself with git and its read tool. Tell it to follow its own rules, keep behavior defects separate from maintenance problems, and state which files it actually read. +3. If no `reviewer` subagent is available, say so and stop; do not review the code yourself in this step. +4. Relay the reviewer's findings faithfully. Do not add findings of your own and do not soften them. + +Do not modify files, run other commands or commit. diff --git a/global/commands/start.md b/core/workflows/start/SKILL.md similarity index 83% rename from global/commands/start.md rename to core/workflows/start/SKILL.md index ecfc3e8..e6149f0 100644 --- a/global/commands/start.md +++ b/core/workflows/start/SKILL.md @@ -1,16 +1,14 @@ --- -description: Adopt this repository into dev-brain (project facts + state) +name: start +description: Adopt the current repository into dev-brain by writing its project facts (AGENTS.md) and saved state (.dev-brain/STATE.md). Run only when the user asks for it. +disable-model-invocation: true --- Adopt the current repository into the dev-brain harness. This is an inspection and documentation task: do not modify application code, dependencies, configuration or git history. -Repository snapshot: -!`git status --short --branch 2>/dev/null || echo "not a git repository"` -!`ls -la` - Steps: -1. Inspect the actual repository: purpose, languages and declared versions, frameworks, package manager, entry points, build/lint/test commands, configuration, and the conventions the code really follows. Use the files, not assumptions. +1. Run `git status --short --branch` and list the repository root. Inspect the actual repository: purpose, languages and declared versions, frameworks, package manager, entry points, build/lint/test commands, configuration, and the conventions the code really follows. Use the files, not assumptions. Never open or list directories or files that may contain personal, clinical or secret data (for example `input/`, `output/`, `.env`). Rely on documentation and configuration, and never copy such data into `AGENTS.md` or `.dev-brain/STATE.md`. 2. Files from the previous kit (`harness/PROJECT_STATE.md`, `harness/PROJECT_MAP.md`, `NOW.md`, a copied `dev-brain/` or `RULES.md`) are input, not a second source of truth. Carry still-true stable facts into `AGENTS.md`, and only the current goal, latest evidence, blockers and next action into `.dev-brain/STATE.md`; leave history in git. Do not delete the old files: list them for the user. 3. If a root `AGENTS.md` exists, merge into it and preserve every existing instruction. Otherwise create it. Keep it under 60 lines and include only: @@ -20,7 +18,7 @@ Steps: - non-obvious architecture or conventions; - gotchas and known limitations. Do not add generic engineering advice; it is already in the global rules. Do not record absolute machine paths or values that only hold on this machine. -4. If `.dev-brain/STATE.md` exists, reconcile it with the current source instead of overwriting user notes. Otherwise create it using this structure. Keep it under 3000 characters: the plugin injects it into every model call and skips larger files. +4. If `.dev-brain/STATE.md` exists, reconcile it with the current source instead of overwriting user notes. Otherwise create it using this structure. Keep it under 3000 characters: it is injected into the agent's context and larger files are skipped. ```markdown # State — diff --git a/evals/offline/check.py b/evals/offline/check.py index b8ff3d4..df586b9 100644 --- a/evals/offline/check.py +++ b/evals/offline/check.py @@ -1,17 +1,18 @@ #!/usr/bin/env python3 -"""Zero-token check of the installed harness against a real OpenCode binary. +"""Zero-token check of the installed kit against the real agent binaries. -A local OpenAI-compatible mock replaces the model: it replays scripted tool calls -and records every request OpenCode sends. Nothing reaches a real provider, so the -check costs no tokens. It verifies what the kit controls: +For every agent CLI found (opencode, claude, codex; override with OPENCODE, +CLAUDE, CODEX), the kit is installed into a throwaway home with install.py and +the model is replaced by evals/offline/mock_model.py, which replays scripted +tool calls and records every request. Nothing reaches a real provider. -- the saved state reaches the main session and not subagent sessions; -- an oversized state is replaced by a short notice; -- the reviewer can read the diff with git but cannot write files. +It verifies what the kit controls: global rules and saved state reach the agent, +an oversized state becomes a notice, workflows expand, and the reviewer reads +the diff with git but cannot write. It does not judge model behavior; use +evals/scenarios/ for that. Cursor has no headless CLI here: its generated files +are only checked for presence. -It does not judge model behavior; use evals/scenarios/ for that. - -Usage: python3 evals/offline/check.py (needs `opencode` V2, git, bash) +usage: python3 evals/offline/check.py """ import json import os @@ -19,12 +20,16 @@ import subprocess import sys import tempfile -import threading -from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from mock_model import MockModel # noqa: E402 + KIT = Path(__file__).resolve().parents[2] -OPENCODE = os.environ.get("OPENCODE", "opencode") +RULES = "Personal engineering rules" # first line of core/AGENTS.md +STATE_MARK = "Saved project state. Treat it" # header of the injected state block +NOTICE = "over the 3000-character budget" +REVIEW_FLOW = "Review the current changes by delegating" # core/workflows/review STATE = """# State — fixture Updated: 2026-01-01 · Branch: main @@ -35,115 +40,124 @@ 1. Review the pending change. """ +failures = [] + + +def check(name, ok, detail=""): + print(f"{'PASS' if ok else 'FAIL'} {name}{f' — {detail}' if detail and not ok else ''}") + if not ok: + failures.append(name) + -class Mock: - """Scripted chat-completions endpoint; requests without tools (titles) get plain text.""" - - def __init__(self): - self.steps, self.requests, self.lock = [], [], threading.Lock() - mock = self - - class Handler(BaseHTTPRequestHandler): - def log_message(self, *args): - pass - - def do_POST(self): - body = json.loads(self.rfile.read(int(self.headers["content-length"]))) - with mock.lock: - mock.requests.append(body) - step = mock.steps.pop(0) if body.get("tools") and mock.steps else {"text": "ok"} - if "tool" in step: - call = {"index": 0, "id": f"call_{len(mock.requests)}", "type": "function", - "function": {"name": step["tool"], "arguments": json.dumps(step["args"])}} - deltas, finish = [{"role": "assistant", "tool_calls": [call]}], "tool_calls" - else: - deltas, finish = [{"role": "assistant", "content": step["text"]}], "stop" - chunks = [{"choices": [{"index": 0, "delta": d, "finish_reason": None}]} for d in deltas] - chunks.append({"choices": [{"index": 0, "delta": {}, "finish_reason": finish}], - "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}}) - self.send_response(200) - self.send_header("content-type", "text/event-stream") - self.end_headers() - for chunk in chunks: - chunk.update({"id": "c", "object": "chat.completion.chunk", "created": 0, "model": "mock"}) - self.wfile.write(f"data: {json.dumps(chunk)}\n\n".encode()) - self.wfile.write(b"data: [DONE]\n\n") - - self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) - threading.Thread(target=self.server.serve_forever, daemon=True).start() - self.url = f"http://127.0.0.1:{self.server.server_port}/v1" - - -def system_text(request): - return "\n".join(m["content"] for m in request["messages"] - if m["role"] == "system" and isinstance(m["content"], str)) - - -def tool_results(requests): - """Tool outputs fed back to the model, once per tool call, in order.""" +def text_of(value): + return value if isinstance(value, str) else json.dumps(value) + + +def system_text(body): + """System and developer instructions of one request, in any of the three wire formats.""" + parts = [text_of(body.get("system", "")), text_of(body.get("instructions", ""))] + for message in body.get("messages") or body.get("input") or []: + if isinstance(message, dict) and message.get("role") in ("system", "developer"): + parts.append(text_of(message.get("content"))) + return "\n".join(parts) + + +def tool_results(bodies): + """Tool outputs fed back to the model, once per call id, in order.""" results = {} - for request in requests: - for message in request["messages"]: - if message["role"] == "tool": - content = message["content"] - results.setdefault(message.get("tool_call_id"), - content if isinstance(content, str) else json.dumps(content)) + for body in bodies: + for message in body.get("messages") or body.get("input") or []: + if not isinstance(message, dict): + continue + if message.get("role") == "tool": # chat completions + results.setdefault(message.get("tool_call_id"), text_of(message.get("content"))) + if message.get("type") == "function_call_output": # responses + results.setdefault(message.get("call_id"), text_of(message.get("output"))) + if message.get("role") == "user" and isinstance(message.get("content"), list): # anthropic + for block in message["content"]: + if isinstance(block, dict) and block.get("type") == "tool_result": + results.setdefault(block.get("tool_use_id"), text_of(block.get("content"))) return list(results.values()) -def run(env, repo, mock, steps, prompt="check"): - """One `opencode run` in the fixture; returns the agent-loop requests (those offering tools).""" - mock.steps, mock.requests = list(steps), [] - # stdin must be closed: `opencode run` reads piped stdin and waits for EOF otherwise. - # PWD must match cwd: OpenCode resolves the project from it. - subprocess.run([OPENCODE, "run", "--standalone", "-m", "mock/mock", prompt], cwd=repo, - env=dict(env, PWD=str(repo)), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, timeout=180) - requests = [r for r in mock.requests if r.get("tools")] - if not requests: - raise SystemExit("FAIL opencode sent no request to the mock model") - return requests +def binary(name, variable): + path = os.environ.get(variable) or shutil.which(name) + return path if path and Path(path).exists() else None -def main(): - if not shutil.which(OPENCODE): - raise SystemExit(f"`{OPENCODE}` not found; set OPENCODE to the V2 binary") - mock = Mock() - sandbox = Path(tempfile.mkdtemp(prefix="dev-brain-offline-")) - # Fully offline: the mock is the only provider, so skip the model catalog download. - env = dict(os.environ, HOME=str(sandbox / "home"), OPENCODE_DISABLE_MODELS_FETCH="1", - OPENCODE_DISABLE_FREE_MODELS="1") - for name in ("CONFIG", "DATA", "STATE", "CACHE"): - env[f"XDG_{name}_HOME"] = str(sandbox / name.lower()) - subprocess.run([str(KIT / "install.sh")], env=env, check=True, stdout=subprocess.DEVNULL) - config_file = sandbox / "config" / "opencode" / "opencode.json" +class Sandbox: + """Throwaway home, fixture repository and installed kit.""" + + def __init__(self, tools, bins): + self.root = Path(tempfile.mkdtemp(prefix="dev-brain-offline-")) + home = self.root / "home" + home.mkdir() + bin_dir = self.root / "bin" + bin_dir.mkdir() + for name, path in bins.items(): + (bin_dir / name).symlink_to(path) + # A clean environment: nothing from the caller's own agent setup leaks in. + self.env = {"PATH": f"{bin_dir}:{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"), + "CLAUDE_CONFIG_DIR": str(home / ".claude"), "CODEX_HOME": str(home / ".codex")} + self.repo = self.root / "repo" + (self.repo / ".dev-brain").mkdir(parents=True) + git = ["git", "-c", "user.name=check", "-c", "user.email=check@example.invalid"] + subprocess.run(["git", "init", "-q", "-b", "main"], cwd=self.repo, check=True) + (self.repo / "app.txt").write_text("hello\n") + subprocess.run(git + ["add", "app.txt"], cwd=self.repo, check=True) + subprocess.run(git + ["commit", "-qm", "fixture"], cwd=self.repo, check=True) + (self.repo / "app.txt").write_text("hello, world\n") + self.small_state() + result = subprocess.run([sys.executable, str(KIT / "install.py"), *tools], env=self.env, + capture_output=True, text=True) + if result.returncode: + raise SystemExit(f"FAIL install.py: {result.stdout}{result.stderr}") + + def small_state(self): + (self.repo / ".dev-brain" / "STATE.md").write_text(STATE) + + def big_state(self): + (self.repo / ".dev-brain" / "STATE.md").write_text(STATE + "- stale line\n" * 300) + + def clean_repo(self): + for name in ("leak.txt", "touched.txt"): + (self.repo / name).unlink(missing_ok=True) + (self.repo / "app.txt").write_text("hello, world\n") + + def run(self, mock, cmd, steps, env=None): + mock.script(steps) + subprocess.run(cmd, cwd=self.repo, env={**self.env, "PWD": str(self.repo), **(env or {})}, + 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 + + +def write_protected(sandbox, results, expected_rejections): + words = ("permission.rejected", "needs approval", "requires approval", "has been denied") + rejected = sum(any(word in r for word in words) for r in results) + return (rejected == expected_rejections and not (sandbox.repo / "leak.txt").exists() + and not (sandbox.repo / "touched.txt").exists() and (sandbox.repo / "app.txt").exists()), rejected + + +def check_opencode(sandbox, mock, opencode): + config_file = Path(sandbox.env["XDG_CONFIG_HOME"]) / "opencode" / "opencode.json" config = json.loads(config_file.read_text()) config["model"] = "mock/mock" config["providers"] = {"mock": { "name": "Mock", "package": "@opencode/ai/providers/openai-compatible", - "settings": {"baseURL": mock.url}, + "settings": {"baseURL": mock.url + "/v1"}, "models": {"mock": {"name": "Mock", "capabilities": {"tools": True, "input": ["text"], "output": ["text"]}, "limit": {"context": 200000, "output": 8000}}}}} - config_file.write_text(json.dumps(config, indent=2)) - - repo = sandbox / "repo" - (repo / ".dev-brain").mkdir(parents=True) - git = ["git", "-c", "user.name=check", "-c", "user.email=check@example.invalid"] - subprocess.run(["git", "init", "-q", "-b", "main"], cwd=repo, check=True) - (repo / "app.txt").write_text("hello\n") - subprocess.run(git + ["add", "app.txt"], cwd=repo, check=True) - subprocess.run(git + ["commit", "-qm", "fixture"], cwd=repo, check=True) - (repo / "app.txt").write_text("hello, world\n") - (repo / ".dev-brain" / "STATE.md").write_text(STATE) - - failures = [] - - def check(name, ok, detail=""): - print(f"{'PASS' if ok else 'FAIL'} {name}{f' — {detail}' if detail and not ok else ''}") - if not ok: - failures.append(name) - - reviewer_steps = [ + config_file.write_text(json.dumps(config)) + cmd = [opencode, "run", "--standalone", "-m", "mock/mock", "check"] + env = {"OPENCODE_DISABLE_MODELS_FETCH": "1", "OPENCODE_DISABLE_FREE_MODELS": "1"} + steps = [ {"tool": "subagent", "args": {"agent": "reviewer", "description": "review", "prompt": "Review all changes."}}, {"tool": "shell", "args": {"command": "git diff HEAD"}}, {"tool": "shell", "args": {"command": "git diff HEAD > leak.txt"}}, @@ -152,26 +166,121 @@ def check(name, ok, detail=""): {"text": "no findings"}, {"text": "done"}, ] - requests = run(env, repo, mock, reviewer_steps) - main_calls = [r for r in requests if any(t["function"]["name"] == "edit" for t in r["tools"])] - child_calls = [r for r in requests if r not in main_calls] - results = tool_results(requests) - check("state injected in the main session", bool(main_calls) and all(", --output, rm)", ok, f"{rejected}/3 rejected") + + sandbox.big_state() + bodies = sandbox.run(mock, cmd, [{"text": "done"}], env) + system = system_text(bodies[0]) if bodies else "" + check("opencode: oversized state becomes a notice", NOTICE in system and "stale line" not in system) + sandbox.small_state() + sandbox.clean_repo() + + +def check_claude(sandbox, mock, claude): + env = {"ANTHROPIC_BASE_URL": mock.url, "ANTHROPIC_API_KEY": "sk-offline-check", + "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1", "DISABLE_AUTOUPDATER": "1"} + + def cmd(prompt): + return [claude, "-p", prompt, "--model", "mock-model"] + + bodies = sandbox.run(mock, cmd("/dev-brain:review"), [{"text": "done"}], env) + everything = json.dumps(bodies) + check("claude-code: global rules loaded", RULES in everything) + check("claude-code: state injected by the SessionStart hook", bool(bodies) and STATE_MARK in system_text(bodies[0])) + check("claude-code: /dev-brain:review expands the workflow", REVIEW_FLOW in everything) + check("claude-code: user-invoked workflows stay out of the skill listing", + "dev-brain:debugging" in everything and "dev-brain:handoff" not in everything) + + steps = [ + {"tool": "Agent", "args": {"description": "review", "prompt": "Review all changes.", + "subagent_type": "dev-brain:reviewer"}}, + {"tool": "Bash", "args": {"command": "git diff HEAD", "description": "Show changes"}}, + {"tool": "Bash", "args": {"command": "git diff HEAD > leak.txt", "description": "Save changes"}}, + {"tool": "Bash", "args": {"command": "touch touched.txt", "description": "Create file"}}, + {"tool": "Bash", "args": {"command": "git status; rm app.txt", "description": "Remove file"}}, + {"text": "no findings"}, + {"text": "done"}, + ] + bodies = sandbox.run(mock, cmd("check the changes"), steps, env) + results = tool_results(bodies) + check("claude-code: reviewer reads the diff with git", any("hello, world" in r for r in results)) + ok, rejected = write_protected(sandbox, results, 3) + check("claude-code: reviewer cannot write without approval", ok, f"{rejected}/3 rejected") + + sandbox.big_state() + bodies = sandbox.run(mock, cmd("hello"), [{"text": "done"}], env) + system = system_text(bodies[0]) if bodies else "" + check("claude-code: oversized state becomes a notice", NOTICE in system and "stale line" not in system) + sandbox.small_state() + sandbox.clean_repo() + + +def check_codex(sandbox, mock, codex): + provider = (f'model_providers.mock={{ name = "mock", base_url = "{mock.url}/v1", ' + 'wire_api = "responses", env_key = "MOCK_KEY" }') + + def cmd(prompt, *extra): + return [codex, "exec", "--skip-git-repo-check", "-c", 'model_provider="mock"', "-c", 'model="mock"', + "-c", provider, *extra, prompt] + + env = {"MOCK_KEY": "offline-check"} + bodies = sandbox.run(mock, cmd("$dev-brain:review"), [{"text": "done"}], env) + everything = json.dumps(bodies) + check("codex: global rules loaded", RULES in everything) + check("codex: $dev-brain:review expands the workflow", REVIEW_FLOW in everything) + check("codex: reviewer role registered", "Read-only reviewer for correctness" in everything) + check("codex: state hook waits for the user's trust", STATE_MARK not in everything) + # Trusting a hook is the user's decision; the check bypasses it only inside its own sandbox. + bodies = sandbox.run(mock, cmd("hello", "--dangerously-bypass-hook-trust"), [{"text": "done"}], env) + check("codex: state injected once the hook is trusted", STATE_MARK in json.dumps(bodies)) + sandbox.big_state() + bodies = sandbox.run(mock, cmd("hello", "--dangerously-bypass-hook-trust"), [{"text": "done"}], env) + everything = json.dumps(bodies) + check("codex: oversized state becomes a notice", NOTICE in everything and "stale line" not in everything) + sandbox.small_state() + + +def check_cursor(sandbox): + home = Path(sandbox.env["HOME"]) / ".cursor" + expected = ["rules/dev-brain.mdc", "agents/reviewer.md", "hooks.json", "skills/review/SKILL.md", + "skills/debugging/SKILL.md"] + missing = [name for name in expected if not (home / name).exists()] + check("cursor: files generated (not run: no headless Cursor here)", not missing, f"missing {missing}") + agent = home / "agents" / "reviewer.md" + check("cursor: reviewer is readonly", agent.exists() and "readonly: true" in agent.read_text()) + + +def main(): + bins = {} + for name, variable in (("opencode", "OPENCODE"), ("claude", "CLAUDE"), ("codex", "CODEX")): + path = binary(name, variable) + if path: + bins[name] = path + names = {"opencode": "opencode", "claude": "claude-code", "codex": "codex"} + tools = [names[name] for name in bins] + ["cursor"] + print(f"agents: {', '.join(tools)}") + sandbox = Sandbox(tools, bins) + mock = MockModel() + try: + if "opencode" in bins: + check_opencode(sandbox, mock, bins["opencode"]) + if "claude" in bins: + check_claude(sandbox, mock, bins["claude"]) + if "codex" in bins: + check_codex(sandbox, mock, bins["codex"]) + check_cursor(sandbox) + finally: + mock.server.shutdown() + shutil.rmtree(sandbox.root, ignore_errors=True) print("ALL PASS" if not failures else f"{len(failures)} FAILED") return 1 if failures else 0 diff --git a/evals/offline/mock_model.py b/evals/offline/mock_model.py new file mode 100644 index 0000000..4ac311c --- /dev/null +++ b/evals/offline/mock_model.py @@ -0,0 +1,173 @@ +"""Local model endpoint that records requests and replays scripted replies. + +Speaks the three wire formats the supported agents use: +- OpenAI chat completions (`/chat/completions`): OpenCode +- Anthropic messages (`/messages`): Claude Code +- OpenAI responses (`/responses`): Codex CLI + +Requests that offer tools are agent-loop calls: each one pops the next matching +scripted step, either {"tool": name, "args": {...}} or {"text": "..."}, optionally +limited with "when" / "unless" text. Other requests (titles, summaries) get a fixed +text. Nothing reaches a real provider. +""" +import json +import re +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + + +class MockModel: + def __init__(self): + self.steps, self.requests, self.lock = [], [], threading.Lock() + mock = self + + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *args): + pass + + def do_GET(self): + self._json({"data": [{"id": "mock", "object": "model", "type": "model", "display_name": "Mock"}], + "models": [], "has_more": False}) + + def do_POST(self): + body = json.loads(self.rfile.read(int(self.headers.get("content-length", 0))) or b"{}") + path = self.path.split("?")[0] + if path.endswith("/count_tokens"): + return self._json({"input_tokens": 1}) + with mock.lock: + mock.requests.append({"path": path, "body": body}) + step = mock.next_step(body) + if path.endswith("/messages"): + self._anthropic(body, step) + elif path.endswith("/responses"): + self._responses(step) + else: + self._chat(step) + + def _json(self, payload): + data = json.dumps(payload).encode() + self.send_response(200) + self.send_header("content-type", "application/json") + self.send_header("content-length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def _sse(self, events): + self.send_response(200) + self.send_header("content-type", "text/event-stream") + self.send_header("cache-control", "no-cache") + self.send_header("connection", "close") + self.end_headers() + for name, data in events: + 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 _chat(self, step): + call_id = f"call_{len(mock.requests)}" + if "tool" in step: + 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: + delta, finish = {"role": "assistant", "content": step["text"]}, "stop" + base = {"id": "c", "object": "chat.completion.chunk", "created": 0, "model": "mock"} + self._sse([ + (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") + + def _anthropic(self, body, step): + if "tool" in step: + block = {"type": "tool_use", "id": f"toolu_{len(mock.requests)}", "name": step["tool"], "input": {}} + delta = {"type": "input_json_delta", "partial_json": json.dumps(step["args"])} + stop = "tool_use" + else: + block, delta, stop = {"type": "text", "text": ""}, {"type": "text_delta", "text": step["text"]}, "end_turn" + usage = {"input_tokens": 1, "output_tokens": 1} + message = {"id": "msg_mock", "type": "message", "role": "assistant", "model": body.get("model", "mock"), + "content": [], "stop_reason": None, "stop_sequence": None, "usage": usage} + if not body.get("stream"): + content = dict(block, input=step["args"]) if "tool" in step else {"type": "text", "text": step["text"]} + return self._json({**message, "content": [content], "stop_reason": stop}) + self._sse([ + ("message_start", {"type": "message_start", "message": message}), + ("content_block_start", {"type": "content_block_start", "index": 0, "content_block": block}), + ("content_block_delta", {"type": "content_block_delta", "index": 0, "delta": delta}), + ("content_block_stop", {"type": "content_block_stop", "index": 0}), + ("message_delta", {"type": "message_delta", "delta": {"stop_reason": stop, "stop_sequence": None}, + "usage": {"output_tokens": 1}}), + ("message_stop", {"type": "message_stop"}), + ]) + + def _responses(self, step): + n = 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"} + if "namespace" in step: + item["namespace"] = step["namespace"] + 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": []} + 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)}), + ]) + + self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=self.server.serve_forever, daemon=True).start() + self.url = f"http://127.0.0.1:{self.server.server_port}" + + def next_step(self, body): + """First scripted step whose optional `when` / `unless` text matches this request. + + Concurrent agents (a parent and its subagent) can then follow separate lanes. + """ + if not body.get("tools"): + return {"text": "ok"} + text = json.dumps(body) + for index, step in enumerate(self.steps): + if step.get("when", "") in text and not (step.get("unless") and step["unless"] in text): + step = self.steps.pop(index) + found = re.search(r'agent_id\\*":\\*"([^"\\]+)', text) + if found and "args" in step: # lets a script wait on the subagent it spawned + step = dict(step, args=json.loads(json.dumps(step["args"]).replace("$AGENT_ID", found.group(1)))) + return step + return {"text": "ok"} + + def script(self, steps): + with self.lock: + self.steps, self.requests = list(steps), [] + + def agent_calls(self): + return [r["body"] for r in self.requests if r["body"].get("tools")] + + +if __name__ == "__main__": + import sys + import time + + mock = MockModel() + log = sys.argv[1] if len(sys.argv) > 1 else None + print(mock.url, flush=True) + seen = 0 + while True: + time.sleep(0.5) + if log and len(mock.requests) > seen: + with open(log, "a", encoding="utf-8") as handle: + for request in mock.requests[seen:]: + handle.write(json.dumps(request) + "\n") + seen = len(mock.requests) diff --git a/evals/results.md b/evals/results.md index efd82c3..a7e015f 100644 --- a/evals/results.md +++ b/evals/results.md @@ -201,3 +201,35 @@ Gotchas found while testing: hph adoption by following `/start`: root `AGENTS.md` 3072 chars (40 lines) + `.dev-brain/STATE.md` 1329 chars replace 21.3 KB of `harness/` as working context; the plugin injected a 1504-char state block. `harness/` is left for the owner to delete. Delivered as a patch, not pushed: this session has no write access to `Stcant/hph`. NOT RUN: any real model (provider endpoints unreachable from the test environment), the TUI, the scenario set in `evals/scenarios/`, the generic `/resume` rule with a model, `cargo` checks in hph. + +## Agent-independent kit: OpenCode, Claude Code, Codex CLI, Cursor (2026-10-25) + +Goal set by the user: the kit must not depend on one agent. Tested binaries: OpenCode 2.1.4, Claude Code 2.1.310, Codex CLI 0.164.0, each against `evals/offline/mock_model.py` (OpenAI chat, Anthropic messages and OpenAI responses wire formats) with isolated homes. Cursor: no CLI reachable from the test environment; its layout comes from cursor.com docs and is checked only for generated files. + +What each agent actually loads (probed before designing): + +| | OpenCode | Claude Code | Codex | Cursor (docs) | +| --- | --- | --- | --- | --- | +| Project `AGENTS.md` | yes | yes (natively) | yes | yes | +| Global rules file | `~/.config/opencode/AGENTS.md` | `~/.claude/CLAUDE.md`, `@/abs/path` import works; `~/.claude/AGENTS.md` ignored | `~/.codex/AGENTS.md` | `~/.cursor/rules/` (known loading bug) or Settings | +| Skill dirs | `~/.claude/skills`, `~/.agents/skills` (same name: deduplicated) | `~/.claude/skills` only | `~/.codex/skills`, `~/.agents/skills` | `~/.cursor`, `~/.agents`, `~/.claude`, `~/.codex` skills | +| `disable-model-invocation` | not tested | honored (not listed) | ignored (listed, ~1200 chars) | honored | +| Claude-format plugin | n/a | commands, skills, agents, hooks | skills only; copies the plugin and drops symlinked dirs | n/a | +| State hook | plugin `context` hook | `SessionStart` additionalContext, reaches the system prompt | `SessionStart`, runs only after the user trusts it | `sessionStart` additional_context dropped (open bug) | + +No skill directory is shared by all four, so `core/` is installed per agent; plugins are namespaced (`dev-brain:`), which also avoids Claude Code's built-in `/review` (a custom `/review` from a plugin did not override it). + +Reviewer enforcement, tested with write attempts (`>`, `touch`, `; rm`, `--output`): + +- OpenCode: rejected by permissions (unchanged). +- Claude Code: `tools: Read, Grep, Glob, Bash(git …:*)` — git reads run; every write "needs approval" and was denied in `-p` mode; no file written. +- Codex: the role from `~/.codex/agents/reviewer.toml` is registered, but `sandbox_mode = "read-only"` is not applied to the spawned agent: with the parent in `workspace-write` (flag or config), the reviewer created a file. Registering it under `[agents.reviewer] config_file` changed nothing. Documented as instruction-only. +- Cursor: `readonly: true` per docs; not run. + +`evals/offline/check.py`, extended to all agents found: ALL PASS twice (21 checks, ~12 s). Mutation check: removing `disable-model-invocation` from one workflow makes `claude-code: user-invoked workflows stay out of the skill listing` FAIL. + +On hph (`/tmp` copy with the adoption patch): Claude Code `/dev-brain:resume` and Codex `$dev-brain:resume` (hook trust bypassed for the test only) both received the hph state, the resume workflow and the hph `AGENTS.md`. + +Removed: `agent: plan` on the plan workflow (OpenCode kept the session in plan mode, refusing implementation afterwards); `!` command expansion in workflows (not portable; the agent now runs `git status`/`git log` itself, one extra tool call). + +NOT RUN: any real model, any TUI, Cursor, the scenario set, Codex reviewer behavior beyond the sandbox test. diff --git a/global/commands/review.md b/global/commands/review.md deleted file mode 100644 index 4ba9fbe..0000000 --- a/global/commands/review.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -description: Review correctness and maintainability of the current changes (read-only subagent) ---- - -Review the current changes by delegating to the read-only `reviewer` subagent with the `subagent` tool. - -Scope requested by the user: $ARGUMENTS -If empty, the scope is every uncommitted change: staged, unstaged and untracked files. - -Changed files (names and counts only; the reviewer reads the content itself): -!`git status --short --branch` -!`git diff HEAD --stat 2>/dev/null || git diff --cached --stat` - -Steps: - -1. If the scope is empty and nothing above is modified, staged or untracked, say so and stop. -2. Call the `subagent` tool once with agent `reviewer`. Give it the scope and the changed-file list above. Do not paste the diff or file contents: the reviewer reads them with git and its read tool. Tell it to follow its own rules, keep behavior defects separate from maintenance problems, and state which files it actually read. -3. Relay the reviewer's findings faithfully. Do not add findings of your own in this step and do not soften them. - -Do not modify files, run further commands or commit. diff --git a/install.py b/install.py new file mode 100644 index 0000000..73e0854 --- /dev/null +++ b/install.py @@ -0,0 +1,322 @@ +#!/usr/bin/env python3 +"""Install dev-brain into one or more coding agents. + +usage: python3 install.py [opencode] [claude-code] [codex] [cursor] + (no arguments: every agent whose CLI or config directory is found) + +core/ is the only source. Each adapter below links it or translates its +frontmatter into what that agent reads; no rule lives in an adapter. +Idempotent: files that are not ours are moved to *.bak., never deleted. +""" +import hashlib +import json +import os +import shutil +import subprocess +import sys +import time +from pathlib import Path + +KIT = Path(__file__).resolve().parent +CORE = KIT / "core" +CONTEXT_SCRIPT = CORE / "bin" / "dev-brain-context" +BUILD = KIT / "build" / "marketplace" +MARKER = "generated by dev-brain install.py" +STAMP = time.strftime("%Y%m%d%H%M%S") +HOME = Path.home() +TOOLS = ("opencode", "claude-code", "codex", "cursor") + + +# ---------- source files ---------- + +def split_frontmatter(path): + """(fields, body) of a Markdown file with simple `key: value` frontmatter.""" + text = path.read_text(encoding="utf-8") + if not text.startswith("---\n"): + return {}, text + head, body = text[4:].split("\n---\n", 1) + fields = {} + for line in head.splitlines(): + if ":" in line and not line.startswith((" ", "#")): + key, value = line.split(":", 1) + fields[key.strip()] = value.strip() + return fields, body.lstrip("\n") + + +def skills(): + return sorted(p for p in (CORE / "skills").iterdir() if (p / "SKILL.md").exists()) + + +def workflows(): + return sorted(p for p in (CORE / "workflows").iterdir() if (p / "SKILL.md").exists()) + + +def reviewer(): + return split_frontmatter(CORE / "agents" / "reviewer.md") + + +# ---------- safe file operations ---------- + +def owned(path): + """True for our links (into this kit) and our generated files.""" + if path.is_symlink(): + return str(Path(os.readlink(path))).startswith(str(KIT)) + if path.is_file(): + try: + return MARKER in path.read_text(encoding="utf-8", errors="ignore")[:400] + except OSError: + return False + return False + + +def clear(path): + if not (path.exists() or path.is_symlink()): + return + if owned(path): + path.unlink() + else: + backup = path.with_name(f"{path.name}.bak.{STAMP}") + path.rename(backup) + print(f" backed up: {path} -> {backup.name}") + + +def link(src, dst): + dst.parent.mkdir(parents=True, exist_ok=True) + if dst.is_symlink() and Path(os.readlink(dst)) == src: + return + clear(dst) + dst.symlink_to(src) + + +def write(dst, text): + dst.parent.mkdir(parents=True, exist_ok=True) + if dst.is_file() and not dst.is_symlink() and dst.read_text(encoding="utf-8") == text: + return + clear(dst) + dst.write_text(text, encoding="utf-8") + + +def update_json(path, change): + """Apply change(dict) to a JSON file; leave it alone if it cannot be parsed.""" + data = {} + if path.exists(): + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (ValueError, OSError) as error: + print(f" warning: cannot parse {path} ({error}); edit it by hand") + return False + change(data) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") + return True + + +def hook_command(fmt): + return f'python3 "{CONTEXT_SCRIPT}" --format {fmt}' + + +def set_hook(data, event, entry, nested): + """Replace our hook entry for `event` (found by script path), keep everyone else's.""" + hooks = data.setdefault("hooks", {}) + entries = [e for e in hooks.get(event, []) if "dev-brain-context" not in json.dumps(e)] + hooks[event] = entries + [entry] + if not nested: + data.setdefault("version", 1) + + +def run(cmd): + result = subprocess.run(cmd, capture_output=True, text=True) + output = (result.stdout + result.stderr).strip().splitlines() + print(f" $ {' '.join(cmd)} -> {'ok' if result.returncode == 0 else 'exit ' + str(result.returncode)}" + + (f" ({output[-1]})" if output and result.returncode else "")) + return result.returncode == 0 + + +def frontmatter(fields, comment=MARKER): + lines = ["---", f"# {comment}"] + for key, value in fields.items(): + lines.extend([f"{key}:"] + [f" - {item}" for item in value] if isinstance(value, list) else [f"{key}: {value}"]) + return "\n".join(lines + ["---", ""]) + "\n" + + +# ---------- shared plugin bundle (Claude Code and Codex) ---------- + +def build_marketplace(): + """A local plugin marketplace with real copies: Codex copies plugins and drops symlinks.""" + plugin = BUILD / "dev-brain" + shutil.rmtree(BUILD, ignore_errors=True) + for source in skills() + workflows(): + shutil.copytree(source, plugin / "skills" / source.name) + (plugin / "bin").mkdir(parents=True) + shutil.copy2(CONTEXT_SCRIPT, plugin / "bin" / CONTEXT_SCRIPT.name) + + fields, body = reviewer() + # Claude Code: only these tools; any other shell command needs the user's approval. + tools = "Read, Grep, Glob, Bash(git diff:*), Bash(git log:*), Bash(git show:*), Bash(git status:*)" + agent = frontmatter({"name": fields["name"], "description": fields["description"], "tools": tools}) + body + (plugin / "agents").mkdir() + (plugin / "agents" / "reviewer.md").write_text(agent, encoding="utf-8") + + hook = {"matcher": "startup|resume|clear|compact", + "hooks": [{"type": "command", "command": 'python3 "${CLAUDE_PLUGIN_ROOT}/bin/dev-brain-context" --format hook'}]} + (plugin / "hooks").mkdir() + (plugin / "hooks" / "hooks.json").write_text(json.dumps({"hooks": {"SessionStart": [hook]}}, indent=2) + "\n") + + digest = hashlib.sha256() + for path in sorted(plugin.rglob("*")): + if path.is_file(): + digest.update(str(path.relative_to(plugin)).encode() + path.read_bytes()) + version = f"1.0.{int(digest.hexdigest()[:6], 16)}" # changes with content, so agents refresh their copy + manifest = {"name": "dev-brain", "version": version, + "description": "Readable, maintainable code with low context cost: workflows, skills, read-only reviewer, saved state."} + (plugin / ".claude-plugin").mkdir() + (plugin / ".claude-plugin" / "plugin.json").write_text(json.dumps(manifest, indent=2) + "\n") + market = {"name": "dev-brain", "owner": {"name": "dev-brain"}, + "plugins": [{"name": "dev-brain", "source": "./dev-brain", "description": manifest["description"]}]} + (BUILD / ".claude-plugin").mkdir(parents=True) + (BUILD / ".claude-plugin" / "marketplace.json").write_text(json.dumps(market, indent=2) + "\n") + return BUILD + + +# ---------- adapters ---------- + +def install_opencode(): + config = Path(os.environ.get("XDG_CONFIG_HOME", HOME / ".config")) / "opencode" + link(CORE / "AGENTS.md", config / "AGENTS.md") + for source in skills(): + link(source, config / "skills" / source.name) + for source in workflows(): # user-invoked: commands cost no context until used + fields, body = split_frontmatter(source / "SKILL.md") + write(config / "commands" / f"{source.name}.md", + frontmatter({"description": fields["description"]}) + body.rstrip() + "\n\nUser input: $ARGUMENTS\n") + fields, body = reviewer() + # Last matching rule wins. Shell is read-only git; chained commands are split and each part + # is checked, but redirection and --output are not, so they are denied explicitly. + permissions = [ + '{ action: edit, resource: "*", effect: deny }', + '{ action: shell, resource: "*", effect: deny }', + '{ action: shell, resource: "git diff *", effect: allow }', + '{ action: shell, resource: "git log *", effect: allow }', + '{ action: shell, resource: "git show *", effect: allow }', + '{ action: shell, resource: "git status *", effect: allow }', + '{ action: shell, resource: "* --output*", effect: deny }', + '{ action: shell, resource: "*>*", effect: deny }', + ] + write(config / "agents" / "reviewer.md", + frontmatter({"description": fields["description"], "mode": "subagent", "permissions": permissions}) + body) + + plugin = str(KIT / "adapters" / "opencode" / "plugin") + + def register(data): + data.setdefault("$schema", "https://opencode.ai/config.json") + plugins = [p for p in data.setdefault("plugins", []) if not (isinstance(p, str) and p.endswith("/plugin/dev-brain"))] + data["plugins"] = plugins + ([plugin] if plugin not in plugins else []) + if not update_json(config / "opencode.json", register): + print(f' add manually: "plugins": ["{plugin}"]') + return ["Restart the background server when no session is active: opencode service restart", + "Workflows: /start /resume /handoff /plan /impact /learn /review"] + + +def install_claude_code(): + config = Path(os.environ.get("CLAUDE_CONFIG_DIR", HOME / ".claude")) + memory = config / "CLAUDE.md" + line = f"@{CORE / 'AGENTS.md'}" + current = memory.read_text(encoding="utf-8") if memory.exists() else "" + if line not in current: + memory.parent.mkdir(parents=True, exist_ok=True) + memory.write_text(current.rstrip("\n") + ("\n\n" if current.strip() else "") + + f"\n{line}\n", encoding="utf-8") + notes = ["Workflows: /dev-brain:review (or /review when the name is free), same for the others"] + if shutil.which("claude"): + run(["claude", "plugin", "marketplace", "add", str(BUILD)]) + run(["claude", "plugin", "marketplace", "update", "dev-brain"]) + run(["claude", "plugin", "install", "dev-brain@dev-brain"]) + else: + notes.insert(0, f"claude not on PATH: run `claude plugin marketplace add {BUILD}` and " + "`claude plugin install dev-brain@dev-brain`") + return notes + + +def install_codex(): + home = Path(os.environ.get("CODEX_HOME", HOME / ".codex")) + link(CORE / "AGENTS.md", home / "AGENTS.md") + fields, body = reviewer() + # The read-only sandbox is enforced by Codex itself, not by the prompt. + # A TOML literal string keeps the body verbatim: no escape sequences. + toml = (f"# {MARKER}\nname = {json.dumps(fields['name'])}\ndescription = {json.dumps(fields['description'])}\n" + f"sandbox_mode = \"read-only\"\ndeveloper_instructions = '''\n{body.strip()}\n'''\n") + write(home / "agents" / "reviewer.toml", toml) + entry = {"matcher": "startup|resume|clear|compact", "hooks": [{"type": "command", "command": hook_command("hook")}]} + update_json(home / "hooks.json", lambda data: set_hook(data, "SessionStart", entry, nested=True)) + notes = ["Approve the SessionStart hook once in the Codex TUI (new hooks need review before they run)", + "Workflows are skills: $review, $resume, ... (or pick them from /skills)"] + if shutil.which("codex"): + run(["codex", "plugin", "marketplace", "add", str(BUILD)]) + run(["codex", "plugin", "add", "dev-brain@dev-brain"]) + else: + notes.insert(0, f"codex not on PATH: run `codex plugin marketplace add {BUILD}` and `codex plugin add dev-brain@dev-brain`") + return notes + + +def install_cursor(): + home = HOME / ".cursor" + rules = (CORE / "AGENTS.md").read_text(encoding="utf-8") + write(home / "rules" / "dev-brain.mdc", + frontmatter({"description": "Personal engineering rules (dev-brain)", "alwaysApply": "true"}) + rules) + for source in skills() + workflows(): + link(source, home / "skills" / source.name) + fields, body = reviewer() + write(home / "agents" / "reviewer.md", + frontmatter({"name": fields["name"], "description": fields["description"], "readonly": "true"}) + body) + update_json(home / "hooks.json", lambda data: set_hook( + data, "sessionStart", {"command": hook_command("cursor")}, nested=False)) + return [f"If the agent ignores the rules, paste {CORE / 'AGENTS.md'} into Cursor Settings > Rules " + "(file-based global rules are not always loaded)", + "Workflows: /review, /resume, ... (skills invoked by name)"] + + +def detect(): + found = [] + if shutil.which("opencode"): + found.append("opencode") + if shutil.which("claude") or (HOME / ".claude").exists(): + found.append("claude-code") + if shutil.which("codex") or (HOME / ".codex").exists(): + found.append("codex") + if shutil.which("cursor") or shutil.which("cursor-agent") or (HOME / ".cursor").exists(): + found.append("cursor") + return found + + +def main(argv): + if any(arg in ("-h", "--help") for arg in argv): + print(__doc__) + return 0 + unknown = [arg for arg in argv if arg not in TOOLS] + if unknown: + print(f"unknown agent: {', '.join(unknown)} (choose from {', '.join(TOOLS)})") + return 2 + chosen = argv or detect() + if not chosen: + print(f"No supported agent found. Name one: python3 install.py {' '.join(TOOLS)}") + return 1 + if {"claude-code", "codex"} & set(chosen): + build_marketplace() + for tool in chosen: + print(f"{tool}:") + if tool == "opencode": + notes = install_opencode() + elif tool == "claude-code": + notes = install_claude_code() + elif tool == "codex": + notes = install_codex() + else: + notes = install_cursor() + for note in notes: + print(f" - {note}") + print("Done. New sessions pick up the rules, workflows, skills and reviewer.") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/install.sh b/install.sh index 5ba290b..b67ffdd 100755 --- a/install.sh +++ b/install.sh @@ -1,75 +1,6 @@ #!/usr/bin/env bash -# Install dev-brain into the global OpenCode configuration. -# Idempotent: existing files that are not ours are backed up, never deleted. - +# Install dev-brain into one or more coding agents. See install.py --help. +# ./install.sh every agent found on this machine +# ./install.sh opencode codex only those set -eu - -repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)" -config_dir="${XDG_CONFIG_HOME:-$HOME/.config}/opencode" -plugin_dir="$repo_dir/plugin/dev-brain" -stamp="$(date +%Y%m%d%H%M%S)" - -link() { - src="$1" - dst="$2" - if [ -L "$dst" ] && [ "$(readlink "$dst")" = "$src" ]; then - return 0 - fi - if [ -e "$dst" ] || [ -L "$dst" ]; then - mv "$dst" "$dst.bak.$stamp" - echo "backed up: $dst -> $dst.bak.$stamp" - fi - ln -s "$src" "$dst" - echo "linked: $dst" -} - -mkdir -p "$config_dir/commands" "$config_dir/agents" "$config_dir/skills" - -link "$repo_dir/global/AGENTS.md" "$config_dir/AGENTS.md" - -for src in "$repo_dir"/global/commands/*.md; do - link "$src" "$config_dir/commands/$(basename "$src")" -done - -for src in "$repo_dir"/global/agents/*.md; do - link "$src" "$config_dir/agents/$(basename "$src")" -done - -for src in "$repo_dir"/global/skills/*/; do - name="$(basename "$src")" - link "${src%/}" "$config_dir/skills/$name" -done - -config_file="$config_dir/opencode.json" -python3 - "$config_file" "$plugin_dir" <<'PY' -import json -import os -import sys - -path, plugin = sys.argv[1], sys.argv[2] -data = {} -if os.path.exists(path): - try: - with open(path, encoding="utf-8") as handle: - data = json.load(handle) - except (json.JSONDecodeError, OSError) as error: - print(f"warning: cannot parse {path}: {error}") - print(f"add this manually: \"plugins\": [\"{plugin}\"]") - sys.exit(0) - -data.setdefault("$schema", "https://opencode.ai/config.json") -plugins = data.setdefault("plugins", []) -if plugin not in plugins: - plugins.append(plugin) - -with open(path, "w", encoding="utf-8") as handle: - json.dump(data, handle, indent=2) - handle.write("\n") -print(f"plugin registered in {path}") -PY - -echo -echo "Installed. New sessions see the rules, skills and plugin." -echo "Commands require a server that started after this install: when no session is active, run 'opencode service restart'." -echo "Available commands: /start /resume /handoff /plan /impact /learn /review" -echo "Check the plugin with: opencode plugin list" +exec python3 "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)/install.py" "$@" diff --git a/plugin/dev-brain/index.ts b/plugin/dev-brain/index.ts deleted file mode 100644 index 94fc099..0000000 --- a/plugin/dev-brain/index.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { Plugin } from "@opencode/plugin" -import { existsSync, readFileSync } from "node:fs" -import { join } from "node:path" - -const STATE_PATH = ".dev-brain/STATE.md" -// The state rides on every model call of the main session, so it must stay a short -// checkpoint. Above the budget it is not injected at all: truncating would drop the -// "Next" section at the end, which is the part that keeps the user oriented. -const MAX_STATE_CHARS = 3000 - -type State = { text: string } | { oversized: number } - -function readState(root: string): State | undefined { - const file = join(root, STATE_PATH) - if (!existsSync(file)) return undefined - try { - const text = readFileSync(file, "utf8").trim() - if (!text) return undefined - return text.length > MAX_STATE_CHARS ? { oversized: text.length } : { text } - } catch { - return undefined - } -} - -function stateMessage(state: State): string { - if ("oversized" in state) { - return `${STATE_PATH} has ${state.oversized} characters, over the ${MAX_STATE_CHARS}-character budget for automatic injection, so it was not injected. Read it when the task needs saved context, and tell the user to run /handoff to compact it.` - } - return [ - ``, - "Saved project state. Treat it as context, not proof or permission: verify against git and the current source before acting on it.", - "", - state.text, - "", - ].join("\n") -} - -export default Plugin.define({ - id: "dev-brain", - async setup(ctx) { - const root = ctx.location.project?.canonical ?? ctx.location.directory - // Subagent sessions (reviewer, explore, ...) get a focused prompt from their parent; - // the project state would only add tokens to each of their calls. - const isSubagent = new Map() - - async function isSubagentSession(sessionID: string): Promise { - const known = isSubagent.get(sessionID) - if (known !== undefined) return known - try { - const session = await ctx.session.get({ sessionID }) - const child = session.parentID !== undefined - isSubagent.set(sessionID, child) - return child - } catch { - return false - } - } - - await ctx.session.hook("context", async (event) => { - if (await isSubagentSession(event.sessionID)) return - - const state = readState(root) - if (state) { - event.system.push({ type: "text", text: stateMessage(state) }) - return - } - - if (existsSync(join(root, ".git"))) { - event.system.push({ - type: "text", - text: `This repository has no ${STATE_PATH}. If the user wants to adopt it, suggest the /start command. Do not create the file unasked.`, - }) - } - }) - - await ctx.session.hook("compaction", (event) => { - event.system.push({ - type: "text", - text: "Preserve in the summary, in this order: current goal and acceptance criteria, verified evidence (command + PASS/FAIL/NOT RUN), blockers and failed attempts, and the next executable action. These are written to .dev-brain/STATE.md after the session.", - }) - }) - }, -}) From 50fcef9736c3bb17c7ff53cf7cf39ce056fd5ab9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 25 Oct 2026 14:27:44 +0100 Subject: [PATCH 2/4] README: make start the documented first step; check it in every agent Adds a section with the start command per agent, what it creates and why the other workflows depend on it. The offline check now verifies that start is available in OpenCode, Claude Code, Codex and Cursor. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Sm3JtGSXFLR6CZYVJXGHtU --- README.md | 20 ++++++++++++++++++++ evals/offline/check.py | 11 +++++++++-- evals/results.md | 2 +- 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 3ae9be3..3ca056b 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,26 @@ Requires `python3` and `git`. Re-run it after pulling changes. Existing files th - **Codex**: approve the `SessionStart` hook once in the TUI; new hooks need review before they run. - **Cursor**: if the agent ignores the rules, paste `core/AGENTS.md` into Settings > Rules (file-based global rules are not always loaded). +## First step in every repository: `start` + +Run `start` once in each repository before relying on the kit's continuity. Everything else builds on the two files it creates: `resume` and `handoff` read and rewrite the state, the agent's context gets it automatically, and every agent reads the project facts. + +| Agent | Command (from the repository root) | +| --- | --- | +| OpenCode | `/start` | +| Claude Code | `/dev-brain:start` | +| Codex CLI | `$dev-brain:start` | +| Cursor | `/start` | + +What it does: + +1. Inspects the real repository: purpose, stack and versions, exact commands, conventions, gotchas. It does not open data directories (`input/`, `output/`, `.env`). +2. Writes or merges the root `AGENTS.md` (project facts, under 60 lines) and creates or reconciles `.dev-brain/STATE.md` (goal, done with evidence, blockers, next actions, under 3000 characters). +3. Uses files from the previous kit (`harness/`, `NOW.md`, `RULES.md`) as input and lists them for you to delete. On hph, 21 KB of `harness/` became a 3.1 KB `AGENTS.md` and a 1.3 KB state. +4. Reports observed facts, unknowns and problems; changes no code, installs nothing, commits nothing. + +Then read both files, fix anything untrue, and commit them yourself if you want them versioned. Until a repository has a state file, the agent only gets a one-line hint suggesting `start`; the global design rules apply either way. + ## Daily use Ask the agent to implement or fix what you need. The workflows support that work; they are not a mandatory sequence or a switch that enables code quality. Invoke them with the agent's syntax from the table above (`/review`, `/dev-brain:review`, `$dev-brain:review`). diff --git a/evals/offline/check.py b/evals/offline/check.py index df586b9..72cd33b 100644 --- a/evals/offline/check.py +++ b/evals/offline/check.py @@ -30,6 +30,7 @@ STATE_MARK = "Saved project state. Treat it" # header of the injected state block NOTICE = "over the 3000-character budget" REVIEW_FLOW = "Review the current changes by delegating" # core/workflows/review +START_FLOW = "Adopt the current repository into the dev-brain harness" # core/workflows/start STATE = """# State — fixture Updated: 2026-01-01 · Branch: main @@ -171,6 +172,8 @@ def check_opencode(sandbox, mock, opencode): child = [b for b in bodies if b not in main] results = tool_results(bodies) check("opencode: global rules loaded", bool(main) and RULES in system_text(main[0])) + start = Path(sandbox.env["XDG_CONFIG_HOME"]) / "opencode" / "commands" / "start.md" + check("opencode: /start command generated", start.exists() and START_FLOW in start.read_text()) check("opencode: state in the main session", bool(main) and all(STATE_MARK in system_text(b) for b in main)) check("opencode: state not in the subagent", bool(child) and not any(STATE_MARK in system_text(b) for b in child)) check("opencode: reviewer reads the diff with git", any("hello, world" in r for r in results)) @@ -197,6 +200,8 @@ def cmd(prompt): check("claude-code: global rules loaded", RULES in everything) check("claude-code: state injected by the SessionStart hook", bool(bodies) and STATE_MARK in system_text(bodies[0])) check("claude-code: /dev-brain:review expands the workflow", REVIEW_FLOW in everything) + bodies = sandbox.run(mock, cmd("/dev-brain:start"), [{"text": "done"}], env) + check("claude-code: /dev-brain:start expands the workflow", START_FLOW in json.dumps(bodies)) check("claude-code: user-invoked workflows stay out of the skill listing", "dev-brain:debugging" in everything and "dev-brain:handoff" not in everything) @@ -238,6 +243,8 @@ def cmd(prompt, *extra): check("codex: global rules loaded", RULES in everything) check("codex: $dev-brain:review expands the workflow", REVIEW_FLOW in everything) check("codex: reviewer role registered", "Read-only reviewer for correctness" in everything) + bodies = sandbox.run(mock, cmd("$dev-brain:start"), [{"text": "done"}], env) + check("codex: $dev-brain:start expands the workflow", START_FLOW in json.dumps(bodies)) check("codex: state hook waits for the user's trust", STATE_MARK not in everything) # Trusting a hook is the user's decision; the check bypasses it only inside its own sandbox. bodies = sandbox.run(mock, cmd("hello", "--dangerously-bypass-hook-trust"), [{"text": "done"}], env) @@ -251,8 +258,8 @@ def cmd(prompt, *extra): def check_cursor(sandbox): home = Path(sandbox.env["HOME"]) / ".cursor" - expected = ["rules/dev-brain.mdc", "agents/reviewer.md", "hooks.json", "skills/review/SKILL.md", - "skills/debugging/SKILL.md"] + expected = ["rules/dev-brain.mdc", "agents/reviewer.md", "hooks.json", "skills/start/SKILL.md", + "skills/review/SKILL.md", "skills/debugging/SKILL.md"] missing = [name for name in expected if not (home / name).exists()] check("cursor: files generated (not run: no headless Cursor here)", not missing, f"missing {missing}") agent = home / "agents" / "reviewer.md" diff --git a/evals/results.md b/evals/results.md index a7e015f..3bac4f9 100644 --- a/evals/results.md +++ b/evals/results.md @@ -226,7 +226,7 @@ Reviewer enforcement, tested with write attempts (`>`, `touch`, `; rm`, `--outpu - Codex: the role from `~/.codex/agents/reviewer.toml` is registered, but `sandbox_mode = "read-only"` is not applied to the spawned agent: with the parent in `workspace-write` (flag or config), the reviewer created a file. Registering it under `[agents.reviewer] config_file` changed nothing. Documented as instruction-only. - Cursor: `readonly: true` per docs; not run. -`evals/offline/check.py`, extended to all agents found: ALL PASS twice (21 checks, ~12 s). Mutation check: removing `disable-model-invocation` from one workflow makes `claude-code: user-invoked workflows stay out of the skill listing` FAIL. +`evals/offline/check.py`, extended to all agents found: ALL PASS twice (21 checks, ~12 s); 24 after adding `start` expansion checks for each agent. Mutation check: removing `disable-model-invocation` from one workflow makes `claude-code: user-invoked workflows stay out of the skill listing` FAIL. On hph (`/tmp` copy with the adoption patch): Claude Code `/dev-brain:resume` and Codex `$dev-brain:resume` (hook trust bypassed for the test only) both received the hph state, the resume workflow and the hph `AGENTS.md`. From 84d0bc98cdd36479ee6febf46e665581b1afd59e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 25 Oct 2026 14:36:05 +0100 Subject: [PATCH 3/4] Ship dev-brain as a Claude Code plugin; drop unused adapters The user works with Claude Code only. The repository is now a plugin marketplace: two commands install it from GitHub, with no installer, build step or CLAUDE.md edit. One SessionStart hook injects the rules and the project state; workflows are skills that cost no context until invoked. The plan workflow is gone in favour of the native, enforced plan mode, and duplicated templates are gone in favour of the start skill. Core files keep standard formats, so another agent remains an adapter away. Docs are rewritten for one agent and results.md is a decision log; the offline check targets Claude Code only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Sm3JtGSXFLR6CZYVJXGHtU --- .claude-plugin/marketplace.json | 11 + .dev-brain/STATE.md | 21 +- .gitignore | 2 - AGENTS.md | 22 +- MANUALE.md | 495 ++++---------------- README.md | 130 ++--- adapters/opencode/plugin/index.ts | 75 --- core/.claude-plugin/plugin.json | 5 + core/agents/reviewer.md | 1 + core/bin/dev-brain-context | 70 +-- core/hooks/hooks.json | 12 + core/{workflows => skills}/handoff/SKILL.md | 0 core/{workflows => skills}/impact/SKILL.md | 0 core/{workflows => skills}/learn/SKILL.md | 0 core/{workflows => skills}/resume/SKILL.md | 0 core/{workflows => skills}/review/SKILL.md | 2 +- core/{workflows => skills}/start/SKILL.md | 0 core/templates/PROJECT_AGENTS.md | 24 - core/templates/STATE.md | 17 - core/workflows/plan/SKILL.md | 23 - evals/offline/check.py | 295 ++++-------- evals/offline/mock_model.py | 128 +---- evals/results.md | 252 ++-------- evals/scenarios/explain.md | 2 +- evals/scenarios/handoff.md | 2 +- evals/scenarios/resume.md | 2 +- evals/setup.sh | 2 +- install.py | 322 ------------- install.sh | 6 - 29 files changed, 340 insertions(+), 1581 deletions(-) create mode 100644 .claude-plugin/marketplace.json delete mode 100644 .gitignore delete mode 100644 adapters/opencode/plugin/index.ts create mode 100644 core/.claude-plugin/plugin.json create mode 100644 core/hooks/hooks.json rename core/{workflows => skills}/handoff/SKILL.md (100%) rename core/{workflows => skills}/impact/SKILL.md (100%) rename core/{workflows => skills}/learn/SKILL.md (100%) rename core/{workflows => skills}/resume/SKILL.md (100%) rename core/{workflows => skills}/review/SKILL.md (95%) rename core/{workflows => skills}/start/SKILL.md (100%) delete mode 100644 core/templates/PROJECT_AGENTS.md delete mode 100644 core/templates/STATE.md delete mode 100644 core/workflows/plan/SKILL.md delete mode 100644 install.py delete mode 100755 install.sh diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json new file mode 100644 index 0000000..0a4a62a --- /dev/null +++ b/.claude-plugin/marketplace.json @@ -0,0 +1,11 @@ +{ + "name": "dev-brain", + "owner": { "name": "Stcant" }, + "plugins": [ + { + "name": "dev-brain", + "source": "./core", + "description": "Readable, maintainable code at low context cost: global rules, project state, workflows, skills and a read-only reviewer." + } + ] +} diff --git a/.dev-brain/STATE.md b/.dev-brain/STATE.md index eeed0b1..da2d847 100644 --- a/.dev-brain/STATE.md +++ b/.dev-brain/STATE.md @@ -2,22 +2,21 @@ Updated: 2026-10-25 · Branch: improve/token-budget-and-review ## Goal -Agent-independent harness (OpenCode, Claude Code, Codex CLI, Cursor; any model provider) for readable, maintainable code at the lowest context cost — acceptance: one `core/` source, `install.py` per agent, every claim backed by `evals/` evidence. +Claude Code plugin 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) -- `core/` + `install.py` adapters for 4 agents; Claude Code and Codex via a local plugin marketplace in `build/`; state via one script `core/bin/dev-brain-context` — evidence: `python3 evals/offline/check.py` ALL PASS (OpenCode 2.1.4, Claude Code 2.1.310, Codex 0.164, mock model); Cursor files only -- `/review` delegates the diff to the reviewer; plugin skips subagents; 3000-char state budget — evidence: `evals/results.md` 2026-10-25 -- hph adoption patch (`AGENTS.md` + 1.3 KB state) — evidence: state and resume workflow reached Claude Code and Codex on the hph copy; not pushed +- Plugin-only layout: rules + state via `SessionStart` hook, workflows as zero-cost skills, `plan` and other adapters removed, docs compacted — evidence: `python3 evals/offline/check.py` ALL PASS twice (Claude Code 2.1.310, mock model) +- hph adopted: `AGENTS.md` + 1.3 KB state, `harness/` retired — evidence: hph PR #10 open +- Review no longer pays the diff three times (7005 → 1101 chars on hph) — evidence: `evals/results.md` 2026-10-25 ## In progress / blockers -- Codex reviewer read-only — status: blocked upstream; `sandbox_mode` not applied to spawned agents in 0.164, instruction only -- Cursor — status: NOT RUN; no CLI in the test environment; `sessionStart` context dropped by an open Cursor bug -- Real-model and TUI behavior of all workflows — status: NOT RUN +- Benefit of the rules on real code — status: NOT RUN; user postponed the benchmark +- Real-model and interactive behavior of the plugin — status: NOT RUN ## Known pre-existing failures -- `opencode run "/command"` does not expand slash commands (CLI limitation) +- none ## Next (max 3) -1. Run `./install.sh` and `python3 evals/offline/check.py` locally; approve the Codex hook; try `review` and `resume` in each agent's TUI with a real model. -2. Apply the hph patch, delete `harness/`, fix hph README's link to it. -3. Add a non-Python maintainability scenario before changing design rules again. +1. Merge PR #2, install from GitHub (`claude plugin marketplace add Stcant/agents-platform`), try `/dev-brain:start` and `/dev-brain:review` in a real session. +2. Review and merge hph PR #10. +3. Benchmark: same real hph tasks with and without the plugin; keep only rules that move the numbers. diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 3d43339..0000000 --- a/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -build/ -__pycache__/ diff --git a/AGENTS.md b/AGENTS.md index d4ca5b1..68e527f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,29 +1,31 @@ # Maintaining dev-brain -This repository is the source of a personal harness for coding agents (OpenCode, Claude Code, Codex CLI, Cursor). It is not an application. +This repository is a Claude Code plugin marketplace with one plugin, `dev-brain`, in `core/`. 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 -- `core/` — the only source. `AGENTS.md` is the always-loaded rule set: keep it short, only instructions that change default behavior. `workflows/` (user-invoked, `disable-model-invocation: true`) and `skills/` use the Agent Skills format; `agents/reviewer.md` has neutral frontmatter; `bin/dev-brain-context` produces the injected state for every adapter; `templates/` are written into projects. -- `adapters/` — only what cannot be expressed as files (the OpenCode plugin). -- `install.py` — links `core/` or translates frontmatter per agent. It must not contain rules or prose for the model beyond frontmatter; if an adapter needs a rule, it belongs in `core/`. -- `evals/` — scenarios, measured results, and `offline/check.py` with `offline/mock_model.py`, a zero-token check against the real agent binaries. +- `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). +- `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 binary. ## Changing the harness 1. Run the relevant scenarios in `evals/scenarios/` against the current version and record the baseline. 2. Make the smallest change that addresses an observed failure. -3. Re-run the same scenarios with the change. After touching `core/`, an adapter or `install.py`, also run `python3 evals/offline/check.py`. +3. Re-run the same scenarios, and `python3 evals/offline/check.py`. 4. Keep the change only if it improves a scenario or removes a real cost. Delete instructions that do not change behavior. -5. Record the result in `evals/results.md` with the date and the evidence. +5. Record the result in `evals/results.md`: date, change, evidence, limits. Keep it a log of decisions, not of sessions. Never add rules by intuition alone. A rule that the model already follows is pure context cost. ## Constraints - All kit content is English. Exception: `MANUALE.md` is the Italian user manual. -- Runtime dependencies: the agent itself, `python3` and `git`. The OpenCode plugin uses only `@opencode/plugin` and Node built-ins. -- Workflows, skills and the reviewer must be portable: no absolute paths, no agent-specific syntax (`$ARGUMENTS`, `!` command expansion) in `core/`. -- Claude Code and Codex install the plugin from `build/` (generated, git-ignored); Codex copies it and drops symlinks, so the build uses real copies. +- Runtime dependencies: Claude Code, `python3`, `git`. +- Skills and rules stay in standard formats (`AGENTS.md`, `SKILL.md`) with no absolute paths, so another agent can be supported later with an adapter instead of a rewrite. +- 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 274df01..5ad3c8b 100644 --- a/MANUALE.md +++ b/MANUALE.md @@ -1,165 +1,62 @@ # dev-brain — Manuale d'uso -> Manuale utente in italiano. Il codice, i workflow e le skill del kit sono in inglese; questo file è l'unica eccezione. -> Versione: 2026-10-25. Funziona con OpenCode (provato su 2.1.4), Claude Code (2.1.310), Codex CLI (0.164) e Cursor (non provato: nessuna CLI disponibile nell'ambiente di test). Indipendente dal provider del modello. - -## Indice - -- Avvio rapido -- 1. Cos'è -- 2. Come è costruito -- 3. Installazione e verifica -- 4. Prima adozione di una repository -- 5. Lavoro quotidiano -- 6. I workflow in dettaglio -- 7. I due file di progetto -- 8. Lo stato nel contesto dell'agente -- 9. Regole, permessi e sicurezza -- 10. Le skill -- 11. Il reviewer -- 12. Manutenzione del kit -- 13. Problemi e domande frequenti -- 14. Limiti noti -- 15. Checklist - ---- +> Manuale utente in italiano; il resto del kit è in inglese. Versione 2026-10-25, plugin 2.0.0, provato su Claude Code 2.1.310. Indipendente dal provider del modello. ## Avvio rapido ```bash -# dalla cartella del kit: installa per ogni agente trovato sulla macchina -./install.sh -# oppure solo quelli che vuoi -./install.sh opencode claude-code codex cursor +claude plugin marketplace add Stcant/agents-platform +claude plugin install dev-brain@dev-brain ``` -Poi fai una normale richiesta di codice. Le regole di leggibilità e manutenibilità sono già attive: non devi scrivere “fallo bene”, né invocare una skill. +Poi, nella radice di ogni repository, una volta sola: -I workflow si invocano con la sintassi del tuo agente: - -| Agente | Esempio | -| --- | --- | -| OpenCode | `/review` | -| Claude Code | `/dev-brain:review` | -| Codex CLI | `$dev-brain:review` | -| Cursor | `/review` | +```text +/dev-brain:start +``` -Sequenza tipica per un progetto adottato: `start` la prima volta, poi `resume` → lavoro → `review` → `handoff`. +Da lì: `resume` a inizio sessione → lavoro → `review` → `handoff` a fine lavoro. Le regole di qualità valgono anche senza nessun workflow. --- ## 1. Cos'è -dev-brain è un harness personale per agenti di coding. Non è un'applicazione e non è un agente autonomo: è un insieme di regole, workflow, skill, un reviewer e un meccanismo di stato. Rende il lavoro più prevedibile e continuo tra sessioni, repository e strumenti. - -L'obiettivo principale è **codice leggibile, manutenibile e facile da modificare**. Stato e workflow servono a sostenerlo. - -Fornisce: - -- regole sempre attive, volutamente poche; -- sette workflow invocati da te: `start`, `resume`, `handoff`, `plan`, `impact`, `learn`, `review`; -- tre skill che il modello carica quando servono: `debugging`, `review-feedback`, `engineering-risk`; -- un reviewer indipendente in sola lettura; -- lo stato del progetto iniettato nel contesto, con un budget di dimensione; -- un controllo offline a costo zero e un metodo di valutazione per capire se una regola funziona davvero. - -Non fa queste cose: - -- non decide quando committare; -- non sostituisce git, i test o la tua revisione; -- non garantisce che il modello segua le regole: le regole sono contesto. Dove l'agente lo permette (permessi, sandbox), alcune cose sono anche imposte; vedi sezione 2. - ---- - -## 2. Come è costruito - -**`core/` è l'unica fonte.** Usa i due formati che tutti gli agenti condividono: +Un plugin per Claude Code. Fa tre cose: -- `AGENTS.md` per le regole; -- Agent Skills (`SKILL.md`) per workflow e skill. +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. +3. **Workflow e reviewer**: procedure ripetibili per adottare una repo, riprendere, chiudere, analizzare l'impatto, capire un flusso e fare review in sola lettura. -`install.py` collega o traduce `core/` in ciò che ogni agente legge. Nessuna regola vive negli adattatori: se cambi una regola in `core/`, cambia per tutti. - -| | OpenCode | Claude Code | Codex CLI | Cursor | -| --- | --- | --- | --- | --- | -| Regole globali | `AGENTS.md` (link) | `CLAUDE.md` importa `core/AGENTS.md` | `AGENTS.md` (link) | `rules/dev-brain.mdc` (copia) | -| Workflow | comandi `/review` | plugin, `/dev-brain:review` | plugin, `$dev-brain:review` | skill, `/review` | -| Skill | `skills/` (link) | plugin | plugin | `skills/` (link) | -| Reviewer in sola lettura | **imposto**: solo `git diff/log/show/status`, `>` e `--output` bloccati | **imposto**: altri comandi chiedono la tua approvazione | **solo istruzione**: `sandbox_mode` non vale per i subagenti (Codex 0.164) | `readonly: true` (non provato) | -| Stato nel contesto | plugin, a ogni chiamata della sessione principale | hook `SessionStart` | hook `SessionStart`, dopo che lo approvi una volta | hook `sessionStart` (bug di Cursor) + regola di riserva | - -**Regola di riserva:** se l'agente non riesce a iniettare lo stato, le regole globali gli dicono di leggere `.dev-brain/STATE.md` prima di continuare un lavoro iniziato. Funziona con qualsiasi agente che legge `AGENTS.md`, ma costa una lettura e dipende dal modello. - -**Perché Claude Code e Codex usano un plugin:** è l'unico canale che porta skill, workflow e hook senza toccare le loro impostazioni a mano, ed è namespaced (`dev-brain:`), quindi non collide con i comandi integrati come `/review`. L'installer costruisce un marketplace locale in `build/` e lo installa con la CLI dell'agente. Codex copia il plugin e ignora i link simbolici, per questo il build contiene copie vere. +Non decide quando committare, non sostituisce test né la tua revisione, e non garantisce che il modello segua le regole: le regole sono contesto. Imposti davvero dallo strumento sono solo due vincoli: il reviewer in sola lettura e il budget dello stato. --- -## 3. Installazione e verifica - -### Prerequisiti - -- almeno uno tra OpenCode V2, Claude Code, Codex CLI, Cursor; -- `python3` e `git`. - -### Installazione - -```bash -cd -./install.sh # agenti trovati: CLI nel PATH o cartella di configurazione presente -./install.sh opencode codex # solo questi -``` - -Lo script: - -1. collega le regole o le traduce nel formato dell'agente; -2. genera comandi, agenti e hook dove servono; -3. per Claude Code e Codex costruisce e installa il plugin `dev-brain`; -4. se trova un file non gestito dal kit, lo sposta in `*.bak.` invece di cancellarlo; -5. è idempotente: rieseguirlo non duplica nulla. - -Passi manuali, una volta sola: - -- **OpenCode:** `opencode service restart` quando non hai sessioni attive, altrimenti il server usa i template in cache. -- **Codex:** approva l'hook `SessionStart` nella TUI. Codex non esegue hook nuovi finché non li hai rivisti. -- **Cursor:** se l'agente ignora le regole, incolla `core/AGENTS.md` in Settings > Rules. Le regole globali su file non sempre vengono caricate (bug noto di Cursor). - -### Verifica - -```bash -python3 evals/offline/check.py -``` +## 2. Installazione -Deve stampare `ALL PASS`. Verifica ogni agente installato senza spendere token (sezione 12). - -### Aggiornamento +Prerequisiti: Claude Code, `python3`, `git`. ```bash -git pull -./install.sh +claude plugin marketplace add Stcant/agents-platform +claude plugin install dev-brain@dev-brain ``` -Rieseguire l'installer serve sempre: Codex e Cursor ricevono copie, e il plugin cambia versione quando cambia il contenuto. - -### Disinstallazione +- **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. -Non c'è uno script. In breve: +Il plugin non tocca `CLAUDE.md` né le tue impostazioni: regole e stato arrivano da un hook `SessionStart`. -- OpenCode: rimuovi `AGENTS.md`, `commands/{start,resume,handoff,plan,impact,learn,review}.md`, `agents/reviewer.md`, `skills/{debugging,review-feedback,engineering-risk}` da `~/.config/opencode/` e il percorso del plugin da `opencode.json`; -- Claude Code: `claude plugin uninstall dev-brain@dev-brain` e togli la riga `@.../core/AGENTS.md` da `~/.claude/CLAUDE.md`; -- Codex: `codex plugin remove dev-brain@dev-brain`, rimuovi `~/.codex/AGENTS.md`, `~/.codex/agents/reviewer.toml` e la voce `dev-brain-context` da `~/.codex/hooks.json`; -- Cursor: rimuovi `~/.cursor/rules/dev-brain.mdc`, `~/.cursor/agents/reviewer.md`, i link in `~/.cursor/skills/` e la voce `dev-brain-context` da `~/.cursor/hooks.json`. - -Ripristina eventuali backup `*.bak.`. I file nei repository (`AGENTS.md`, `.dev-brain/STATE.md`) restano. +**Verifica:** `python3 evals/offline/check.py` dalla cartella del kit deve stampare `ALL PASS` (sezione 8). --- -## 4. Prima adozione di una repository +## 3. Primo passo in ogni repository: `/dev-brain:start` -Lancia il workflow `start` nella radice della repository. Crea o aggiorna due file: +Crea o aggiorna due file: ```text / -├── AGENTS.md fatti del progetto, meno di 60 righe +├── AGENTS.md fatti del progetto, meno di 60 righe (Claude Code lo legge da solo) └── .dev-brain/ └── STATE.md obiettivo, fatto, blocchi, prossime azioni, meno di 3000 caratteri ``` @@ -167,137 +64,61 @@ Lancia il workflow `start` nella radice della repository. Crea o aggiorna due fi Cosa fa: - legge codice, configurazione, README e comandi reali; -- se `AGENTS.md` esiste, lo integra preservando le istruzioni presenti; -- se `.dev-brain/STATE.md` esiste, lo riconcilia invece di sovrascriverlo; -- se trova file del vecchio kit (`harness/PROJECT_STATE.md`, `harness/PROJECT_MAP.md`, `NOW.md`, `RULES.md`), li usa come fonte e te li elenca da eliminare, senza cancellarli; -- riporta fatti osservati, incognite, file legacy e problemi trovati; -- non modifica codice, dipendenze, configurazione o storia git, non installa nulla, non committa. - -**Esempio reale:** in hph i 21 KB di `harness/` sono diventati un `AGENTS.md` di 3,1 KB e uno stato di 1,3 KB. - -### Privacy - -Non aprire e non elencare directory che possono contenere dati personali, clinici o segreti (`input/`, `output/`, `.env`). Usa README e configurazione. Non copiare mai questi dati in `AGENTS.md`, nello stato o nella chat: lo stato viene inviato al provider del modello. +- integra un `AGENTS.md` esistente preservandone le istruzioni; +- riconcilia uno stato esistente invece di sovrascriverlo; +- usa i file del vecchio kit (`harness/`, `NOW.md`, `RULES.md`) come fonte e te li elenca da eliminare; +- riporta fatti, incognite e problemi. -### Dopo `start` +Non tocca codice, dipendenze o git, e non installa nulla. Non apre directory con dati personali, clinici o segreti (`input/`, `output/`, `.env`). -Leggi i due file e correggi ciò che non è vero. Sono pensati per essere versionati; se e quando decidi tu, committali separatamente dal codice: - -```bash -git diff -- AGENTS.md .dev-brain/STATE.md -git add AGENTS.md .dev-brain/STATE.md -git commit -m "Adopt dev-brain project instructions and state" -``` +Dopo: rileggi i due file, correggi ciò che non è vero, e committali tu se vuoi versionarli. Esempio reale: in hph i 21 KB di `harness/` sono diventati 4,4 KB (PR #10 su hph). --- -## 5. Lavoro quotidiano +## 4. I workflow -Il lavoro principale resta una normale richiesta di implementazione o correzione, con risultato atteso e vincoli. I workflow sono strumenti di supporto, non una sequenza obbligatoria. +Si invocano con `/dev-brain:`. Il testo dopo il nome è l'argomento. Non costano contesto finché non li usi (`disable-model-invocation`). -| Momento | Workflow | Cosa ottieni | +| Workflow | Quando | Scrive | | --- | --- | --- | -| Prima volta in una repo | `start` | `AGENTS.md` + `.dev-brain/STATE.md` | -| Inizio sessione | `resume` | Stato riconciliato con git e codice | -| Modifica non banale | `plan` | Piano in massimo 5 passi, con verifiche | -| Prima di toccare codice condiviso | `impact` | Consumatori, contratti, test, incognite | -| Capire un flusso | `learn` | Spiegazione basata sul codice reale | -| Prima di committare | `review` | Review indipendente delle modifiche | -| Fine lavoro | `handoff` | Stato aggiornato con evidenza fresca | - -Un flusso tipico: - -1. `resume`: obiettivo, ultimo risultato verificato, blocchi, prossima azione. -2. Se la modifica è non banale, `plan` e poi `impact`. -3. Implementa. -4. Fai eseguire test e controlli all'agente principale, o eseguili tu: il reviewer non li lancia. -5. `review`. -6. `handoff`. -7. Committa solo se hai deciso di farlo. - ---- - -## 6. I workflow in dettaglio - -Ogni workflow è una skill in `core/workflows//SKILL.md` con `disable-model-invocation: true`: parte solo quando lo chiedi tu. Il testo che scrivi dopo il nome del workflow è l'argomento (obiettivo, area, scope). - -### `start` - -Prima adozione, o riallineamento dei fatti del progetto. **Scrive:** solo `AGENTS.md` e `.dev-brain/STATE.md`. Dettagli nella sezione 4. - -### `resume` - -**Quando:** all'inizio di una sessione, soprattutto dopo una pausa. - -- legge stato e `AGENTS.md`, esegue `git status` e `git log`; -- se lo stato è vecchio, lo dice prima di proseguire; -- esegue un controllo registrato solo se è veloce e in sola lettura. Riporta come `NOT RUN`, senza eseguirlo, ciò che installa, scarica, compila o crea ambienti (`uv sync`, `pip install`, `npm install`, `uv run` senza `.venv`, `cargo test`, build complete); -- riporta obiettivo, ultimo risultato verificato, blocchi e una prossima azione. - -**Scrive:** no. È un'istruzione al modello, non un blocco tecnico. - -### `handoff` - -**Quando:** alla fine di un lavoro significativo. - -- ricostruisce cosa è successo davvero da diff, controlli e conversazione; -- riscrive lo stato: obiettivo, fatto con evidenza (massimo 5), blocchi, prossime azioni (massimo 3), meno di 3000 caratteri; -- aggiorna `AGENTS.md` solo se è cambiato un fatto stabile. - -**Scrive:** lo stato. Non committa. Lo stato non è un diario: sostituisci le righe vecchie. - -### `plan` - -**Quando:** una modifica non banale, prima di scrivere codice. Produce un piano-contratto in sola lettura, massimo 5 passi. Ogni passo è un risultato concreto con file o simboli, input → output, dipendenze e un controllo che può fallire. Le decisioni che cambiano comportamento o dati ti vengono chieste prima. - -Non cambia agente: dopo il piano puoi chiedere subito di implementare. Prima, in OpenCode, la sessione restava bloccata in modalità `plan`. - -### `impact` - -**Quando:** prima di cambiare un contratto, un formato, un dato persistito o codice condiviso. Analisi in sola lettura di consumatori, contratti a rischio, test e configurazione, file da modificare e da rivedere, controlli esistenti, incognite. Etichette `OBSERVED`, `INFERRED`, `UNKNOWN`. +| `start` | Prima adozione | `AGENTS.md`, stato | +| `resume` | Inizio sessione: riconcilia lo stato con git e codice, riporta obiettivo, ultimo risultato verificato, blocchi, una prossima azione | No | +| `handoff` | Fine lavoro: riscrive lo stato con evidenza fresca (massimo 5 “Done”, 3 “Next”, meno di 3000 caratteri) | Stato | +| `impact ` | Prima di toccare codice condiviso: consumatori, contratti, test, incognite (OBSERVED / INFERRED / UNKNOWN) | No | +| `learn ` | Capire un flusso o uno stack: catena reale di file e simboli, ordine di lettura | No | +| `review [scope]` | Prima di committare: delega al reviewer tutte le modifiche non committate | No | -### `learn` +**Pianificazione:** usa il **plan mode** nativo (Shift+Tab). È in sola lettura per costruzione, cosa che un workflow scritto come prompt non può garantire. Per questo il workflow `plan` è stato rimosso. -**Quando:** devi capire un flusso, un componente o uno stack nuovo. Procede per strati: ambito, inventario, connessioni reali, un flusso concreto, ordine di lettura. Formato: +**`resume`** esegue un controllo registrato solo se è veloce e in sola lettura. Riporta come `NOT RUN` ciò che installa, scarica o compila (`npm install`, `uv sync`, `cargo test`…). -```text -Flow: -> : -> : -``` +**`review`** passa al reviewer solo nomi e conteggi dei file: il diff lo legge lui con git. Prima il diff si pagava tre volte. Su un diff di 5,9 KB il messaggio è sceso da 7005 a 1101 caratteri. -### `review` - -**Quando:** prima di committare o aprire una PR. +--- -- l'agente principale esegue `git status` e `git diff HEAD --stat`: nomi e conteggi, non il contenuto; -- delega al reviewer, che legge da solo le modifiche con git; -- riporta i risultati senza ammorbidirli. +## 5. Il reviewer -Senza scope copre tutto ciò che non è committato: in staging, non in staging e file nuovi. Con uno scope (per esempio “ultimo commit”) il reviewer usa `git show` o `git log`. +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. -**Perché così:** prima il diff completo entrava nel contesto principale, veniva ricopiato come output nel prompt del subagente e riletto dal reviewer: si pagava tre volte. Su un diff di 5,9 KB in hph il messaggio di review è sceso da 7005 a 1101 caratteri. +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`. --- -## 7. I due file di progetto +## 6. Le skill -### `AGENTS.md` +Il modello le carica quando servono; puoi anche chiederle per nome. -Tutti e quattro gli agenti lo leggono nella radice del progetto. Contiene solo fatti che l'agente non può dedurre in fretta: +| Skill | Quando | Metodo | +| --- | --- | --- | +| `debugging` | Bug, test che fallisce | Riprodurre, localizzare, ipotizzare, testare, correggere la causa, verificare | +| `engineering-risk` | Auth, input, segreti, dati persistiti, migrazioni, concorrenza, prestazioni | Solo il riferimento pertinente: sicurezza, dati, prestazioni | +| `review-feedback` | Commenti di review | Classifica: SUPPORTED, UNSUPPORTED, NEEDS CONTEXT, OUT OF SCOPE | -```markdown -# - - -## Stack -## Comandi (con directory ed effetti collaterali) -## Struttura -## Convenzioni e gotcha -## Da non fare -``` +--- -Meno di 60 righe. Niente consigli generici (stanno nelle regole globali), niente path assoluti della tua macchina. +## 7. Lo stato -### `.dev-brain/STATE.md` +Formato di `.dev-brain/STATE.md`: ```markdown # State — @@ -319,199 +140,55 @@ Updated: · Branch: 1. ``` -Regole: meno di 3000 caratteri (oltre viene iniettato solo un avviso); ogni voce “Done” ha un comando e un esito reale; `PASS` significa eseguito e passato; sostituisci le righe vecchie; niente dati sensibili; una sola sessione alla volta fa `handoff`. - ---- - -## 8. Lo stato nel contesto dell'agente - -Uno script unico, `core/bin/dev-brain-context`, produce il testo per tutti gli agenti: - -- con uno stato valido: un blocco `` con l'avviso che è contesto, non prova né permesso; -- oltre i 3000 caratteri: una riga che dice al modello di leggerlo quando serve e di proporti `handoff` per compattarlo. Non viene troncato, perché il taglio eliminerebbe proprio “Next”, che sta in fondo; -- in una repo git senza stato: una riga che suggerisce `start`, senza creare nulla; -- fuori da una repo: niente. - -Come arriva all'agente: - -- **OpenCode:** il plugin lo aggiunge a ogni chiamata della sessione principale; i subagenti non lo ricevono. Rilegge il file solo quando cambia. In compattazione chiede al riassunto di conservare obiettivo, evidenza, blocchi e prossima azione. -- **Claude Code:** hook `SessionStart` all'avvio, al resume, dopo `/clear` e dopo la compattazione. -- **Codex:** stesso hook, dopo la tua approvazione nella TUI. -- **Cursor:** hook `sessionStart`. Cursor ha un bug aperto che scarta questo contesto, quindi vale la regola di riserva. - -Per disattivarlo in una repository, rinomina `.dev-brain/STATE.md`. - ---- - -## 9. Regole, permessi e sicurezza - -Le regole globali vivono in `core/AGENTS.md`. - -### Precedenza - -```text -correttezza > sicurezza e integrità dei dati > compatibilità col progetto > manutenibilità > semplicità > prestazioni misurate -``` - -### Qualità del codice, sempre attiva - -- la soluzione più semplice che soddisfa davvero i requisiti, non quella con meno righe; niente funzionalità ipotetiche; -- idiomi del linguaggio e convenzioni del progetto, senza imporre classi o livelli; -- nomi che esprimono l'intento, responsabilità coese, effetti espliciti; divisione per responsabilità; -- una sola fonte per la stessa regola di business, senza accoppiare concetti diversi solo perché il codice si assomiglia; -- contratti e gestione degli errori preservati, niente fallback silenziosi; -- rilettura del codice modificato prima della consegna, senza refactor estranei. - -### Autorizzazione - -- leggere o adottare una repository non autorizza modifiche; -- nessun commit, amend o push se non lo decidi tu; implementare, testare, fare review o handoff non è un permesso di commit; -- nessun cambio di branch, operazione distruttiva, migrazione, deploy o pubblicazione senza un permesso esplicito; -- il lavoro non committato si preserva; niente pulizie non richieste; -- niente letture di segreti, dati personali o clinici senza necessità. - -### Test, debug e reporting - -- per un bug o un comportamento nuovo, prima un test mirato che fallisce per il motivo giusto; -- dopo 3 tentativi equivalenti falliti, fermarsi e riportare; -- ogni controllo come `PASS`, `FAIL`, `NOT RUN` o `N/A`, con il comando reale; “implementato” non è “verificato”; -- la spiegazione dettagliata (Flow / Why / Checks / Read next) solo se la chiedi: consuma token. +Arriva in ogni sessione insieme alle regole: all'avvio, al resume, dopo `/clear`, dopo la compattazione. Sopra i 3000 caratteri arriva solo un avviso che chiede di compattarlo con `handoff`. Non viene troncato, perché il taglio eliminerebbe proprio “Next”. In una repo senza stato arriva una riga che suggerisce `start`. -### Cosa significa “permesso” - -Che hai chiesto esplicitamente quell'azione. Non basta che sia utile. Il kit non modifica le permission globali dei tuoi agenti: impone restrizioni solo al reviewer. - ---- - -## 10. Le skill - -Il modello le carica quando il compito corrisponde alla descrizione; puoi anche chiederle per nome. - -| Skill | Quando | Cosa impone | -| --- | --- | --- | -| `debugging` | Bug, test che fallisce, comportamento inatteso | Riprodurre, localizzare, ipotizzare, testare, correggere la causa, verificare | -| `review-feedback` | Commenti di review o findings di un altro agente | Classificare ogni commento prima di implementarlo | -| `engineering-risk` | Auth, input, segreti, dati persistiti, migrazioni, concorrenza, servizi esterni, prestazioni | Leggere solo il riferimento pertinente | - -`review-feedback` classifica in `SUPPORTED` (correggi con un controllo), `UNSUPPORTED` (rispondi con l'evidenza), `NEEDS CONTEXT` (fai la domanda), `OUT OF SCOPE` (registra e proponi a parte). - ---- - -## 11. Il reviewer - -Subagente indipendente, in sola lettura. Riporta difetti di correttezza, sicurezza, integrità dei dati o requisiti, separati dai problemi concreti di manutenibilità. Per ogni finding: `file:line`, trigger o scenario di manutenzione, impatto, correzione minima, confidenza. Niente preferenze cosmetiche. Se non trova nulla, lo dice. - -Quanto è davvero “in sola lettura” dipende dall'agente (verificato nel controllo offline): - -- **OpenCode:** imposto. Sono permessi solo `git diff`, `git log`, `git show`, `git status`. Bloccati `>`, `--output` e i comandi concatenati che contengono altro. OpenCode non blocca da solo la redirezione `>`, per questo c'è una regola esplicita. -- **Claude Code:** imposto con una lista di strumenti. Ogni comando che crea o modifica file chiede la tua approvazione: rispondi no. -- **Codex:** solo istruzione. Il file del reviewer dichiara `sandbox_mode = "read-only"`, ma Codex 0.164 non lo applica ai subagenti generati: con il genitore in `workspace-write` il reviewer ha scritto un file nel test. -- **Cursor:** `readonly: true`, che secondo la documentazione blocca modifiche e comandi che cambiano lo stato. Non provato. - -Non esegue test o build e non conosce l'intento se non è nello scope. +Regole: evidenza reale con comando, righe vecchie sostituite (non è un diario), nessun dato sensibile (viene inviato al provider), una sola sessione alla volta fa `handoff`. Per disattivarlo in una repo, rinomina il file. --- -## 12. Manutenzione del kit - -### Struttura +## 8. Manutenzione del kit ```text -core/ unica fonte: AGENTS.md, workflows/, skills/, agents/reviewer.md, bin/, templates/ -adapters/ codice specifico che non si può esprimere come file (plugin OpenCode) -install.py collega o traduce core/ per ogni agente; install.sh è un wrapper -evals/ scenari, fixture, risultati, controllo offline -MANUALE.md questo manuale +.claude-plugin/marketplace.json elenca il plugin +core/ il plugin: AGENTS.md, skills/, agents/, hooks/, bin/ +evals/ scenari, fixture, risultati, controllo offline ``` -### Modificare il kit - -1. Una modifica piccola e mirata, in `core/` se riguarda il comportamento del modello. -2. Se cambia il comportamento, esegui gli scenari in `evals/scenarios/` e registra il baseline. -3. Applica la modifica e riesegui gli stessi scenari. -4. Esegui `python3 evals/offline/check.py`. -5. Tieni la modifica solo se migliora uno scenario o rimuove un costo reale; registra l'esito in `evals/results.md`. - -Non aggiungere regole per intuizione: una regola che il modello già segue è solo costo di contesto. Niente sintassi specifica di un agente in `core/` (`$ARGUMENTS`, espansioni `!`). - -### Controllo offline, a costo zero +Per modificare il kit: -```bash -python3 evals/offline/check.py # OPENCODE / CLAUDE / CODEX= se non sono nel PATH -``` +1. Una modifica piccola, motivata da un fallimento osservato. +2. Scenari prima e dopo (`evals/scenarios/`), più `python3 evals/offline/check.py`. +3. Tienila solo se migliora qualcosa o toglie un costo reale. +4. Alza `version` in `core/.claude-plugin/plugin.json` e registra la decisione in `evals/results.md`. -Per ogni CLI trovata installa il kit in una home temporanea e sostituisce il modello con un server locale finto che registra ogni richiesta. In circa 10 secondi, senza spendere token, verifica: +Il **controllo offline** installa il plugin in una home temporanea e sostituisce il modello con un server locale finto che registra ogni richiesta. In circa 15 secondi, senza token, verifica: -- regole globali caricate; -- stato nella sessione principale (e non nei subagenti, in OpenCode); -- stato troppo lungo sostituito dall'avviso; -- workflow che si espandono; +- regole e stato nella sessione; +- avviso per lo stato troppo lungo; +- workflow che si espandono e restano fuori dall'elenco delle skill; - reviewer che legge il diff ma non scrive. -Per Cursor controlla solo i file generati. Non valuta la qualità delle risposte: per quella restano gli scenari. +Non valuta la qualità delle risposte. -### Scenari con un modello reale - -```bash -# Solo dopo aver autorizzato i commit locali delle fixture: -./evals/setup.sh -cd /tmp/opencode/dev-brain-evals/bugfix -opencode run --standalone -m "The discount test fails. Fix the code." < /dev/null -``` - -Negli script chiudi lo stdin (`< /dev/null`): `opencode run` legge lo stdin quando non è un terminale e resta in attesa. - -### Backup - -- i file non gestiti vengono salvati come `*.bak.`; -- il kit è referenziato con percorso assoluto: se sposti la cartella, riesegui l'installer; -- non copiare fatti di progetto nel repository del kit. +`core/AGENTS.md` e le skill restano in formati standard: supportare un altro agente in futuro richiede un adattatore, non una riscrittura. --- -## 13. Problemi e domande frequenti +## 9. Problemi frequenti -| Sintomo | Causa e soluzione | +| Sintomo | Soluzione | | --- | --- | -| OpenCode: i comandi non compaiono o una modifica non ha effetto | `opencode service restart` quando non hai sessioni attive; apri una nuova sessione | -| OpenCode: `opencode run "/resume"` non espande il comando | Limite della CLI: usa la TUI | -| Uno script con `opencode run` resta fermo | Aggiungi `< /dev/null` | -| Claude Code: `/review` apre la review integrata | Usa `/dev-brain:review`: i comandi integrati hanno la precedenza | -| Codex: lo stato non arriva | Approva l'hook `SessionStart` nella TUI; nel frattempo vale la regola di riserva | -| Codex: dopo un aggiornamento vedo la versione vecchia | Riesegui `./install.sh codex`: Codex usa una copia del plugin | -| Cursor: le regole non vengono applicate | Incolla `core/AGENTS.md` in Settings > Rules | -| Lo stato non viene iniettato | Controlla che `.dev-brain/STATE.md` sia nella radice, non vuoto, sotto i 3000 caratteri; i subagenti non lo ricevono per scelta | -| Lo stato cresce troppo | Arriva solo l'avviso: compattalo con `handoff` | -| Il reviewer chiede di eseguire un comando che scrive | Rispondi no: il reviewer è in sola lettura | -| L'installer ha spostato un mio file | Cerca `.bak.` e unisci il contenuto | -| Un file JSON non viene aggiornato | Contiene commenti o non è JSON valido: l'installer non lo tocca e lo segnala; aggiungi la voce a mano | -| Ho dati clinici o segreti nello stato | Rimuovili subito, valuta la rotazione delle credenziali, non committare: lo stato viene inviato al provider | +| `/review` apre la review integrata | Usa `/dev-brain:review`: i comandi integrati hanno la precedenza | +| Lo stato non arriva | File nella radice, non vuoto, sotto 3000 caratteri; `python3` disponibile; nuova sessione | +| Dopo un aggiornamento vedo la versione vecchia | `claude plugin marketplace update dev-brain` e nuova sessione | +| Il reviewer chiede di eseguire un comando che scrive | Rispondi no | +| Ho dati sensibili nello stato | Rimuovili subito; non committare | --- -## 14. Limiti noti - -- Le prove con modelli reali usano fixture piccole e pochi run; i risultati dipendono dal modello. Dettagli in `evals/results.md`. -- Il controllo offline verifica cosa il kit invia e permette, non la qualità delle risposte. -- La nuova architettura multi-agente non è ancora stata provata con un modello reale, né nelle TUI. -- Cursor non è stato eseguito: i suoi file sono generati secondo la documentazione e controllati solo per presenza. -- Codex: il reviewer in sola lettura è solo un'istruzione (`sandbox_mode` non applicato ai subagenti in 0.164). -- Le regole sono contesto: il modello può non seguirle. Workflow e skill riducono la variabilità, non la eliminano. -- `resume` dipende dal rispetto delle istruzioni di sola lettura. -- Codex elenca anche i workflow tra le skill (non rispetta `disable-model-invocation`): circa 1200 caratteri (~300 token) in più nel prompt di sistema. -- Una sola sessione dovrebbe aggiornare lo stato alla volta. -- Non c'è uno script di disinstallazione. - ---- +## 10. Limiti noti -## 15. Checklist - -- [ ] `./install.sh` eseguito senza errori -- [ ] `python3 evals/offline/check.py` stampa `ALL PASS` -- [ ] OpenCode: server riavviato; Codex: hook approvato; Cursor: regole visibili in Settings -- [ ] `start` eseguito su almeno una repository -- [ ] `AGENTS.md` sotto 60 righe, senza path assoluti né dati sensibili -- [ ] `.dev-brain/STATE.md` sotto 3000 caratteri, con evidenza reale -- [ ] I due file di progetto revisionati; eventuale commit separato, solo per tua decisione -- [ ] `resume`, `review` e `handoff` provati in una sessione reale con ogni agente che usi -- [ ] Nessun dato clinico, personale o segreto in stato, istruzioni o chat +- L'effetto delle regole sulla qualità del codice **non è misurato** con un modello reale: le prove esistenti sono poche e sintetiche (`evals/results.md`). È il prossimo lavoro da fare. +- 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. diff --git a/README.md b/README.md index 3ca056b..02ca9a1 100644 --- a/README.md +++ b/README.md @@ -1,136 +1,74 @@ # dev-brain -Personal engineering harness for coding agents: **OpenCode, Claude Code, Codex CLI and Cursor**, with any model provider. One install, used across every repository. - -Its primary goal is to guide normal coding requests toward readable, maintainable code, adapted to each project's language and conventions. Workflows and saved state are supporting tools, not the purpose of the kit. +A Claude Code plugin 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 Claude Code can use. It provides: -- rules that are always loaded, kept short and limited to behavior the model would not follow by default; -- user-invoked workflows: start, resume, handoff, plan, impact, learn, review; -- an independent read-only reviewer; -- three on-demand skills: debugging, review feedback, engineering risk; -- the project's saved state injected into the agent's context, within a size budget. - -Project facts stay in each repository. Nothing from one project is reused in another. +- global engineering rules, injected into every session; +- the project's saved state, injected within a 3000-character budget; +- 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. > Manuale utente in italiano: [MANUALE.md](MANUALE.md). -## Code quality by default - -The global rules apply to ordinary coding requests; no special workflow is required. They favor complete but simple solutions, cohesive responsibilities, explicit effects, intention-revealing names and a single source for shared business rules. They reject speculative abstractions, forced layering and silent error handling. Before delivery the agent checks its changed code for these problems without adding an unsolicited explanation. - -These are language-independent criteria, not a Python style guide. The agent discovers the stack and follows its idioms. The review workflow adds an independent check for defects and concrete maintenance costs, not cosmetic preferences. - -| Always active | Used when helpful | Requires your explicit decision | -| --- | --- | --- | -| Code-design guidance and self-review of changed code | Planning, impact analysis, independent review and session continuity | Commits, amendments and pushes; unrelated refactors, new dependencies or architecture changes must be proposed first | - -Detailed change walkthroughs are on request only. See [`core/AGENTS.md`](core/AGENTS.md) for the full rules. Instructions guide the model; they do not guarantee good code. - -## How it is built - -`core/` is the only source. It uses the formats the agents share: `AGENTS.md` for rules and Agent Skills (`SKILL.md`) for workflows and skills. `install.py` links or translates it into what each agent reads; no rule lives in an adapter. - -| | OpenCode | Claude Code | Codex CLI | Cursor | -| --- | --- | --- | --- | --- | -| Global rules | `AGENTS.md` (link) | `CLAUDE.md` imports `core/AGENTS.md` | `AGENTS.md` (link) | `rules/dev-brain.mdc` (copy) | -| Workflows | commands `/review` | plugin `/dev-brain:review` | plugin skills `$dev-brain:review` | skills `/review` | -| Skills | `skills/` (links) | plugin | plugin | `skills/` (links) | -| Read-only reviewer | permissions: only `git diff/log/show/status`; `>` and `--output` denied | tools: Read, Grep, Glob, read-only git; other commands need your approval | `sandbox_mode = "read-only"`, **not enforced on spawned agents** (Codex 0.164): instruction only | `readonly: true` | -| Saved state | plugin, every main-session call | `SessionStart` hook | `SessionStart` hook, after you approve it once | `sessionStart` hook (Cursor bug drops it) + rule fallback | - -When an agent cannot inject the state, the global rules tell it to read `.dev-brain/STATE.md` before continuing earlier work. The state text and its 3000-character budget come from one script, `core/bin/dev-brain-context`, used by every adapter. - ## Install ```bash -./install.sh # every agent found on this machine -./install.sh opencode claude-code # or name them: opencode claude-code codex cursor +claude plugin marketplace add Stcant/agents-platform +claude plugin install dev-brain@dev-brain ``` -Requires `python3` and `git`. Re-run it after pulling changes. Existing files that are not managed by this kit are moved to `*.bak.`, never deleted. - -- **OpenCode**: restart the background server when no session is active (`opencode service restart`). -- **Claude Code / Codex**: the installer builds a local plugin marketplace in `build/` and installs `dev-brain` from it with the agent's own CLI. -- **Codex**: approve the `SessionStart` hook once in the TUI; new hooks need review before they run. -- **Cursor**: if the agent ignores the rules, paste `core/AGENTS.md` into Settings > Rules (file-based global rules are not always loaded). - -## First step in every repository: `start` +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). -Run `start` once in each repository before relying on the kit's continuity. Everything else builds on the two files it creates: `resume` and `handoff` read and rewrite the state, the agent's context gets it automatically, and every agent reads the project facts. +## First step in every repository: `/dev-brain:start` -| Agent | Command (from the repository root) | -| --- | --- | -| OpenCode | `/start` | -| Claude Code | `/dev-brain:start` | -| Codex CLI | `$dev-brain:start` | -| Cursor | `/start` | - -What it does: +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. 1. Inspects the real repository: purpose, stack and versions, exact commands, conventions, gotchas. It does not open data directories (`input/`, `output/`, `.env`). 2. Writes or merges the root `AGENTS.md` (project facts, under 60 lines) and creates or reconciles `.dev-brain/STATE.md` (goal, done with evidence, blockers, next actions, under 3000 characters). 3. Uses files from the previous kit (`harness/`, `NOW.md`, `RULES.md`) as input and lists them for you to delete. On hph, 21 KB of `harness/` became a 3.1 KB `AGENTS.md` and a 1.3 KB state. 4. Reports observed facts, unknowns and problems; changes no code, installs nothing, commits nothing. -Then read both files, fix anything untrue, and commit them yourself if you want them versioned. Until a repository has a state file, the agent only gets a one-line hint suggesting `start`; the global design rules apply either way. +Then read both files, fix anything untrue, and commit them yourself if you want them versioned. Until a repository has a state file, the session only gets a one-line hint suggesting `start`; the global rules apply either way. ## Daily use -Ask the agent to implement or fix what you need. The workflows support that work; they are not a mandatory sequence or a switch that enables code quality. Invoke them with the agent's syntax from the table above (`/review`, `/dev-brain:review`, `$dev-brain:review`). +Ask Claude Code to implement or fix what you need. The rules already apply; the workflows support the work. | Workflow | When | | --- | --- | -| `start` | First adoption of a repository: writes project facts in the root `AGENTS.md` and creates `.dev-brain/STATE.md`; migrates files from the previous kit (`harness/`) without deleting them | -| `resume` | Start of a session: reconciles the saved state with the real repository | -| `handoff` | End of meaningful work: rewrites the state with verified results and next actions | -| `plan` | Non-trivial change: read-only plan-contract with at most five steps | -| `impact` | Before editing: callers, contracts, tests and unknowns | -| `learn` | Explain a real flow or an unfamiliar stack | -| `review` | Review all uncommitted changes (staged, unstaged, untracked) through the read-only reviewer, which reads the diff itself with git | - -## What lives in a project - -``` -/ -├── AGENTS.md project facts: stack, commands, conventions, gotchas (under 60 lines) -└── .dev-brain/ - └── STATE.md goal, done with evidence, blockers, max 3 next actions (under 3000 characters) -``` +| `/dev-brain:start` | First adoption of a repository (see above) | +| `/dev-brain:resume` | Start of a session: reconciles the saved state with git and the code | +| `/dev-brain:handoff` | End of meaningful work: rewrites the state with verified results and next actions | +| `/dev-brain:impact ` | Before editing shared code: callers, contracts, tests, unknowns | +| `/dev-brain:learn ` | Explain a real flow or an unfamiliar stack | +| `/dev-brain:review [scope]` | Review all uncommitted changes through the read-only reviewer, which reads the diff itself with git | -All four agents read the project `AGENTS.md`. Both files are intended for version control, but committing them always requires your explicit decision. The state is a working document, not a diary. - -## Evaluation +For planning use Claude Code's native plan mode (Shift+Tab): it is read-only by enforcement, which a prompt cannot match. -`evals/offline/check.py` installs the kit into a throwaway home for every agent CLI it finds, replaces the model with a local mock that records every request (`evals/offline/mock_model.py`), and checks in about ten seconds, at zero token cost, what the kit controls: rules and state reach the agent, oversized state becomes a notice, workflows expand, the reviewer reads the diff but cannot write. Cursor is checked only for its generated files. Run it after changing `core/`, an adapter or the installer: +| Always active | Used when helpful | Requires your explicit decision | +| --- | --- | --- | +| Code-design guidance and self-review of changed code | Impact analysis, independent review, session continuity | Commits, amendments and pushes; unrelated refactors, new dependencies or architecture changes must be proposed first | -```bash -python3 evals/offline/check.py # OPENCODE / CLAUDE / CODEX= if not on PATH -``` +## What is enforced, what is instructed -`evals/scenarios/` describes realistic tasks and the expected model behavior; `evals/results.md` records measured results and limits. Every change to rules, workflows or skills should be justified by a scenario. +- **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. -Run a scenario manually in a fixture: +## Evaluation ```bash -# Only after explicitly authorizing local fixture commits: -./evals/setup.sh # copies fixtures to /tmp/opencode/dev-brain-evals and recreates git history -cd /tmp/opencode/dev-brain-evals/bugfix -opencode run --standalone -m "The discount test fails. Fix the code." < /dev/null +python3 evals/offline/check.py # CLAUDE= if claude is not on PATH ``` -In scripts, close stdin: `opencode run` waits for EOF on non-terminal stdin. - -## Migration from the previous kit - -Content of the old visible `dev-brain/` folder remains in git history at commit `08baebc`. For a repository that received a copy (`RULES.md`, `NOW.md`, `harness/PROJECT_STATE.md`, `harness/PROJECT_MAP.md`), run the `start` workflow: it carries still-true facts into `AGENTS.md` and `.dev-brain/STATE.md` and lists the old files for you to delete. +Installs the plugin into a throwaway home, replaces the model with a local mock that records every request, and checks in about 15 seconds, at zero token cost: 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. It does not judge model behavior; `evals/scenarios/` describes the real-model scenarios and `evals/results.md` records decisions and evidence. ## Layout ``` -core/ the only source: AGENTS.md rules, workflows/, skills/, agents/reviewer.md, bin/, templates/ -adapters/ agent-specific code that cannot be expressed as files (OpenCode plugin) -install.py links or translates core/ for each agent; install.sh is a wrapper -evals/ scenarios, fixtures, results, offline mock check -MANUALE.md Italian user manual +.claude-plugin/marketplace.json marketplace listing the plugin +core/ the plugin: AGENTS.md rules, skills/, agents/, hooks/, bin/ +evals/ scenarios, fixtures, results, offline check +MANUALE.md Italian user manual ``` diff --git a/adapters/opencode/plugin/index.ts b/adapters/opencode/plugin/index.ts deleted file mode 100644 index 06ceb5d..0000000 --- a/adapters/opencode/plugin/index.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { Plugin } from "@opencode/plugin" -import { execFileSync } from "node:child_process" -import { statSync } from "node:fs" -import { join } from "node:path" -import { fileURLToPath } from "node:url" - -// The state text and its size budget come from the shared core script, so every -// agent adapter injects exactly the same thing. -const CONTEXT_SCRIPT = fileURLToPath(new URL("../../../core/bin/dev-brain-context", import.meta.url)) -const STATE_PATH = ".dev-brain/STATE.md" - -function stateVersion(root: string): string { - try { - const stat = statSync(join(root, STATE_PATH)) - return `${stat.mtimeMs}:${stat.size}` - } catch { - return "none" - } -} - -export default Plugin.define({ - id: "dev-brain", - async setup(ctx) { - const root = ctx.location.project?.canonical ?? ctx.location.directory - let cached: { version: string; text: string } | undefined - - // The context hook runs on every model call: rerun the script only when the file changes. - function contextText(): string { - const version = stateVersion(root) - if (cached?.version !== version) { - let text = "" - try { - text = execFileSync("python3", [CONTEXT_SCRIPT, "--format", "text", "--root", root], { - encoding: "utf8", - timeout: 5000, - }).trim() - } catch { - // Without python3 nothing is injected; the global rules tell the agent to read the file. - } - cached = { version, text } - } - return cached.text - } - - // Subagent sessions (reviewer, explore, ...) get a focused prompt from their parent; - // the project state would only add tokens to each of their calls. - const isSubagent = new Map() - - async function isSubagentSession(sessionID: string): Promise { - const known = isSubagent.get(sessionID) - if (known !== undefined) return known - try { - const session = await ctx.session.get({ sessionID }) - const child = session.parentID !== undefined - isSubagent.set(sessionID, child) - return child - } catch { - return false - } - } - - await ctx.session.hook("context", async (event) => { - if (await isSubagentSession(event.sessionID)) return - const text = contextText() - if (text) event.system.push({ type: "text", text }) - }) - - await ctx.session.hook("compaction", (event) => { - event.system.push({ - type: "text", - text: "Preserve in the summary, in this order: current goal and acceptance criteria, verified evidence (command + PASS/FAIL/NOT RUN), blockers and failed attempts, and the next executable action. These are written to .dev-brain/STATE.md after the session.", - }) - }) - }, -}) diff --git a/core/.claude-plugin/plugin.json b/core/.claude-plugin/plugin.json new file mode 100644 index 0000000..7c36f46 --- /dev/null +++ b/core/.claude-plugin/plugin.json @@ -0,0 +1,5 @@ +{ + "name": "dev-brain", + "version": "2.0.0", + "description": "Readable, maintainable code at low context cost: global rules, project state, workflows, skills and a read-only reviewer." +} diff --git a/core/agents/reviewer.md b/core/agents/reviewer.md index f0b31bf..a0f64ea 100644 --- a/core/agents/reviewer.md +++ b/core/agents/reviewer.md @@ -1,6 +1,7 @@ --- name: reviewer description: Read-only reviewer for correctness, security, data integrity and concrete maintenance problems +tools: Read, Grep, Glob, Bash(git diff:*), Bash(git log:*), Bash(git show:*), Bash(git status:*) --- You are an independent reviewer. You did not write this code; be skeptical. diff --git a/core/bin/dev-brain-context b/core/bin/dev-brain-context index 62be177..88ee6ef 100755 --- a/core/bin/dev-brain-context +++ b/core/bin/dev-brain-context @@ -1,20 +1,16 @@ #!/usr/bin/env python3 -"""Print the saved project state for an agent's context, within a size budget. +"""SessionStart hook: give the agent the global rules and the project's saved state. -One implementation for every adapter: - --format text raw text (OpenCode plugin) - --format hook SessionStart hook JSON for Claude Code and Codex - --format cursor sessionStart hook JSON for Cursor - -The project is found from the hook's JSON on stdin (`cwd`, or Cursor's -`workspace_roots`), else from --root, else from the current directory. -Prints nothing when there is nothing useful to add. +Claude Code runs it at startup, resume, /clear and after compaction, and adds the +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 argparse import json import os import sys +RULES = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir, "AGENTS.md") STATE_PATH = os.path.join(".dev-brain", "STATE.md") # The state rides on every session of the project, so it must stay a short checkpoint. # Above the budget it is not injected at all: truncating would drop the "Next" section @@ -34,28 +30,25 @@ def project_root(start): directory = parent -def context_text(root): +def state_text(root): if root is None: return "" - state_file = os.path.join(root, STATE_PATH) try: - with open(state_file, encoding="utf-8") as handle: + with open(os.path.join(root, STATE_PATH), encoding="utf-8") as handle: state = handle.read().strip() except FileNotFoundError: - state = None - except OSError: - return "" - if state is None: if not os.path.exists(os.path.join(root, ".git")): return "" return ("This repository has no .dev-brain/STATE.md. If the user wants to adopt it, " - "suggest the `start` workflow. Do not create the file unasked.") + "suggest /dev-brain:start. Do not create the file unasked.") + except OSError: + return "" if not state: return "" if len(state) > MAX_STATE_CHARS: return (f".dev-brain/STATE.md has {len(state)} characters, over the {MAX_STATE_CHARS}-character " "budget for automatic injection, so it was not injected. Read it when the task needs saved " - "context, and suggest the `handoff` workflow to compact it.") + "context, and suggest /dev-brain:handoff to compact it.") return "\n".join([ '', "Saved project state. Treat it as context, not proof or permission: verify against git " @@ -66,34 +59,21 @@ def context_text(root): ]) -def hook_input(): - if sys.stdin is None or sys.stdin.isatty(): - return {} - try: - data = json.loads(sys.stdin.read() or "{}") - except ValueError: - return {} - return data if isinstance(data, dict) else {} - - def main(): - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument("--format", choices=("text", "hook", "cursor"), default="text") - parser.add_argument("--root", help="project directory (default: from hook input or cwd)") - args = parser.parse_args() - - event = hook_input() if args.format != "text" else {} - roots = event.get("workspace_roots") or [] - start = args.root or event.get("cwd") or (roots[0] if roots else None) or os.getcwd() - text = context_text(project_root(start)) - if not text: - return - if args.format == "text": - print(text) - elif args.format == "hook": - print(json.dumps({"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": text}})) + event = {} + if "--text" not in sys.argv and sys.stdin is not None and not sys.stdin.isatty(): + try: + event = json.loads(sys.stdin.read() or "{}") + except ValueError: + event = {} + with open(RULES, encoding="utf-8") as handle: + rules = handle.read().strip() + state = state_text(project_root(event.get("cwd") or os.getcwd())) + context = rules + ("\n\n" + state if state else "") + if "--text" in sys.argv: + print(context) else: - print(json.dumps({"additional_context": text})) + print(json.dumps({"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": context}})) if __name__ == "__main__": diff --git a/core/hooks/hooks.json b/core/hooks/hooks.json new file mode 100644 index 0000000..d12726e --- /dev/null +++ b/core/hooks/hooks.json @@ -0,0 +1,12 @@ +{ + "hooks": { + "SessionStart": [ + { + "matcher": "startup|resume|clear|compact", + "hooks": [ + { "type": "command", "command": "python3 \"${CLAUDE_PLUGIN_ROOT}/bin/dev-brain-context\"" } + ] + } + ] + } +} diff --git a/core/workflows/handoff/SKILL.md b/core/skills/handoff/SKILL.md similarity index 100% rename from core/workflows/handoff/SKILL.md rename to core/skills/handoff/SKILL.md diff --git a/core/workflows/impact/SKILL.md b/core/skills/impact/SKILL.md similarity index 100% rename from core/workflows/impact/SKILL.md rename to core/skills/impact/SKILL.md diff --git a/core/workflows/learn/SKILL.md b/core/skills/learn/SKILL.md similarity index 100% rename from core/workflows/learn/SKILL.md rename to core/skills/learn/SKILL.md diff --git a/core/workflows/resume/SKILL.md b/core/skills/resume/SKILL.md similarity index 100% rename from core/workflows/resume/SKILL.md rename to core/skills/resume/SKILL.md diff --git a/core/workflows/review/SKILL.md b/core/skills/review/SKILL.md similarity index 95% rename from core/workflows/review/SKILL.md rename to core/skills/review/SKILL.md index 6721279..4b1fc46 100644 --- a/core/workflows/review/SKILL.md +++ b/core/skills/review/SKILL.md @@ -4,7 +4,7 @@ description: Review correctness and maintainability of the current changes throu disable-model-invocation: true --- -Review the current changes by delegating to the read-only `reviewer` subagent. +Review the current changes by delegating to the read-only `reviewer` subagent (`dev-brain:reviewer` in Claude Code). Scope: the text the user gave with this request. If none, every uncommitted change: staged, unstaged and untracked files. diff --git a/core/workflows/start/SKILL.md b/core/skills/start/SKILL.md similarity index 100% rename from core/workflows/start/SKILL.md rename to core/skills/start/SKILL.md diff --git a/core/templates/PROJECT_AGENTS.md b/core/templates/PROJECT_AGENTS.md deleted file mode 100644 index a86d192..0000000 --- a/core/templates/PROJECT_AGENTS.md +++ /dev/null @@ -1,24 +0,0 @@ -# - - - -## Stack -- - -## Commands -- Install: `` (run from ``) -- Dev: `` -- Test: `` -- Lint / type check: `` -- Build: `` - -## Structure -- `` — -- `` — - -## Conventions and gotchas -- -- - -## Do not -- diff --git a/core/templates/STATE.md b/core/templates/STATE.md deleted file mode 100644 index bcd42e1..0000000 --- a/core/templates/STATE.md +++ /dev/null @@ -1,17 +0,0 @@ -# State — -Updated: · Branch: - -## Goal - — acceptance: - -## Done (latest first, max 5) -- — evidence: PASS|FAIL|NOT RUN - -## In progress / blockers -- — status: implemented|verified|blocked — - -## Known pre-existing failures -- — — since - -## Next (max 3) -1. diff --git a/core/workflows/plan/SKILL.md b/core/workflows/plan/SKILL.md deleted file mode 100644 index df48609..0000000 --- a/core/workflows/plan/SKILL.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -name: plan -description: Produce a read-only plan-contract of at most 5 steps for a non-trivial change. Run only when the user asks for it. -disable-model-invocation: true ---- - -Plan the work the user described with this request. - -This is read-only: do not edit files, install dependencies or change git state. - -First inspect the real code and configuration affected. Then produce a plan with at most 5 steps. Each step is a working deliverable, not an activity, and uses this table: - -| # | Deliverable | Files / symbols | Input -> Output | Depends on | Check and expected result | -| - | ----------- | --------------- | --------------- | ---------- | ------------------------- | - -Rules: - -- No placeholders such as "handle edge cases". Name the concrete behavior. -- Producer and consumer of a shared interface must use the same contract. -- The check must be something that can fail if the step is wrong; state the expected result. -- Separate required work from optional improvements; list what is explicitly out of scope. -- If a decision needs the user, ask it before the plan rather than guessing. -- Finish with the main risk and the assumption most likely to be wrong. diff --git a/evals/offline/check.py b/evals/offline/check.py index 72cd33b..7f5856e 100644 --- a/evals/offline/check.py +++ b/evals/offline/check.py @@ -1,18 +1,16 @@ #!/usr/bin/env python3 -"""Zero-token check of the installed kit against the real agent binaries. +"""Zero-token check of the dev-brain plugin against the real Claude Code binary. -For every agent CLI found (opencode, claude, codex; override with OPENCODE, -CLAUDE, CODEX), the kit is installed into a throwaway home with install.py and -the model is replaced by evals/offline/mock_model.py, which replays scripted +The plugin is installed from this repository's marketplace into a throwaway home, +and the model is replaced by evals/offline/mock_model.py, which replays scripted tool calls and records every request. Nothing reaches a real provider. -It verifies what the kit controls: global rules and saved state reach the agent, -an oversized state becomes a notice, workflows expand, and the reviewer reads -the diff with git but cannot write. It does not judge model behavior; use -evals/scenarios/ for that. Cursor has no headless CLI here: its generated files -are only checked for presence. +It verifies what the kit controls: global rules and saved state reach the session, +an oversized state becomes a notice, workflows expand and stay out of the skill +listing, and the reviewer reads the diff with git but cannot write. It does not +judge model behavior; use evals/scenarios/ for that. -usage: python3 evals/offline/check.py +usage: python3 evals/offline/check.py (CLAUDE= if claude is not on PATH) """ import json import os @@ -29,8 +27,11 @@ RULES = "Personal engineering rules" # first line of core/AGENTS.md STATE_MARK = "Saved project state. Treat it" # header of the injected state block NOTICE = "over the 3000-character budget" -REVIEW_FLOW = "Review the current changes by delegating" # core/workflows/review -START_FLOW = "Adopt the current repository into the dev-brain harness" # core/workflows/start +WORKFLOWS = { + "start": "Adopt the current repository into the dev-brain harness", + "resume": "Reconcile the saved state with reality", + "review": "Review the current changes by delegating", +} STATE = """# State — fixture Updated: 2026-01-01 · Branch: main @@ -50,59 +51,43 @@ def check(name, ok, detail=""): failures.append(name) -def text_of(value): - return value if isinstance(value, str) else json.dumps(value) - - def system_text(body): - """System and developer instructions of one request, in any of the three wire formats.""" - parts = [text_of(body.get("system", "")), text_of(body.get("instructions", ""))] - for message in body.get("messages") or body.get("input") or []: - if isinstance(message, dict) and message.get("role") in ("system", "developer"): - parts.append(text_of(message.get("content"))) - return "\n".join(parts) + """The system prompt plus system-role messages, where Claude Code puts hook context.""" + parts = [body.get("system", "")] + [m.get("content") for m in body.get("messages", []) if m.get("role") == "system"] + return "\n".join(part if isinstance(part, str) else json.dumps(part) for part in parts) def tool_results(bodies): - """Tool outputs fed back to the model, once per call id, in order.""" + """Tool outputs fed back to the model, once per tool_use id, in order.""" results = {} for body in bodies: - for message in body.get("messages") or body.get("input") or []: - if not isinstance(message, dict): - continue - if message.get("role") == "tool": # chat completions - results.setdefault(message.get("tool_call_id"), text_of(message.get("content"))) - if message.get("type") == "function_call_output": # responses - results.setdefault(message.get("call_id"), text_of(message.get("output"))) - if message.get("role") == "user" and isinstance(message.get("content"), list): # anthropic + for message in body.get("messages", []): + if message.get("role") == "user" and isinstance(message.get("content"), list): for block in message["content"]: if isinstance(block, dict) and block.get("type") == "tool_result": - results.setdefault(block.get("tool_use_id"), text_of(block.get("content"))) + content = block.get("content") + results.setdefault(block.get("tool_use_id"), + content if isinstance(content, str) else json.dumps(content)) return list(results.values()) -def binary(name, variable): - path = os.environ.get(variable) or shutil.which(name) - return path if path and Path(path).exists() else None - - class Sandbox: - """Throwaway home, fixture repository and installed kit.""" + """Throwaway home with the plugin installed, and a fixture repository with a pending change.""" - def __init__(self, tools, bins): + def __init__(self, claude, mock): + self.claude, self.mock = claude, mock self.root = Path(tempfile.mkdtemp(prefix="dev-brain-offline-")) home = self.root / "home" home.mkdir() - bin_dir = self.root / "bin" - bin_dir.mkdir() - for name, path in bins.items(): - (bin_dir / name).symlink_to(path) - # A clean environment: nothing from the caller's own agent setup leaks in. - self.env = {"PATH": f"{bin_dir}:{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"), - "CLAUDE_CONFIG_DIR": str(home / ".claude"), "CODEX_HOME": str(home / ".codex")} + # A clean environment: nothing from the caller's own Claude Code setup leaks in. + self.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", "CLAUDE_CONFIG_DIR": str(home / ".claude"), + "ANTHROPIC_BASE_URL": mock.url, "ANTHROPIC_API_KEY": "sk-offline-check", + "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1", "DISABLE_AUTOUPDATER": "1"} + for args in (["marketplace", "add", str(KIT)], ["install", "dev-brain@dev-brain"]): + result = subprocess.run([claude, "plugin", *args], env=self.env, capture_output=True, text=True) + if result.returncode: + raise SystemExit(f"FAIL claude plugin {' '.join(args)}: {result.stdout}{result.stderr}") self.repo = self.root / "repo" (self.repo / ".dev-brain").mkdir(parents=True) git = ["git", "-c", "user.name=check", "-c", "user.email=check@example.invalid"] @@ -111,180 +96,62 @@ def __init__(self, tools, bins): subprocess.run(git + ["add", "app.txt"], cwd=self.repo, check=True) subprocess.run(git + ["commit", "-qm", "fixture"], cwd=self.repo, check=True) (self.repo / "app.txt").write_text("hello, world\n") - self.small_state() - result = subprocess.run([sys.executable, str(KIT / "install.py"), *tools], env=self.env, - capture_output=True, text=True) - if result.returncode: - raise SystemExit(f"FAIL install.py: {result.stdout}{result.stderr}") - - def small_state(self): - (self.repo / ".dev-brain" / "STATE.md").write_text(STATE) - - def big_state(self): - (self.repo / ".dev-brain" / "STATE.md").write_text(STATE + "- stale line\n" * 300) + self.write_state(STATE) - def clean_repo(self): - for name in ("leak.txt", "touched.txt"): - (self.repo / name).unlink(missing_ok=True) - (self.repo / "app.txt").write_text("hello, world\n") + def write_state(self, text): + (self.repo / ".dev-brain" / "STATE.md").write_text(text) - def run(self, mock, cmd, steps, env=None): - mock.script(steps) - subprocess.run(cmd, cwd=self.repo, env={**self.env, "PWD": str(self.repo), **(env or {})}, - stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, - timeout=240) - bodies = mock.agent_calls() + def run(self, prompt, steps): + self.mock.script(steps) + subprocess.run([self.claude, "-p", prompt, "--model", "mock-model"], 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(f"{Path(cmd[0]).name} sent a request to the mock model", False) + check("claude sent a request to the mock model", False) return bodies -def write_protected(sandbox, results, expected_rejections): - words = ("permission.rejected", "needs approval", "requires approval", "has been denied") - rejected = sum(any(word in r for word in words) for r in results) - return (rejected == expected_rejections and not (sandbox.repo / "leak.txt").exists() - and not (sandbox.repo / "touched.txt").exists() and (sandbox.repo / "app.txt").exists()), rejected - - -def check_opencode(sandbox, mock, opencode): - config_file = Path(sandbox.env["XDG_CONFIG_HOME"]) / "opencode" / "opencode.json" - config = json.loads(config_file.read_text()) - config["model"] = "mock/mock" - config["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}}}}} - config_file.write_text(json.dumps(config)) - cmd = [opencode, "run", "--standalone", "-m", "mock/mock", "check"] - env = {"OPENCODE_DISABLE_MODELS_FETCH": "1", "OPENCODE_DISABLE_FREE_MODELS": "1"} - steps = [ - {"tool": "subagent", "args": {"agent": "reviewer", "description": "review", "prompt": "Review all changes."}}, - {"tool": "shell", "args": {"command": "git diff HEAD"}}, - {"tool": "shell", "args": {"command": "git diff HEAD > leak.txt"}}, - {"tool": "shell", "args": {"command": "git diff HEAD --output=leak.txt"}}, - {"tool": "shell", "args": {"command": "git status; rm app.txt"}}, - {"text": "no findings"}, - {"text": "done"}, - ] - bodies = sandbox.run(mock, cmd, steps, env) - main = [b for b in bodies if any(t["function"]["name"] == "edit" for t in b["tools"])] - child = [b for b in bodies if b not in main] - results = tool_results(bodies) - check("opencode: global rules loaded", bool(main) and RULES in system_text(main[0])) - start = Path(sandbox.env["XDG_CONFIG_HOME"]) / "opencode" / "commands" / "start.md" - check("opencode: /start command generated", start.exists() and START_FLOW in start.read_text()) - check("opencode: state in the main session", bool(main) and all(STATE_MARK in system_text(b) for b in main)) - check("opencode: state not in the subagent", bool(child) and not any(STATE_MARK in system_text(b) for b in child)) - check("opencode: reviewer reads the diff with git", any("hello, world" in r for r in results)) - ok, rejected = write_protected(sandbox, results, 3) - check("opencode: reviewer cannot write (>, --output, rm)", ok, f"{rejected}/3 rejected") - - sandbox.big_state() - bodies = sandbox.run(mock, cmd, [{"text": "done"}], env) - system = system_text(bodies[0]) if bodies else "" - check("opencode: oversized state becomes a notice", NOTICE in system and "stale line" not in system) - sandbox.small_state() - sandbox.clean_repo() - - -def check_claude(sandbox, mock, claude): - env = {"ANTHROPIC_BASE_URL": mock.url, "ANTHROPIC_API_KEY": "sk-offline-check", - "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1", "DISABLE_AUTOUPDATER": "1"} - - def cmd(prompt): - return [claude, "-p", prompt, "--model", "mock-model"] - - bodies = sandbox.run(mock, cmd("/dev-brain:review"), [{"text": "done"}], env) - everything = json.dumps(bodies) - check("claude-code: global rules loaded", RULES in everything) - check("claude-code: state injected by the SessionStart hook", bool(bodies) and STATE_MARK in system_text(bodies[0])) - check("claude-code: /dev-brain:review expands the workflow", REVIEW_FLOW in everything) - bodies = sandbox.run(mock, cmd("/dev-brain:start"), [{"text": "done"}], env) - check("claude-code: /dev-brain:start expands the workflow", START_FLOW in json.dumps(bodies)) - check("claude-code: user-invoked workflows stay out of the skill listing", - "dev-brain:debugging" in everything and "dev-brain:handoff" not in everything) - - steps = [ - {"tool": "Agent", "args": {"description": "review", "prompt": "Review all changes.", - "subagent_type": "dev-brain:reviewer"}}, - {"tool": "Bash", "args": {"command": "git diff HEAD", "description": "Show changes"}}, - {"tool": "Bash", "args": {"command": "git diff HEAD > leak.txt", "description": "Save changes"}}, - {"tool": "Bash", "args": {"command": "touch touched.txt", "description": "Create file"}}, - {"tool": "Bash", "args": {"command": "git status; rm app.txt", "description": "Remove file"}}, - {"text": "no findings"}, - {"text": "done"}, - ] - bodies = sandbox.run(mock, cmd("check the changes"), steps, env) - results = tool_results(bodies) - check("claude-code: reviewer reads the diff with git", any("hello, world" in r for r in results)) - ok, rejected = write_protected(sandbox, results, 3) - check("claude-code: reviewer cannot write without approval", ok, f"{rejected}/3 rejected") - - sandbox.big_state() - bodies = sandbox.run(mock, cmd("hello"), [{"text": "done"}], env) - system = system_text(bodies[0]) if bodies else "" - check("claude-code: oversized state becomes a notice", NOTICE in system and "stale line" not in system) - sandbox.small_state() - sandbox.clean_repo() - - -def check_codex(sandbox, mock, codex): - provider = (f'model_providers.mock={{ name = "mock", base_url = "{mock.url}/v1", ' - 'wire_api = "responses", env_key = "MOCK_KEY" }') - - def cmd(prompt, *extra): - return [codex, "exec", "--skip-git-repo-check", "-c", 'model_provider="mock"', "-c", 'model="mock"', - "-c", provider, *extra, prompt] - - env = {"MOCK_KEY": "offline-check"} - bodies = sandbox.run(mock, cmd("$dev-brain:review"), [{"text": "done"}], env) - everything = json.dumps(bodies) - check("codex: global rules loaded", RULES in everything) - check("codex: $dev-brain:review expands the workflow", REVIEW_FLOW in everything) - check("codex: reviewer role registered", "Read-only reviewer for correctness" in everything) - bodies = sandbox.run(mock, cmd("$dev-brain:start"), [{"text": "done"}], env) - check("codex: $dev-brain:start expands the workflow", START_FLOW in json.dumps(bodies)) - check("codex: state hook waits for the user's trust", STATE_MARK not in everything) - # Trusting a hook is the user's decision; the check bypasses it only inside its own sandbox. - bodies = sandbox.run(mock, cmd("hello", "--dangerously-bypass-hook-trust"), [{"text": "done"}], env) - check("codex: state injected once the hook is trusted", STATE_MARK in json.dumps(bodies)) - sandbox.big_state() - bodies = sandbox.run(mock, cmd("hello", "--dangerously-bypass-hook-trust"), [{"text": "done"}], env) - everything = json.dumps(bodies) - check("codex: oversized state becomes a notice", NOTICE in everything and "stale line" not in everything) - sandbox.small_state() - - -def check_cursor(sandbox): - home = Path(sandbox.env["HOME"]) / ".cursor" - expected = ["rules/dev-brain.mdc", "agents/reviewer.md", "hooks.json", "skills/start/SKILL.md", - "skills/review/SKILL.md", "skills/debugging/SKILL.md"] - missing = [name for name in expected if not (home / name).exists()] - check("cursor: files generated (not run: no headless Cursor here)", not missing, f"missing {missing}") - agent = home / "agents" / "reviewer.md" - check("cursor: reviewer is readonly", agent.exists() and "readonly: true" in agent.read_text()) - - def main(): - bins = {} - for name, variable in (("opencode", "OPENCODE"), ("claude", "CLAUDE"), ("codex", "CODEX")): - path = binary(name, variable) - if path: - bins[name] = path - names = {"opencode": "opencode", "claude": "claude-code", "codex": "codex"} - tools = [names[name] for name in bins] + ["cursor"] - print(f"agents: {', '.join(tools)}") - sandbox = Sandbox(tools, bins) + claude = os.environ.get("CLAUDE") or shutil.which("claude") + if not claude: + raise SystemExit("claude not found; set CLAUDE to the Claude Code binary") mock = MockModel() + sandbox = Sandbox(claude, mock) try: - if "opencode" in bins: - check_opencode(sandbox, mock, bins["opencode"]) - if "claude" in bins: - check_claude(sandbox, mock, bins["claude"]) - if "codex" in bins: - check_codex(sandbox, mock, bins["codex"]) - check_cursor(sandbox) + bodies = sandbox.run("hello", [{"text": "done"}]) + system = system_text(bodies[0]) if bodies else "" + everything = json.dumps(bodies) + check("global rules in the system prompt", RULES in system) + check("saved state in the system prompt", STATE_MARK in system) + check("workflows stay out of the skill listing (zero context cost)", + "dev-brain:debugging" in everything and "dev-brain:handoff" not in everything) + for name, marker in WORKFLOWS.items(): + bodies = sandbox.run(f"/dev-brain:{name}", [{"text": "done"}]) + check(f"/dev-brain:{name} expands the workflow", marker in json.dumps(bodies)) + + steps = [ + {"tool": "Agent", "args": {"description": "review", "prompt": "Review all changes.", + "subagent_type": "dev-brain:reviewer"}}, + {"tool": "Bash", "args": {"command": "git diff HEAD", "description": "Show changes"}}, + {"tool": "Bash", "args": {"command": "git diff HEAD > leak.txt", "description": "Save changes"}}, + {"tool": "Bash", "args": {"command": "touch touched.txt", "description": "Create file"}}, + {"tool": "Bash", "args": {"command": "git status; rm app.txt", "description": "Remove file"}}, + {"text": "no findings"}, + {"text": "done"}, + ] + results = tool_results(sandbox.run("check the changes", steps)) + check("reviewer reads the diff with git", any("hello, world" in r for r in results)) + words = ("needs approval", "requires approval", "has been denied") + rejected = sum(any(word in r for word in words) for r in results) + written = (sandbox.repo / "leak.txt").exists() or (sandbox.repo / "touched.txt").exists() + check("reviewer cannot write without approval", + rejected == 3 and not written and (sandbox.repo / "app.txt").exists(), f"{rejected}/3 rejected") + + sandbox.write_state(STATE + "- stale line\n" * 300) + bodies = sandbox.run("hello", [{"text": "done"}]) + system = system_text(bodies[0]) if bodies else "" + check("oversized state becomes a notice", NOTICE in system and "stale line" not in system) 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 4ac311c..0508120 100644 --- a/evals/offline/mock_model.py +++ b/evals/offline/mock_model.py @@ -1,17 +1,11 @@ -"""Local model endpoint that records requests and replays scripted replies. +"""Local Anthropic Messages endpoint that records requests and replays scripted replies. -Speaks the three wire formats the supported agents use: -- OpenAI chat completions (`/chat/completions`): OpenCode -- Anthropic messages (`/messages`): Claude Code -- OpenAI responses (`/responses`): Codex CLI - -Requests that offer tools are agent-loop calls: each one pops the next matching -scripted step, either {"tool": name, "args": {...}} or {"text": "..."}, optionally -limited with "when" / "unless" text. Other requests (titles, summaries) get a fixed -text. Nothing reaches a real provider. +Requests that offer tools are agent-loop calls: each one pops the first scripted step +whose optional "when" / "unless" text matches the request, either +{"tool": name, "args": {...}} or {"text": "..."}. Other requests get a fixed text. +Nothing reaches a real provider. """ import json -import re import threading from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer @@ -28,23 +22,16 @@ def log_message(self, *args): pass def do_GET(self): - self._json({"data": [{"id": "mock", "object": "model", "type": "model", "display_name": "Mock"}], - "models": [], "has_more": False}) + self._json({"data": [], "has_more": False}) def do_POST(self): body = json.loads(self.rfile.read(int(self.headers.get("content-length", 0))) or b"{}") - path = self.path.split("?")[0] - if path.endswith("/count_tokens"): + if self.path.split("?")[0].endswith("/count_tokens"): return self._json({"input_tokens": 1}) with mock.lock: - mock.requests.append({"path": path, "body": body}) + mock.requests.append(body) step = mock.next_step(body) - if path.endswith("/messages"): - self._anthropic(body, step) - elif path.endswith("/responses"): - self._responses(step) - else: - self._chat(step) + self._reply(body, step) def _json(self, payload): data = json.dumps(payload).encode() @@ -54,48 +41,20 @@ def _json(self, payload): self.end_headers() self.wfile.write(data) - def _sse(self, events): - self.send_response(200) - self.send_header("content-type", "text/event-stream") - self.send_header("cache-control", "no-cache") - self.send_header("connection", "close") - self.end_headers() - for name, data in events: - 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 _chat(self, step): - call_id = f"call_{len(mock.requests)}" - if "tool" in step: - 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: - delta, finish = {"role": "assistant", "content": step["text"]}, "stop" - base = {"id": "c", "object": "chat.completion.chunk", "created": 0, "model": "mock"} - self._sse([ - (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") - - def _anthropic(self, body, step): + def _reply(self, body, step): if "tool" in step: block = {"type": "tool_use", "id": f"toolu_{len(mock.requests)}", "name": step["tool"], "input": {}} delta = {"type": "input_json_delta", "partial_json": json.dumps(step["args"])} stop = "tool_use" else: block, delta, stop = {"type": "text", "text": ""}, {"type": "text_delta", "text": step["text"]}, "end_turn" - usage = {"input_tokens": 1, "output_tokens": 1} message = {"id": "msg_mock", "type": "message", "role": "assistant", "model": body.get("model", "mock"), - "content": [], "stop_reason": None, "stop_sequence": None, "usage": usage} + "content": [], "stop_reason": None, "stop_sequence": None, + "usage": {"input_tokens": 1, "output_tokens": 1}} if not body.get("stream"): content = dict(block, input=step["args"]) if "tool" in step else {"type": "text", "text": step["text"]} return self._json({**message, "content": [content], "stop_reason": stop}) - self._sse([ + events = [ ("message_start", {"type": "message_start", "message": message}), ("content_block_start", {"type": "content_block_start", "index": 0, "content_block": block}), ("content_block_delta", {"type": "content_block_delta", "index": 0, "delta": delta}), @@ -103,49 +62,27 @@ def _anthropic(self, body, step): ("message_delta", {"type": "message_delta", "delta": {"stop_reason": stop, "stop_sequence": None}, "usage": {"output_tokens": 1}}), ("message_stop", {"type": "message_stop"}), - ]) - - def _responses(self, step): - n = 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"} - if "namespace" in step: - item["namespace"] = step["namespace"] - 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": []} - 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)}), - ]) + ] + self.send_response(200) + self.send_header("content-type", "text/event-stream") + 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()) + self.wfile.flush() + self.close_connection = True self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) threading.Thread(target=self.server.serve_forever, daemon=True).start() self.url = f"http://127.0.0.1:{self.server.server_port}" def next_step(self, body): - """First scripted step whose optional `when` / `unless` text matches this request. - - Concurrent agents (a parent and its subagent) can then follow separate lanes. - """ if not body.get("tools"): return {"text": "ok"} text = json.dumps(body) for index, step in enumerate(self.steps): if step.get("when", "") in text and not (step.get("unless") and step["unless"] in text): - step = self.steps.pop(index) - found = re.search(r'agent_id\\*":\\*"([^"\\]+)', text) - if found and "args" in step: # lets a script wait on the subagent it spawned - step = dict(step, args=json.loads(json.dumps(step["args"]).replace("$AGENT_ID", found.group(1)))) - return step + return self.steps.pop(index) return {"text": "ok"} def script(self, steps): @@ -153,21 +90,4 @@ def script(self, steps): self.steps, self.requests = list(steps), [] def agent_calls(self): - return [r["body"] for r in self.requests if r["body"].get("tools")] - - -if __name__ == "__main__": - import sys - import time - - mock = MockModel() - log = sys.argv[1] if len(sys.argv) > 1 else None - print(mock.url, flush=True) - seen = 0 - while True: - time.sleep(0.5) - if log and len(mock.requests) > seen: - with open(log, "a", encoding="utf-8") as handle: - for request in mock.requests[seen:]: - handle.write(json.dumps(request) + "\n") - seen = len(mock.requests) + return [body for body in self.requests if body.get("tools")] diff --git a/evals/results.md b/evals/results.md index 3bac4f9..a8fca5e 100644 --- a/evals/results.md +++ b/evals/results.md @@ -1,235 +1,51 @@ # Evaluation results -Fixtures are copied to `/tmp/opencode/dev-brain-evals` by `evals/setup.sh`, which recreates their git history; the source fixtures in this repository contain no `.git` directory. +A log of decisions and the evidence behind them, newest first. Full run details are in git history (before 2026-10-25: `git show 50fcef9:evals/results.md`). -Environment: OpenCode v2.1.3, model `opencode/deepseek-v4.1-flash-free`, 2026-10-22. -Baseline = same model, `XDG_CONFIG_HOME` pointing to an empty directory (no rules, skills, commands or plugin), `opencode run --standalone`. +## Open question: does the kit improve the code? -## Bugfix with regression evidence +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. -Prompt: "The discount test fails. Fix the code." +## 2026-10-25 — Claude Code only, distributed as a plugin -| | Baseline | dev-brain | -| --- | --- | --- | -| Order of work | Edited `discount.py` first, then ran the suite | Ran `python3 -m unittest -v` first, observed FAILED, then edited | -| Root cause | Correct one-line sign fix | Correct one-line sign fix | -| Verification | `python3 -m unittest -v` PASS after the change | PASS after the change; FAIL before is recorded in the answer | -| Session state | Untouched | Read and updated `.dev-brain/STATE.md` | -| Explanation | Short summary | Flow / Why / Checks / Read next, including what was not tested | -| Unrequested work | None | None | +The user works with Claude Code only. Adapters for OpenCode, Codex CLI and Cursor were removed; `core/` keeps standard formats (`AGENTS.md`, `SKILL.md`) so another agent remains an adapter away. -Result: dev-brain improves the evidence trail (test-first, explicit before/after, state handoff) without adding scope. Baseline already solved the task. +- Global rules and state come from one `SessionStart` hook (`startup|resume|clear|compact`); no edit to `CLAUDE.md` or settings. Claude Code puts the hook output in a system-role message. +- Workflows are plugin skills with `disable-model-invocation: true`: not listed in the system prompt (verified), invoked as `/dev-brain:`. The bare `/review` keeps opening Claude Code's built-in review. +- `plan` removed: Claude Code's plan mode is read-only by enforcement; a prompt cannot match that. +- Templates removed: the `start` skill holds them, once. +- Evidence: `python3 evals/offline/check.py` ALL PASS twice (Claude Code 2.1.310, mock model): rules and state in context, oversized state → notice, `start`/`resume`/`review` expand, workflows absent from the listing, reviewer reads `git diff` and has `>`, `touch`, `; rm` refused pending approval, no file written. +- Limits: no real model, no interactive session. -Rule change after this run (2026-10-22): the Flow / Why / Checks / Read next walkthrough is now produced only when the user asks. The "Explanation" column above describes the old behavior; the default output is now a concise report of what changed, the checks run and what was not checked. No new scenario run was performed. +## 2026-10-25 — Multi-agent probe (superseded, findings kept) -## Resume with stale state +Tested OpenCode 2.1.4, Claude Code 2.1.310, Codex 0.164 against the mock; Cursor from docs only. -Prompt: baseline "Resume work in this repository. Recap where we left off and what to do next."; dev-brain `/resume`. +- Claude Code reads project `AGENTS.md` natively; global rules need `CLAUDE.md` (`@/abs/path` import works) or a hook. +- No skill directory is read by all four agents; Codex copies plugins and drops symlinked directories. +- Codex 0.164 does not apply a custom agent's `sandbox_mode = "read-only"` to the spawned agent: with a writable parent, the reviewer wrote a file. Codex hooks run only after the user trusts them. +- Cursor's `sessionStart` `additional_context` is dropped (open Cursor bug). -| | Baseline | dev-brain | -| --- | --- | --- | -| Finds the state | Yes, after listing the directory | Injected into context by the plugin; command reads it | -| Detects divergence | Yes: `subtract` already implemented, state stale | Yes: same conclusion | -| Old evidence | Mentions the saved PASS | Runs a fresh suite and says it is a new result | -| Edits | Asks before updating state | Asks before updating state | +## 2026-10-25 — Review and state token cost (tested on hph) -Result: both correct on this fixture. dev-brain makes the state visible without discovery and is stricter about evidence freshness. The fixture is too easy to separate the two strongly. +- The review command embedded the full diff, then the agent copied it into the subagent prompt: the diff was paid as input, output and reviewer input. Now the reviewer reads it with read-only git; on a 5.9 KB hph diff the command message went from 7005 to 1101 characters. +- `git diff` missed staged changes and stopped on untracked-only changes; now `git status` + `git diff HEAD --stat` (fallback `--cached`). +- The state was injected into subagents too, and an 80-line cap did not bound size (this repo's state was 3.9 KB). Now: main session only, 3000-character budget, a notice above it (not truncated: truncation would drop `Next`). +- `resume` guarded only Python (`uv`/`.venv`); now any install, download or compile is reported NOT RUN. +- `start` now migrates previous-kit files; hph's 21 KB `harness/` became `AGENTS.md` 3.1 KB + state 1.3 KB (hph PR #10). Its old next action was already done. +- Gotchas found: OpenCode did not block `>` without an explicit rule; `opencode run` waits on non-terminal stdin. -## Explain a real code flow +## 2026-10-22 — Review policy covers maintenance problems -Prompt: baseline "Explain how an order is created in this codebase."; dev-brain `/learn how an order is created`. +Scenario `scenarios/maintainability.md`, model `github-copilot/claude-haiku-5.5`, one run per version. Before: the reviewer excluded a duplicated shipping rule because no behavior changed. After: reported as a maintenance problem with the two locations and a shared calculation as the fix; similar but unrelated label functions correctly not merged. Generated code was already readable before and after: no generation-quality gain shown. Python only. -| | Baseline | dev-brain | -| --- | --- | --- | -| Call chain | Correct: `app.py -> service.py -> store.py` | Correct, same chain | -| Real symbols | Yes | Yes | -| Evidence labels | No | OBSERVED / INFERRED / UNKNOWN | -| Runtime check | No | Ran `python3 app.py 42 12.5` and used the real output | -| Reading order | Implicit | Explicit, four entries | -| Limits | Some | Explicit "Not verified" section | +## 2026-10-22 — Workflow scenarios on OpenCode (historical) -Result: both accurate; dev-brain adds labels, a reading order and a runtime check. Longer answer. +Model `opencode/deepseek-v4.1-flash-free`, baseline = no kit. -## Handoff - -Prompt: `/handoff` with an uncommitted fix and no checks run in that session. - -- The agent inspected the diff, ran `python3 -m unittest -v` itself, and recorded the fresh PASS with the command. -- It marked the change "verified locally, not committed", kept the next actions at two, removed the obsolete failure entry. -- No commit and no application edit beyond the existing fix. - -Result: PASS. - -## Review - -- Direct `--agent reviewer`: shell is denied, edit is denied; the agent says it cannot run `git status` and does not guess. Permissions work. -- Orchestrated review through the `subagent` tool: the reviewer returned no correctness findings for the one-line fix, correctly noted that the second test does not guard the defect, and reported the suite as NOT RUN (no shell). Honest and read-only. -- First command version used `subagent: true` in frontmatter. In a session created without an active model the command switched nothing and produced no run. Changed to a normal command that instructs the main agent to call the `subagent` tool with agent `reviewer`. - -## Adoption - -`/start` was exercised on an unadopted fixture with `--auto` (the command itself was read and followed; the API-invoked command stopped at the write permission prompt, as expected without a user to approve). Result: - -- root `AGENTS.md`: 27 lines with stack, layout, commands, conventions and gotchas, no generic advice; -- `.dev-brain/STATE.md`: goal, evidence, blockers and three next actions; -- no code, configuration or git changes; -- packaging and test-harness gaps reported as problems, not fixed. - -One imperfection: the generated `AGENTS.md` contains an absolute repository path. The command now forbids absolute machine paths. - -## Real repository: docling-parser (clinical data) - -`/start` was run on `/home/stefano/codici/docling-parser` with explicit constraints: no access to `input/` or `output/` content, no conversions, no changes to the uncommitted Docling upgrade or the old `harness/` files. - -- Created a 35-line root `AGENTS.md` and a `.dev-brain/STATE.md`; `git status` showed only those additions beyond the pre-existing changes. -- Fresh checks: `uv lock --check` PASS; `uv run --frozen python -m py_compile main.py` PASS; `uv run --frozen python main.py --help` PASS; Docling 2.138.0, pypdfium2 5.9.0. -- Plugin injection: a plan session reproduced the goal and first next action from the new state. -- `/resume` through the API expanded correctly. With an explicit model, it reconciled the state with git, re-ran `uv lock --check` and `--help`, and found README drift (Docling `>=2.100` vs `>=2.129.0`; page furniture described at the end vs interleaved) plus an output inventory mismatch (4 `.md` + 1 `.json` vs the recorded three-file sample). -- Privacy defect: during `/resume` the agent listed `input/` and `output/` filenames. The guard allowed "names/config only"; filenames can be identifying. The rule now forbids opening or listing those directories, and the project `AGENTS.md` was corrected. -- API-created sessions need an explicit `agent` and `model`; without them the command expands but no model call runs. This is a client-session issue, not a command-registration defect. - -Result: adoption and injection PASS; privacy guard tightened after an observed failure. - -## Command expansion - -- `GET /api/command` lists all seven commands with descriptions. -- Invoking `plan` through the session command API produced the expanded prompt ("Plan this work: add a multiply function") and switched the session to the `plan` agent. Expansion works. -- `opencode run "/resume"` does not expand slash commands: the model receives the literal text and has to find the command file. This is a CLI-path limitation, not a registration problem. Use the TUI for commands. - -## Limitations - -- No automated TUI interaction; command behavior was verified through the server API and the CLI. -- One model and one run per scenario; small synthetic fixtures. -- The baseline is a no-harness configuration, not the previous dev-brain version. A comparison against the old kit still needs a separate run. -- The on-request walkthrough rule changed after the bugfix run; its effect on default output length has not been re-measured. - -## Test on a docling-parser copy (2026-10-22, model `github-copilot/claude-haiku-5.5`) - -Setup: a disposable copy under `/tmp/opencode/docling-test`, made with `rsync` excluding `input/`, `output/` and `.venv/`. It keeps git history, the uncommitted Docling changes and the dev-brain files. The real repository was not modified and no clinical data was copied. - -Finding 1 — the running server caches command templates. Edits to `global/commands/*.md` did not reach expansions made through the running server (the expanded `/review` message lacked the new section). Tests through the server therefore used the old text. `opencode run --standalone` (private server, fresh files) used the new text. Restart the background server after editing commands when no session is active. - -Finding 2 — `/resume` ran `uv run --frozen python main.py --help`, which created a 3.5 GB `.venv` in the tmpfs `/tmp` and failed with `No space left on device`. -- Original template, through the server: FAIL — `.venv` created. -- Fix attempt 1 (generic "never create environments"), through the server, old template still served: FAIL — `.venv` created again. -- Fix attempt 2 (precondition: `test -d .venv` before `uv run`), `--standalone`, new template: PASS — `.venv` absent after the run; `--help` reported NOT RUN. Side effect: `uv lock --check`, which is read-only, was also skipped, so the rule is stricter than needed. -- The rule depends on model compliance; the harness does not enforce it. - -Finding 3 — `/review` did not include untracked files; the baseline reviewer stated that `.dev-brain/`, `AGENTS.md` and `harness/` were not reviewed. -- Fix: `git ls-files --others --exclude-standard` (names only; ignored `input/` and `output/` excluded) added to the command, and the reviewer is told to read untracked files in scope. -- Result (`--standalone`, new template): PASS — untracked files listed and reviewed for secrets and paths without opening `input/` or `output/`; no confirmed defect. The reviewer raised a suspicion about the `main.py` Docling API calls against 2.138, outside the diff; it is not verified. - -NOT RUN in this test: `uv lock --check`, `py_compile`, `--help` (no environment), sample conversions, the `/resume` privacy guard against real `output/` content (the copy has no `output/`), `/handoff`, and the TUI itself. - -## Readability and maintainability as the primary goal (2026-10-22) - -The user clarified that readable, maintainable code is the purpose of dev-brain, across languages; workflow and session state are supporting tools. Inspection of `08baebc:dev-brain/RULES.md` showed that the global-rule reduction had dropped its explicit design criteria. The reviewer also explicitly excluded maintenance-only findings. - -Changes: restored a compact, language-independent `Code design` section in `global/AGENTS.md`; broadened the reviewer and `/review` prompt to distinguish concrete maintenance problems from present behavior defects. This restores the user's requirements; the experiment below does not establish a benefit for every individual design instruction. - -Scenario: `evals/scenarios/maintainability.md`, with its stdlib-only fixture. A duplicated shipping rule represents shared business knowledge; two identical label functions have independent owners and must not be merged just for DRY. Generation adds express shipping while preserving standard shipping, public callers and output keys. Review receives the original fixture as a new-file diff. - -Environment: OpenCode v2.1.3, `github-copilot/claude-haiku-5.5`, four fresh `--standalone` runs (generation and review policy before/after), no delegation, no commits. Baseline means the current kit before this change, not no harness. Disposable copies and raw JSONL transcripts: `/tmp/opencode/dev-brain-quality-4mfgq_ok/`; policies were snapshotted before each phase. Those local artifacts are temporary, not a permanent archive. - -Commands (from the matching fresh copy): - -```bash -opencode run --standalone --agent build --model github-copilot/claude-haiku-5.5 --format json "$(cat ../generation-prompt.txt)" -opencode run --standalone --agent build --model github-copilot/claude-haiku-5.5 --format json "$(cat ../baseline-review-prompt.txt)" -opencode run --standalone --agent build --model github-copilot/claude-haiku-5.5 --format json "$(cat ../updated-review-prompt.txt)" -python3 -B -m unittest -v -``` - -The generation prompt was identical before/after. For policy evaluation the reviewer body was supplied to `build` with the same diff and request; only the supplied policy and installed global rules changed. This avoids delegation and does **not** test the actual `/review` command or reviewer permissions. The final wording of the finding-format bullet was then clarified from "trigger" to "trigger or maintenance scenario"; no model rerun was made for that editorial clarification. - -| Check | Before | After | -| --- | --- | --- | -| Generation: suite independently rerun with `python3 -B -m unittest -v` | PASS, 4 tests | PASS, 4 tests | -| New tests on original source | Expected FAIL: missing `express` argument | Expected FAIL: missing `express` argument | -| Order observed in tool transcript | Tests fail before implementation | Tests fail before implementation | -| Shipping rule | One helper shared by both entry points | One helper shared by both entry points | -| Unrelated label policies | Unchanged and separate | Unchanged and separate | -| Speculative architecture/dependencies | None | None | -| Policy review: duplicated business rule | Excluded because no behavior changes today | Reported separately as a maintenance problem, with a shared helper as the smallest remedy | -| Policy review: similar but unrelated labels | No finding | Explicitly rejects merging them | - -The baseline reviewer said: "I excluded the duplicated shipping rule [...] because neither changes behavior now." The updated policy identified changing the shipping threshold/fee as the maintenance scenario requiring edits in two locations. That is the observed improvement. The updated response also raised conditional input-validation questions; these are not confirmed defects, because no external-input contract was supplied. - -Additional local `python3 -B` assertions independently checked eight `(subtotal, express)` combinations per implementation, unchanged label ASTs, one threshold decision and no added imports/classes: PASS for both. Generated tests were replayed against separate copies of the original source: both failed for the intended missing argument, not an import/setup error. JSONL inspection found no error events or delegation; the review-policy runs used no tools. - -Fixture check: `python3 -B -m unittest discover -s evals/fixtures/maintainability -v` PASS (2 original tests). The fixture deliberately retains the duplicated rule for the review scenario; it is not the generated implementation. - -Conclusion: the review policy now covers an observed gap in maintenance review. Generated code was already simple and readable in the baseline, so this run shows no generation-quality gain. One model, one run per task/version, Python only: no general quality claim or cross-language behavior claim. Instructions express a language-independent requirement, not a guarantee. - -Final static checks: `git diff --check` PASS; `bash -n evals/setup.sh` PASS; per-file `git diff --no-index --check -- /dev/null ` PASS for all 12 changed/new paths (exit 1 for a differing new file is not a whitespace failure). A local `python3 -B` check also verified balanced Markdown fences, Python AST parsing, no machine paths in the edited global definitions, installed symlinks to the edited rules/reviewer/command, and instruction/state line budgets: PASS. The initial checker incorrectly required exit 0 from `--no-index`; it was corrected and rerun, with no source whitespace defect found. - -NOT RUN: the updated `/review` delegation/TUI path, scenarios in other languages, the full historical scenario set, or `evals/setup.sh` (it creates fixture commits; no commit was authorized). No docling work or service restart was performed. - -## Token budget and review cost, tested on hph (2026-10-25) - -Environment: OpenCode v2.1.4 (`@opencode/cli`), isolated `XDG_*` directories, kit installed with `install.sh`. The model was a local OpenAI-compatible mock that records each request and replays scripted tool calls (now `evals/offline/check.py`). No real model was called, so this measures what the harness sends and permits, not answer quality. Test repository: disposable copies of `Stcant/hph` (Rust/Leptos/PostgreSQL) at `d6ee299`. - -Baseline findings on the previous kit: - -- `/review` embedded the full `git diff` in the command message (7005 chars for a 5.9 KB diff in hph), then asked the main agent to paste it into the subagent prompt: the diff was paid as main input, main output and reviewer input. The title request also received the whole expanded message. -- `/review` used `git diff`: staged-only changes produced an empty diff (`git diff --stat` printed nothing for a staged edit); untracked-only changes hit the "diff is empty, stop" step. -- The plugin injected the state into subagent calls too (reviewer, explore, general). Its 80-line cap did not bound size: this repository's own state was 3900 chars. -- `/resume` had a Python-only guard (`uv run` / `.venv`). In hph the recorded checks are `cargo test`/`cargo leptos build`, which compile the workspace. -- `/start` ignored previous-kit files: hph carries `harness/PROJECT_STATE.md` (14.6 KB) and `PROJECT_MAP.md` (6.8 KB), whose "next action" (merge PR #8) was already done (`f54564b`). -- `/plan` leaves the session on the `plan` agent; a follow-up "implement it" is refused by the plan-mode reminder. Expected OpenCode behavior, now stated in the manual. - -Changes and evidence: - -| Check | Before | After | -| --- | --- | --- | -| `/review` message in the main session (hph, 5.9 KB diff) | 7005 chars, diff copied again as output | 1101 chars; the reviewer runs `git diff HEAD` itself | -| Staged-only / untracked-only / no-commit repo | empty diff / stop / `git diff` only | visible through `git status --short` + `git diff HEAD --stat` (fallback `--cached`) | -| Reviewer shell | none | `git diff/log/show/status` allowed; `>`, `--output`, `; rm`, `&& touch`, `\| tee`, `$(touch)` rejected, no file written | -| State in subagent calls | injected | not injected (session `parentID` check) | -| Oversized state (3.7 KB) | first 80 lines injected | one-line notice, no content | -| Compaction hook text in the summary request | not observed | present (API `session.compact`) | -| Always-loaded rules (`global/AGENTS.md`) | 4788 chars | 4543 chars: reporting and walkthrough rules merged, none removed | - -`evals/offline/check.py`: ALL PASS on this branch (three consecutive runs, ~5 s each); on `main` it fails 4 of 5 checks (subagent injection, reviewer git read, write protection, oversized state). A deny on the `subagent` action inside the reviewer made sessions using it hang; it is not needed because nested subagents are already blocked (`Subagent depth limit reached (1)`). - -Gotchas found while testing: - -- OpenCode does not block shell redirection by itself: without the explicit `*>*` deny, `git diff HEAD > file` ran and wrote the file. Chained commands are split and each part is checked. -- `opencode run` reads stdin when it is not a terminal and waits for EOF. Scripts must use `< /dev/null`; earlier intermittent "hangs" in automated runs had this cause. -- The background service serves cached command templates until `opencode service restart` (confirmed again). - -hph adoption by following `/start`: root `AGENTS.md` 3072 chars (40 lines) + `.dev-brain/STATE.md` 1329 chars replace 21.3 KB of `harness/` as working context; the plugin injected a 1504-char state block. `harness/` is left for the owner to delete. Delivered as a patch, not pushed: this session has no write access to `Stcant/hph`. - -NOT RUN: any real model (provider endpoints unreachable from the test environment), the TUI, the scenario set in `evals/scenarios/`, the generic `/resume` rule with a model, `cargo` checks in hph. - -## Agent-independent kit: OpenCode, Claude Code, Codex CLI, Cursor (2026-10-25) - -Goal set by the user: the kit must not depend on one agent. Tested binaries: OpenCode 2.1.4, Claude Code 2.1.310, Codex CLI 0.164.0, each against `evals/offline/mock_model.py` (OpenAI chat, Anthropic messages and OpenAI responses wire formats) with isolated homes. Cursor: no CLI reachable from the test environment; its layout comes from cursor.com docs and is checked only for generated files. - -What each agent actually loads (probed before designing): - -| | OpenCode | Claude Code | Codex | Cursor (docs) | -| --- | --- | --- | --- | --- | -| Project `AGENTS.md` | yes | yes (natively) | yes | yes | -| Global rules file | `~/.config/opencode/AGENTS.md` | `~/.claude/CLAUDE.md`, `@/abs/path` import works; `~/.claude/AGENTS.md` ignored | `~/.codex/AGENTS.md` | `~/.cursor/rules/` (known loading bug) or Settings | -| Skill dirs | `~/.claude/skills`, `~/.agents/skills` (same name: deduplicated) | `~/.claude/skills` only | `~/.codex/skills`, `~/.agents/skills` | `~/.cursor`, `~/.agents`, `~/.claude`, `~/.codex` skills | -| `disable-model-invocation` | not tested | honored (not listed) | ignored (listed, ~1200 chars) | honored | -| Claude-format plugin | n/a | commands, skills, agents, hooks | skills only; copies the plugin and drops symlinked dirs | n/a | -| State hook | plugin `context` hook | `SessionStart` additionalContext, reaches the system prompt | `SessionStart`, runs only after the user trusts it | `sessionStart` additional_context dropped (open bug) | - -No skill directory is shared by all four, so `core/` is installed per agent; plugins are namespaced (`dev-brain:`), which also avoids Claude Code's built-in `/review` (a custom `/review` from a plugin did not override it). - -Reviewer enforcement, tested with write attempts (`>`, `touch`, `; rm`, `--output`): - -- OpenCode: rejected by permissions (unchanged). -- Claude Code: `tools: Read, Grep, Glob, Bash(git …:*)` — git reads run; every write "needs approval" and was denied in `-p` mode; no file written. -- Codex: the role from `~/.codex/agents/reviewer.toml` is registered, but `sandbox_mode = "read-only"` is not applied to the spawned agent: with the parent in `workspace-write` (flag or config), the reviewer created a file. Registering it under `[agents.reviewer] config_file` changed nothing. Documented as instruction-only. -- Cursor: `readonly: true` per docs; not run. - -`evals/offline/check.py`, extended to all agents found: ALL PASS twice (21 checks, ~12 s); 24 after adding `start` expansion checks for each agent. Mutation check: removing `disable-model-invocation` from one workflow makes `claude-code: user-invoked workflows stay out of the skill listing` FAIL. - -On hph (`/tmp` copy with the adoption patch): Claude Code `/dev-brain:resume` and Codex `$dev-brain:resume` (hook trust bypassed for the test only) both received the hph state, the resume workflow and the hph `AGENTS.md`. - -Removed: `agent: plan` on the plan workflow (OpenCode kept the session in plan mode, refusing implementation afterwards); `!` command expansion in workflows (not portable; the agent now runs `git status`/`git log` itself, one extra tool call). - -NOT RUN: any real model, any TUI, Cursor, the scenario set, Codex reviewer behavior beyond the sandbox test. +- Bugfix: both fixed the sign error; the kit ran the failing test first and recorded before/after evidence. +- Resume with stale state: both noticed the stale next action; the kit reran the suite instead of quoting the old PASS. +- Explain a flow: both correct; the kit added OBSERVED/INFERRED labels, a reading order and a runtime check, at greater length. +- Handoff: fresh evidence, two next actions, no commit. +- Adoption on docling-parser (clinical data): the agent listed `input/`/`output/` filenames; the rule now forbids opening or listing data directories. +- `resume` created a 3.5 GB `.venv`; fixed by the no-install rule. diff --git a/evals/scenarios/explain.md b/evals/scenarios/explain.md index b681ca5..85a2663 100644 --- a/evals/scenarios/explain.md +++ b/evals/scenarios/explain.md @@ -4,7 +4,7 @@ Fixture: `evals/fixtures/explain` (three Python modules, no dependencies) Prompt: -> /learn how an order is created +> /dev-brain:learn how an order is created Expected behavior: diff --git a/evals/scenarios/handoff.md b/evals/scenarios/handoff.md index eb61d78..e230701 100644 --- a/evals/scenarios/handoff.md +++ b/evals/scenarios/handoff.md @@ -4,7 +4,7 @@ Fixture: same as `bugfix`, after the fix. Prompt: -> /handoff +> /dev-brain:handoff Expected behavior: diff --git a/evals/scenarios/resume.md b/evals/scenarios/resume.md index 02d1172..1936099 100644 --- a/evals/scenarios/resume.md +++ b/evals/scenarios/resume.md @@ -6,7 +6,7 @@ The saved `.dev-brain/STATE.md` says the next action is to implement `subtract`, Prompt: -> /resume +> /dev-brain:resume Expected behavior: diff --git a/evals/setup.sh b/evals/setup.sh index ba034cc..659a10e 100755 --- a/evals/setup.sh +++ b/evals/setup.sh @@ -5,7 +5,7 @@ set -eu here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)" -dest="${TMPDIR:-/tmp}/opencode/dev-brain-evals" +dest="${TMPDIR:-/tmp}/dev-brain-evals" name="dev-brain eval" email="dev-brain@example.invalid" diff --git a/install.py b/install.py deleted file mode 100644 index 73e0854..0000000 --- a/install.py +++ /dev/null @@ -1,322 +0,0 @@ -#!/usr/bin/env python3 -"""Install dev-brain into one or more coding agents. - -usage: python3 install.py [opencode] [claude-code] [codex] [cursor] - (no arguments: every agent whose CLI or config directory is found) - -core/ is the only source. Each adapter below links it or translates its -frontmatter into what that agent reads; no rule lives in an adapter. -Idempotent: files that are not ours are moved to *.bak., never deleted. -""" -import hashlib -import json -import os -import shutil -import subprocess -import sys -import time -from pathlib import Path - -KIT = Path(__file__).resolve().parent -CORE = KIT / "core" -CONTEXT_SCRIPT = CORE / "bin" / "dev-brain-context" -BUILD = KIT / "build" / "marketplace" -MARKER = "generated by dev-brain install.py" -STAMP = time.strftime("%Y%m%d%H%M%S") -HOME = Path.home() -TOOLS = ("opencode", "claude-code", "codex", "cursor") - - -# ---------- source files ---------- - -def split_frontmatter(path): - """(fields, body) of a Markdown file with simple `key: value` frontmatter.""" - text = path.read_text(encoding="utf-8") - if not text.startswith("---\n"): - return {}, text - head, body = text[4:].split("\n---\n", 1) - fields = {} - for line in head.splitlines(): - if ":" in line and not line.startswith((" ", "#")): - key, value = line.split(":", 1) - fields[key.strip()] = value.strip() - return fields, body.lstrip("\n") - - -def skills(): - return sorted(p for p in (CORE / "skills").iterdir() if (p / "SKILL.md").exists()) - - -def workflows(): - return sorted(p for p in (CORE / "workflows").iterdir() if (p / "SKILL.md").exists()) - - -def reviewer(): - return split_frontmatter(CORE / "agents" / "reviewer.md") - - -# ---------- safe file operations ---------- - -def owned(path): - """True for our links (into this kit) and our generated files.""" - if path.is_symlink(): - return str(Path(os.readlink(path))).startswith(str(KIT)) - if path.is_file(): - try: - return MARKER in path.read_text(encoding="utf-8", errors="ignore")[:400] - except OSError: - return False - return False - - -def clear(path): - if not (path.exists() or path.is_symlink()): - return - if owned(path): - path.unlink() - else: - backup = path.with_name(f"{path.name}.bak.{STAMP}") - path.rename(backup) - print(f" backed up: {path} -> {backup.name}") - - -def link(src, dst): - dst.parent.mkdir(parents=True, exist_ok=True) - if dst.is_symlink() and Path(os.readlink(dst)) == src: - return - clear(dst) - dst.symlink_to(src) - - -def write(dst, text): - dst.parent.mkdir(parents=True, exist_ok=True) - if dst.is_file() and not dst.is_symlink() and dst.read_text(encoding="utf-8") == text: - return - clear(dst) - dst.write_text(text, encoding="utf-8") - - -def update_json(path, change): - """Apply change(dict) to a JSON file; leave it alone if it cannot be parsed.""" - data = {} - if path.exists(): - try: - data = json.loads(path.read_text(encoding="utf-8")) - except (ValueError, OSError) as error: - print(f" warning: cannot parse {path} ({error}); edit it by hand") - return False - change(data) - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") - return True - - -def hook_command(fmt): - return f'python3 "{CONTEXT_SCRIPT}" --format {fmt}' - - -def set_hook(data, event, entry, nested): - """Replace our hook entry for `event` (found by script path), keep everyone else's.""" - hooks = data.setdefault("hooks", {}) - entries = [e for e in hooks.get(event, []) if "dev-brain-context" not in json.dumps(e)] - hooks[event] = entries + [entry] - if not nested: - data.setdefault("version", 1) - - -def run(cmd): - result = subprocess.run(cmd, capture_output=True, text=True) - output = (result.stdout + result.stderr).strip().splitlines() - print(f" $ {' '.join(cmd)} -> {'ok' if result.returncode == 0 else 'exit ' + str(result.returncode)}" - + (f" ({output[-1]})" if output and result.returncode else "")) - return result.returncode == 0 - - -def frontmatter(fields, comment=MARKER): - lines = ["---", f"# {comment}"] - for key, value in fields.items(): - lines.extend([f"{key}:"] + [f" - {item}" for item in value] if isinstance(value, list) else [f"{key}: {value}"]) - return "\n".join(lines + ["---", ""]) + "\n" - - -# ---------- shared plugin bundle (Claude Code and Codex) ---------- - -def build_marketplace(): - """A local plugin marketplace with real copies: Codex copies plugins and drops symlinks.""" - plugin = BUILD / "dev-brain" - shutil.rmtree(BUILD, ignore_errors=True) - for source in skills() + workflows(): - shutil.copytree(source, plugin / "skills" / source.name) - (plugin / "bin").mkdir(parents=True) - shutil.copy2(CONTEXT_SCRIPT, plugin / "bin" / CONTEXT_SCRIPT.name) - - fields, body = reviewer() - # Claude Code: only these tools; any other shell command needs the user's approval. - tools = "Read, Grep, Glob, Bash(git diff:*), Bash(git log:*), Bash(git show:*), Bash(git status:*)" - agent = frontmatter({"name": fields["name"], "description": fields["description"], "tools": tools}) + body - (plugin / "agents").mkdir() - (plugin / "agents" / "reviewer.md").write_text(agent, encoding="utf-8") - - hook = {"matcher": "startup|resume|clear|compact", - "hooks": [{"type": "command", "command": 'python3 "${CLAUDE_PLUGIN_ROOT}/bin/dev-brain-context" --format hook'}]} - (plugin / "hooks").mkdir() - (plugin / "hooks" / "hooks.json").write_text(json.dumps({"hooks": {"SessionStart": [hook]}}, indent=2) + "\n") - - digest = hashlib.sha256() - for path in sorted(plugin.rglob("*")): - if path.is_file(): - digest.update(str(path.relative_to(plugin)).encode() + path.read_bytes()) - version = f"1.0.{int(digest.hexdigest()[:6], 16)}" # changes with content, so agents refresh their copy - manifest = {"name": "dev-brain", "version": version, - "description": "Readable, maintainable code with low context cost: workflows, skills, read-only reviewer, saved state."} - (plugin / ".claude-plugin").mkdir() - (plugin / ".claude-plugin" / "plugin.json").write_text(json.dumps(manifest, indent=2) + "\n") - market = {"name": "dev-brain", "owner": {"name": "dev-brain"}, - "plugins": [{"name": "dev-brain", "source": "./dev-brain", "description": manifest["description"]}]} - (BUILD / ".claude-plugin").mkdir(parents=True) - (BUILD / ".claude-plugin" / "marketplace.json").write_text(json.dumps(market, indent=2) + "\n") - return BUILD - - -# ---------- adapters ---------- - -def install_opencode(): - config = Path(os.environ.get("XDG_CONFIG_HOME", HOME / ".config")) / "opencode" - link(CORE / "AGENTS.md", config / "AGENTS.md") - for source in skills(): - link(source, config / "skills" / source.name) - for source in workflows(): # user-invoked: commands cost no context until used - fields, body = split_frontmatter(source / "SKILL.md") - write(config / "commands" / f"{source.name}.md", - frontmatter({"description": fields["description"]}) + body.rstrip() + "\n\nUser input: $ARGUMENTS\n") - fields, body = reviewer() - # Last matching rule wins. Shell is read-only git; chained commands are split and each part - # is checked, but redirection and --output are not, so they are denied explicitly. - permissions = [ - '{ action: edit, resource: "*", effect: deny }', - '{ action: shell, resource: "*", effect: deny }', - '{ action: shell, resource: "git diff *", effect: allow }', - '{ action: shell, resource: "git log *", effect: allow }', - '{ action: shell, resource: "git show *", effect: allow }', - '{ action: shell, resource: "git status *", effect: allow }', - '{ action: shell, resource: "* --output*", effect: deny }', - '{ action: shell, resource: "*>*", effect: deny }', - ] - write(config / "agents" / "reviewer.md", - frontmatter({"description": fields["description"], "mode": "subagent", "permissions": permissions}) + body) - - plugin = str(KIT / "adapters" / "opencode" / "plugin") - - def register(data): - data.setdefault("$schema", "https://opencode.ai/config.json") - plugins = [p for p in data.setdefault("plugins", []) if not (isinstance(p, str) and p.endswith("/plugin/dev-brain"))] - data["plugins"] = plugins + ([plugin] if plugin not in plugins else []) - if not update_json(config / "opencode.json", register): - print(f' add manually: "plugins": ["{plugin}"]') - return ["Restart the background server when no session is active: opencode service restart", - "Workflows: /start /resume /handoff /plan /impact /learn /review"] - - -def install_claude_code(): - config = Path(os.environ.get("CLAUDE_CONFIG_DIR", HOME / ".claude")) - memory = config / "CLAUDE.md" - line = f"@{CORE / 'AGENTS.md'}" - current = memory.read_text(encoding="utf-8") if memory.exists() else "" - if line not in current: - memory.parent.mkdir(parents=True, exist_ok=True) - memory.write_text(current.rstrip("\n") + ("\n\n" if current.strip() else "") + - f"\n{line}\n", encoding="utf-8") - notes = ["Workflows: /dev-brain:review (or /review when the name is free), same for the others"] - if shutil.which("claude"): - run(["claude", "plugin", "marketplace", "add", str(BUILD)]) - run(["claude", "plugin", "marketplace", "update", "dev-brain"]) - run(["claude", "plugin", "install", "dev-brain@dev-brain"]) - else: - notes.insert(0, f"claude not on PATH: run `claude plugin marketplace add {BUILD}` and " - "`claude plugin install dev-brain@dev-brain`") - return notes - - -def install_codex(): - home = Path(os.environ.get("CODEX_HOME", HOME / ".codex")) - link(CORE / "AGENTS.md", home / "AGENTS.md") - fields, body = reviewer() - # The read-only sandbox is enforced by Codex itself, not by the prompt. - # A TOML literal string keeps the body verbatim: no escape sequences. - toml = (f"# {MARKER}\nname = {json.dumps(fields['name'])}\ndescription = {json.dumps(fields['description'])}\n" - f"sandbox_mode = \"read-only\"\ndeveloper_instructions = '''\n{body.strip()}\n'''\n") - write(home / "agents" / "reviewer.toml", toml) - entry = {"matcher": "startup|resume|clear|compact", "hooks": [{"type": "command", "command": hook_command("hook")}]} - update_json(home / "hooks.json", lambda data: set_hook(data, "SessionStart", entry, nested=True)) - notes = ["Approve the SessionStart hook once in the Codex TUI (new hooks need review before they run)", - "Workflows are skills: $review, $resume, ... (or pick them from /skills)"] - if shutil.which("codex"): - run(["codex", "plugin", "marketplace", "add", str(BUILD)]) - run(["codex", "plugin", "add", "dev-brain@dev-brain"]) - else: - notes.insert(0, f"codex not on PATH: run `codex plugin marketplace add {BUILD}` and `codex plugin add dev-brain@dev-brain`") - return notes - - -def install_cursor(): - home = HOME / ".cursor" - rules = (CORE / "AGENTS.md").read_text(encoding="utf-8") - write(home / "rules" / "dev-brain.mdc", - frontmatter({"description": "Personal engineering rules (dev-brain)", "alwaysApply": "true"}) + rules) - for source in skills() + workflows(): - link(source, home / "skills" / source.name) - fields, body = reviewer() - write(home / "agents" / "reviewer.md", - frontmatter({"name": fields["name"], "description": fields["description"], "readonly": "true"}) + body) - update_json(home / "hooks.json", lambda data: set_hook( - data, "sessionStart", {"command": hook_command("cursor")}, nested=False)) - return [f"If the agent ignores the rules, paste {CORE / 'AGENTS.md'} into Cursor Settings > Rules " - "(file-based global rules are not always loaded)", - "Workflows: /review, /resume, ... (skills invoked by name)"] - - -def detect(): - found = [] - if shutil.which("opencode"): - found.append("opencode") - if shutil.which("claude") or (HOME / ".claude").exists(): - found.append("claude-code") - if shutil.which("codex") or (HOME / ".codex").exists(): - found.append("codex") - if shutil.which("cursor") or shutil.which("cursor-agent") or (HOME / ".cursor").exists(): - found.append("cursor") - return found - - -def main(argv): - if any(arg in ("-h", "--help") for arg in argv): - print(__doc__) - return 0 - unknown = [arg for arg in argv if arg not in TOOLS] - if unknown: - print(f"unknown agent: {', '.join(unknown)} (choose from {', '.join(TOOLS)})") - return 2 - chosen = argv or detect() - if not chosen: - print(f"No supported agent found. Name one: python3 install.py {' '.join(TOOLS)}") - return 1 - if {"claude-code", "codex"} & set(chosen): - build_marketplace() - for tool in chosen: - print(f"{tool}:") - if tool == "opencode": - notes = install_opencode() - elif tool == "claude-code": - notes = install_claude_code() - elif tool == "codex": - notes = install_codex() - else: - notes = install_cursor() - for note in notes: - print(f" - {note}") - print("Done. New sessions pick up the rules, workflows, skills and reviewer.") - return 0 - - -if __name__ == "__main__": - sys.exit(main(sys.argv[1:])) diff --git a/install.sh b/install.sh deleted file mode 100755 index b67ffdd..0000000 --- a/install.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/env bash -# Install dev-brain into one or more coding agents. See install.py --help. -# ./install.sh every agent found on this machine -# ./install.sh opencode codex only those -set -eu -exec python3 "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)/install.py" "$@" From b4f94e12b789589f3b9e889cb5a1ca086e911e7d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 25 Oct 2026 14:38:30 +0100 Subject: [PATCH 4/4] Ignore Python bytecode caches from the offline check Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Sm3JtGSXFLR6CZYVJXGHtU --- .gitignore | 1 + 1 file changed, 1 insertion(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c18dd8d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +__pycache__/