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 51044a1..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 -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. +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) -- `/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) +- 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 -- 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 +- 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 `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. -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 new file mode 100644 index 0000000..c18dd8d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +__pycache__/ diff --git a/AGENTS.md b/AGENTS.md index b446c83..68e527f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,29 +1,31 @@ # 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 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 -- `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/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 the plugin, agents or `install.sh`, 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. -- 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: 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 f2d10ee..5ad3c8b 100644 --- a/MANUALE.md +++ b/MANUALE.md @@ -1,464 +1,124 @@ # 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). - -## 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 -- 12. Manutenzione del kit -- 13. Migrazione dal vecchio dev-brain -- 14. Problemi e domande frequenti -- 15. Limiti noti -- 16. Checklist -- Riferimenti +> 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 -# 1. dalla cartella del kit -./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. -``` - -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 -``` - -Per riprendere una sessione usando lo stato salvato: - -```text -/resume +claude plugin marketplace add Stcant/agents-platform +claude plugin install dev-brain@dev-brain ``` -Per aggiornare lo stato alla fine del lavoro: +Poi, nella radice di ogni repository, una volta sola: ```text -/handoff +/dev-brain:start ``` -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. +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 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. - -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. - -Fornisce: +Un plugin per Claude Code. Fa tre cose: -- regole sempre attive, volutamente poche; -- sette comandi per il flusso ricorrente; -- tre skill caricate solo quando servono; -- 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. +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. -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. - -### 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 | +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. --- -## 2. 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. - -### Installazione - -```bash -cd -./install.sh -``` - -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. - -Non riavvia il server e non modifica le tue permission. - -### Verifica - -```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: - -```bash -# quando non hai sessioni attive -opencode service restart -``` - -Poi apri una nuova sessione. +## 2. Installazione -### Aggiornamento +Prerequisiti: Claude Code, `python3`, `git`. ```bash -cd -git pull -./install.sh +claude plugin marketplace add Stcant/agents-platform +claude plugin install dev-brain@dev-brain ``` -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. +- **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. -### Disinstallazione +Il plugin non tocca `CLAUDE.md` né le tue impostazioni: regole e stato arrivano da un hook `SessionStart`. -Non c'è uno script di disinstallazione. Per rimuovere il kit: - -```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} -``` - -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. +**Verifica:** `python3 evals/offline/check.py` dalla cartella del kit deve stampare `ALL PASS` (sezione 8). --- -## 3. Prima adozione di una repository - -Nella repository, dalla radice: - -```text -/start -``` +## 3. Primo passo in ogni repository: `/dev-brain:start` -Il comando è pensato per l'adozione iniziale. Ispeziona il repository e 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 + └── 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 `.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. +- 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. -Cosa non fa: +Non tocca codice, dipendenze o git, e non installa nulla. Non apre directory con dati personali, clinici o segreti (`input/`, `output/`, `.env`). -- non installa dipendenze; -- non esegue l'applicazione, migrazioni o conversioni; -- non committa; -- non decide al posto tuo se un problema va corretto. - -### 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. - -### 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: - -```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" -``` - -Se hai lavoro non committato, `/start` non lo tocca. Un albero pulito rende però più chiara l'evidenza nello stato. +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). --- -## 4. Lavoro quotidiano +## 4. I workflow -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. +Si invocano con `/dev-brain:`. Il testo dopo il nome è l'argomento. Non costano contesto finché non li usi (`disable-model-invocation`). -| Momento | Comando | 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 [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`. -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. -7. Committa solo se hai deciso di farlo. - ---- +| `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 | -## 5. I comandi in dettaglio +**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. -### `/start` +**`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`…). -**Quando:** prima adozione di una repository, o quando vuoi riallineare i fatti del progetto. - -**Cosa produce:** root `AGENTS.md` e `.dev-brain/STATE.md`. - -**Scrive:** sì, solo quei due file (o li aggiorna). - -**Non fa:** modifiche al codice, installazioni, conversioni, commit. - -**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` - -**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; -- se lo stato è vecchio, lo dice prima di proseguire; -- esegue un controllo registrato solo se è sicuro e in sola lettura; -- 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`. - -**Nota:** i risultati vecchi non vengono presentati come appena eseguiti. - -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. - ---- - -### `/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`). - -**Non fa:** non committa e non modifica il codice. - -**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. - -**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: - -- 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. +**`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. --- -### `/impact ` +## 5. Il reviewer -**Quando:** prima di cambiare un contratto, un formato, un dato persistito o codice condiviso. +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. -**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:** - -```text -Flow: -> : -> : -``` - -**Etichette:** `OBSERVED`, `INFERRED`, `UNKNOWN`. Non è un tutorial generico: se una cosa non è stata verificata, lo dice. +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`. --- -### `/review [scope]` - -**Quando:** prima di committare o aprire una PR. +## 6. Le skill -**Cosa fa:** +Il modello le carica quando servono; puoi anche chiederle per nome. -- 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; -- 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. - -**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. +| 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 | --- -## 6. 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. +## 7. Lo stato -Contenuto consigliato: - -```markdown -# - - - -## Stack -- - -## Comandi -- Install: `` (dalla directory `<...>`) -- Test: `` -- Lint / type check: `` -- Build: `` - -## 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. - -### `.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: +Formato di `.dev-brain/STATE.md`: ```markdown # State — @@ -471,7 +131,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,380 +140,55 @@ 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. - ---- - -## 7. Il plugin - -Il plugin `plugin/dev-brain/index.ts` fa quattro cose. - -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. - -Dettagli: - -- 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. - ---- - -## 8. Regole, permessi e sicurezza - -Le regole globali vivono in `global/AGENTS.md` e vengono installate come `~/.config/opencode/AGENTS.md`. - -### Precedenza - -```text -correttezza > sicurezza e integrità dei dati > compatibilità col progetto > manutenibilità > semplicità > prestazioni misurate -``` - -### 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. - -### 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`. - -### 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à +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`. -- 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. - -### 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. +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. --- -## 9. Le skill - -Le skill sono istruzioni specializzate che il modello carica quando il compito corrisponde alla descrizione. Non hanno comandi slash propri. - -| Skill | Quando si carica | 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: +## 8. Manutenzione del kit ```text -Carica la skill debugging e usa il suo metodo. +.claude-plugin/marketplace.json elenca il plugin +core/ il plugin: AGENTS.md, skills/, agents/, hooks/, bin/ +evals/ scenari, fixture, risultati, controllo offline ``` -`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. +Per modificare il kit: -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: +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`. -- `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. +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: -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”. +- 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. -Limiti: +Non valuta la qualità delle risposte. -- 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. +`core/AGENTS.md` e le skill restano in formati standard: supportare un altro agente in futuro richiede un adattatore, non una riscrittura. --- -## 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 -``` +## 9. Problemi frequenti -### Modifica non banale - -```text -/plan -/impact -# implementa -# esegui i test -/review -/handoff -# commit manuale, se decidi -``` - -### Bug - -```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 -``` - -### Feedback di review - -```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 -``` - ---- - -## 12. Manutenzione del kit - -### Struttura del repository del kit - -```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 -MANUALE.md questo manuale -``` - -### Modificare il kit - -1. Apri una modifica piccola e mirata. -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 - -```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. - -### Controllo offline, a costo zero - -```bash -python3 evals/offline/check.py # OPENCODE= se non è 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: - -- 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). - -Non valuta la qualità delle risposte del modello: per quella restano gli scenari. Lancialo dopo ogni modifica a plugin, agenti o installer. - -`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. - -### Lingua - -Tutto il contenuto del kit è in inglese, tranne questo manuale utente. - -### Backup e aggiornamenti - -- 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 -``` - ---- - -## 14. Problemi e domande frequenti - -| Sintomo | Causa e soluzione | +| Sintomo | 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 | - ---- - -## 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. -- 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 - -- [ ] `./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 -- [ ] `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 -- [ ] Nessun dato clinico, personale o segreto in stato, istruzioni o chat +| `/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 | --- -## Riferimenti +## 10. Limiti noti -- `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 +- 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 33751d4..02ca9a1 100644 --- a/README.md +++ b/README.md @@ -1,134 +1,74 @@ # dev-brain -Personal engineering harness for OpenCode V2. 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. +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; -- commands for the recurring workflow: 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. - -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 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. - -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. - -| 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. - -Instructions guide the model; they do not guarantee good code. Behavioral tests and maintenance scenarios are evaluated separately in `evals/`. - ## Install ```bash -./install.sh +claude plugin marketplace add Stcant/agents-platform +claude plugin install dev-brain@dev-brain ``` -The script symlinks the kit into `~/.config/opencode` and registers the plugin in `~/.config/opencode/opencode.json`: +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). -| 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` | +## First step in every repository: `/dev-brain:start` -Existing files that are not managed by this kit are moved to `*.bak.`, never deleted. The script is idempotent. +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. -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. +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 session only gets a one-line hint suggesting `start`; the global rules apply either way. ## 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 Claude Code to implement or fix what you need. The rules already apply; the workflows support the work. -| 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. - -## 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 | -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. +For planning use Claude Code's native plan mode (Shift+Tab): it is read-only by enforcement, which a prompt cannot match. -## Plugin +| 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 | -`plugin/dev-brain/index.ts` uses only `@opencode/plugin` and Node built-ins: +## What is enforced, what is instructed -- `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. +- **Reviewer read-only: enforced.** Its tool list allows Read, Grep, Glob and `git diff/log/show/status`; any command that creates, changes or removes files needs your approval. +- **State budget: enforced.** Over 3000 characters only a notice is injected, telling the model to read the file and suggest `handoff`. +- **Everything else is instructed:** rules guide the model; they do not guarantee good code. ## Evaluation -`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: - -```bash -python3 evals/offline/check.py # set OPENCODE= if opencode is 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. - -Run a scenario manually in a fixture: - ```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." +python3 evals/offline/check.py # CLAUDE= if claude is not on PATH ``` -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). - -## 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. +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 ``` -global/ always-loaded rules, commands, agents, skills -plugin/ OpenCode V2 plugin -templates/ STATE.md and project AGENTS.md templates -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/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/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..a0f64ea 100644 --- a/global/agents/reviewer.md +++ b/core/agents/reviewer.md @@ -1,24 +1,12 @@ --- +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 } +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. -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..88ee6ef --- /dev/null +++ b/core/bin/dev-brain-context @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +"""SessionStart hook: give the agent the global rules and the project's saved state. + +Claude Code runs it at startup, resume, /clear and after compaction, and adds the +printed `additionalContext` to the session. The project is found from the hook's +JSON on stdin (`cwd`), else from the current directory. `--text` prints the plain +context instead, for checking it by hand. +""" +import json +import os +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 +# 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 state_text(root): + if root is None: + return "" + try: + with open(os.path.join(root, STATE_PATH), encoding="utf-8") as handle: + state = handle.read().strip() + except FileNotFoundError: + 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 /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 /dev-brain:handoff 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 main(): + 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({"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": context}})) + + +if __name__ == "__main__": + 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/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/commands/handoff.md b/core/skills/handoff/SKILL.md similarity index 69% rename from global/commands/handoff.md rename to core/skills/handoff/SKILL.md index 5486be8..b5fb04f 100644 --- a/global/commands/handoff.md +++ b/core/skills/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/skills/impact/SKILL.md similarity index 76% rename from global/commands/impact.md rename to core/skills/impact/SKILL.md index 0b495d8..1339700 100644 --- a/global/commands/impact.md +++ b/core/skills/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/skills/learn/SKILL.md similarity index 75% rename from global/commands/learn.md rename to core/skills/learn/SKILL.md index c25db02..4ebb790 100644 --- a/global/commands/learn.md +++ b/core/skills/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/resume.md b/core/skills/resume/SKILL.md similarity index 75% rename from global/commands/resume.md rename to core/skills/resume/SKILL.md index 753e3f3..4699cd4 100644 --- a/global/commands/resume.md +++ b/core/skills/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/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/core/skills/review/SKILL.md b/core/skills/review/SKILL.md new file mode 100644 index 0000000..4b1fc46 --- /dev/null +++ b/core/skills/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 (`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. + +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/skills/start/SKILL.md similarity index 83% rename from global/commands/start.md rename to core/skills/start/SKILL.md index ecfc3e8..e6149f0 100644 --- a/global/commands/start.md +++ b/core/skills/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..7f5856e 100644 --- a/evals/offline/check.py +++ b/evals/offline/check.py @@ -1,17 +1,16 @@ #!/usr/bin/env python3 -"""Zero-token check of the installed harness against a real OpenCode binary. +"""Zero-token check of the dev-brain plugin against the real Claude Code binary. -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: +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. -- 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 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. -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 (CLAUDE= if claude is not on PATH) """ import json import os @@ -19,12 +18,20 @@ 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" +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 @@ -35,143 +42,119 @@ 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) + + +def system_text(body): + """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) + -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 tool_results(bodies): + """Tool outputs fed back to the model, once per tool_use 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", []): + 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": + 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 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 +class Sandbox: + """Throwaway home with the plugin installed, and a fixture repository with a pending change.""" + + 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() + # 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"] + 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.write_state(STATE) + + def write_state(self, text): + (self.repo / ".dev-brain" / "STATE.md").write_text(text) + + 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("claude sent a request to the mock model", False) + return bodies 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" - 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}, - "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 = [ - {"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"}, - ] - 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(" 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) 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..0508120 --- /dev/null +++ b/evals/offline/mock_model.py @@ -0,0 +1,93 @@ +"""Local Anthropic Messages endpoint that records requests and replays scripted replies. + +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 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": [], "has_more": False}) + + def do_POST(self): + body = json.loads(self.rfile.read(int(self.headers.get("content-length", 0))) or b"{}") + if self.path.split("?")[0].endswith("/count_tokens"): + return self._json({"input_tokens": 1}) + with mock.lock: + mock.requests.append(body) + step = mock.next_step(body) + self._reply(body, 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 _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" + message = {"id": "msg_mock", "type": "message", "role": "assistant", "model": body.get("model", "mock"), + "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}) + 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}), + ("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"}), + ] + 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): + 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): + return self.steps.pop(index) + return {"text": "ok"} + + def script(self, steps): + with self.lock: + self.steps, self.requests = list(steps), [] + + def agent_calls(self): + return [body for body in self.requests if body.get("tools")] diff --git a/evals/results.md b/evals/results.md index efd82c3..a8fca5e 100644 --- a/evals/results.md +++ b/evals/results.md @@ -1,203 +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. +- 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/global/commands/plan.md b/global/commands/plan.md deleted file mode 100644 index a75c082..0000000 --- a/global/commands/plan.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -description: Produce a plan-contract for a change (read-only, max 5 steps) -agent: plan ---- - -Plan this work: $ARGUMENTS - -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/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.sh b/install.sh deleted file mode 100755 index 5ba290b..0000000 --- a/install.sh +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env bash -# Install dev-brain into the global OpenCode configuration. -# Idempotent: existing files that are not ours are backed up, never deleted. - -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" 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.", - }) - }) - }, -}) diff --git a/templates/PROJECT_AGENTS.md b/templates/PROJECT_AGENTS.md deleted file mode 100644 index a86d192..0000000 --- a/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/templates/STATE.md b/templates/STATE.md deleted file mode 100644 index bcd42e1..0000000 --- a/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.