Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 23 additions & 9 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -54,21 +54,31 @@ TELEGRAM_CHAT_ID=your_telegram_chat_id

# ── Agent Toggles (true/false) ───────────────────────────────────────────

# Names consumed by src/config/settings.py (from_env).
PM_AGENT_ENABLED=true
UI_AGENT_ENABLED=true
DEV_AGENT_ENABLED=true
# One toggle per agent (ts/src/agents/catalog.ts), read by `run-agent all`.
SECRET_GUARD_ENABLED=true
PR_ASSISTANT_ENABLED=true
FLOW_WATCH_ENABLED=true
DEPENDENCY_MANAGER_ENABLED=true
REPO_STANDARDS_ENABLED=true
BRANCH_CLEANER_ENABLED=true
BUILDER_ENABLED=true
PROJECT_CREATOR_ENABLED=true
# Stage toggles (former agents, now steps of the agents above); false skips that step in a full run.
SECURITY_SCANNER_ENABLED=true
SECRET_REMOVER_ENABLED=true
CI_HEALTH_ENABLED=true
PR_SLA_ENABLED=true
SECRET_REMOVER_ENABLED=true
PROJECT_CREATOR_ENABLED=true
BRANCH_CLEANER_ENABLED=true
INTELLIGENCE_AGENT_ENABLED=true
README_CURATOR_ENABLED=true
CODE_REVIEWER_ENABLED=true
DEPENDENCY_MANAGER_ENABLED=true
PM_AGENT_ENABLED=true
DEV_AGENT_ENABLED=true
UI_AGENT_ENABLED=true
# Telegram user ids (comma-separated) allowed to approve a secret-guard history rewrite.
# Empty: only a button press in the private chat TELEGRAM_CHAT_ID counts.
TELEGRAM_APPROVER_IDS=

# repo-standards: max standardization PRs (AGENTS.md, .agents/) opened per run; repos missing AGENTS.md go first.
REPO_STANDARDS_MAX_PRS=5

# Minimum README rubric score (0-100); below it the curator opens an improvement PR.
README_MIN_SCORE=80
Expand Down Expand Up @@ -225,6 +235,10 @@ DEBUG=false
# OLLAMA_MODEL=
# OPENCODE_MODEL=
# OPENCODE_REVIEW_MODEL=
# Refresh the global AGENTS.md + skills from juninmd/skills before opencode runs (replaces ~/.config/opencode/skills).
# The Docker image sets it to true; keep it off on a dev machine.
# AGENT_CONTRACT_REFRESH=false
# AGENT_CONTRACT_TTL_MINUTES=60
# TOKENIX_ENABLED=true
# TOKENIX_BIN=
# TOKENIX_HOME=
Expand Down
93 changes: 46 additions & 47 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Esta regra é **não negociável** e se aplica a:
- Issues criadas por qualquer agente
- Comentários automáticos em PRs/issues

**Agentes que criam PRs:** `senior_developer`, `ci_health`, `intelligence_standardizer`, `interface_developer`, `conflict_resolver`, `project_creator`, `readme_curator`, `dependency_manager`
**Agentes que criam PRs:** `builder` (sempre draft + `keep-draft`), `repo-standards`, `dependency-manager`, `secret-guard` (allowlist de falsos positivos), `project-creator`; o `pr-assistant` só faz commits nos PRs existentes

---

Expand Down Expand Up @@ -52,50 +52,48 @@ variáveis: [README.md](README.md). Fila durável, política de merge e operaç
| `ts/src/config/`, `ts/src/insight/`, `ts/src/notifications/` | Settings e políticas, explicação de PRs, Telegram |
| `ts/scripts/` | `benchmark.ts`, `seed-demo-queue.ts`, checagens de política e dry-runs |

## 👤 Agentes (17 registrados)

Prioridade: **Critical** (segurança) › **High** (bloqueios de PR/CI) › **Medium** › **Low**.
Toggle de cada agente: variável `*_ENABLED` (ver `.env.example`).

### Segurança (Critical)

| Agente | Papel | Notas |
|---|---|---|
| `security-scanner` 🔒 | Gitleaks em todos os repositórios do owner (ignora allowlist, somente leitura); atribui achados ao autor do commit; aplica a política **no-cron-workflow** (`workflow_policy.ts`) | Diário 06:00 UTC |
| `secret-remover` 🛡️ | Classifica achados com IA, reescreve o histórico git para remover segredos reais, atualiza allowlist de falsos positivos | Depende de `security-scanner` |

### Pull requests e CI (High)

| Agente | Papel | Notas |
|---|---|---|
| `pr-assistant` 🤖 | Aplica sugestões de revisão (Gemini Code Assist), atualiza o branch contra a base, corrige CI/conflitos (opt-in), faz **squash merge** via `MergePolicy` | A cada 15 min; trabalha em **todos** os repos do owner |
| `conflict-resolver` ⚔️ | Encontra PRs com conflito e resolve com IA de forma segura | Sempre habilitado |
| `code-reviewer` 👀 | Revisão de PRs: qualidade, bugs, segurança, performance | |
| `ci-health` ⚕️ | Monitora pipelines, detecta falhas/flaky e dispara remediação | |
| `pr-sla` ⏱️ | Idade/tempo de revisão de PRs, alerta de PRs paradas | Low |

### Desenvolvimento e documentação (Medium/Low)

| Agente | Papel | Notas |
|---|---|---|
| `senior-developer` 🏗️ | Análise de segurança, CI/CD, dívida técnica, modernização e roadmap; faz `git pull` da branch principal antes de implementar | Semanal; burst no fim do dia |
| `dependency-manager` 📦 | Detecta ecossistemas (node/python/go/rust/php); CVEs primeiro, depois patch/minor (nunca major inseguro); atualiza lockfile, roda testes, abre **um** PR agrupado via opencode | |
| `readme-curator` 📚 | Varre todos os repos do owner (sem allowlist; ignora arquivados e forks), do README mais antigo para o mais novo; reescreve os ausentes, com mais de 6 meses (`README_MAX_AGE_DAYS`, 180) ou abaixo de `README_MIN_SCORE` (80); sempre em inglês | |
| `intelligence-standardizer` 🧬 | Garante `AGENTS.md` + `.agents/` nos 10 repos mais recentes, boas práticas (KISS, YAGNI, DRY, SRP) e limite de linhas | Diário |
| `product-manager` 📋 | Backlog, roadmap e documentação de produto | Low |
| `interface-developer` 🎨 | UI/UX, acessibilidade e responsividade via tarefas opencode | Low |
| `project-creator` 🚀 | Gera ideia ancorada no portfólio real do dono (repos feitos à mão = padrão; autogerados = anti-exemplo; critério `fit` ≥ 4), cria repositório privado e inicia a implementação com opencode | Low; semanal domingo 00:00 UTC |

### Higiene

| Agente | Papel | Notas |
|---|---|---|
| `branch-cleaner` 🧹 | Remove branches já mergeadas (nunca a principal, nunca branches com PR aberto) | |

## 👤 Agentes (8, um escopo cada)

Prioridade: **Critical** (segurança) › **High** (PR/CI) › **Medium** › **Low**. Toggle de cada agente: `*_ENABLED`
(ver `.env.example`). Agentes compostos rodam os antigos agentes como **etapas** (`stages` no catálogo,
`ts/src/agents/core/composite.ts`); o toggle antigo (ex.: `PR_SLA_ENABLED=false`) pula só aquela etapa.

| Agente | Escopo | Etapas | Autonomia |
|---|---|---|---|
| `secret-guard` 🔒 | Gitleaks em todo o portfólio (somente leitura) + política no-cron; classifica achados com IA; falso positivo vira PR de allowlist; segredo real só sai do histórico **com aprovação do dono** | `scan` (security_scanner), `remove` (secret_remover) | suggest |
| `pr-assistant` 🤖 | Dono de todo PR: gate AGENTS.md, revisão só do diff, SAST, conflitos inline, checks (locais em repo sem Actions) e squash merge via `MergePolicy` | — | merge |
| `flow-watch` ⚕️ | Reporta pipelines com falha e PRs paradas no Telegram; não abre PR, task nem comentário | `ci` (ci_health), `sla` (pr_sla) | observe |
| `dependency-manager` 📦 | CVEs primeiro, depois patch/minor, um PR agrupado e testado | — | fix |
| `repo-standards` 🧬 | `AGENTS.md` + `.agents/` em todos os repos ativos (sem AGENTS.md primeiro, `REPO_STANDARDS_MAX_PRS` por run, nunca dois PRs abertos) e README | `agents-md` (intelligence_standardizer), `readme` (readme_curator) | fix |
| `branch-cleaner` 🧹 | Remove branches mergeadas (nunca a principal nem com PR aberto) | — | fix |
| `builder` 🏗️ | Roadmap, código e UI via opencode; PR sempre **draft + `keep-draft`**, o bot revisa mas nunca marca pronto nem mergeia (nem com `/merge`) | `plan` (product_manager), `code` (senior_developer), `ui` (interface_developer) | fix, sem merge |
| `project-creator` 🚀 | Cria um projeto novo ancorado no portfólio (opt-in, semanal) | — | suggest |

**Nomes antigos** continuam aceitos pelo CLI e rodam só a etapa correspondente (`AGENT_ALIASES` em `catalog.ts`):
`security-scanner`, `secret-remover`, `ci-health`, `pr-sla`, `intelligence-standardizer`, `readme-curator`,
`product-manager`, `senior-developer`, `interface-developer`. `code-reviewer` e `conflict-resolver` viraram parte do
`pr-assistant`: esses nomes agora terminam sem fazer nada (aviso no log), para um CronJob antigo não rodar uma segunda passada nos PRs.

### Aprovação de reescrita de histórico (secret-guard)

Reescrever histórico é irreversível. Para cada conjunto de achados o `secret-guard` abre uma issue `secret-guard`
no repositório (só quantidade e regras; arquivos e linhas vão só no Telegram privado) e manda um botão **Aprovar** no Telegram.
Aprovar apaga o arquivo inteiro de todo o histórico (`git-filter-repo --invert-paths`) e faz force-push de branches e tags.
Se a issue não puder ser criada (issues desligadas), o botão é reenviado a cada execução.
Aprova: o dono comentando `/aprovar` na issue, ou o botão no chat privado `TELEGRAM_CHAT_ID`
(ou um id em `TELEGRAM_APPROVER_IDS`). Achados novos geram uma nova aprovação. Sem aprovação, nada é reescrito.

### Contrato comum (todo run com opencode)

- Global `AGENTS.md` + skills de [juninmd/skills](https://github.com/juninmd/skills), sempre o commit mais novo:
`core/agent-contract.ts` busca de novo no máximo a cada hora (`AGENT_CONTRACT_REFRESH`, ligado na imagem) e,
se falhar, mantém a cópia da imagem. O commit aparece no corpo dos PRs e no rodapé da revisão.
- tokenix como índice de código (MCP), versão mais nova na build da imagem com checksum.
- Modelos free do opencode; em erro, fallback `litellm/cloud/auto`.
- Identidade única: GitHub App `juninmd-bot`.

### Ideias ainda não implementadas
Performance Optimizer ⚡ (gargalos, bundle size), Documentation Curator 📚
(docs de API, cobertura de docs), Test Coverage Guardian 🧪 (caminhos sem teste).
Performance Optimizer ⚡ (gargalos, bundle size), Test Coverage Guardian 🧪 (caminhos sem teste).

## 📜 Development Rules (Antigravity Protocol)

Expand All @@ -112,7 +110,7 @@ Performance Optimizer ⚡ (gargalos, bundle size), Documentation Curator 📚

- **Ciclo**: Plan → Act (ou delegar ao opencode) → Validate → Communicate.
- **Canais**: resultados em `results/*.json`; Telegram como hub de notificações; PRs/issues/comentários no GitHub; opencode para trabalho de código complexo.
- **Coordenação**: agentes não se chamam diretamente. Dependências declaradas em `ts/src/agents/core/orchestration.ts` (hoje: `secret-remover` → `security-scanner`). `validate()` rejeita dependências ausentes e ciclos; um dependente só roda se a dependência realmente teve sucesso.
- **Coordenação**: agentes não se chamam diretamente. Dependências entre agentes ficam em `ts/src/agents/orchestration.ts` (hoje nenhuma); dentro de um agente composto as etapas rodam em ordem e uma etapa pode depender da anterior (ex.: `remove` só roda se `scan` teve sucesso).
- **Exclusividade**: a fila durável garante um job por `(kind, key)`; labels de PR e deduplicação de tarefas evitam trabalho sobreposto.
- **Resultado tipado**: todo run gera `RunResult` (`ts/src/results.ts`); `run-agent all` sai com erro se algum agente falhar. PRs bloqueadas por CI pendente/observe não contam como falha.

Expand All @@ -135,7 +133,7 @@ GitHub API 5.000 req/h (monitorado pelo `BaseAgent`); burst opcional de tarefas

## 🧾 Merge Gate e falhas de billing do CI

**AGENTS.md obrigatório:** repositório sem `AGENTS.md` na raiz nunca tem PR mesclado pelo bot (`agents_md_missing`; erro de API = `agents_md_check_failed`, falha fechada), mesmo sem código relacionado, dependabot ou `/merge` do owner. Implementado em `pr_assistant/agents-md-gate.ts`; o `intelligence-standardizer` abre o PR que cria o arquivo.
**AGENTS.md obrigatório:** repositório sem `AGENTS.md` na raiz nunca tem PR mesclado pelo bot (`agents_md_missing`; erro de API = `agents_md_check_failed`, falha fechada), mesmo sem código relacionado, dependabot ou `/merge` do owner. Implementado em `pr_assistant/agents-md-gate.ts`; o `repo-standards` abre o PR que cria o arquivo.

Quando o GitHub Actions se recusa a iniciar um job por billing ("recent account
payments have failed", "spending limit needs to be increased"), o job **nunca
Expand All @@ -156,9 +154,10 @@ bloqueia o merge**:
## 🛠️ Agent Development Guidelines

### Criar um novo agente
1. Criar `ts/src/agents/<nome>/` com `agent.ts` (herda de `BaseAgent`; implementa `persona`, `mission`, `run()`) e `instructions.md` (`## Persona`, `## Mission`).
0. Antes de criar um agente, veja se o trabalho cabe como etapa de um agente existente (escopo único por agente).
1. Criar `ts/src/agents/<nome>/` com `agent.ts` (herda de `BaseAgent`, ou de `CompositeAgent` para etapas; implementa `persona`, `mission`, `run()`) e `instructions.md` curto (`## Persona`, `## Mission`), sem regras genéricas: as skills e o AGENTS.md global já valem.
2. Adicionar **um** `AgentSpec` em `ts/src/agents/catalog.ts` (prioridade, toggle, IA/Telegram, dependências). Registry, batch runner, orquestrador, health checks, entry points e dashboard derivam dele.
3. Se tiver toggle: campo `enable_<nome>` em `Settings` e a variável em `.env.example`; entry point em `pyproject.toml` (`<nome> = "src.scripts:<nome_com_underscore>"`).
3. Se tiver toggle: a variável em `.env.example` (`Settings.enabled` deriva do catálogo).
4. Escrever testes e atualizar este arquivo e o README. `ts/tests/` (catálogo) falha se algum passo faltar.

### Boas práticas
Expand Down
2 changes: 2 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ RUN git clone --depth 1 https://github.com/juninmd/skills /tmp/skills \
&& chown -R appuser:appuser /home/appuser/.config

USER appuser
# Re-fetch juninmd/skills (global AGENTS.md + skills) at runtime, at most hourly; the copy baked above is the fallback.
ENV AGENT_CONTRACT_REFRESH=true
# cwd stays /app so relative defaults (config/*.json, data/) resolve like in the Python image

ENV OLLAMA_HOST="http://ollama.ai.svc.cluster.local:11434"
Expand Down
49 changes: 28 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,30 @@ The durable queue, merge policy and operations are in

## Agents

17 agents are declared in one table, `ts/src/agents/catalog.ts`, and run through one CLI:

| Agent | What it does |
|---|---|
| `pr-assistant` | Reviews PRs, resolves comments, fixes CI, updates branches and squash-merges when the safe-merge policy allows |
| `conflict-resolver` | Finds PRs with merge conflicts and resolves them with AI |
| `code-reviewer` | AI review of PRs for quality, bugs and security; non-blocking tips on outdated stack/libs and README drift (`REVIEW_ADVISORIES=false` to disable) |
| `ci-health` | Monitors pipelines, detects failures and triggers remediation |
| `pr-sla` | Tracks PR age and review time, flags stale PRs |
| `security-scanner` | Gitleaks secret scanning plus the no-cron-workflow policy |
| `secret-remover` | Classifies findings and purges real secrets from git history |
| `dependency-manager` | Opens one grouped, tested PR with security and patch/minor updates |
| `readme-curator` | Rewrites missing, old (>6 months) or low-scoring READMEs |
| `intelligence-standardizer` | Enforces `AGENTS.md` / `.agents/` across repositories |
| `senior-developer` | Repository analysis and improvement tasks |
| `product-manager` | Roadmaps and feature planning |
| `interface-developer` | UI/UX and accessibility tasks |
| `project-creator` | Scaffolds new projects from generated ideas |
| `branch-cleaner` | Deletes branches already merged into the default branch |
8 agents, each with one scope, are declared in one table, `ts/src/agents/catalog.ts`, and run through one CLI.
Some of them run former agents as internal **stages**.

| Agent | Scope | Stages | Autonomy |
|---|---|---|---|
| `secret-guard` | Gitleaks on the whole portfolio + no-cron policy; removes a real secret from git history **only after the owner approves** (Telegram button or `/aprovar` on the approval issue) | `scan`, `remove` | suggest |
| `pr-assistant` | Owns every PR: AGENTS.md gate, diff-only review, SAST, inline conflicts, checks and squash merge via the safe-merge policy | | merge |
| `flow-watch` | Reports failing pipelines and stale PRs on Telegram; opens nothing | `ci`, `sla` | observe |
| `dependency-manager` | CVEs first, then safe patch/minor updates, in one grouped, tested PR | | fix |
| `repo-standards` | `AGENTS.md` / `.agents/` in every active repo (missing AGENTS.md first, capped per run, one open PR per repo) and README upkeep | `agents-md`, `readme` | fix |
| `branch-cleaner` | Deletes branches already merged into the default branch | | fix |
| `builder` | Roadmap, code and UI improvements via opencode. PRs are **draft + `keep-draft`**: reviewed by the bot, never marked ready or merged by it | `plan`, `code`, `ui` | fix, no merge |
| `project-creator` | Scaffolds a new project from a portfolio-grounded idea (opt-in) | | suggest |

Former names still work and run only their stage, so existing CronJobs keep their behavior:
`security-scanner`, `secret-remover`, `ci-health`, `pr-sla`, `intelligence-standardizer`, `readme-curator`,
`product-manager`, `senior-developer`, `interface-developer`. `code-reviewer` and `conflict-resolver` are retired
(their work runs inside `pr-assistant`): those names now exit as a no-op with a warning, so a leftover CronJob
never starts a second PR pass.

Every opencode run uses the owner's contract: global `AGENTS.md` + skills from
[juninmd/skills](https://github.com/juninmd/skills) (refreshed at runtime, at most hourly, with the image copy as
fallback; the commit goes into PR bodies and review footers), the tokenix code index, free opencode models with
`litellm/cloud/auto` as fallback, and the `juninmd-bot` GitHub App identity.

## Quick start

Expand All @@ -47,7 +52,7 @@ cp ../.env.example ../.env # fill in GITHUB_TOKEN, AI keys...

bun src/cli/run-agent.ts pr-assistant # run one agent
bun src/cli/run-agent.ts pr-assistant --pr owner/repo#42 # target a single PR
bun src/cli/run-agent.ts readme-curator --ai-provider gemini --ai-model gemini-2.5-flash
bun src/cli/run-agent.ts repo-standards --ai-provider gemini --ai-model gemini-2.5-flash
bun src/cli/run-agent.ts all # all enabled agents, in dependency order
```

Expand Down Expand Up @@ -81,7 +86,9 @@ Everything is read from environment variables (see `.env.example` and
| `GITHUB_TOKEN` / `GH_PAT` | GitHub access (a GitHub App is also supported) |
| `GITHUB_OWNER` | Account whose repositories are managed |
| `ENABLE_AI`, `AI_PROVIDER`, `AI_MODEL` | AI on/off and model (`gemini`, `openai`, `ollama`, `litellm`) |
| `*_ENABLED` (e.g. `PR_ASSISTANT_ENABLED`) | Per-agent toggles used by `run-agent all` |
| `*_ENABLED` (e.g. `PR_ASSISTANT_ENABLED`) | Per-agent toggles used by `run-agent all`; former agent toggles (e.g. `PR_SLA_ENABLED`) skip that stage |
| `TELEGRAM_APPROVER_IDS` | Telegram user ids allowed to approve a secret-guard history rewrite (default: the private chat only) |
| `AGENT_CONTRACT_REFRESH`, `REPO_STANDARDS_MAX_PRS` | Runtime refresh of skills + global AGENTS.md (on in the image); standardization PRs per run |
| `TELEGRAM_BOT_TOKEN`, `TELEGRAM_CHAT_ID` | Notifications |
| `CONFLICT_OPENCODE_ENABLED`, `PIPELINE_FIX_ENABLED` | Opt-in opencode conflict / CI fixing |
| `REVIEW_WAIVE_AFTER_MINUTES`, `REVIEW_WAIVE_MAX_LINES`, `REVIEW_WAIVE_MAX_PER_RUN` | When a model outage may let a PR merge without model review |
Expand Down
Loading
Loading