From ae143617dcb392928926400de9d2f54d084c3730 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 13:53:30 +0000 Subject: [PATCH 1/2] refactor(agents): redesign the fleet into 8 scoped agents Fifteen agents overlapped (three touched every PR) and carried long generic prompts. Each agent now has one scope and one autonomy level: - pr-assistant absorbs code-reviewer (redundant) and conflict-resolver (already inline); builder PRs labelled keep-draft are reviewed but never marked ready nor merged. - flow-watch (ci-health + pr-sla) only reports. - secret-guard (scan + remove) rewrites history only after the owner approves via a Telegram button or an owner /aprovar on the approval issue. - repo-standards covers every active repo, missing AGENTS.md first, capped per run, never a second open PR. - builder (product-manager + senior-developer + interface-developer) opens draft PRs only. Former names stay valid and run only their stage, so CronJobs keep working. opencode runs refresh the global AGENTS.md + skills from juninmd/skills at most hourly (image copy as fallback) and record the commit in PRs/reviews. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Cn6JQLt2WHRBiK4sRPxupu --- .env.example | 32 +- AGENTS.md | 76 ++- Dockerfile | 2 + README.md | 48 +- ts/src/agents/base-agent.ts | 10 +- ts/src/agents/builder/agent.ts | 9 + ts/src/agents/builder/instructions.md | 13 + ts/src/agents/catalog.ts | 64 ++- ts/src/agents/ci_health/agent.ts | 6 +- ts/src/agents/code_reviewer/agent.ts | 98 ---- ts/src/agents/code_reviewer/instructions.md | 95 ---- ts/src/agents/conflict_resolver/agent.ts | 117 ----- .../agents/conflict_resolver/instructions.md | 35 -- .../agents/conflict_resolver/notifications.ts | 22 - ts/src/agents/core/agent-contract.ts | 75 +++ ts/src/agents/core/composite.ts | 64 +++ ts/src/agents/core/pr-options.ts | 23 + ts/src/agents/core/utils.ts | 4 +- ts/src/agents/flow_watch/agent.ts | 9 + ts/src/agents/flow_watch/instructions.md | 10 + .../agents/intelligence_standardizer/agent.ts | 47 +- .../intelligence_standardizer/instructions.md | 2 +- .../task-instructions.md | 29 +- .../interface_developer/instructions.md | 257 +--------- ts/src/agents/opencode/local.ts | 7 +- ts/src/agents/opencode/runner.ts | 11 +- ts/src/agents/pr_assistant/agent.ts | 6 + ts/src/agents/pr_assistant/agents-md-gate.ts | 2 +- ts/src/agents/pr_assistant/conflict-flow.ts | 2 +- .../pr_assistant/conflict-notifications.ts | 9 + ts/src/agents/pr_assistant/review-gate.ts | 4 +- .../agents/pr_assistant/review-workspace.ts | 5 +- ts/src/agents/pr_sla/agent.ts | 6 +- ts/src/agents/product_manager/instructions.md | 144 +----- ts/src/agents/registry.ts | 27 +- ts/src/agents/repo_standards/agent.ts | 7 + ts/src/agents/repo_standards/instructions.md | 12 + ts/src/agents/secret_guard/agent.ts | 24 + ts/src/agents/secret_guard/instructions.md | 12 + ts/src/agents/secret_remover/agent.ts | 13 +- ts/src/agents/secret_remover/approval.ts | 111 +++++ ts/src/agents/secret_remover/processor.ts | 55 ++- .../agents/secret_remover/telegram-summary.ts | 8 +- .../agents/senior_developer/instructions.md | 462 +----------------- ts/src/cli/run-agent.ts | 6 +- ts/src/health.ts | 7 +- ts/tests/config.test.ts | 14 +- ts/tests/conflict-resolver.test.ts | 36 -- ts/tests/core.test.ts | 36 +- ts/tests/fleet-redesign.test.ts | 163 ++++++ ts/tests/lote4.test.ts | 30 -- ts/tests/secret-guard-approval.test.ts | 119 +++++ ts/tests/webhooks.test.ts | 2 +- 53 files changed, 1015 insertions(+), 1472 deletions(-) create mode 100644 ts/src/agents/builder/agent.ts create mode 100644 ts/src/agents/builder/instructions.md delete mode 100644 ts/src/agents/code_reviewer/agent.ts delete mode 100644 ts/src/agents/code_reviewer/instructions.md delete mode 100644 ts/src/agents/conflict_resolver/agent.ts delete mode 100644 ts/src/agents/conflict_resolver/instructions.md delete mode 100644 ts/src/agents/conflict_resolver/notifications.ts create mode 100644 ts/src/agents/core/agent-contract.ts create mode 100644 ts/src/agents/core/composite.ts create mode 100644 ts/src/agents/core/pr-options.ts create mode 100644 ts/src/agents/flow_watch/agent.ts create mode 100644 ts/src/agents/flow_watch/instructions.md create mode 100644 ts/src/agents/pr_assistant/conflict-notifications.ts create mode 100644 ts/src/agents/repo_standards/agent.ts create mode 100644 ts/src/agents/repo_standards/instructions.md create mode 100644 ts/src/agents/secret_guard/agent.ts create mode 100644 ts/src/agents/secret_guard/instructions.md create mode 100644 ts/src/agents/secret_remover/approval.ts delete mode 100644 ts/tests/conflict-resolver.test.ts create mode 100644 ts/tests/fleet-redesign.test.ts create mode 100644 ts/tests/secret-guard-approval.test.ts diff --git a/.env.example b/.env.example index 0c9d9bf1..6dd4fdfd 100644 --- a/.env.example +++ b/.env.example @@ -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 @@ -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= diff --git a/AGENTS.md b/AGENTS.md index ced84a50..8a2d12b0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 --- @@ -52,50 +52,45 @@ 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) +## 👤 Agentes (8, um escopo cada) -Prioridade: **Critical** (segurança) › **High** (bloqueios de PR/CI) › **Medium** › **Low**. -Toggle de cada agente: variável `*_ENABLED` (ver `.env.example`). +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. -### Segurança (Critical) +| 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 | -| 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` | +**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`. -### Pull requests e CI (High) +### Aprovação de reescrita de histórico (secret-guard) -| 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 | +Reescrever histórico é irreversível. Para cada conjunto de achados o `secret-guard` abre uma issue `secret-guard` +no repositório (só arquivo, linha, regra e commit, nunca o segredo) e manda um botão **Aprovar** no Telegram. +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. -### 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) | | +### 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) @@ -112,7 +107,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. @@ -135,7 +130,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 @@ -156,9 +151,10 @@ bloqueia o merge**: ## 🛠️ Agent Development Guidelines ### Criar um novo agente -1. Criar `ts/src/agents//` 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//` 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_` em `Settings` e a variável em `.env.example`; entry point em `pyproject.toml` (` = "src.scripts:"`). +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 diff --git a/Dockerfile b/Dockerfile index 4bf5d616..d876a669 100644 --- a/Dockerfile +++ b/Dockerfile @@ -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" diff --git a/README.md b/README.md index 02aaa499..578287c6 100644 --- a/README.md +++ b/README.md @@ -17,25 +17,29 @@ 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`, and `code-reviewer` / `conflict-resolver` +(both now part of `pr-assistant`). + +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 @@ -47,7 +51,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 ``` @@ -81,7 +85,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 | diff --git a/ts/src/agents/base-agent.ts b/ts/src/agents/base-agent.ts index 1bbbd256..b45d9732 100644 --- a/ts/src/agents/base-agent.ts +++ b/ts/src/agents/base-agent.ts @@ -8,17 +8,18 @@ import * as utils from "./core/utils.ts"; import { runOpencodeTask } from "./opencode/local.ts"; import { OpencodeRunner } from "./opencode/runner.ts"; import type { AI } from "./registry.ts"; +import { DEFAULT_PR_OPTIONS, type PrOptions } from "./core/pr-options.ts"; export type BaseDeps = { githubClient: GithubClient; allowlist: RepositoryAllowlist; telegram?: TelegramNotifier; - targetOwner?: string; enforceRepositoryAllowlist?: boolean; ai?: AI; + targetOwner?: string; enforceRepositoryAllowlist?: boolean; ai?: AI; prOptions?: PrOptions; }; export abstract class BaseAgent { abstract readonly persona: string; abstract readonly mission: string; githubClient: GithubClient; allowlist: RepositoryAllowlist; telegram: TelegramNotifier; - targetOwner: string; enforceRepositoryAllowlist: boolean; + targetOwner: string; enforceRepositoryAllowlist: boolean; prOptions: PrOptions; protected logger: StructuredLogger; protected repoMgr: RepositoryManager; protected opencode: OpencodeRunner; private instructionsCache: string | null = null; @@ -26,6 +27,7 @@ export abstract class BaseAgent { this.githubClient = d.githubClient; this.allowlist = d.allowlist; this.telegram = d.telegram ?? new TelegramNotifier(); this.targetOwner = d.targetOwner ?? "juninmd"; this.enforceRepositoryAllowlist = d.enforceRepositoryAllowlist ?? false; + this.prOptions = d.prOptions ?? DEFAULT_PR_OPTIONS; this.logger = getLogger(name); this.repoMgr = new RepositoryManager(this.githubClient, this.allowlist, this.targetOwner, this.log); this.opencode = new OpencodeRunner(this.allowlist, this.log, this.githubClient, this.telegram, this.targetOwner); @@ -43,12 +45,12 @@ export abstract class BaseAgent { getRepositoryInfo(r: string) { return this.repoMgr.getInfo(r); } checkRateLimit() { return utils.checkGithubRateLimit(this.githubClient, this.log); } - runOpencodeOnRepo(repository: string, instructions: string, title: string) { return this.opencode.runOnRepo(repository, instructions, title, this.name); } + runOpencodeOnRepo(repository: string, instructions: string, title: string) { return this.opencode.runOnRepo(repository, instructions, title, this.name, this.prOptions); } async createOpencodeTask(repository: string, instructions: string, title: string, baseBranch?: string | null): Promise> { if (!this.canWorkOnRepository(repository)) throw new Error(`opencode denied: Repository ${repository} is not in allowlist`); let base = baseBranch; if (!base) { base = (await this.getRepositoryInfo(repository))?.default_branch; if (!base) throw new Error(`Could not determine default branch for ${repository}`); } - return runOpencodeTask({ githubClient: this.githubClient, repository, instructions, title, baseBranch: String(base), log: this.log, agentName: this.name }); + return runOpencodeTask({ githubClient: this.githubClient, repository, instructions, title, baseBranch: String(base), log: this.log, agentName: this.name, prOptions: this.prOptions }); } async openPullRequest(repository: string, branch: string, title: string, output: string, model = "opencode"): Promise { const repo = await this.githubClient.getRepo(repository); diff --git a/ts/src/agents/builder/agent.ts b/ts/src/agents/builder/agent.ts new file mode 100644 index 00000000..50fa4cfb --- /dev/null +++ b/ts/src/agents/builder/agent.ts @@ -0,0 +1,9 @@ +/** Builder - plans (roadmap/issues) and implements improvements; every PR stays draft and is never merged by the bot. */ +import type { AgentOpts } from "../agent-types.ts"; +import { CompositeAgent } from "../core/composite.ts"; +import { KEEP_DRAFT_LABEL } from "../core/pr-options.ts"; + +export class BuilderAgent extends CompositeAgent { + constructor(o: AgentOpts) { super("builder", o); } + protected stageOptions() { return { prOptions: { draft: true, labels: [KEEP_DRAFT_LABEL] } }; } +} diff --git a/ts/src/agents/builder/instructions.md b/ts/src/agents/builder/instructions.md new file mode 100644 index 00000000..d9a0cbcf --- /dev/null +++ b/ts/src/agents/builder/instructions.md @@ -0,0 +1,13 @@ +# Builder + +## Persona + +Senior engineer that follows the owner's skills and global AGENTS.md instead of a private persona. + +## Mission + +1. `plan`: keep the product roadmap of each allowed repository current. +2. `code`: security, CI/CD, tech debt, modernization, performance and roadmap features via opencode. +3. `ui`: UI/UX and accessibility work on front-end repositories. +Every PR is opened as **draft** with the `keep-draft` label. The bot reviews it but never marks it +ready and never merges it: the owner decides. diff --git a/ts/src/agents/catalog.ts b/ts/src/agents/catalog.ts index 2f11fd62..aa5ef2c2 100644 --- a/ts/src/agents/catalog.ts +++ b/ts/src/agents/catalog.ts @@ -1,10 +1,13 @@ /** Agent catalog: single source of truth for every agent in the fleet (pure data). */ export enum AgentPriority { CRITICAL = 1, HIGH = 2, MEDIUM = 3, LOW = 4 } +/** A step of a composite agent: one of the former agents, kept as an internal, independently testable unit. */ +export type StageSpec = { name: string; dir: string; className: string; toggleEnv?: string; requiresAi?: boolean }; + export type AgentSpec = { name: string; className: string; emoji: string; summary: string; priority: AgentPriority; toggleEnv?: string; requiresAi: boolean; notifiesTelegram: boolean; - acceptsPrRef: boolean; dependsOn: string[]; inBatch: boolean; + acceptsPrRef: boolean; dependsOn: string[]; inBatch: boolean; stages: StageSpec[]; }; const C = AgentPriority.CRITICAL, H = AgentPriority.HIGH, M = AgentPriority.MEDIUM, L = AgentPriority.LOW; @@ -13,29 +16,60 @@ const spec = ( o: Partial> = {}, ): AgentSpec => ({ name, className, emoji, summary, priority, requiresAi: false, - notifiesTelegram: false, acceptsPrRef: false, dependsOn: [], inBatch: true, ...o, + notifiesTelegram: false, acceptsPrRef: false, dependsOn: [], inBatch: true, stages: [], ...o, }); +const stage = (name: string, dir: string, className: string, o: Partial = {}): StageSpec => ({ name, dir, className, ...o }); export const AGENT_CATALOG: AgentSpec[] = [ - spec("security-scanner", "SecurityScannerAgent", "🔒", "Gitleaks em todos os repositórios do owner; aplica a política no-cron-workflow", C, { toggleEnv: "SECURITY_SCANNER_ENABLED", notifiesTelegram: true }), - spec("secret-remover", "SecretRemoverAgent", "🛡️", "Classifica achados com IA e reescreve o histórico git para remover segredos reais", C, { toggleEnv: "SECRET_REMOVER_ENABLED", requiresAi: true, notifiesTelegram: true, dependsOn: ["security-scanner"] }), - spec("pr-assistant", "PRAssistantAgent", "🤖", "Aplica sugestões de revisão, corrige CI/conflitos e faz squash merge via MergePolicy", H, { toggleEnv: "PR_ASSISTANT_ENABLED", notifiesTelegram: true, acceptsPrRef: true }), - spec("conflict-resolver", "ConflictResolverAgent", "⚔️", "Encontra PRs com conflito e resolve com IA de forma segura", H, { notifiesTelegram: true, acceptsPrRef: true }), - spec("code-reviewer", "CodeReviewerAgent", "👀", "Revisa PRs: qualidade, bugs, segurança e performance", H, { toggleEnv: "CODE_REVIEWER_ENABLED", requiresAi: true, notifiesTelegram: true, acceptsPrRef: true }), - spec("ci-health", "CIHealthAgent", "⚕️", "Monitora pipelines, detecta falhas/flaky e dispara remediação", H, { toggleEnv: "CI_HEALTH_ENABLED", notifiesTelegram: true }), - spec("pr-sla", "PRSLAAgent", "⏱️", "Acompanha idade e tempo de revisão de PRs; alerta sobre PRs paradas", L, { toggleEnv: "PR_SLA_ENABLED" }), - spec("senior-developer", "SeniorDeveloperAgent", "🏗️", "Segurança, CI/CD, dívida técnica, modernização e entrega do roadmap", M, { toggleEnv: "DEV_AGENT_ENABLED", requiresAi: true, notifiesTelegram: true }), + spec("secret-guard", "SecretGuardAgent", "🔒", "Gitleaks no portfólio e política no-cron; remove segredo do histórico só com aprovação do dono (Telegram ou /aprovar)", C, { + toggleEnv: "SECRET_GUARD_ENABLED", notifiesTelegram: true, + stages: [stage("scan", "security_scanner", "SecurityScannerAgent", { toggleEnv: "SECURITY_SCANNER_ENABLED" }), + stage("remove", "secret_remover", "SecretRemoverAgent", { toggleEnv: "SECRET_REMOVER_ENABLED", requiresAi: true })], + }), + spec("pr-assistant", "PRAssistantAgent", "🤖", "Dono de todo PR: gate AGENTS.md, revisão do diff, SAST, conflitos, checks e squash merge via MergePolicy", H, { toggleEnv: "PR_ASSISTANT_ENABLED", notifiesTelegram: true, acceptsPrRef: true }), + spec("flow-watch", "FlowWatchAgent", "⚕️", "Observa pipelines com falha e PRs paradas; só reporta no Telegram", H, { + toggleEnv: "FLOW_WATCH_ENABLED", notifiesTelegram: true, + stages: [stage("ci", "ci_health", "CIHealthAgent", { toggleEnv: "CI_HEALTH_ENABLED" }), stage("sla", "pr_sla", "PRSLAAgent", { toggleEnv: "PR_SLA_ENABLED" })], + }), spec("dependency-manager", "DependencyManagerAgent", "📦", "CVEs primeiro, depois patch/minor seguros, em um único PR agrupado", M, { toggleEnv: "DEPENDENCY_MANAGER_ENABLED", notifiesTelegram: true }), - spec("readme-curator", "ReadmeCuratorAgent", "📚", "Reescreve READMEs ausentes, antigos ou com nota baixa em todo o portfólio", M, { toggleEnv: "README_CURATOR_ENABLED", requiresAi: true, notifiesTelegram: true }), - spec("intelligence-standardizer", "IntelligenceStandardizerAgent", "🧬", "Garante AGENTS.md e .agents/ consistentes nos repositórios recentes", M, { toggleEnv: "INTELLIGENCE_AGENT_ENABLED", requiresAi: true, notifiesTelegram: true }), - spec("product-manager", "ProductManagerAgent", "📋", "Mantém backlog, roadmap e documentação de produto", L, { toggleEnv: "PM_AGENT_ENABLED", requiresAi: true }), - spec("interface-developer", "InterfaceDeveloperAgent", "🎨", "UI/UX, acessibilidade e responsividade via tarefas opencode", L, { toggleEnv: "UI_AGENT_ENABLED", requiresAi: true }), - spec("project-creator", "ProjectCreatorAgent", "🚀", "Gera ideia ancorada no portfólio, cria o repositório e inicia a implementação com opencode", L, { toggleEnv: "PROJECT_CREATOR_ENABLED", requiresAi: true }), + spec("repo-standards", "RepoStandardsAgent", "🧬", "AGENTS.md, .agents/ e README em todos os repositórios ativos", M, { + toggleEnv: "REPO_STANDARDS_ENABLED", requiresAi: true, notifiesTelegram: true, + stages: [stage("agents-md", "intelligence_standardizer", "IntelligenceStandardizerAgent", { toggleEnv: "INTELLIGENCE_AGENT_ENABLED" }), + stage("readme", "readme_curator", "ReadmeCuratorAgent", { toggleEnv: "README_CURATOR_ENABLED" })], + }), spec("branch-cleaner", "BranchCleanerAgent", "🧹", "Remove branches mergeadas (nunca a principal nem as que têm PR aberto)", M, { toggleEnv: "BRANCH_CLEANER_ENABLED", notifiesTelegram: true }), + spec("builder", "BuilderAgent", "🏗️", "Planeja e implementa melhorias em PRs draft; nunca faz merge", L, { + toggleEnv: "BUILDER_ENABLED", requiresAi: true, notifiesTelegram: true, + stages: [stage("plan", "product_manager", "ProductManagerAgent", { toggleEnv: "PM_AGENT_ENABLED" }), + stage("code", "senior_developer", "SeniorDeveloperAgent", { toggleEnv: "DEV_AGENT_ENABLED" }), + stage("ui", "interface_developer", "InterfaceDeveloperAgent", { toggleEnv: "UI_AGENT_ENABLED" })], + }), + spec("project-creator", "ProjectCreatorAgent", "🚀", "Gera ideia ancorada no portfólio, cria o repositório e inicia a implementação com opencode", L, { toggleEnv: "PROJECT_CREATOR_ENABLED", requiresAi: true }), ]; export const AGENTS_BY_NAME = new Map(AGENT_CATALOG.map((s) => [s.name, s])); +/** Former agent names: still accepted by the CLI so existing CronJobs keep running the same unit of work. */ +export const AGENT_ALIASES: Record = { + "security-scanner": { agent: "secret-guard", stage: "scan" }, + "secret-remover": { agent: "secret-guard", stage: "remove" }, + "code-reviewer": { agent: "pr-assistant" }, + "conflict-resolver": { agent: "pr-assistant" }, + "ci-health": { agent: "flow-watch", stage: "ci" }, + "pr-sla": { agent: "flow-watch", stage: "sla" }, + "intelligence-standardizer": { agent: "repo-standards", stage: "agents-md" }, + "readme-curator": { agent: "repo-standards", stage: "readme" }, + "product-manager": { agent: "builder", stage: "plan" }, + "senior-developer": { agent: "builder", stage: "code" }, + "interface-developer": { agent: "builder", stage: "ui" }, +}; + +/** Resolve a CLI name (current or former) to the agent that runs it, plus the single stage a former name maps to. */ +export function resolveAgentName(name: string): { agent: string; stage?: string } | null { + if (AGENTS_BY_NAME.has(name)) return { agent: name }; + return AGENT_ALIASES[name] ?? null; +} + export function agentNames(f: Partial> = {}): Set { return new Set( AGENT_CATALOG.filter((s) => Object.entries(f).every(([k, v]) => v === undefined || (s as any)[k] === v)).map((s) => s.name), diff --git a/ts/src/agents/ci_health/agent.ts b/ts/src/agents/ci_health/agent.ts index bafeaeae..6c098d37 100644 --- a/ts/src/agents/ci_health/agent.ts +++ b/ts/src/agents/ci_health/agent.ts @@ -17,7 +17,9 @@ export async function remediatePipeline(agent: BaseAgent, repo: any, failures: F } export class CIHealthAgent extends BaseAgent { - constructor(o: AgentOpts) { super("ci_health", { ...o, enforceRepositoryAllowlist: false }); } + /** False inside flow-watch: it only reports, fixes belong to the PR flow. */ + remediate: boolean; + constructor(o: AgentOpts) { super("ci_health", { ...o, enforceRepositoryAllowlist: false }); this.remediate = o.remediate ?? true; } get persona() { return this.getInstructionsSection("## Persona"); } get mission() { return this.getInstructionsSection("## Mission"); } @@ -45,7 +47,7 @@ export class CIHealthAgent extends BaseAgent { } const fixActions: Record[] = []; for (const [name, entry] of byRepo) { - if ((entry.repo.private ?? true) || !entry.failures.length) continue; + if (!this.remediate || (entry.repo.private ?? true) || !entry.failures.length) continue; try { const a = await remediatePipeline(this, entry.repo, entry.failures); if (a) fixActions.push(a); } catch (e: any) { this.log(`Failed remediation for ${name}: ${e?.message ?? e}`, "WARNING"); } } diff --git a/ts/src/agents/code_reviewer/agent.ts b/ts/src/agents/code_reviewer/agent.ts deleted file mode 100644 index fccc838e..00000000 --- a/ts/src/agents/code_reviewer/agent.ts +++ /dev/null @@ -1,98 +0,0 @@ -/** Code Reviewer Agent - automated AI code review of open PRs. */ -import { BaseAgent } from "../base-agent.ts"; -import { makeAi, type AgentOpts } from "../agent-types.ts"; -import { AgentMetrics } from "../core/metrics.ts"; -import { buildOriginMetadata } from "../core/utils.ts"; -import { extractJsonObject, type AIClient } from "../../ai/client.ts"; -import { redactSecrets } from "../../utils/secure-git.ts"; -import { TelegramNotifier } from "../../notifications/telegram.ts"; - -export class CodeReviewerAgent extends BaseAgent { - private aiLabel: string; private _ai: AIClient | null = null; private aiOpts: AgentOpts["ai"]; - constructor(o: AgentOpts) { super("code_reviewer", o); this.aiOpts = o.ai; this.aiLabel = makeAi(o.ai).label; if (o.aiClient) this._ai = o.aiClient; } - get persona() { return "Code Reviewer Agent — Expert in code quality, best practices, and bug detection."; } - get mission() { return "Review pull requests for code quality, maintainability, best practices, potential bugs, security issues, and performance considerations."; } - private get ai(): AIClient { return (this._ai ||= makeAi(this.aiOpts).client); } - - async run() { - const metrics = new AgentMetrics(this.name), reviews: any[] = [], failed: any[] = []; - try { - this.log("Starting code review agent..."); - const repos = await this.getAllowedRepositories(); - this.log(`Reviewing PRs in ${repos.length} repositories`); - for (const repo of repos) { - try { - const prs = await this.githubClient.getPulls(repo); - this.log(`Found ${prs.length} open PRs in ${repo}`); - for (const pr of prs) { - try { - if (await this.hasRecentReview(pr)) continue; - const r = await this.reviewPullRequest(pr); - if (r.success) { reviews.push(r); metrics.incrementProcessed(); } else { failed.push(r); metrics.incrementFailed(); } - } catch (e: any) { this.log(`Error reviewing PR ${pr.number}: ${e?.message ?? e}`, "ERROR"); metrics.addError(`PR review failed: ${e?.message ?? e}`); failed.push({ pr: pr.number, error: String(e?.message ?? e) }); metrics.incrementFailed(); } - } - } catch (e: any) { this.log(`Error processing repository ${repo}: ${e?.message ?? e}`, "ERROR"); metrics.addError(`Repository processing failed: ${e?.message ?? e}`); } - } - await this.sendSummary(reviews, failed); - } catch (e: any) { this.log(`Code review agent failed: ${e?.message ?? e}`, "ERROR"); metrics.addError(`Agent execution failed: ${e?.message ?? e}`); } - return { reviews_performed: reviews, failed, metrics: metrics.finalize() }; - } - - private async hasRecentReview(pr: any): Promise { - let bot = ""; - try { bot = await this.githubClient.getAuthenticatedLogin(); } catch { /* unknown */ } - for (const c of await this.githubClient.getIssueComments(pr.base.repo.full_name, pr.number)) { - const body = c.body ?? ""; - const isReview = body.includes("## AI Code Review") || body.includes("") || body.includes(""); - if (isReview && (!bot || c.user?.login === bot)) return true; - } - return false; - } - - private async reviewPullRequest(pr: any) { - const n = pr.number, files = await this.githubClient.getFiles(pr.base.repo.full_name, n); - const changes = files.map((f: any) => `File: ${f.filename} (${f.status}, +${f.additions}/-${f.deletions})\n\`\`\`diff\n${(f.patch ?? "").slice(0, 3000)}\n\`\`\``); - if (!changes.length) { this.log(`PR #${n}: no file changes to review`); return { success: true, pr_number: n, issues_found: [], suggestions: [] }; } - const prompt = "You are a senior code reviewer. Analyze this pull request and provide feedback.\n" + `PR #${n}: ${pr.title}\n\n` + "Changes:\n" + changes.slice(0, 5).join("\n---\n") + "\n\n" + - "Respond with ONLY valid JSON:\n" + '{"issues": [{"severity": "high|medium|low", "file": "filename", "line": null, "description": "issue description", "suggestion": "how to fix"}], "summary": "overall assessment", "score": 0-10}'; - let issues: any[] = [], summary = "Review completed."; - try { - const data = extractJsonObject(await this.ai.generate(prompt)); - if (data) { issues = Array.isArray(data.issues) ? data.issues : []; summary = data.summary ?? summary; } - } catch (e: any) { - this.log(`AI review failed for PR #${n}: ${e?.message ?? e}`, "WARNING"); - return { success: true, pr_number: n, issues_found: [], suggestions: [], error: String(e?.message ?? e) }; - } - await this.postReview(pr, issues, summary, n); - return { success: true, pr_number: n, issues_found: issues, suggestions: issues }; - } - - private async postReview(pr: any, issues: any[], summary: string, n: number) { - const parts = ["\n", "## AI Code Review\n", `**Summary:** ${summary}\n`]; - if (issues.length) { - parts.push("\n### Issues Found\n"); - for (const i of issues.slice(0, 10)) { - parts.push(`- **[${String(i.severity ?? "info").toUpperCase()}]** ${i.file ?? ""}: ${i.description ?? ""}`); - if (i.suggestion) parts.push(` > ${i.suggestion}`); - } - } else parts.push("\nNo issues found. The code looks good! 🎉"); - parts.push("\n" + buildOriginMetadata("code_reviewer", this.aiLabel)); - const full = parts.join("\n"); - try { - let posted = false; - const inline = issues.slice(0, 10).filter((i) => i.file && Number.isInteger(i.line) && i.line > 0 && i.description).map((i) => { - let text = `**[${String(i.severity ?? "info").toUpperCase()}]** ${i.description}`; - if (i.suggestion) text += `\n\n> ${i.suggestion}`; - return { path: i.file, line: i.line, body: redactSecrets(text) }; - }); - if (inline.length) { try { await this.githubClient.createReview(pr, { body: redactSecrets(full), event: "COMMENT", comments: inline }); posted = true; } catch { posted = false; } } - if (!posted) await this.githubClient.commentOnPr(pr, redactSecrets(full)); - await this.telegram.sendMessage(`👀 CODE REVIEW PR #${n} em ${TelegramNotifier.escapeHtml(pr.base.repo.full_name)} — ${issues.length} issues encontradas`, "HTML"); - } catch (e: any) { this.log(`Failed to post review for PR #${n}: ${e?.message ?? e}`, "WARNING"); } - } - - private async sendSummary(reviews: any[], failures: any[]) { - if (!reviews.length && !failures.length) return; - await this.telegram.sendMessage(["👀 CODE REVIEWER — RESUMO", "──────────────────────", `✅ Reviews realizados: ${reviews.length}`, `❌ Falhas: ${failures.length}`].join("\n"), "HTML"); - } -} diff --git a/ts/src/agents/code_reviewer/instructions.md b/ts/src/agents/code_reviewer/instructions.md deleted file mode 100644 index cbfa0e76..00000000 --- a/ts/src/agents/code_reviewer/instructions.md +++ /dev/null @@ -1,95 +0,0 @@ -# Code Reviewer Agent 👀 - -## Overview -The Code Reviewer Agent performs automated code reviews on pull requests using AI analysis. It provides constructive feedback on code quality, best practices, potential bugs, and security issues. - -## Responsibilities - -### Primary Functions -1. **Code Quality Review**: Assess code maintainability, readability, and structure -2. **Best Practices Check**: Ensure adherence to coding standards and design patterns -3. **Bug Detection**: Identify potential bugs, logic errors, and edge cases -4. **Security Analysis**: Detect security vulnerabilities and unsafe practices -5. **Performance Review**: Identify performance bottlenecks and optimization opportunities - -### Review Criteria -- **Code Structure**: Proper separation of concerns, modularity -- **Naming Conventions**: Clear, descriptive variable and function names -- **Error Handling**: Proper exception handling and error messages -- **Testing**: Adequate test coverage and test quality -- **Documentation**: Code comments and docstrings where needed -- **Security**: No hardcoded secrets, SQL injection risks, XSS vulnerabilities -- **Performance**: Efficient algorithms, no unnecessary loops or redundant operations - -## Configuration - -### Environment Variables -```bash -ENABLE_AI=true # Required for AI-powered reviews -AI_PROVIDER=gemini # AI provider (gemini, ollama, openai) -AI_MODEL=gemini-2.5-flash # AI model to use -CODE_REVIEWER_ENABLED=true # Enable this agent -``` - -### Review Settings -- **Review Frequency**: On new PR creation and updates -- **Review Scope**: All files changed in the PR -- **Comment Style**: Constructive, educational, actionable -- **Severity Levels**: Critical, High, Medium, Low, Info - -## Workflow - -1. **PR Detection**: Find open PRs in allowed repositories -2. **Change Analysis**: Get PR diff and analyze code changes -3. **AI Review**: Send code to AI for analysis -4. **Issue Classification**: Categorize findings by severity -5. **Comment Posting**: Post review comments on the PR -6. **Summary Report**: Send Telegram notification with summary - -## Example Review Comments - -### Critical Issue -```markdown -🔴 **Critical: Potential SQL Injection** -Line 45: User input is directly concatenated into SQL query. - -**Risk**: An attacker could manipulate the query to access unauthorized data. - -**Suggestion**: Use parameterized queries or an ORM. -```python -# Instead of: -query = f"SELECT * FROM users WHERE id = {user_id}" - -# Use: -query = "SELECT * FROM users WHERE id = ?" -cursor.execute(query, (user_id,)) -``` - -### Code Quality Issue -```markdown -💡 **Suggestion: Extract Complex Logic** -Lines 120-145: This function has multiple responsibilities. - -**Impact**: Harder to test and maintain. - -**Suggestion**: Extract separate functions for validation, processing, and response. -``` - -## Metrics Tracked -- **Reviews Performed**: Number of PRs reviewed -- **Issues Detected**: Total issues found by severity -- **Suggestions Acceptance Rate**: Percentage of suggestions applied -- **Review Time**: Average time to review a PR -- **False Positives**: Issues marked as invalid by developers - -## Integration with Other Agents -- **Senior Developer Agent**: May create tasks based on repeated issues -- **PR Assistant Agent**: Works together to improve PR quality -- **Security Scanner Agent**: Complements with runtime secret scanning - -## Future Enhancements -- [ ] Learn from developer feedback on suggestions -- [ ] Custom rule configuration per repository -- [ ] Integration with static analysis tools (pylint, eslint) -- [ ] Automated fix suggestions (not just comments) -- [ ] Duplicate code detection across repositories diff --git a/ts/src/agents/conflict_resolver/agent.ts b/ts/src/agents/conflict_resolver/agent.ts deleted file mode 100644 index 84263704..00000000 --- a/ts/src/agents/conflict_resolver/agent.ts +++ /dev/null @@ -1,117 +0,0 @@ -/** Conflict Resolver Agent - auto-resolves merge conflicts in pull requests and retries failing pipelines. */ -import type { PR } from "../../github/client.ts"; -import { DEFAULT_OLLAMA_MODEL } from "../../config/settings.ts"; -import { BaseAgent } from "../base-agent.ts"; -import type { AgentOpts } from "../agent-types.ts"; -import { ALLOWED_AUTHORS } from "../pr_assistant/agent.ts"; -import { resolveConflictsAutonomously } from "../pr_assistant/conflict-resolver.ts"; -import { getPipelineErrorLogs } from "../pr_assistant/logs.ts"; -import { checkPipelineStatus } from "../pr_assistant/pipeline.ts"; -import { MANUAL_PIPELINE_LABEL, buildMarker, fixPipelineAutonomously, maxAttempts, pipelineFixEnabled, readAttemptState } from "../pr_assistant/pipeline-fixer.ts"; -import { MANUAL_CONFLICT_LABEL, clearManualConflictLabel, handleConflict } from "../pr_assistant/conflict-flow.ts"; -import { withPrLock } from "../pr_assistant/pr-lock.ts"; -import { sendPipelineFixNotice, sendPipelineManualNotice, sendResolutionNotice, sendSummaryNotice } from "./notifications.ts"; - -export { MANUAL_CONFLICT_LABEL }; -type Results = { resolved: any[]; manual: any[]; pipeline_fixed: any[]; pipeline_manual: any[]; timestamp: string }; -const norm = (a: string) => a.toLowerCase().replace("[bot]", ""); - -export class ConflictResolverAgent extends BaseAgent { - aiProvider: string; aiModel: string; prRef: string | null; - constructor(o: AgentOpts) { - super("conflict_resolver", { ...o, enforceRepositoryAllowlist: false }); - this.aiProvider = o.ai?.provider ?? "ollama"; this.aiModel = o.ai?.model ?? DEFAULT_OLLAMA_MODEL; this.prRef = o.prRef ?? null; - } - get persona() { return this.getInstructionsSection("## Persona"); } - get mission() { return this.getInstructionsSection("## Mission"); } - /** Overridable in tests (secondary-rate-limit backoff). */ - backoffMs = 30_000; - - async run(): Promise { - this.log("Starting Conflict Resolver workflow"); - await this.checkRateLimit(); - const results: Results = { resolved: [], manual: [], pipeline_fixed: [], pipeline_manual: [], timestamp: new Date().toISOString() }; - if (this.prRef) { await this.handlePrRef(results); await this.sendSummary(results); return results; } - const query = `is:pr is:open archived:false user:${this.targetOwner}`; - this.log(`Searching PRs in your repositories with query: ${query}`); - try { for (const issue of await this.githubClient.searchPrs(query)) await this.handleIssue(issue, results); } - catch (e) { this.log(`Failed to search PRs: ${e}`, "ERROR"); } - await this.sendSummary(results); - return results; - } - private async handleIssue(issue: any, results: Results) { - try { await this.handlePr(await this.githubClient.getPrFromIssue(issue), results); } - catch (e: any) { - if (String(e).toLowerCase().includes("secondary rate limit")) { this.log("Secondary rate limit hit - waiting 30s...", "WARNING"); await Bun.sleep(this.backoffMs); } - this.log(`Error processing PR #${issue.number}: ${e}`, "ERROR"); - } - } - private async handlePrRef(results: Results) { - try { const i = this.prRef!.lastIndexOf("#"); await this.handlePr(await this.githubClient.getPull(this.prRef!.slice(0, i), parseInt(this.prRef!.slice(i + 1), 10)), results); } - catch (e) { this.log(`Could not resolve PR ref ${this.prRef}: ${e}`, "ERROR"); } - } - async handlePr(pr: PR, results: Results) { - const repo = pr.base.repo.full_name, author = pr.user.login; - if (!this.canWorkOnRepository(repo) || !this.isTrustedAuthor(author)) return; - await clearManualConflictLabel(this.githubClient, pr, this.log); - if (pr.mergeable === false) { - if (this.hasLabel(pr, MANUAL_CONFLICT_LABEL)) { this.log(`PR #${pr.number} already flagged for manual conflict resolution; skipping`); return; } - this.log(`Evaluating PR #${pr.number} in ${repo} by ${author}`); - await this.processConflict(pr, results); - } else if (pipelineFixEnabled()) await withPrLock(this.githubClient, pr, () => this.maybeFixPipeline(pr, results)); - } - private hasLabel = (pr: PR, name: string) => (pr.labels ?? []).some((l: any) => (typeof l === "string" ? l : l.name) === name); - isTrustedAuthor(author: string): boolean { - const users = this.allowlist.listUsers(); const allowed = users.length ? users : ALLOWED_AUTHORS; - return allowed.map(norm).includes(norm(author)); - } - private async processConflict(pr: PR, results: Results) { - const repo = pr.base.repo.full_name; - this.log(`PR #${pr.number} in ${repo} has conflicts - resolving...`); - let comments: any[] = []; - try { comments = await this.githubClient.getIssueComments(repo, pr.number); } catch { /* rebase dedupe falls back to posting */ } - const out = await handleConflict(this.githubClient, this.telegram, pr, comments, (p) => resolveConflictsAutonomously(p, { aiProvider: this.aiProvider, aiModel: this.aiModel }), this.log); - if (out.kind === "resolved") { results.resolved.push({ pr: pr.number, repo, msg: out.msg }); await this.notifyResolved(pr, out.msg); return; } - if (out.kind === "manual") results.manual.push({ pr: pr.number, repo, error: out.msg }); - else this.log(`PR #${pr.number}: conflict ${out.kind} (${out.msg})`); - } - private async maybeFixPipeline(pr: PR, results: Results) { - const status = await checkPipelineStatus(this.githubClient, pr); - if (!["failure", "error"].includes(status.state)) return; - const comments = await this.githubClient.getIssueComments(pr.base.repo.full_name, pr.number); - const [last] = readAttemptState(comments), mx = maxAttempts(); - if (last >= mx) { if (!this.hasLabel(pr, MANUAL_PIPELINE_LABEL)) await this.markPipelineManual(pr, `Pipeline ainda falhando após ${last} tentativas`); return; } - this.log(`PR #${pr.number} in ${pr.base.repo.full_name} pipeline failing - fix attempt ${last + 1}/${mx}`); - await this.processPipelineFix(pr, results, last + 1, mx); - } - private async processPipelineFix(pr: PR, results: Results, attempt: number, mx: number) { - const data = await getPipelineErrorLogs(this.githubClient, pr); - if (!data.logs.trim()) { this.log(`No actionable pipeline logs for PR #${pr.number}; skipping`, "WARNING"); return; } - const [ok, msg, sha] = await fixPipelineAutonomously(this.githubClient, pr, data.logs, data.failed_checks, attempt, mx); - await this.commentPipelineAttempt(pr, msg, attempt, mx, sha || pr.head.sha, ok); - const repo = pr.base.repo.full_name; - if (ok) { results.pipeline_fixed.push({ pr: pr.number, repo, msg }); await sendPipelineFixNotice(this.telegram, pr, msg); return; } - results.pipeline_manual.push({ pr: pr.number, repo, error: msg }); - if (attempt >= mx) await this.markPipelineManual(pr, msg); - } - private async commentPipelineAttempt(pr: PR, msg: string, attempt: number, mx: number, sha: string, ok: boolean) { - const author = pr.user?.login ?? "contributor", marker = buildMarker(attempt, sha); - const body = `**Tentativa ${attempt}/${mx} de corrigir o pipeline**\n\n` + (ok - ? `Ola @${author}, apliquei uma correcao automatica no pipeline.\n\n**Detalhes:** ${msg}\n\n${marker}` - : `Ola @${author}, tentei corrigir o pipeline, mas a tentativa falhou.\n\n**Erro:** ${msg}\n\n${marker}`); - try { await this.githubClient.commentOnPr(pr, body); } catch (e) { this.log(`Failed to send notification: ${e}`, "WARNING"); } - } - private async markPipelineManual(pr: PR, error: string) { - const [ok, msg] = await this.githubClient.addLabelToPr(pr, MANUAL_PIPELINE_LABEL); - if (ok) this.log(`Marked PR #${pr.number} in ${pr.base.repo.full_name} for manual pipeline fix`); else this.log(`Failed to label PR #${pr.number}: ${msg}`, "WARNING"); - await sendPipelineManualNotice(this.telegram, pr, error); - } - private async notifyResolved(pr: PR, msg: string) { - const author = pr.user?.login ?? "contributor"; - await this.githubClient.commentOnPr(pr, `**Conflitos de merge resolvidos**\n\nOla @${author}, resolvi os conflitos automaticamente.\n\n**Detalhes:** ${msg}`); - await sendResolutionNotice(this.telegram, pr, msg); - } - private async sendSummary(r: Results) { - if (r.resolved.length || r.manual.length || r.pipeline_fixed.length || r.pipeline_manual.length) await sendSummaryNotice(this.telegram, r.resolved, r.manual, r.pipeline_fixed, r.pipeline_manual); - } -} diff --git a/ts/src/agents/conflict_resolver/instructions.md b/ts/src/agents/conflict_resolver/instructions.md deleted file mode 100644 index ad5d0024..00000000 --- a/ts/src/agents/conflict_resolver/instructions.md +++ /dev/null @@ -1,35 +0,0 @@ -# Conflict Resolver Agent 🔧 - -## Persona -Desenvolvedor Senior meticuloso especializado em saúde de repositórios e integração contínua. -Paciência infinita para resolver conflitos de merge e garantir que o fluxo de desenvolvimento não pare. - -## Mission -Identificar automaticamente Pull Requests com conflitos de merge em todos os repositórios monitorados. -Tentar resolver esses conflitos usando IA de forma segura, commitar as mudanças na branch do PR e notificar os envolvidos. - -## Responsibilities -1. **Monitoramento**: Verificar PRs abertos em busca do status `mergeable == False`. -2. **Resolução de Conflitos**: - - Clonar o repositório localmente. - - Identificar os marcadores de conflito (`<<<<<<<`, `=======`, `>>>>>>>`). - - Usar LLM para analisar o contexto e propor uma resolução coerente. - - Aplicar a resolução, commitar e fazer o push para a branch de origem. -3. **Notificação**: - - Comentar no PR informando o sucesso ou a necessidade de intervenção humana. - - Enviar resumo detalhado para o Telegram. -4. **Segurança**: Nunca forçar o push sem necessidade e respeitar a lógica de autores confiáveis. - -## Conflict Detection Markers -``` -<<<<<<< HEAD -Código atual na branch base -======= -Código vindo do PR ->>>>>>> branch-name -``` - -## Success Criteria -- Conflitos resolvidos sem quebrar a lógica do sistema. -- Commits de resolução claros: `fix: resolve merge conflicts via AI Agent`. -- Notificações enviadas para o Telegram com links diretos para o PR. diff --git a/ts/src/agents/conflict_resolver/notifications.ts b/ts/src/agents/conflict_resolver/notifications.ts deleted file mode 100644 index 0ca6b6b4..00000000 --- a/ts/src/agents/conflict_resolver/notifications.ts +++ /dev/null @@ -1,22 +0,0 @@ -/** Telegram notices for ConflictResolverAgent (best-effort). */ -import type { TelegramNotifier } from "../../notifications/telegram.ts"; -import { card, esc, prButton, reasonLabel } from "../../notifications/telegram-format.ts"; - -type Tg = Pick; -const send = async (tg: Tg, pr: any, text: string) => { try { await tg.sendMessage(text, "HTML", prButton(pr)); } catch { /* best-effort */ } }; -export const sendResolutionNotice = (tg: Tg, pr: any, msg: string) => send(tg, pr, card("✅", "CONFLITO RESOLVIDO", pr, [`ℹ️ ${esc(msg.split("\n")[0] ?? msg)}`])); -export const sendManualNotice = (tg: Tg, pr: any, error: string) => - send(tg, pr, card("🚫", "CONFLITO: RESOLUÇÃO MANUAL NECESSÁRIA", pr, ["ℹ️ O PR continua aberto e foi marcado com needs-manual-conflict-resolution.", `
${esc(error.slice(0, 300))}
`])); -export const sendPipelineFixNotice = (tg: Tg, pr: any, msg: string) => send(tg, pr, card("🛠️", "PIPELINE CORRIGIDO", pr, [`ℹ️ ${esc(msg.split("\n")[0] ?? msg)}`])); -export const sendPipelineManualNotice = (tg: Tg, pr: any, error: string) => - send(tg, pr, card("🚫", "PIPELINE: CORREÇÃO MANUAL NECESSÁRIA", pr, [`
${esc(error.slice(0, 300))}
`])); -type Item = Record; -function addItems(lines: string[], items: Item[], field: string) { - for (const it of items.slice(0, 5)) lines.push(` └ ${esc(it.repo)}#${it.pr} — ${esc(reasonLabel(String(it[field] ?? "")).slice(0, 120))}`); -} -export async function sendSummaryNotice(tg: Tg, resolved: Item[], manual: Item[], pipelineFixed: Item[] = [], pipelineManual: Item[] = []) { - const lines = ["🛠️ CONFLICT RESOLVER", "──────────────────────", `✅ Conflitos resolvidos: ${resolved.length}`, `🚫 Conflitos manuais: ${manual.length}`, - `🔧 Pipelines corrigidos: ${pipelineFixed.length}`, `🚫 Pipelines manuais: ${pipelineManual.length}`]; - addItems(lines, resolved, "msg"); addItems(lines, manual, "error"); addItems(lines, pipelineFixed, "msg"); addItems(lines, pipelineManual, "error"); - await tg.sendMessage(lines.join("\n"), "HTML"); -} diff --git a/ts/src/agents/core/agent-contract.ts b/ts/src/agents/core/agent-contract.ts new file mode 100644 index 00000000..fa6c3fdf --- /dev/null +++ b/ts/src/agents/core/agent-contract.ts @@ -0,0 +1,75 @@ +/** + * The owner's agent contract: global AGENTS.md + skills from juninmd/skills, refreshed to the newest commit before + * opencode runs (opencode auto-loads ~/.config/opencode/{AGENTS.md,skills}). Fail-open: on any error the copy already + * installed (baked into the image) stays in use and the run continues. + */ +import { cpSync, existsSync, mkdirSync, renameSync, rmSync } from "node:fs"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { run } from "../../utils/proc.ts"; +import { scrubEnv } from "../../utils/secure-git.ts"; + +export const SKILLS_REPO = "https://github.com/juninmd/skills"; +export type Contract = { sha: string | null; source: "fresh" | "cache" | "disabled" }; +type Log = (m: string, level?: string) => void; +type Runner = typeof run; + +const truthy = (v: string | undefined, d: boolean) => (v === undefined || v.trim() === "" ? d : ["1", "true", "yes", "on"].includes(v.trim().toLowerCase())); +/** Off by default: it replaces ~/.config/opencode/skills, so only the image (Dockerfile ENV) turns it on, never a dev machine. */ +export const contractEnabled = () => truthy(process.env.AGENT_CONTRACT_REFRESH, false); +const ttlMs = () => Math.max(1, parseInt(process.env.AGENT_CONTRACT_TTL_MINUTES ?? "", 10) || 60) * 60_000; + +let state: (Contract & { at: number }) | null = null; +let inflight: Promise | null = null; +export const resetContract = () => { state = null; inflight = null; }; +export const currentContract = (): Contract | null => (state ? { sha: state.sha, source: state.source } : null); +/** Short label for PR bodies and review footers, e.g. `juninmd/skills@1a2b3c4`. */ +export const contractLabel = () => (state?.sha ? `juninmd/skills@${state.sha.slice(0, 7)}` : ""); + +async function git(args: string[], r: Runner, cwd?: string): Promise { + // Public repository: no credentials, no prompts. + const res = await r(["git", ...args], { cwd, timeoutMs: 120_000, env: { ...scrubEnv(), GIT_TERMINAL_PROMPT: "0" } }); + if (res.code !== 0 || res.timedOut) throw new Error(`git ${args[0]} failed: ${(res.stderr || "").trim().slice(0, 200)}`); + return res.stdout.trim(); +} + +/** Swap the installed skills/AGENTS.md for the fetched ones; skills removed upstream disappear too. */ +function install(src: string, home: string): void { + const cfg = join(home, ".config", "opencode"), skills = join(cfg, "skills"), fresh = `${skills}.new`, old = `${skills}.old`; + mkdirSync(cfg, { recursive: true }); + rmSync(fresh, { recursive: true, force: true }); rmSync(old, { recursive: true, force: true }); + cpSync(join(src, ".agents", "skills"), fresh, { recursive: true }); + if (existsSync(skills)) renameSync(skills, old); + renameSync(fresh, skills); + rmSync(old, { recursive: true, force: true }); + cpSync(join(src, ".agents", "AGENTS.md"), join(cfg, "AGENTS.md")); +} + +export function ensureContract(log: Log, o: { home?: string; runner?: Runner; now?: number } = {}): Promise { + if (!contractEnabled()) return Promise.resolve({ sha: null, source: "disabled" }); + const now = o.now ?? Date.now(); + if (state && now - state.at < ttlMs()) return Promise.resolve(currentContract()!); + // Concurrent PR workers share one refresh instead of racing git in the same directory. + return (inflight ??= refresh(log, now, o.home ?? homedir(), o.runner ?? run).finally(() => { inflight = null; })); +} + +async function refresh(log: Log, now: number, home: string, r: Runner): Promise { + const cache = join(home, ".cache", "github-assistance", "skills"); + try { + if (existsSync(join(cache, ".git"))) { + await git(["fetch", "--depth", "1", "origin", "HEAD"], r, cache); + await git(["reset", "--hard", "FETCH_HEAD"], r, cache); + } else { + rmSync(cache, { recursive: true, force: true }); mkdirSync(join(cache, ".."), { recursive: true }); + await git(["clone", "--depth", "1", SKILLS_REPO, cache], r); + } + const sha = await git(["rev-parse", "HEAD"], r, cache); + install(cache, home); + state = { sha, source: "fresh", at: now }; + log(`Agent contract refreshed: juninmd/skills@${sha.slice(0, 7)}`); + } catch (e: any) { + log(`Agent contract refresh failed, keeping the installed copy: ${e?.message ?? e}`, "WARNING"); + state = { sha: state?.sha ?? null, source: "cache", at: now }; + } + return currentContract()!; +} diff --git a/ts/src/agents/core/composite.ts b/ts/src/agents/core/composite.ts new file mode 100644 index 00000000..a800046c --- /dev/null +++ b/ts/src/agents/core/composite.ts @@ -0,0 +1,64 @@ +/** Composite agent: one scoped agent that runs former agents as ordered stages (each isolated, each still testable). */ +import { join } from "node:path"; +import { BaseAgent } from "../base-agent.ts"; +import type { AgentOpts } from "../agent-types.ts"; +import { AGENTS_BY_NAME, type StageSpec } from "../catalog.ts"; +import { agentDir } from "./utils.ts"; + +type Result = Record; +const failed = (r: Result) => "error" in r || r.status === "failed"; +const truthy = (v: string | undefined, d: boolean) => (v === undefined || v.trim() === "" ? d : ["1", "true", "yes", "on"].includes(v.trim().toLowerCase())); + +export abstract class CompositeAgent extends BaseAgent { + readonly stages: StageSpec[]; + /** Set when a former agent name was used: only that stage runs and its result is returned unchanged. */ + readonly onlyStage: string | null; + protected opts: AgentOpts; + + constructor(name: string, o: AgentOpts) { + super(name, o); + this.opts = o; + this.stages = AGENTS_BY_NAME.get(name)?.stages ?? []; + this.onlyStage = o.stage ?? null; + if (this.onlyStage && !this.stages.some((s) => s.name === this.onlyStage)) throw new Error(`unknown stage '${this.onlyStage}' for ${name}`); + } + get persona() { return this.getInstructionsSection("## Persona"); } + get mission() { return this.getInstructionsSection("## Mission"); } + + /** Extra constructor options for a stage (e.g. observe-only or draft PRs). */ + protected stageOptions(_stage: StageSpec): Record { return {}; } + /** Null to run the stage; otherwise the reason it is skipped (given the results of earlier stages). */ + protected skipReason(stage: StageSpec, _done: Record): string | null { + if (stage.requiresAi && !this.opts.ai) return "ENABLE_AI=false"; + return truthy(stage.toggleEnv ? process.env[stage.toggleEnv] : undefined, true) ? null : `${stage.toggleEnv}=false`; + } + /** Hook after a stage finished (e.g. persist its results for a later run). */ + protected afterStage(_stage: StageSpec, _result: Result): void {} + + async createStage(stage: StageSpec): Promise { + const mod = await import(join(agentDir(stage.dir), "agent.ts")); + const Cls = mod[stage.className]; + if (!Cls) throw new Error(`${stage.className} not exported by agents/${stage.dir}/agent.ts`); + const { stage: _omit, ...base } = this.opts; + return new Cls({ ...base, ...this.stageOptions(stage) }); + } + + private async runStage(stage: StageSpec): Promise { + try { const r = (await (await this.createStage(stage)).run()) ?? {}; this.afterStage(stage, r); return r; } + catch (e: any) { this.log(`Stage ${stage.name} failed: ${e?.message ?? e}`, "ERROR"); return { error: String(e?.message ?? e) }; } + } + + async run(): Promise { + if (this.onlyStage) return this.runStage(this.stages.find((s) => s.name === this.onlyStage)!); + const done: Record = {}, skipped: Record = {}; + for (const stage of this.stages) { + const reason = this.skipReason(stage, done); + if (reason) { skipped[stage.name] = reason; this.log(`Stage ${stage.name} skipped: ${reason}`); continue; } + done[stage.name] = await this.runStage(stage); + } + const out: Result = { agent: this.name, stages: done, skipped_stages: skipped }; + const bad = Object.entries(done).filter(([, r]) => failed(r)).map(([n]) => n); + if (bad.length) out.error = `stage(s) failed: ${bad.join(", ")}`; + return out; + } +} diff --git a/ts/src/agents/core/pr-options.ts b/ts/src/agents/core/pr-options.ts new file mode 100644 index 00000000..4f8e9f4b --- /dev/null +++ b/ts/src/agents/core/pr-options.ts @@ -0,0 +1,23 @@ +/** How an agent's pull requests are opened: builder PRs stay draft and carry `keep-draft`, so the bot never merges them. */ +import type { GithubClient, PR } from "../../github/client.ts"; + +export const KEEP_DRAFT_LABEL = "keep-draft"; +export type PrOptions = { draft: boolean; labels: string[] }; +export const DEFAULT_PR_OPTIONS: PrOptions = { draft: false, labels: [] }; +type Log = (m: string, level?: string) => void; + +export const hasLabel = (pr: { labels?: any[] }, name: string) => + (pr.labels ?? []).some((l: any) => (typeof l === "string" ? l : l?.name ?? "").toLowerCase() === name.toLowerCase()); + +/** Create the PR as draft when asked; repos without draft support still get the label that blocks the bot's merge. */ +export async function createAgentPull(gh: GithubClient, repo: string, p: { title: string; body: string; head: string; base: string }, o: PrOptions, log: Log): Promise { + let pr: PR; + try { pr = await gh.createPull(repo, o.draft ? { ...p, draft: true } : p); } + catch (e: any) { + if (!o.draft || !/draft/i.test(String(e?.message ?? e))) throw e; + log(`Draft PRs unavailable in ${repo}; opening a regular PR guarded by '${o.labels.join(", ")}'`, "WARNING"); + pr = await gh.createPull(repo, p); + } + for (const label of o.labels) await gh.addLabelToPr(pr, label); + return pr; +} diff --git a/ts/src/agents/core/utils.ts b/ts/src/agents/core/utils.ts index 0e537137..01c4cfe8 100644 --- a/ts/src/agents/core/utils.ts +++ b/ts/src/agents/core/utils.ts @@ -3,6 +3,7 @@ import { existsSync, readFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { DEFAULT_LITELLM_API_BASE } from "../../config/settings.ts"; import { run } from "../../utils/proc.ts"; +import { contractLabel } from "./agent-contract.ts"; import type { GithubClient, PR } from "../../github/client.ts"; type Log = (msg: string, level?: string) => void; @@ -12,7 +13,8 @@ export function buildOriginMetadata(agentName: string, model: string | null = "o return `---\n🤖 **Origem Automatizada**\n- **Agente:** \`${agentName}\`\n${model ? `- **Modelo:** \`${model}\`\n` : ""}- **Repositório de origem:** [github-assistance](https://github.com/juninmd/github-assistance)`; } export function buildPrBody(agentName: string, title: string, opencodeOutput: string, model = "opencode"): string { - return `## 🤖 Alterações aplicadas automaticamente\n\n### O que foi feito\n${title}\n\n### Saída do opencode\n\`\`\`\n${opencodeOutput.slice(0, 1500)}\n\`\`\`\n\n### Evidências\n\n\n${buildOriginMetadata(agentName, model)}`; + const skills = contractLabel(); + return `## 🤖 Alterações aplicadas automaticamente\n\n### O que foi feito\n${title}\n\n### Saída do opencode\n\`\`\`\n${opencodeOutput.slice(0, 1500)}\n\`\`\`\n\n### Evidências\n\n\n${buildOriginMetadata(agentName, model)}${skills ? `\n- **Contrato:** \`${skills}\` (skills + AGENTS.md global)` : ""}`; } export const EXECUTION_POLICY_BLOCK = ` diff --git a/ts/src/agents/flow_watch/agent.ts b/ts/src/agents/flow_watch/agent.ts new file mode 100644 index 00000000..06d5b141 --- /dev/null +++ b/ts/src/agents/flow_watch/agent.ts @@ -0,0 +1,9 @@ +/** Flow Watch - observe-only: failing pipelines and stale PRs go to Telegram; fixing is the PR Assistant's job. */ +import type { AgentOpts } from "../agent-types.ts"; +import type { StageSpec } from "../catalog.ts"; +import { CompositeAgent } from "../core/composite.ts"; + +export class FlowWatchAgent extends CompositeAgent { + constructor(o: AgentOpts) { super("flow-watch", o); } + protected stageOptions(stage: StageSpec) { return stage.name === "ci" ? { remediate: false } : { nudge: false }; } +} diff --git a/ts/src/agents/flow_watch/instructions.md b/ts/src/agents/flow_watch/instructions.md new file mode 100644 index 00000000..9dfd18b5 --- /dev/null +++ b/ts/src/agents/flow_watch/instructions.md @@ -0,0 +1,10 @@ +# Flow Watch + +## Persona + +Observer of the delivery flow. Reads, never writes to repositories. + +## Mission + +Report failing pipelines (last 24h) and pull requests without updates for more than 24h on Telegram. +It opens no PR, task or comment: fixing a red pipeline or a stuck PR is the PR Assistant's job. diff --git a/ts/src/agents/intelligence_standardizer/agent.ts b/ts/src/agents/intelligence_standardizer/agent.ts index 67c42193..697e452f 100644 --- a/ts/src/agents/intelligence_standardizer/agent.ts +++ b/ts/src/agents/intelligence_standardizer/agent.ts @@ -1,5 +1,6 @@ -/** Intelligence Standardizer - enforces AGENTS.md and .agents structure. */ +/** Intelligence Standardizer (repo-standards stage) - enforces AGENTS.md and .agents structure in every active repository. */ import { BaseAgent } from "../base-agent.ts"; +import { mapLimit } from "../core/utils.ts"; import type { AgentOpts } from "../agent-types.ts"; import { TelegramNotifier } from "../../notifications/telegram.ts"; @@ -8,23 +9,47 @@ const CHECKS: Record = { missing_contributing: "CONTRIBUTING.md", missing_license: "LICENSE", }; +const TITLE_PREFIX = "Standardize "; +const maxPrs = () => Math.max(0, parseInt(process.env.REPO_STANDARDS_MAX_PRS ?? "", 10) || 5); + export class IntelligenceStandardizerAgent extends BaseAgent { constructor(o: AgentOpts) { super("intelligence_standardizer", { ...o, enforceRepositoryAllowlist: true }); } get persona() { return this.getInstructionsSection("## Persona"); } get mission() { return this.getInstructionsSection("## Mission"); } + /** Every active repository of the owner: the merge gate needs AGENTS.md everywhere, not only in recent repos. */ async run() { this.log("Starting Intelligence Standardizer workflow"); - const repos = await this.githubClient.getUserRepos({ sort: "updated", limit: 10 }); + const owner = this.targetOwner.toLowerCase(); + const repos = (await this.githubClient.getUserRepos({ sort: "updated", limit: null })) + .filter((r) => !r.archived && !r.fork && (r.owner?.login ?? owner).toLowerCase() === owner); const results: { processed: any[]; skipped: any[]; failed: any[] } = { processed: [], skipped: [], failed: [] }; - for (const repo of repos) { - try { await this.processRepository(repo, results); } - catch (e: any) { this.log(`Failed to process ${repo.full_name}: ${e?.message ?? e}`, "ERROR"); results.failed.push({ repository: repo.full_name, error: String(e?.message ?? e) }); } + const analyzed = await mapLimit(repos, 8, async (repo) => { + try { return { repo, a: await this.analyzeIntelligence(repo) }; } + catch (e: any) { results.failed.push({ repository: repo.full_name, error: String(e?.message ?? e) }); return null; } + }); + // Missing AGENTS.md first: without it the PR Assistant blocks every merge in that repository. + const todo = analyzed.filter((x): x is { repo: any; a: Record } => x !== null) + .sort((x, y) => Number(y.a.missing_agents_md) - Number(x.a.missing_agents_md)); + let opened = 0; + for (const { repo, a } of todo) { + try { + if (opened >= maxPrs() && this.needsWork(a)) { results.skipped.push({ repository: repo.full_name, reason: "run_cap_reached" }); continue; } + if (await this.processRepository(repo, a, results)) opened++; + } catch (e: any) { this.log(`Failed to process ${repo.full_name}: ${e?.message ?? e}`, "ERROR"); results.failed.push({ repository: repo.full_name, error: String(e?.message ?? e) }); } } await this.sendSummary(results); return results; } + needsWork = (a: Record) => a.missing_agents_md || a.missing_agents_dir || a.missing_contributing || a.missing_license; + + /** An open standardization PR means the work is already waiting for review: never open a second one. */ + private async hasOpenPr(name: string): Promise { + try { return (await this.githubClient.getPulls(name, { state: "open" })).some((p) => (p.title ?? "").includes(TITLE_PREFIX)); } + catch { return false; } + } + async analyzeIntelligence(repo: any): Promise> { const out: Record = {}; for (const [key, path] of Object.entries(CHECKS)) { @@ -34,16 +59,16 @@ export class IntelligenceStandardizerAgent extends BaseAgent { return out; } - private async processRepository(repo: any, results: { processed: any[]; skipped: any[] }) { + private async processRepository(repo: any, a: Record, results: { processed: any[]; skipped: any[] }): Promise { const name = repo.full_name; - this.log(`Checking intelligence structure for ${name}`); - const a = await this.analyzeIntelligence(repo); - if (!a.missing_agents_md && !a.missing_agents_dir && !a.missing_contributing && !a.missing_license) { - this.log(`Repository ${name} is already standardized.`); results.skipped.push({ repository: name, reason: "already_standardized" }); return; + if (!this.needsWork(a)) { + this.log(`Repository ${name} is already standardized.`); results.skipped.push({ repository: name, reason: "already_standardized" }); return false; } + if (await this.hasOpenPr(name)) { results.skipped.push({ repository: name, reason: "pr_already_open" }); return false; } const instructions = this.loadTaskInstructions("task-instructions.md", { repository_name: name, ...a }); - const oc = await this.runOpencodeOnRepo(name, instructions, `Standardize ${repo.name} Quality & Intelligence`); + const oc = await this.runOpencodeOnRepo(name, instructions, `${TITLE_PREFIX}${repo.name} Quality & Intelligence`); results.processed.push({ repository: name, pr_url: oc.pr_url, ...a }); + return true; } private async sendSummary(r: { processed: any[]; skipped: any[]; failed: any[] }) { diff --git a/ts/src/agents/intelligence_standardizer/instructions.md b/ts/src/agents/intelligence_standardizer/instructions.md index b3cefcf8..9613f2cd 100644 --- a/ts/src/agents/intelligence_standardizer/instructions.md +++ b/ts/src/agents/intelligence_standardizer/instructions.md @@ -8,7 +8,7 @@ Your mission is to ensure that every repository in the portfolio follows the "In 1. Having a comprehensive `AGENTS.md` file at the root. 2. Having a `.agents/` directory with `skills/`, `agents/`, `rules/`, and `workflows/` subdirectories. 3. Enforcing code quality standards (KISS, YAGNI, DRY, SRP). -4. Ensuring small, modular files (max 180 lines). +4. Ensuring the repository AGENTS.md stays short and specific (commands, constraints), linking to the global rules. 5. Ensuring the project is always in a "buildable" and "linted" state. ## Strategic Approach diff --git a/ts/src/agents/intelligence_standardizer/task-instructions.md b/ts/src/agents/intelligence_standardizer/task-instructions.md index 1563e47d..371ee29b 100644 --- a/ts/src/agents/intelligence_standardizer/task-instructions.md +++ b/ts/src/agents/intelligence_standardizer/task-instructions.md @@ -4,26 +4,19 @@ Implement the "Intelligence System" (AGENTS.md and .agents folder) into the repository. This is critical for agent-to-agent collaboration and long-term project maintainability. ## Structure 🏗️ -1. **Root**: Create an `AGENTS.md` file. Use the `github-assistance` AGENTS.md as a template for style, but tailor the content to the specific agents and personas of this project. -2. **Directory**: Create a `.agents/` directory with the following structure: - - `skills/`: Individual .md files for specific technical capabilities. - - `agents/`: Descriptions of the personas used. - - `rules/`: Project-specific constraints and global rules. - - `workflows/`: Step-by-step guides for common operations (e.g., /deploy, /test). +1. **Root**: Create a short `AGENTS.md`. Write only facts an agent would otherwise get wrong in this repository: + package manager, exact build/test/lint commands, deploy constraints, directories that must not be touched. + Do not restate generic advice ("follow best practices") and do not copy the global rules: link to them instead — + the owner's global instructions live at https://github.com/juninmd/skills/blob/master/.agents/AGENTS.md and the + skills at https://github.com/juninmd/skills. +2. **Directory**: Create a `.agents/` directory with `rules/` (project-specific constraints only) and, when useful, + `workflows/` (step-by-step guides for operations such as deploy or release). 3. **CI/CD**: Ensure the repository uses the centralized GitHub Actions from `juninmd/base-actions`. -## Core Principles 💎 -You MUST enforce these in all subsequent edits: -- **KISS (Keep It Simple, Stupid)**: Prioritize readability and simplicity. -- **YAGNI (You Aren't Gonna Need It)**: Do not add code for features that aren't currently required. -- **DRY (Don't Repeat Yourself)**: Eliminate redundancy. -- **SRP (Single Responsibility Principle)**: Each class/function should have one reason to change. -- **Max 180 lines per file**: If a file exceeds this, refactor it into smaller, logical modules. - ## Validation 🧪 -- After making a change, check for common development scripts: `lint`, `build`, `dev`. -- If they exist, run them to ensure the project stays healthy. -- If they don't exist, recommend creating them. +- Read the repository before writing: every command you document must exist (package.json scripts, Makefile, etc.). +- Run the existing lint/build/test scripts, if any, to ensure the project stays healthy. +- Change documentation and config only; never change application code in this task. {{#if missing_agents_md}} You are missing the root `AGENTS.md`. This is priority #1. @@ -59,7 +52,7 @@ jobs: {{#if missing_contributing}} You are missing `CONTRIBUTING.md`. - Create it based on standard practices. -- Include sections for: Getting Started, Development Environment, Code Style (ruff), and Testing (pytest). +- Include sections for: Getting Started, Development Environment, Code Style and Testing, using the repository's own stack and commands. {{/if}} {{#if missing_license}} diff --git a/ts/src/agents/interface_developer/instructions.md b/ts/src/agents/interface_developer/instructions.md index b57789e6..c58e0e0d 100644 --- a/ts/src/agents/interface_developer/instructions.md +++ b/ts/src/agents/interface_developer/instructions.md @@ -1,259 +1,10 @@ -# Interface Developer Agent Instructions +# Interface Developer (builder stage `ui`) ## Persona -You are a highly skilled Frontend/UI Developer with expertise in modern web technologies. -You are passionate about creating exceptional user experiences that are: -- Beautiful and intuitive -- Accessible to all users (WCAG 2.1 AA compliant) -- Performant and responsive -- Built with modern best practices - -### Technical Expertise - -**Frameworks & Libraries**: -- React, Vue, Angular and modern JavaScript frameworks -- TypeScript for type safety -- Next.js, Nuxt, SvelteKit for full-stack frameworks - -**Styling**: -- CSS3, Sass, Less -- Tailwind CSS, CSS-in-JS -- Styled Components, Emotion -- CSS Modules - -**Tools & Practices**: -- MCP Stitch for rapid UI prototyping -- Design systems and component libraries -- Storybook for component documentation -- Figma, Sketch for design collaboration - -**Focus Areas**: -- Accessibility (a11y) and WCAG compliance -- Internationalization (i18n) -- Performance optimization -- Responsive and mobile-first design -- Progressive Web Apps (PWA) +Front-end engineer that applies the owner's skills (frontend-engineering, accessibility) and the repository's AGENTS.md. ## Mission -Develop and enhance user interfaces for projects in the allowlist. - -### Primary Responsibilities - -1. Use MCP Stitch to rapidly prototype new UI features and screens -2. Implement pixel-perfect designs with accessibility in mind -3. Create reusable component libraries and design systems -4. Ensure all UI components are performant and responsive -5. Write comprehensive component documentation -6. Maintain design consistency across the application - -## UI Development Guidelines - -### Phase 1: Design with Stitch - -1. **Rapid Prototyping** - - Use MCP Stitch to generate interactive mockups - - Iterate quickly on design concepts - - Validate with stakeholders before implementation - -2. **Accessibility First** - - WCAG 2.1 AA compliance minimum - - Keyboard navigation support - - Screen reader optimization - - Color contrast verification - -3. **Responsive Design** - - Mobile-first approach - - Breakpoints: mobile (320px+), tablet (768px+), desktop (1024px+) - - Flexible layouts using Grid and Flexbox - - Touch-friendly interactions - -### Phase 2: Implementation - -1. **Component Development** - - Use project's framework (React/Vue/Angular) - - TypeScript for type safety - - Follow atomic design principles - - Create self-contained, reusable components - -2. **Code Quality** - - Clean, maintainable code - - Proper separation of concerns - - Avoid inline styles (use CSS modules or styled components) - - Follow project's coding conventions - -3. **Testing** - - Unit tests for component logic - - Accessibility tests (jest-axe, pa11y) - - Visual regression tests (Percy, Chromatic) - - E2E tests for critical user flows - -### Phase 3: Optimization - -1. **Performance** - - Code splitting and lazy loading - - Image optimization (WebP, AVIF) - - Bundle size optimization - - Critical CSS extraction - - Minimize render-blocking resources - -2. **Accessibility Audit** - - Lighthouse accessibility score: 95+ - - Manual keyboard navigation testing - - Screen reader testing (NVDA, JAWS, VoiceOver) - - ARIA labels and landmarks - -3. **Cross-browser Testing** - - Chrome, Firefox, Safari, Edge - - Mobile browsers (iOS Safari, Chrome Mobile) - - Progressive enhancement approach - -### Phase 4: Documentation - -1. **Component Documentation** - - Create/Update DESIGN.md with: - - Component library overview - - Design tokens (colors, spacing, typography) - - Usage examples and best practices - - Accessibility guidelines - -2. **Code Documentation** - - JSDoc comments for props and events - - Storybook stories for each component - - README for component folders - -3. **Design System** - - Document design patterns - - Color palettes and themes - - Typography scale - - Spacing system - - Icon library - -## Task Instructions Template - -When creating an opencode task for UI development: - -```markdown -# Task: UI Enhancement with MCP Stitch - -## Repository: {repository} -Language: {language} - -## Identified Improvements -{improvements_list} - -## Development Instructions - -### Phase 1: Design with Stitch -1. Use MCP Stitch to rapidly prototype UI improvements -2. Generate interactive mockups for new/updated components -3. Iterate on designs based on best practices: - - Accessibility (WCAG 2.1 AA) - - Responsive design (mobile-first) - - Performance (lazy loading, optimized assets) - - Modern design patterns - -### Phase 2: Implementation -1. Convert Stitch prototypes into production-ready components -2. Use appropriate framework (React/Vue/Angular based on project) -3. Implement with TypeScript for type safety -4. Follow project's existing design system or create one if missing -5. Add comprehensive component documentation -6. Include unit tests for all components - -### Phase 3: Polish -1. Ensure all components are accessible: - - Proper ARIA labels - - Keyboard navigation - - Screen reader support -2. Optimize performance: - - Code splitting - - Lazy loading - - Image optimization -3. Add Storybook/component showcase if not present - -### Phase 4: Documentation -1. Update/Create DESIGN.md with: - - Component library overview - - Design tokens (colors, spacing, typography) - - Usage examples - - Accessibility guidelines -2. Add inline JSDoc comments -3. Create README for component folder if needed - -## Success Criteria -- All UI improvements implemented and tested -- Accessibility score of 95+ on Lighthouse -- Performance score of 90+ on Lighthouse -- Clear documentation for future developers -- PR with screenshots/videos of changes - -Create a PR with all improvements and detailed description. -``` - -## UI Analysis Criteria - -When analyzing repositories for UI needs: - -1. **Technology Detection** - - Identify frontend framework (React, Vue, Angular, etc.) - - Check for TypeScript usage - - Review existing component structure - - Assess design system maturity - -2. **Issue Identification** - - UI/UX related issues - - Accessibility complaints - - Performance problems - - Mobile responsiveness issues - - Design inconsistencies - -3. **Documentation Gaps** - - Missing DESIGN.md - - Lack of component documentation - - No design system guidelines - - Missing Storybook or component showcase - -4. **Improvement Opportunities** - - Outdated UI patterns - - Accessibility violations - - Performance bottlenecks - - Missing responsive breakpoints - - Inconsistent styling - -## Best Practices - -1. **Accessibility is Non-Negotiable**: Every component must be keyboard accessible and screen reader friendly -2. **Performance Matters**: 90+ Lighthouse score should be the baseline -3. **Mobile First**: Design for mobile, enhance for desktop -4. **Component Reusability**: Build once, use everywhere -5. **Document Everything**: Future developers will thank you -6. **Test Thoroughly**: Unit, integration, visual, and accessibility tests -7. **Stay Current**: Use modern CSS features, latest framework patterns -8. **Design Systems**: Consistency through systematic approach -9. **Progressive Enhancement**: Work for everyone, enhance for capable browsers -10. **User Feedback**: Incorporate real user testing and feedback - -## Common UI Patterns - -### Accessible Components -- Modals with focus trap and Esc key handler -- Dropdowns with keyboard navigation -- Forms with clear labels and error messages -- Buttons with loading and disabled states -- Toast notifications with ARIA live regions - -### Performance Patterns -- Virtualized lists for large datasets -- Lazy loading images with intersection observer -- Code splitting by route -- Debounced search inputs -- Optimized re-renders with React.memo/Vue computed - -### Responsive Patterns -- Flexible grid layouts -- Responsive typography (clamp, fluid type) -- Mobile navigation patterns (drawer, bottom nav) -- Adaptive component rendering -- Touch-friendly interaction areas (44x44px minimum) +On front-end repositories, turn open UI/UX issues and a missing `DESIGN.md` into one tracked issue and one opencode PR +(draft, `keep-draft`). Changes must not break existing behavior; keyboard, screen reader and contrast count as part of done. diff --git a/ts/src/agents/opencode/local.ts b/ts/src/agents/opencode/local.ts index bf2741cd..6b7409c4 100644 --- a/ts/src/agents/opencode/local.ts +++ b/ts/src/agents/opencode/local.ts @@ -10,6 +10,8 @@ import { run, type RunResult } from "../../utils/proc.ts"; import { scanClone } from "../../utils/secret-scan.ts"; import { authConfigArgs, githubCloneUrl, redactSecrets, scrubEnv } from "../../utils/secure-git.ts"; import type { GithubClient } from "../../github/client.ts"; +import { ensureContract } from "../core/agent-contract.ts"; +import { createAgentPull, DEFAULT_PR_OPTIONS, type PrOptions } from "../core/pr-options.ts"; const OPENCODE_TIMEOUT_MS = 1_200_000, GIT_TIMEOUT_MS = 300_000; type Log = (m: string, level?: string) => void; @@ -27,11 +29,12 @@ async function git(args: string[], cwd: string): Promise { const result = (status: string, repository: string, extra: Record = {}) => ({ status, task_url: null, task_id: null, engine: "opencode-local", repository, ...extra }); /** `task_created` when a PR is opened; otherwise `no_changes` or a failure reason. */ -export async function runOpencodeTask(o: { githubClient: GithubClient; repository: string; instructions: string; title: string; baseBranch: string; log: Log; agentName?: string }): Promise> { +export async function runOpencodeTask(o: { githubClient: GithubClient; repository: string; instructions: string; title: string; baseBranch: string; log: Log; agentName?: string; prOptions?: PrOptions }): Promise> { const { githubClient, repository, instructions, title, baseBranch, log } = o, agentName = o.agentName ?? "github-assistance"; const token = process.env.GITHUB_TOKEN || process.env.GH_PAT || ""; if (!token) return result("failed", repository, { error: "missing GITHUB_TOKEN" }); const branch = `opencode/${slugify(title)}`; + await ensureContract(log); const tmp = mkdtempSync(join(tmpdir(), "oc-")); let usedModel = ""; try { @@ -77,7 +80,7 @@ export async function runOpencodeTask(o: { githubClient: GithubClient; repositor } finally { rmSync(tmp, { recursive: true, force: true }); } try { - const pr = await githubClient.createPull(repository, { title, body: buildPrBody(agentName, title, instructions, usedModel), head: branch, base: baseBranch }); + const pr = await createAgentPull(githubClient, repository, { title, body: buildPrBody(agentName, title, instructions, usedModel), head: branch, base: baseBranch }, o.prOptions ?? DEFAULT_PR_OPTIONS, log); await assignOwner(githubClient, pr, undefined, log); await requestReviewOwner(githubClient, pr, undefined, log); log(`Opened PR #${pr.number} for ${repository} via opencode`, "INFO"); diff --git a/ts/src/agents/opencode/runner.ts b/ts/src/agents/opencode/runner.ts index fc93cf9c..6c98cfc5 100644 --- a/ts/src/agents/opencode/runner.ts +++ b/ts/src/agents/opencode/runner.ts @@ -13,6 +13,8 @@ import { authConfigArgs, githubCloneUrl, scrubEnv } from "../../utils/secure-git import type { RepositoryAllowlist } from "../../config/allowlist.ts"; import type { GithubClient } from "../../github/client.ts"; import { TelegramNotifier } from "../../notifications/telegram.ts"; +import { ensureContract } from "../core/agent-contract.ts"; +import { createAgentPull, DEFAULT_PR_OPTIONS, type PrOptions } from "../core/pr-options.ts"; type Log = (m: string, level?: string) => void; const envInt = (n: string, d: number, min = 1) => { const v = parseInt(process.env[n] ?? "", 10); return Number.isNaN(v) ? d : Math.max(min, v); }; @@ -66,12 +68,13 @@ export class OpencodeRunner { return this.telegram.sendMessage(text); } - async runOnRepo(repository: string, instructions: string, title: string, agentName = "agent"): Promise> { + async runOnRepo(repository: string, instructions: string, title: string, agentName = "agent", prOptions: PrOptions = DEFAULT_PR_OPTIONS): Promise> { if (!this.allowlist.isAllowed(repository)) throw new Error(`opencode denied: Repository ${repository} is not in allowlist`); const model = await this.getPreferredOrRandomFreeOpencodeModel(); const stamp = new Date().toISOString().replace(/\D/g, "").slice(0, 12); const branch = "agent/" + title.toLowerCase().replace(/[^a-z0-9-]/g, "-").slice(0, 60) + "-" + stamp; await this.audit("🚀", "iniciando", repository, title); + await ensureContract(this.log); const tmp = mkdtempSync(join(tmpdir(), "oc-")); let runResult: RunResult | null = null, usedModel = model; try { @@ -113,15 +116,15 @@ export class OpencodeRunner { }); if (outcome) return outcome; } finally { rmSync(tmp, { recursive: true, force: true }); } - const prUrl = await this.openPullRequest(repository, branch, title, (runResult as RunResult | null)?.stdout ?? "", agentName, usedModel); + const prUrl = await this.openPullRequest(repository, branch, title, (runResult as RunResult | null)?.stdout ?? "", agentName, usedModel, prOptions); this.log(`[${title}] PR opened: ${prUrl}`); await this.audit("✅", "pr_aberto", repository, title, prUrl); return { status: "success", branch, pr_url: prUrl, model: usedModel, agent: agentName }; } - async openPullRequest(repository: string, branch: string, title: string, output: string, agentName = "agent", model = "opencode"): Promise { + async openPullRequest(repository: string, branch: string, title: string, output: string, agentName = "agent", model = "opencode", prOptions: PrOptions = DEFAULT_PR_OPTIONS): Promise { const repo = await this.gh.getRepo(repository); - const pr = await this.gh.createPull(repository, { title: `[agent/${agentName}] ${title}`, body: buildPrBody(agentName, title, redactText(output), model), head: branch, base: repo.default_branch }); + const pr = await createAgentPull(this.gh, repository, { title: `[agent/${agentName}] ${title}`, body: buildPrBody(agentName, title, redactText(output), model), head: branch, base: repo.default_branch }, prOptions, this.log); await assignOwner(this.gh, pr, this.targetOwner, this.log); await requestReviewOwner(this.gh, pr, this.targetOwner, this.log); return pr.html_url; diff --git a/ts/src/agents/pr_assistant/agent.ts b/ts/src/agents/pr_assistant/agent.ts index a4efcd65..d6555c2a 100644 --- a/ts/src/agents/pr_assistant/agent.ts +++ b/ts/src/agents/pr_assistant/agent.ts @@ -20,6 +20,7 @@ import { enabled as flagEnabled } from "./review-flags.ts"; import { botAuthActive, botLogin } from "../../github/bot-auth.ts"; import { reviewerLogins } from "./bot-identity.ts"; import { clearManualConflictLabel, handleConflict, type Resolver } from "./conflict-flow.ts"; +import { hasLabel, KEEP_DRAFT_LABEL } from "../core/pr-options.ts"; import { resolveConflictsAutonomously } from "./conflict-resolver.ts"; import { laneAllowsMerge } from "./dependency-lane.ts"; import { runLocalChecks, type LocalChecks } from "./local-checks.ts"; @@ -124,6 +125,11 @@ export class PRAssistantAgent extends BaseAgent { const [status, comments] = await Promise.all([checkPipelineStatus(this.githubClient, pr), this.githubClient.getIssueComments(repo, pr.number)]); const cmds = ownerCommands(comments, this.targetOwner); if (cmds.hold) { this.recordSkip(results, pr.number, pr.title, repo, "owner_hold"); return; } + // Builder PRs: reviewed like any other, but never marked ready nor merged by the bot (not even on `/merge`). + if (hasLabel(pr, KEEP_DRAFT_LABEL)) { + if (!this.simulationMode) await this.reviews.runOpencodeReview(pr, comments, { force: this.reviewForced(cmds, comments) }); + this.recordSkip(results, pr.number, pr.title, repo, "keep_draft"); return; + } if (status.no_ci) await this.tagNoCi(pr); await this.tryAcceptSuggestions(pr); await this.warnExposedSecrets(pr, comments); diff --git a/ts/src/agents/pr_assistant/agents-md-gate.ts b/ts/src/agents/pr_assistant/agents-md-gate.ts index 0a1178cc..6c127587 100644 --- a/ts/src/agents/pr_assistant/agents-md-gate.ts +++ b/ts/src/agents/pr_assistant/agents-md-gate.ts @@ -2,7 +2,7 @@ import type { GithubClient, PR } from "../../github/client.ts"; export const AGENTS_MD_MARKER = ""; -const BODY = `${AGENTS_MD_MARKER}\n## 🚫 AGENTS.md ausente\n\nEste repositório não tem \`AGENTS.md\` na raiz, que é obrigatório. O bot **não aprova nem mescla** este PR até o arquivo existir (o agente \`intelligence-standardizer\` abre um PR para criá-lo).`; +const BODY = `${AGENTS_MD_MARKER}\n## 🚫 AGENTS.md ausente\n\nEste repositório não tem \`AGENTS.md\` na raiz, que é obrigatório. O bot **não aprova nem mescla** este PR até o arquivo existir (o agente \`repo-standards\` abre um PR para criá-lo).`; /** Checks the default branch. missing = definitely absent; unknown = API error (fail closed, retried next round). */ export async function agentsMdState(gh: Pick, repo: string): Promise<"present" | "missing" | "unknown"> { diff --git a/ts/src/agents/pr_assistant/conflict-flow.ts b/ts/src/agents/pr_assistant/conflict-flow.ts index 7d8ea5ba..1686e817 100644 --- a/ts/src/agents/pr_assistant/conflict-flow.ts +++ b/ts/src/agents/pr_assistant/conflict-flow.ts @@ -4,7 +4,7 @@ * cleared as soon as the PR is mergeable again. */ import type { GithubClient, PR } from "../../github/client.ts"; -import { sendManualNotice } from "../conflict_resolver/notifications.ts"; +import { sendManualNotice } from "./conflict-notifications.ts"; import { isDependabot, requestDependabotRebase } from "./dependency-lane.ts"; import { withPrLock } from "./pr-lock.ts"; diff --git a/ts/src/agents/pr_assistant/conflict-notifications.ts b/ts/src/agents/pr_assistant/conflict-notifications.ts new file mode 100644 index 00000000..20b1f313 --- /dev/null +++ b/ts/src/agents/pr_assistant/conflict-notifications.ts @@ -0,0 +1,9 @@ +/** Telegram notice when a PR conflict needs a human (best-effort). */ +import type { TelegramNotifier } from "../../notifications/telegram.ts"; +import { card, esc, prButton } from "../../notifications/telegram-format.ts"; + +type Tg = Pick; +export async function sendManualNotice(tg: Tg, pr: any, error: string): Promise { + const text = card("🚫", "CONFLITO: RESOLUÇÃO MANUAL NECESSÁRIA", pr, ["ℹ️ O PR continua aberto e foi marcado com needs-manual-conflict-resolution.", `
${esc(error.slice(0, 300))}
`]); + try { await tg.sendMessage(text, "HTML", prButton(pr)); } catch { /* best-effort */ } +} diff --git a/ts/src/agents/pr_assistant/review-gate.ts b/ts/src/agents/pr_assistant/review-gate.ts index 14d99d63..8c3df00a 100644 --- a/ts/src/agents/pr_assistant/review-gate.ts +++ b/ts/src/agents/pr_assistant/review-gate.ts @@ -1,6 +1,7 @@ /** Draft + commit-status gate for critical review findings (best-effort; never throws into the run). */ import type { GithubClient, PR } from "../../github/client.ts"; import { GATE_NAME, LABEL_CRITICAL, blocks, isApproved, type ReviewVerdict } from "./review-verdict.ts"; +import { hasLabel, KEEP_DRAFT_LABEL } from "../core/pr-options.ts"; const CRITICAL_COLOR = "b60205"; export const gateEnabled = () => ["1", "true", "yes", "on"].includes((process.env.REVIEW_GATE_ENABLED ?? "true").toLowerCase()); @@ -22,7 +23,8 @@ export async function applyGate(pr: PR, gh: GithubClient, verdict: ReviewVerdict await bestEffort(() => status("failure", "Achados críticos — corrija antes do merge."), log, "status"); } else if (isApproved(verdict)) { await bestEffort(() => status("success", "Revisão aprovada."), log, "status"); - if (pr.draft) await bestEffort(() => gh.setDraft(pr, false), log, "mark_ready"); + // `keep-draft` (builder PRs): the owner alone decides when it leaves draft. + if (pr.draft && !hasLabel(pr, KEEP_DRAFT_LABEL)) await bestEffort(() => gh.setDraft(pr, false), log, "mark_ready"); await bestEffort(() => gh.removeLabel(pr, LABEL_CRITICAL), log, "unlabel"); } } diff --git a/ts/src/agents/pr_assistant/review-workspace.ts b/ts/src/agents/pr_assistant/review-workspace.ts index 5a90477f..ee1b1b6c 100644 --- a/ts/src/agents/pr_assistant/review-workspace.ts +++ b/ts/src/agents/pr_assistant/review-workspace.ts @@ -6,6 +6,7 @@ import { DEFAULT_LITELLM_API_BASE } from "../../config/settings.ts"; import { recordTrace } from "../../insight/cost.ts"; import { availableSkills, harnessVersion, parseEvents, type RunTrace } from "../opencode/trace.ts"; import * as tokenix from "../../utils/tokenix.ts"; +import { contractLabel, ensureContract } from "../core/agent-contract.ts"; import { getLogger } from "../../utils/logger.ts"; import { run } from "../../utils/proc.ts"; import { freeExhausted, isFreeModel, isFreeQuotaError, markFreeExhausted } from "./review-models.ts"; @@ -94,6 +95,7 @@ export async function runOpencode(cloneDir: string, prompt: string, model: strin if (left < 30) { log.warning(`opencode skipped (${model}): review deadline reached`); return null; } timeoutSec = Math.min(timeoutSec, left); if (isFreeModel(model) && freeExhausted()) return null; // account quota already spent: don't pay a doomed call per model + await ensureContract((m, level) => (level === "WARNING" ? log.warning(m) : log.info(m))); try { result = await tokenix.session(cloneDir, async (ready) => { on = ready; @@ -105,7 +107,8 @@ export async function runOpencode(cloneDir: string, prompt: string, model: strin if (result.code !== 0) { log.warning(`opencode exit ${result.code}${result.timedOut ? " (timeout)" : ""} (${model}): ${brief(result.stderr || result.stdout)}`); return null; } const [text, facts] = parseEvents(result.stdout); const version = await harnessVersion(opencodeCmd()); - lastTraceValue = { harness: `opencode ${version}`.trim() + tokenix.harnessSuffix(on), model, skills_available: availableSkills([cloneDir]), ...facts }; + const skills = contractLabel(); + lastTraceValue = { harness: `opencode ${version}`.trim() + tokenix.harnessSuffix(on) + (skills ? ` + ${skills}` : ""), model, skills_available: availableSkills([cloneDir]), ...facts }; recordTrace(lastTraceValue); return text; } diff --git a/ts/src/agents/pr_sla/agent.ts b/ts/src/agents/pr_sla/agent.ts index 712feeff..2cecde1f 100644 --- a/ts/src/agents/pr_sla/agent.ts +++ b/ts/src/agents/pr_sla/agent.ts @@ -8,7 +8,9 @@ const nudgeComment = (hours: number) => `⏱️ **SLA Alert — revisão pendente**\n\nEste pull request está sem atualização há **${hours}h** e ultrapassou o SLA de 24h.\n\nPor favor, um dos revisores avalie ou deixe um comentário com o status.\n\n${buildOriginMetadata("pr_sla", "N/A (regra determinística)")}`; export class PRSLAAgent extends BaseAgent { - constructor(o: AgentOpts) { super("pr_sla", o); } + /** False inside flow-watch: stale PRs are reported on Telegram, not nudged with PR comments. */ + nudgeEnabled: boolean; + constructor(o: AgentOpts) { super("pr_sla", o); this.nudgeEnabled = o.nudge ?? true; } get persona() { return this.getInstructionsSection("## Persona"); } get mission() { return this.getInstructionsSection("## Mission"); } @@ -27,7 +29,7 @@ export class PRSLAAgent extends BaseAgent { if (last < threshold) { const hours = Math.floor((Date.now() - last) / 3600_000); stale.push({ repo: pr.base.repo.full_name, number: String(pr.number), title: pr.title, url: pr.html_url, hours_without_update: String(hours) }); - const url = await this.nudge(pr, hours); + const url = this.nudgeEnabled ? await this.nudge(pr, hours) : null; if (url) nudged.push(url); } } catch (e: any) { this.log(`Failed to inspect PR SLA: ${e?.message ?? e}`, "WARNING"); } diff --git a/ts/src/agents/product_manager/instructions.md b/ts/src/agents/product_manager/instructions.md index d6d6705c..12c7aa87 100644 --- a/ts/src/agents/product_manager/instructions.md +++ b/ts/src/agents/product_manager/instructions.md @@ -1,146 +1,10 @@ -# Product Manager Agent Instructions +# Product Manager (builder stage `plan`) ## Persona -You are an experienced Product Manager with a strong technical background. -You think strategically about product development, user needs, and business value. - -### Core Competencies - -- Breaking down complex product visions into actionable roadmaps -- Prioritizing features based on impact and effort -- Writing clear, detailed product requirements -- Understanding technical constraints and opportunities -- Balancing innovation with practical delivery - -### Communication Style - -You communicate clearly and focus on outcomes, not just outputs. +Product lead that turns a repository's open issues into a short, prioritized roadmap. ## Mission -Create and maintain product roadmaps for each repository in the allowlist. - -### Primary Responsibilities - -1. Analyze repository goals, existing issues, and user feedback -2. Prioritize features based on business value and technical feasibility -3. Generate detailed roadmap documents (ROADMAP.md) that guide development -4. Ensure all planned work aligns with the project's vision -5. Provide clear value propositions for each feature - -## Roadmap Creation Guidelines - -When creating a ROADMAP.md file, include: - -### 1. Vision & Goals -- Clear articulation of the project's purpose -- Long-term objectives and success criteria - -### 2. Current Status -- Where the project is now -- Recent achievements and milestones - -### 3. Quarterly Roadmap -Organize by quarters (Q1, Q2, Q3, Q4): - -**High Priority** (Critical items): -- Security fixes -- Critical bugs -- Must-have features for upcoming releases - -**Medium Priority** (Important enhancements): -- Feature enhancements -- User experience improvements -- Performance optimizations - -**Low Priority** (Nice to have): -- Technical debt reduction -- Code refactoring -- Documentation improvements - -### 4. Feature Details - -For each major feature, document: -- **User Value Proposition**: Why this matters to users -- **Technical Approach**: High-level implementation strategy -- **Success Criteria**: How we measure success -- **Estimated Effort**: Small (1-3 days) / Medium (1-2 weeks) / Large (2+ weeks) -- **Dependencies**: What needs to be done first -- **Risks**: Potential blockers or concerns - -### 5. Reference GitHub Issues - -- Link to specific issues when available -- Use format: `Closes #123` or `Relates to #456` -- Keep roadmap aligned with issue tracker - -## Task Instructions Template - -When creating an opencode task for roadmap generation: - -```markdown -# Task: Create/Update Product Roadmap - -## Repository Information -- Name: {repository} -- Description: {description} -- Primary Language: {language} -- Total Open Issues: {count} - -## Current Priorities -{priority_breakdown} - -## Instructions - -Create or update a `ROADMAP.md` file in the repository root with: - -1. **Vision & Goals** - Clear articulation of the project's purpose and goals -2. **Current Status** - Where the project is now -3. **Quarterly Roadmap** - Organized by quarters (Q1, Q2, Q3, Q4) - - High priority items (bugs, critical features) - - Medium priority items (enhancements, improvements) - - Low priority items (technical debt, optimizations) -4. **Feature Details** - For each major feature: - - User value proposition - - Technical approach (high-level) - - Success criteria - - Estimated effort (Small/Medium/Large) -5. **Dependencies & Risks** - Any blockers or concerns - -Use GitHub issues as reference where possible. Link to specific issues in the roadmap. -Keep the roadmap practical and achievable. Focus on incremental value delivery. - -Create a PR with the roadmap and request review. -``` - -## Analysis Criteria - -When analyzing repositories: - -1. **Issue Categorization** - - Bugs: Items with labels `bug`, `defect` - - Features: Items with labels `feature`, `enhancement` - - Technical Debt: Items with labels `tech-debt`, `refactor` - -2. **Priority Assessment** - - Consider issue age and activity - - Evaluate user impact - - Assess technical complexity - - Review community feedback - -3. **Roadmap Alignment** - - Ensure features support project goals - - Balance quick wins with strategic initiatives - - Consider resource availability - - Maintain realistic timelines - -## Best Practices - -1. **Be Data-Driven**: Use metrics and user feedback to inform decisions -2. **Stay Focused**: Prioritize ruthlessly - say no to avoid scope creep -3. **Communicate Clearly**: Write for both technical and non-technical audiences -4. **Iterate Regularly**: Update roadmaps based on progress and feedback -5. **Think Long-term**: Balance immediate needs with strategic vision -6. **Enable Teams**: Provide clear direction while allowing autonomy -7. **Measure Success**: Define clear metrics for each initiative +Keep `ROADMAP.md` current for each allowed repository (skipped while it is up to date) through an opencode PR +(draft, `keep-draft`). Priorities come from real issues and the repository description, never invented features. diff --git a/ts/src/agents/registry.ts b/ts/src/agents/registry.ts index 8306d615..a3a3858f 100644 --- a/ts/src/agents/registry.ts +++ b/ts/src/agents/registry.ts @@ -5,7 +5,7 @@ import { RepositoryAllowlist } from "../config/allowlist.ts"; import { DEFAULT_MODELS, type Settings } from "../config/settings.ts"; import { GithubClient } from "../github/client.ts"; import { TelegramNotifier } from "../notifications/telegram.ts"; -import { agentNames, AGENTS_BY_NAME } from "./catalog.ts"; +import { agentNames, AGENTS_BY_NAME, resolveAgentName } from "./catalog.ts"; import { agentDir } from "./core/utils.ts"; import type { BaseAgent } from "./base-agent.ts"; @@ -39,19 +39,22 @@ export const isPorted = (name: string) => existsSync(join(agentDir(name), "agent export type AgentCtor = new (o: Record) => BaseAgent; export async function createAgent(name: string, s: Settings, o: { provider?: string; model?: string; prRef?: string } = {}): Promise { - const spec = AGENTS_BY_NAME.get(name); - if (!spec) throw new Error(`unknown agent: ${name}`); - if (!isPorted(name)) throw new Error(`agent '${name}' ainda não foi portado para Bun`); - const mod = await import(join(agentDir(name), "agent.ts")); + const target = resolveAgentName(name); + const spec = target ? AGENTS_BY_NAME.get(target.agent) : undefined; + if (!target || !spec) throw new Error(`unknown agent: ${name}`); + const agent = target.agent, stage = spec.stages.find((st) => st.name === target.stage); + if (!isPorted(agent)) throw new Error(`agent '${agent}' ainda não foi portado para Bun`); + const mod = await import(join(agentDir(agent), "agent.ts")); const Cls: AgentCtor = mod[spec.className]; - if (!Cls) throw new Error(`${spec.className} not exported by agents/${name}/agent.ts`); + if (!Cls) throw new Error(`${spec.className} not exported by agents/${agent}/agent.ts`); const kwargs: Record = { ...createBaseDeps(s), targetOwner: s.githubOwner }; kwargs.telegram = new TelegramNotifier(s.telegramBotToken, s.telegramChatId, `[${name.replace(/-/g, " ").toUpperCase()}]`); - if (AGENTS_WITH_AI.has(name)) { - if (!s.enableAi) throw new Error(`Agent '${name}' requires AI but ENABLE_AI is false.`); - kwargs.ai = buildAiConfig(s, o.provider, o.model); - } - if (name === "pr-assistant") Object.assign(kwargs, { commentAiEnabled: s.enableAi, simulationMode: s.simulationMode, autonomyPolicyPath: s.autonomyPolicyPath, settings: s }); - if (AGENTS_WITH_PR_REF.has(name) && o.prRef) kwargs.prRef = o.prRef; + const needsAi = AGENTS_WITH_AI.has(agent) || !!stage?.requiresAi; + if (needsAi && !s.enableAi) throw new Error(`Agent '${name}' requires AI but ENABLE_AI is false.`); + // A composite with an optional AI stage (secret-guard) gets the client only when AI is on; the stage is skipped otherwise. + if (needsAi || (s.enableAi && spec.stages.some((st) => st.requiresAi))) kwargs.ai = buildAiConfig(s, o.provider, o.model); + if (stage) kwargs.stage = stage.name; + if (agent === "pr-assistant") Object.assign(kwargs, { commentAiEnabled: s.enableAi, simulationMode: s.simulationMode, autonomyPolicyPath: s.autonomyPolicyPath, settings: s }); + if (AGENTS_WITH_PR_REF.has(agent) && o.prRef) kwargs.prRef = o.prRef; return new Cls(kwargs); } diff --git a/ts/src/agents/repo_standards/agent.ts b/ts/src/agents/repo_standards/agent.ts new file mode 100644 index 00000000..20cd9df5 --- /dev/null +++ b/ts/src/agents/repo_standards/agent.ts @@ -0,0 +1,7 @@ +/** Repo Standards - AGENTS.md, .agents/ and README kept short, specific and present in every active repository. */ +import type { AgentOpts } from "../agent-types.ts"; +import { CompositeAgent } from "../core/composite.ts"; + +export class RepoStandardsAgent extends CompositeAgent { + constructor(o: AgentOpts) { super("repo-standards", o); } +} diff --git a/ts/src/agents/repo_standards/instructions.md b/ts/src/agents/repo_standards/instructions.md new file mode 100644 index 00000000..065a2d78 --- /dev/null +++ b/ts/src/agents/repo_standards/instructions.md @@ -0,0 +1,12 @@ +# Repo Standards + +## Persona + +Keeper of each repository's agent and human entry points. + +## Mission + +1. `agents-md`: every active repository (not archived, not a fork) has a short, specific `AGENTS.md` + and `.agents/`. The PR Assistant refuses to merge without `AGENTS.md`, so missing files come first. +2. `readme`: missing, old or low-scoring READMEs are rewritten. +One open PR per repository at a time; a capped number of PRs per run. diff --git a/ts/src/agents/secret_guard/agent.ts b/ts/src/agents/secret_guard/agent.ts new file mode 100644 index 00000000..a06b8212 --- /dev/null +++ b/ts/src/agents/secret_guard/agent.ts @@ -0,0 +1,24 @@ +/** Secret Guard - scan the portfolio, classify findings, rewrite history only after the owner's explicit approval. */ +import type { AgentOpts } from "../agent-types.ts"; +import type { StageSpec } from "../catalog.ts"; +import { CompositeAgent } from "../core/composite.ts"; +import { saveResults } from "../core/reporting.ts"; + +type Result = Record; + +export class SecretGuardAgent extends CompositeAgent { + private scan: Result | null = null; + constructor(o: AgentOpts) { super("secret-guard", o); } + + protected skipReason(stage: StageSpec, done: Record): string | null { + if (stage.name === "remove" && done.scan && ("error" in done.scan || done.scan.status === "failed")) return "scan failed"; + return super.skipReason(stage, done); + } + protected stageOptions(stage: StageSpec) { return stage.name === "remove" && this.scan ? { scanResults: this.scan } : {}; } + protected afterStage(stage: StageSpec, r: Result): void { + if (stage.name !== "scan" || "error" in r) return; + this.scan = r; + // Keeps `run-agent secret-remover` (former name) working from the latest scan file. + try { saveResults("security-scanner", r); } catch (e: any) { this.log(`could not save scan results: ${e?.message ?? e}`, "WARNING"); } + } +} diff --git a/ts/src/agents/secret_guard/instructions.md b/ts/src/agents/secret_guard/instructions.md new file mode 100644 index 00000000..2b61d816 --- /dev/null +++ b/ts/src/agents/secret_guard/instructions.md @@ -0,0 +1,12 @@ +# Secret Guard + +## Persona + +Security guard of the portfolio. Conservative: when in doubt, it does not touch history. + +## Mission + +1. `scan`: gitleaks on every repository of the owner (read-only) and the no-cron-workflow policy. +2. `remove`: classify each finding with AI. False positives go to the gitleaks allowlist (PR). + Real secrets are removed from git history **only after the owner approves**: a Telegram button press + or an owner `/aprovar` comment on the approval issue. Without approval nothing is rewritten. diff --git a/ts/src/agents/secret_remover/agent.ts b/ts/src/agents/secret_remover/agent.ts index c57285d5..25eea908 100644 --- a/ts/src/agents/secret_remover/agent.ts +++ b/ts/src/agents/secret_remover/agent.ts @@ -2,6 +2,7 @@ import { BaseAgent } from "../base-agent.ts"; import { makeAi, type AgentOpts } from "../agent-types.ts"; import { FindingProcessor } from "./processor.ts"; +import { ApprovalGate, TelegramApprovals } from "./approval.ts"; import { findLatestResults } from "./utils.ts"; import { sendErrorNotification } from "./telegram-summary.ts"; import { TelegramNotifier } from "../../notifications/telegram.ts"; @@ -11,23 +12,31 @@ const MAX_FINDINGS_PER_RUN = 300; // guard against runaway AI calls export class SecretRemoverAgent extends BaseAgent { processor: FindingProcessor; + private scanResults: Record | null; + private telegramApprovals: { poll(): Promise> }; + private approved = new Set(); constructor(o: AgentOpts) { super("secret_remover", { ...o, enforceRepositoryAllowlist: false }); const ai = { ...o.ai, provider: process.env.SECRET_REMOVER_AI_PROVIDER ?? o.ai?.provider, model: process.env.SECRET_REMOVER_AI_MODEL ?? o.ai?.model }; - this.processor = new FindingProcessor(o.aiClient ?? makeAi(ai).client, this.telegram, this.githubClient, this.log); + this.scanResults = o.scanResults ?? null; + const approvers = (process.env.TELEGRAM_APPROVER_IDS ?? "").split(",").map((x) => x.trim()).filter(Boolean); + this.telegramApprovals = o.telegramApprovals ?? new TelegramApprovals(this.telegram.botToken, this.telegram.chatId, approvers, this.log); + const gate = new ApprovalGate(this.githubClient, this.telegram, this.targetOwner, this.approved, this.log); + this.processor = new FindingProcessor(o.aiClient ?? makeAi(ai).client, this.telegram, this.githubClient, this.log, o.approvalGate === undefined ? gate : o.approvalGate); } get persona() { return this.getInstructionsSection("## Persona"); } get mission() { return this.getInstructionsSection("## Mission"); } async run() { this.log("Starting Secret Remover workflow"); - const latest = findLatestResults(this.log, RESULTS_GLOB); + const latest = this.scanResults ?? findLatestResults(this.log, RESULTS_GLOB); if (!latest) { const msg = "No security scanner results found in results/."; this.log(msg, "ERROR"); await sendErrorNotification(this.telegram, this.targetOwner, msg); return { error: msg }; } const repos: any[] = latest.repositories_with_findings ?? []; + if (repos.length) for (const id of await this.telegramApprovals.poll()) this.approved.add(id); this.log(`Processing ${repos.length} repositories with findings`); const actions: any[] = [], errors: any[] = []; let count = 0; diff --git a/ts/src/agents/secret_remover/approval.ts b/ts/src/agents/secret_remover/approval.ts new file mode 100644 index 00000000..d0d43d55 --- /dev/null +++ b/ts/src/agents/secret_remover/approval.ts @@ -0,0 +1,111 @@ +/** + * Owner approval for git history rewrites (irreversible): a Telegram button press or an owner `/aprovar` comment on + * the approval issue. Fail-closed: any error means "not approved". The approval is bound to the exact set of findings. + */ +import { createHash } from "node:crypto"; +import type { GithubClient } from "../../github/client.ts"; +import { TelegramNotifier } from "../../notifications/telegram.ts"; + +type Log = (m: string, level?: string) => void; +export const APPROVAL_LABEL = "secret-guard"; +export const APPROVE_RE = /^\s*\/aprovar\b/i; +const CALLBACK_RE = /^sg:([0-9a-f]{10})$/; +const marker = (id: string) => ``; +const telegramMarker = (id: string) => ``; +const esc = TelegramNotifier.escapeHtml; + +export type Finding = Record; +export type Approval = { approved: boolean; via: "github" | "telegram" | null; issue: number | null }; + +const findingKey = (f: Finding) => [f.rule_id ?? f.RuleID ?? "", f.file ?? "", f.line ?? "", f.commit ?? ""].join(":"); +/** Same findings -> same id; any new or changed finding needs a new approval. */ +export const approvalId = (repo: string, findings: Finding[]) => + createHash("sha256").update([repo, ...findings.map(findingKey).sort()].join("\n")).digest("hex").slice(0, 10); + +/** Callback ids approved on Telegram since the last poll; only the owner's private chat (or listed user ids) count. */ +export class TelegramApprovals { + constructor(private token: string | null | undefined, private chatId: string | null | undefined, private approverIds: string[], private log: Log, private fetchFn: typeof fetch = fetch) {} + + private api(method: string, params: Record) { + return this.fetchFn(`https://api.telegram.org/bot${this.token}/${method}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(params), signal: AbortSignal.timeout(20_000) }) + .then((r) => r.json() as Promise); + } + authorized(cq: any): boolean { + if (this.approverIds.length) return this.approverIds.includes(String(cq.from?.id ?? "")); + return String(cq.message?.chat?.id ?? "") === String(this.chatId) && cq.message?.chat?.type === "private"; + } + async poll(): Promise> { + const ids = new Set(); + if (!this.token || !this.chatId) return ids; + try { + const res = await this.api("getUpdates", { timeout: 0, allowed_updates: ["callback_query"] }); + if (!res?.ok) { this.log(`Telegram getUpdates refused: ${res?.description ?? "unknown"}`, "WARNING"); return ids; } + let last = -1; + for (const u of res.result ?? []) { + last = Math.max(last, u.update_id); + const cq = u.callback_query, m = CALLBACK_RE.exec(cq?.data ?? ""); + if (!cq || !m) continue; + const ok = this.authorized(cq); + if (ok) ids.add(m[1]); + await this.api("answerCallbackQuery", { callback_query_id: cq.id, text: ok ? "Aprovado. A remoção roda na próxima execução do secret-guard." : "Sem permissão para aprovar." }).catch(() => {}); + } + if (last >= 0) await this.api("getUpdates", { offset: last + 1, timeout: 0, limit: 1, allowed_updates: ["callback_query"] }); + } catch (e: any) { this.log(`Telegram approvals unavailable: ${e?.message ?? e}`, "WARNING"); } + return ids; + } +} + +function issueBody(id: string, findings: Finding[]): string { + const rows = findings.slice(0, 50).map((f) => `- \`${f.file ?? "?"}\` linha ${f.line ?? 0} · regra \`${f.rule_id ?? f.RuleID ?? "?"}\` · commit \`${String(f.commit ?? "HEAD").slice(0, 8)}\``); + return [marker(id), "## 🔐 Remoção de segredo do histórico aguardando aprovação", "", + `O secret-guard classificou ${findings.length} achado(s) como segredo real. Remover reescreve o histórico git do branch padrão (force-push), o que **não tem volta**.`, "", + ...rows, "", + "**Para aprovar:** comente `/aprovar` aqui (só o dono do repositório conta) ou toque em **Aprovar** na mensagem do Telegram.", + "Sem aprovação nada é reescrito. Rotacione o segredo de qualquer forma: removê-lo do histórico não o invalida."].join("\n"); +} + +export class ApprovalGate { + constructor(private gh: GithubClient, private telegram: TelegramNotifier, private owner: string, private telegramApproved: Set, private log: Log) {} + + private async openIssues(repo: string): Promise { + return (await this.gh.getOpenIssues(repo, 100)).filter((i) => (i.labels ?? []).some((l: any) => (typeof l === "string" ? l : l.name) === APPROVAL_LABEL)); + } + private isOwner = (c: any) => (c.user?.login ?? "").toLowerCase() === this.owner.toLowerCase(); + + async check(repo: string, id: string): Promise { + try { + const issue = (await this.openIssues(repo)).find((i) => (i.body ?? "").includes(marker(id))); + if (this.telegramApproved.has(id)) { + if (issue) await this.gh.post(`/repos/${repo}/issues/${issue.number}/comments`, { body: `${telegramMarker(id)}\n✅ Aprovado pelo dono via Telegram.` }).catch(() => {}); + return { approved: true, via: "telegram", issue: issue?.number ?? null }; + } + if (!issue) return { approved: false, via: null, issue: null }; + const comments = await this.gh.getIssueComments(repo, issue.number); + if (comments.some((c: any) => this.isOwner(c) && APPROVE_RE.test(c.body ?? ""))) return { approved: true, via: "github", issue: issue.number }; + // A Telegram approval persisted by the bot on an earlier run (only a Bot account can author it). + if (comments.some((c: any) => c.user?.type === "Bot" && (c.body ?? "").includes(telegramMarker(id)))) return { approved: true, via: "telegram", issue: issue.number }; + return { approved: false, via: null, issue: issue.number }; + } catch (e: any) { this.log(`Approval check failed for ${repo}: ${e?.message ?? e}`, "WARNING"); return { approved: false, via: null, issue: null }; } + } + + /** Open (once per finding set) the approval issue and send the Telegram button. Older requests are superseded. */ + async request(repo: string, id: string, findings: Finding[]): Promise<{ issue: number | null; created: boolean }> { + try { + const open = await this.openIssues(repo), existing = open.find((i) => (i.body ?? "").includes(marker(id))); + if (existing) return { issue: existing.number, created: false }; + const issue = await this.gh.createIssue(repo, { title: "🔐 secret-guard: aprovar remoção de segredo do histórico", body: issueBody(id, findings), labels: [APPROVAL_LABEL] }); + for (const old of open) await this.close(repo, old.number, `Substituída por #${issue.number} (achados mudaram).`); + await this.telegram.sendMessage( + `🔐 SECRET GUARD — APROVAÇÃO NECESSÁRIA\n──────────────────────\n📦 ${esc(repo)}\n🔥 ${findings.length} segredo(s) real(is) no histórico.\nRemover reescreve o histórico (irreversível). Nada acontece sem sua aprovação.`, + "HTML", { inline_keyboard: [[{ text: "✅ Aprovar reescrita", callback_data: `sg:${id}` }], [{ text: "🔗 Ver issue", url: issue.html_url }]] }); + return { issue: issue.number, created: true }; + } catch (e: any) { this.log(`Could not request approval for ${repo}: ${e?.message ?? e}`, "WARNING"); return { issue: null, created: false }; } + } + + async close(repo: string, issue: number, note: string): Promise { + try { + await this.gh.post(`/repos/${repo}/issues/${issue}/comments`, { body: note }); + await this.gh.patch(`/repos/${repo}/issues/${issue}`, { state: "closed", state_reason: "completed" }); + } catch (e: any) { this.log(`Could not close approval issue #${issue} in ${repo}: ${e?.message ?? e}`, "WARNING"); } + } +} diff --git a/ts/src/agents/secret_remover/processor.ts b/ts/src/agents/secret_remover/processor.ts index 26920ca2..15ab297f 100644 --- a/ts/src/agents/secret_remover/processor.ts +++ b/ts/src/agents/secret_remover/processor.ts @@ -10,11 +10,16 @@ import { authConfigArgs, githubCloneUrl } from "../../utils/secure-git.ts"; import * as gitUtils from "./git-utils.ts"; import * as utils from "./utils.ts"; import { sendFindingNotification } from "./telegram-summary.ts"; +import { approvalId, type ApprovalGate } from "./approval.ts"; type Log = (m: string, level?: string) => void; +type Removal = { f: Record; originalLine: string }; +type Notify = (f: Record, action: string, originalLine: string) => Promise; export class FindingProcessor { - constructor(private ai: AIClient, private telegram: TelegramNotifier, private gh: GithubClient, private log: Log) {} + /** Without a gate nothing is ever rewritten: history rewrites always need the owner's approval. */ + constructor(private ai: AIClient, private telegram: TelegramNotifier, private gh: GithubClient, private log: Log, private gate: ApprovalGate | null = null, + private removeFn: typeof gitUtils.removeSecretFromHistory = gitUtils.removeSecretFromHistory) {} /** Falls back to IGNORE on any AI error to avoid destructive mistakes. */ async analyze(finding: Record): Promise<{ action: string; reason: string }> { @@ -23,7 +28,7 @@ export class FindingProcessor { async processRepo(repo: string, findings: Record[], defaultBranch: string) { this.log(`Analysing ${findings.length} finding(s) for ${repo}`); - let ignored = 0, removed = 0; + let ignored = 0, removed = 0, awaiting = 0; const actions: Record[] = [], ignoredFindings: Record[] = []; const token = process.env.GITHUB_TOKEN; if (!token) throw new Error("GITHUB_TOKEN not available for repository analysis"); @@ -32,26 +37,54 @@ export class FindingProcessor { const cloneDir = join(tmp, "repo"); this.log(`Cloning ${repo} for analysis...`); await runChecked(["git", ...authConfigArgs(token), "clone", "--single-branch", "--branch", defaultBranch, githubCloneUrl(repo), cloneDir]); + const toRemove: Removal[] = []; + const notify = (f: Record, action: string, originalLine: string) => { + const sha = f.commit ?? "HEAD", file = f.file ?? "", line = parseInt(f.line, 10) || 0; + return sendFindingNotification(this.telegram, { repo, finding: f, action, originalLine, + commitUrl: utils.buildCommitUrl(repo, sha), fileLineUrl: utils.buildFileLineUrl(repo, sha, file, line), repoUrl: utils.buildRepoUrl(repo) }); + }; for (const finding of findings) { const f: Record = { ...finding }; f.redacted_context = utils.buildRedactedContext(cloneDir, f); const originalLine = utils.getOriginalLine(cloneDir, f); const decision = await this.analyze(f); f._action = decision.action; f._reason = decision.reason ?? ""; - const sha = f.commit ?? "HEAD", file = f.file ?? "", line = parseInt(f.line, 10) || 0; - if (decision.action === "REMOVE_FROM_HISTORY") { - const ok = await gitUtils.removeSecretFromHistory(repo, f, cloneDir, this.log, token); - actions.push({ finding: f, status: ok ? "REMOVED" : "ERROR" }); - if (ok) removed++; - } else { ignored++; ignoredFindings.push(f); actions.push({ finding: f, status: "IGNORED" }); } - await sendFindingNotification(this.telegram, { repo, finding: f, action: decision.action, originalLine, - commitUrl: utils.buildCommitUrl(repo, sha), fileLineUrl: utils.buildFileLineUrl(repo, sha, file, line), repoUrl: utils.buildRepoUrl(repo) }); + if (decision.action === "REMOVE_FROM_HISTORY") { toRemove.push({ f, originalLine }); continue; } + ignored++; ignoredFindings.push(f); actions.push({ finding: f, status: "IGNORED" }); + await notify(f, decision.action, originalLine); } + const r = await this.resolveRemovals(repo, toRemove, cloneDir, token, notify, actions); + removed = r.removed; awaiting = r.awaiting; if (ignoredFindings.length) { const ok = await gitUtils.applyAllowlistLocally(this.gh, repo, ignoredFindings, cloneDir, token, this.log, defaultBranch); actions.push({ status: ok ? "ALLOWLIST_APPLIED" : "ALLOWLIST_ERROR", findings_count: ignoredFindings.length }); } } finally { rmSync(tmp, { recursive: true, force: true }); } - return { repository: repo, ignored, to_remove: removed, actions }; + return { repository: repo, ignored, to_remove: removed, awaiting_approval: awaiting, actions }; + } + + /** Real secrets: rewrite history only with the owner's approval for this exact finding set; otherwise ask for it. */ + async resolveRemovals(repo: string, toRemove: Removal[], cloneDir: string, token: string, notify: Notify, actions: Record[]): Promise<{ removed: number; awaiting: number }> { + let removed = 0, awaiting = 0; + if (!toRemove.length) return { removed, awaiting }; + const id = approvalId(repo, toRemove.map((x) => x.f)); + const approval = this.gate ? await this.gate.check(repo, id) : { approved: false, via: null, issue: null }; + if (approval.approved) { + this.log(`History rewrite for ${repo} approved by the owner via ${approval.via}`); + for (const { f, originalLine } of toRemove) { + const ok = await this.removeFn(repo, f, cloneDir, this.log, token); + actions.push({ finding: f, status: ok ? "REMOVED" : "ERROR", approved_via: approval.via }); + if (ok) removed++; + await notify(f, ok ? "REMOVE_FROM_HISTORY" : "REMOVE_FAILED", originalLine); + } + if (approval.issue && removed === toRemove.length) await this.gate!.close(repo, approval.issue, `✅ ${removed} segredo(s) removido(s) do histórico. Rotacione as credenciais.`); + return { removed, awaiting }; + } + const req = this.gate ? await this.gate.request(repo, id, toRemove.map((x) => x.f)) : { issue: null, created: false }; + for (const { f, originalLine } of toRemove) { + awaiting++; actions.push({ finding: f, status: "AWAITING_APPROVAL", approval_issue: req.issue }); + if (req.created) await notify(f, "AWAITING_APPROVAL", originalLine); // once per request, not on every run + } + return { removed, awaiting }; } } diff --git a/ts/src/agents/secret_remover/telegram-summary.ts b/ts/src/agents/secret_remover/telegram-summary.ts index 881bb23d..641fa2b5 100644 --- a/ts/src/agents/secret_remover/telegram-summary.ts +++ b/ts/src/agents/secret_remover/telegram-summary.ts @@ -1,10 +1,14 @@ import { TelegramNotifier } from "../../notifications/telegram.ts"; const esc = TelegramNotifier.escapeHtml; +const HEADLINE: Record = { + REMOVE_FROM_HISTORY: "🔥 Secret Removida do Histórico", + AWAITING_APPROVAL: "⏳ Secret real — aguardando sua aprovação para reescrever o histórico", + REMOVE_FAILED: "❌ Falha ao remover a secret do histórico", +}; export function buildFindingMessage(repo: string, finding: Record, originalLine: string, action: string): string { - const remove = action === "REMOVE_FROM_HISTORY"; const preview = originalLine ? esc(originalLine.slice(0, 200)) : "não disponível"; - return `${remove ? "🔥" : "✅"} Secret ${remove ? "Removida do Histórico" : "Falso Positivo (Ignorado)"}\n\n` + + return `${HEADLINE[action] ?? "✅ Secret Falso Positivo (Ignorado)"}\n\n` + `📦 Repositório: ${esc(repo)}\n📄 Arquivo: ${esc(finding.file ?? "unknown")} (Linha ${finding.line ?? 0})\n` + `🤖 Motivo: ${esc(finding._reason ?? "No reason provided")}\n\n📝 Conteúdo original (redactado):\n${preview}`; } diff --git a/ts/src/agents/senior_developer/instructions.md b/ts/src/agents/senior_developer/instructions.md index 5f2ede40..48b7fecc 100644 --- a/ts/src/agents/senior_developer/instructions.md +++ b/ts/src/agents/senior_developer/instructions.md @@ -1,461 +1,13 @@ -# Senior Developer Agent Instructions +# Senior Developer (builder stage `code`) ## Persona -You are a Senior Software Engineer with 10+ years of experience building production systems. -You are meticulous about code quality, security, and operational excellence. - -### Core Principles - -1. **Security First** - Never commit secrets, always validate inputs, follow OWASP guidelines -2. **Test Everything** - Unit, integration, and E2E tests for all features (80%+ coverage) -3. **CI/CD is Mandatory** - Automate build, test, and deployment -4. **Documentation Matters** - Code should be self-documenting with clear comments -5. **Performance & Scalability** - Design for growth, optimize for production -6. **Clean Architecture** - Follow **SOLID** principles and design patterns -7. **DRY** - Don't Repeat Yourself -8. **KISS** - Keep It Simple, Stupid -9. **YAGNI** - You Aren't Gonna Need It - -### Expertise Areas - -**Backend Technologies**: -- Python (FastAPI, Django, Flask) -- Node.js (Express, NestJS, Fastify) -- Go, Java, C# - -**Databases**: -- PostgreSQL, MySQL (relational) -- MongoDB, CouchDB (document) -- Redis, Memcached (cache) - -**Cloud & Infrastructure**: -- AWS (EC2, Lambda, S3, RDS) -- GCP (Compute Engine, Cloud Functions, Cloud SQL) -- Azure (VMs, Functions, Cosmos DB) - -**DevOps & Tools**: -- Docker, Kubernetes -- GitHub Actions, GitLab CI, Jenkins -- Terraform, CloudFormation -- Prometheus, Grafana - -**Security**: -- OWASP Top 10 -- OAuth2, JWT authentication -- Secrets management (Vault, AWS Secrets Manager) -- Dependency scanning -- SAST/DAST tools +Senior engineer that applies the owner's skills (https://github.com/juninmd/skills) and global AGENTS.md, +plus each repository's own `AGENTS.md`. No private rule set: when they disagree, the repository's AGENTS.md wins. ## Mission -Implement features from product roadmaps with production-grade quality. - -### Primary Responsibilities - -1. Implement features securely and efficiently -2. Ensure comprehensive test coverage (**80% minimum**) -3. Set up robust CI/CD pipelines -4. Maintain .gitignore to prevent secrets exposure -5. Generate executables/installers for end-user applications -6. Conduct security audits and dependency updates -7. Implement monitoring and observability -8. **Productive Development**: Do not use mocks or fake implementations. Use mocks **ONLY** for tests. -9. **File Length**: Each file must have a **maximum of 180 lines of code**. -10. **Branch Synchronization**: Always ensure the source branch is fully up-to-date by doing a `git pull` on the main/default branch before implementing improvements or changes. - -## Development Standards - -### Security Checklist - -#### 1. Secrets Management -```gitignore -# Environment and secrets -.env -.env.local -.env.*.local -*.key -*.pem -*.p12 -secrets/ -config/secrets.yml -api_keys.txt -``` - -**Rules**: -- ✅ All secrets in environment variables -- ✅ Use secrets managers in production -- ✅ No hardcoded credentials -- ✅ Scan for committed secrets (git-secrets, truffleHog) -- ✅ Rotate keys regularly - -#### 2. Input Validation -- Validate all user inputs -- Sanitize data before storage -- Use parameterized queries (prevent SQL injection) -- Implement rate limiting -- Validate file uploads (type, size, content) - -#### 3. Authentication & Authorization -- Use established libraries (Passport, OAuth2) -- Implement proper session management -- Use HTTPS everywhere -- Implement CSRF protection -- Follow principle of least privilege - -#### 4. Dependencies -- Keep dependencies updated -- Use Dependabot or Renovate -- Run `npm audit` / `pip-audit` regularly -- Pin versions in production -- Review security advisories - -### Code Quality Standards - -#### 1. Testing Requirements -```python -# Minimum 80% code coverage -pytest --cov=src --cov-report=html --cov-fail-under=80 -``` - -**Test Types**: -- **Unit Tests**: Test individual functions/methods -- **Integration Tests**: Test component interactions -- **E2E Tests**: Test complete user workflows -- **Edge Cases**: Test boundary conditions and error handling - -#### 2. Code Style -- Follow language-specific style guides (PEP 8, Airbnb JS) -- Use linters (pylint, eslint, golangci-lint) -- Use formatters (black, prettier, gofmt) -- Meaningful variable/function names -- Keep functions small and focused (< 50 lines) -- **File Limit**: Maximum 180 lines of code per file. -- **Principles**: Strictly adhere to DRY, KISS, and SOLID. - -#### 3. Documentation -- **Docstrings/JSDoc**: For all public APIs -- **README**: Setup, usage, deployment instructions -- **API Documentation**: OpenAPI/Swagger specs -- **Architecture Diagrams**: For complex systems -- **CHANGELOG**: Track changes between versions - -### CI/CD Pipeline Template - -```yaml -name: CI/CD Pipeline - -on: - push: - branches: [ main, develop ] - pull_request: - branches: [ main ] - -jobs: - lint: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - name: Run linters - run: | - # Language-specific linting - - test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - name: Run tests - run: | - # Unit and integration tests - # Coverage reporting - - security: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - name: Security scan - run: | - # Dependency audit - # Secret scanning - # SAST (Semgrep, SonarQube) - - build: - needs: [lint, test, security] - runs-on: ubuntu-latest - steps: - - name: Build application - run: | - # Build production bundle - # Create executables (Electron, PyInstaller) - - - name: Upload artifacts - uses: actions/upload-artifact@v3 - with: - name: build-artifacts - path: dist/ - - deploy: - needs: build - if: github.ref == 'refs/heads/main' - runs-on: ubuntu-latest - steps: - - name: Deploy to production - run: | - # Deployment logic -``` - -### Desktop Application Packaging - -For desktop applications requiring executables: - -#### Electron (JavaScript/TypeScript) -```json -{ - "build": { - "appId": "com.company.app", - "productName": "MyApp", - "directories": { - "output": "dist" - }, - "win": { - "target": ["nsis", "portable"], - "icon": "build/icon.ico" - }, - "mac": { - "target": ["dmg", "zip"], - "icon": "build/icon.icns" - }, - "linux": { - "target": ["AppImage", "deb"], - "icon": "build/icon.png" - } - } -} -``` - -#### Python (PyInstaller) -```bash -pyinstaller --onefile \ - --windowed \ - --icon=icon.ico \ - --name=MyApp \ - --add-data="assets:assets" \ - main.py -``` - -#### Code Signing -- Windows: SignTool with certificate -- macOS: codesign with Apple Developer certificate -- Linux: GPG signing for packages - -## Task Instructions - -### Security Hardening Template - -```markdown -# Task: Security Hardening for {repository} - -## Identified Issues -{issues_list} - -## Security Checklist - -### 1. Secrets Management -- [ ] Ensure comprehensive .gitignore -- [ ] Scan for accidentally committed secrets -- [ ] Use environment variables for all sensitive data -- [ ] Implement secrets rotation strategy - -### 2. Dependency Security -- [ ] Set up Dependabot or Renovate -- [ ] Run npm audit / pip-audit and fix vulnerabilities -- [ ] Pin dependency versions in production -- [ ] Review dependency licenses - -### 3. Code Security -- [ ] Implement input validation for all user inputs -- [ ] Use parameterized queries (prevent SQL injection) -- [ ] Implement rate limiting on APIs -- [ ] Add CORS configuration -- [ ] Implement proper authentication/authorization -- [ ] Add security headers (CSP, HSTS, X-Frame-Options) - -### 4. CI/CD Security -- [ ] Use GitHub Secrets for sensitive variables -- [ ] Implement secret scanning in workflows -- [ ] Add SAST (Static Application Security Testing) -- [ ] Implement dependency scanning - -Create a PR with all security improvements. -``` - -### CI/CD Setup Template - -```markdown -# Task: CI/CD Pipeline Setup for {repository} - -## Required Improvements -{improvements_list} - -## Implementation Plan - -### 1. GitHub Actions Workflow -Create comprehensive CI/CD pipeline: -- Linting and formatting checks -- Unit and integration tests -- Security scanning -- Build and artifact creation -- Automated deployment - -### 2. Testing Setup -- [ ] Add unit tests (target: 80%+ coverage) -- [ ] Add integration tests for critical paths -- [ ] Set up test coverage reporting -- [ ] Add pre-commit hooks for running tests - -### 3. Build Configuration -For desktop applications: -- [ ] Set up electron-builder or PyInstaller -- [ ] Configure for multiple platforms (Windows, macOS, Linux) -- [ ] Sign executables for distribution -- [ ] Create installers (.exe, .dmg, .deb) - -For web applications: -- [ ] Optimize production build -- [ ] Set up CDN deployment -- [ ] Configure caching strategies -- [ ] Implement asset minification - -### 4. Release Automation -- [ ] Set up semantic-release or similar -- [ ] Automate changelog generation -- [ ] Create GitHub releases with artifacts -- [ ] Implement version bumping - -Create a comprehensive CI/CD setup in a PR. -``` - -### Feature Implementation Template - -```markdown -# Task: Implement Features from Roadmap - -## Repository: {repository} - -## Features to Implement -{features_list} - -## Development Standards - -### Code Quality -1. Follow existing code style and patterns. -2. Add comprehensive type hints/TypeScript types. -3. Write self-documenting code with clear variable names. -4. Add docstrings/JSDoc for public APIs. -5. Strictly follow **DRY**, **KISS**, **SOLID**, and **YAGNI**. -6. **File length constraint**: Maximum 180 lines of code per file. - -### Testing Requirements -1. Unit tests for all new functions/methods -2. Integration tests for feature workflows -3. Achieve minimum 80% code coverage -4. Test edge cases and error conditions - -### Security Checklist -- [ ] Validate all inputs -- [ ] Sanitize outputs to prevent XSS -- [ ] Use parameterized queries -- [ ] No hardcoded secrets -- [ ] Add secrets to .gitignore -- [ ] Implement proper error handling - -### Performance -- [ ] Optimize database queries -- [ ] Implement caching where appropriate -- [ ] Lazy load heavy resources -- [ ] Profile and optimize critical paths - -### Documentation -- [ ] Update README with new features -- [ ] Add API documentation -- [ ] Include usage examples -- [ ] Update CHANGELOG - -### CI/CD Integration -- [ ] Ensure all tests pass in CI -- [ ] Add any new build steps to workflow -- [ ] Update deployment configuration if needed - -## Deliverables -1. Fully implemented and tested features -2. Documentation updates -3. PR with clear description and screenshots/videos -4. All CI checks passing - -Implement features incrementally - one feature per commit for easy review. -``` - -## Best Practices - -### Error Handling -```python -# Good: Specific exceptions with context -try: - result = risky_operation() -except ValueError as e: - logger.error(f"Invalid value in operation: {e}") - raise HTTPException(status_code=400, detail=str(e)) -except Exception as e: - logger.error(f"Unexpected error: {e}") - raise HTTPException(status_code=500, detail="Internal error") -``` - -### Logging -```python -import logging - -logger = logging.getLogger(__name__) - -# Use appropriate log levels -logger.debug("Detailed diagnostic info") -logger.info("Normal operation") -logger.warning("Warning condition") -logger.error("Error occurred", exc_info=True) -logger.critical("Critical system failure") -``` - -### Database Queries -```python -# Bad: SQL injection risk -query = f"SELECT * FROM users WHERE id = {user_id}" - -# Good: Parameterized query -query = "SELECT * FROM users WHERE id = %s" -cursor.execute(query, (user_id,)) -``` - -### API Rate Limiting -```python -from fastapi import FastAPI -from slowapi import Limiter, _rate_limit_exceeded_handler -from slowapi.util import get_remote_address - -limiter = Limiter(key_func=get_remote_address) -app.state.limiter = limiter - -@app.get("/api/resource") -@limiter.limit("100/hour") -async def get_resource(): - return {"data": "value"} -``` - -## Performance Optimization - -1. **Database**: Use indexes, query optimization, connection pooling -2. **Caching**: Redis for frequently accessed data -3. **Async**: Use async/await for I/O operations -4. **Load Balancing**: Distribute traffic across instances -5. **CDN**: Serve static assets from CDN -6. **Compression**: gzip/brotli for responses -7. **Pagination**: Limit result sets -8. **Lazy Loading**: Load data on demand +Analyze the allowed repositories (oldest-updated first, capped per run) and delegate scoped tasks to opencode: +security, CI/CD, tech debt, modernization, performance and roadmap features. One concern per PR. +PRs are opened as draft with `keep-draft`; the bot never marks them ready or merges them. +The task templates (`task-instructions-*.md`) carry the per-task details. diff --git a/ts/src/cli/run-agent.ts b/ts/src/cli/run-agent.ts index d46e3098..186c3491 100644 --- a/ts/src/cli/run-agent.ts +++ b/ts/src/cli/run-agent.ts @@ -1,7 +1,7 @@ #!/usr/bin/env bun /** Usage: bun run-agent [--pr owner/repo#N] [--ai-provider X] [--ai-model Y] */ import { parseArgs } from "node:util"; -import { AGENTS_BY_NAME } from "../agents/catalog.ts"; +import { AGENT_ALIASES, AGENTS_BY_NAME, resolveAgentName } from "../agents/catalog.ts"; import { settingsFromEnv } from "../config/settings.ts"; import { runHealthChecks } from "../health.ts"; import { anyBatchFailure, isFailedResult, runAgent, runAll } from "../run-agent.ts"; @@ -15,8 +15,8 @@ const { values, positionals } = parseArgs({ options: { pr: { type: "string" }, "ai-provider": { type: "string" }, "ai-model": { type: "string" } }, }); const name = positionals[0]; -if (!name || (name !== "all" && !AGENTS_BY_NAME.has(name))) { - console.error(`usage: run-agent <${[...AGENTS_BY_NAME.keys(), "all"].join("|")}> [--pr owner/repo#N]`); +if (!name || (name !== "all" && !resolveAgentName(name))) { + console.error(`usage: run-agent <${[...AGENTS_BY_NAME.keys(), "all"].join("|")}> [--pr owner/repo#N]\nformer names still accepted: ${Object.keys(AGENT_ALIASES).join(", ")}`); process.exit(2); } const settings = await settingsFromEnv(); diff --git a/ts/src/health.ts b/ts/src/health.ts index 70cbbec9..c1d54a95 100644 --- a/ts/src/health.ts +++ b/ts/src/health.ts @@ -1,5 +1,5 @@ /** Pre-flight health checks before agent execution. */ -import { AGENTS_BY_NAME } from "./agents/catalog.ts"; +import { AGENTS_BY_NAME, resolveAgentName } from "./agents/catalog.ts"; import type { Settings } from "./config/settings.ts"; export class HealthReport { @@ -12,9 +12,10 @@ export class HealthReport { export function runHealthChecks(s: Settings, agent: string): HealthReport { const r = new HealthReport(); - const all = agent === "all", spec = AGENTS_BY_NAME.get(agent); + const all = agent === "all", target = resolveAgentName(agent), spec = target ? AGENTS_BY_NAME.get(target.agent) : undefined; + const stageAi = !!spec?.stages.some((st) => st.requiresAi && (!target?.stage || st.name === target.stage)); s.githubToken ? r.passed.push("GITHUB_TOKEN present") : r.errors.push("GITHUB_TOKEN is missing — GitHub operations will fail"); - if (s.enableAi && (spec?.requiresAi || all)) { + if (s.enableAi && (spec?.requiresAi || stageAi || all)) { const p = s.aiProvider; if (p === "gemini" && !s.geminiApiKey) r.errors.push("AI_PROVIDER=gemini but GEMINI_API_KEY is missing"); else if (p === "openai" && !s.openaiApiKey) r.errors.push("AI_PROVIDER=openai but OPENAI_API_KEY is missing"); diff --git a/ts/tests/config.test.ts b/ts/tests/config.test.ts index 8efbdd9c..6b1bf48d 100644 --- a/ts/tests/config.test.ts +++ b/ts/tests/config.test.ts @@ -29,7 +29,7 @@ test("settings: defaults, validation, toggles from catalog", async () => { const s = await testSettings(); expect([s.automationMode, s.webhookRetentionDays, s.aiProvider, s.aiModel]).toEqual(["observe", 3, "litellm", "cloud/auto"]); expect(Object.keys(s.enabled).length).toBe(AGENT_CATALOG.filter((a) => a.toggleEnv).length); - expect((await testSettings({ PR_SLA_ENABLED: "off" })).enabled["pr-sla"]).toBe(false); + expect((await testSettings({ FLOW_WATCH_ENABLED: "off" })).enabled["flow-watch"]).toBe(false); expect(testSettings({ QUEUE_MAX_ATTEMPTS: "0" })).rejects.toThrow("QUEUE_MAX_ATTEMPTS must be a positive integer"); expect(testSettings({ ENABLE_AI: "true", AI_PROVIDER: "nope" })).rejects.toThrow("AI_PROVIDER must be one of"); expect((await testSettings({ AI_PROVIDER: "ollama" })).aiModel).toBe("qwen3:1.7b"); @@ -44,18 +44,18 @@ test("catalog: unique kebab names; capability filters", () => { const names = AGENT_CATALOG.map((a) => a.name); expect(new Set(names).size).toBe(names.length); for (const n of names) expect(n).toMatch(/^[a-z]+(-[a-z]+)*$/); - expect(AGENT_CATALOG.length).toBe(15); - expect(agentNames({ requiresAi: true }).has("senior-developer")).toBe(true); + expect(AGENT_CATALOG.map((a) => a.name)).toEqual(["secret-guard", "pr-assistant", "flow-watch", "dependency-manager", "repo-standards", "branch-cleaner", "builder", "project-creator"]); + expect(agentNames({ requiresAi: true }).has("builder")).toBe(true); expect(agentNames({ requiresAi: false }).has("pr-assistant")).toBe(true); }); test("fleet explains why an agent cannot run", async () => { - const s = await testSettings({ CODE_REVIEWER_ENABLED: "false" }); + const s = await testSettings({ FLOW_WATCH_ENABLED: "false" }); const by = Object.fromEntries(fleetStatus(s).agents.map((a) => [a.name, a])); - expect(by["code-reviewer"].blocked_reason).toBe("CODE_REVIEWER_ENABLED=false"); - expect(by["product-manager"].blocked_reason).toBe("ENABLE_AI=false"); + expect(by["flow-watch"].blocked_reason).toBe("FLOW_WATCH_ENABLED=false"); + expect(by["builder"].blocked_reason).toBe("ENABLE_AI=false"); expect(by["pr-assistant"].runnable).toBe(true); - expect(by["security-scanner"].priority).toBe("critical"); + expect(by["secret-guard"].priority).toBe("critical"); }); test("priorities accumulate across repo, label and title", () => { diff --git a/ts/tests/conflict-resolver.test.ts b/ts/tests/conflict-resolver.test.ts deleted file mode 100644 index 2a0e99bc..00000000 --- a/ts/tests/conflict-resolver.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { expect, test } from "bun:test"; -import { ConflictResolverAgent } from "../src/agents/conflict_resolver/agent.ts"; -import { sendSummaryNotice } from "../src/agents/conflict_resolver/notifications.ts"; -import { RepositoryAllowlist } from "../src/config/allowlist.ts"; - -const pr = (o: any = {}) => ({ number: 3, title: "t", html_url: "u", mergeable: false, labels: [], user: { login: "juninmd" }, head: { sha: "a", ref: "f", repo: { full_name: "o/r" } }, base: { ref: "main", repo: { full_name: "o/r" } }, ...o }); -const mk = (gh: any = {}) => { - const sent: string[] = []; - const a = new ConflictResolverAgent({ githubClient: gh, allowlist: new RepositoryAllowlist("/nonexistent.json"), telegram: { sendMessage: async (t: string) => { sent.push(t); return true; } } as any }); - return { a, sent }; -}; -const res = () => ({ resolved: [], manual: [], pipeline_fixed: [], pipeline_manual: [], timestamp: "" }) as any; - -test("trusted authors fall back to defaults; untrusted ignored", async () => { - const { a } = mk(); - expect(a.isTrustedAuthor("renovate[bot]")).toBe(true); - expect(a.isTrustedAuthor("rando")).toBe(false); - const r = res(); await a.handlePr(pr({ user: { login: "rando" } }) as any, r); - expect(r.manual).toHaveLength(0); -}); -test("already-flagged PR is skipped", async () => { - const { a } = mk(); const r = res(); - await a.handlePr(pr({ labels: [{ name: "needs-manual-conflict-resolution" }] }) as any, r); - expect(r.resolved.length + r.manual.length).toBe(0); -}); -test("summary lists counts and links", async () => { - const sent: string[] = []; - await sendSummaryNotice({ sendMessage: async (t: string) => { sent.push(t); return true; } } as any, [{ repo: "o/r", pr: 1, msg: "ok" }], [{ repo: "o/r", pr: 2, error: "" }]); - expect(sent[0]).toContain("resolvidos: 1"); expect(sent[0]).toContain("<x>"); expect(sent[0]).toContain("o/r/pull/2"); -}); -test("run with search failure still returns results", async () => { - const { a } = mk({ searchPrs: async () => { throw new Error("boom"); }, getRateLimit: async () => ({ remaining: 5000 }) }); - a.checkRateLimit = async () => 5000; - const r = await a.run(); - expect(r.resolved).toEqual([]); -}); diff --git a/ts/tests/core.test.ts b/ts/tests/core.test.ts index 61046956..62e44e3a 100644 --- a/ts/tests/core.test.ts +++ b/ts/tests/core.test.ts @@ -25,27 +25,28 @@ const realFetch = globalThis.fetch; afterEach(() => { globalThis.fetch = realFetch; }); test("orchestrator: batches respect deps; cycles and missing deps fail loudly; external deps allowed", () => { - const o = createDefaultOrchestrator(); - const b = o.parallelBatches(["secret-remover", "security-scanner", "pr-sla"]); - expect(b[0]).toContain("security-scanner"); - expect(b[1]).toEqual(["secret-remover"]); - expect(o.parallelBatches(["secret-remover"])).toEqual([["secret-remover"]]); // dep outside run: not a cycle + const o = new AgentOrchestrator(); + o.register("scan", AgentPriority.CRITICAL); o.register("remove", AgentPriority.CRITICAL, ["scan"]); o.register("sla", AgentPriority.LOW); + const b = o.parallelBatches(["remove", "scan", "sla"]); + expect(b[0]).toContain("scan"); + expect(b[1]).toEqual(["remove"]); + expect(o.parallelBatches(["remove"])).toEqual([["remove"]]); // dep outside run: not a cycle const c = new AgentOrchestrator(); c.register("a", AgentPriority.LOW, ["b"]); c.register("b", AgentPriority.LOW, ["a"]); expect(() => c.parallelBatches(["a", "b"])).toThrow("circular dependency"); const m = new AgentOrchestrator(); m.register("a", AgentPriority.LOW, ["ghost"]); expect(() => m.parallelBatches(["a"])).toThrow("missing dependencies: ghost"); - expect(o.order(["pr-sla", "security-scanner", "pr-assistant"])).toEqual(["security-scanner", "pr-assistant", "pr-sla"]); + // The real fleet has no cross-agent dependencies left (secret-guard runs scan -> remove internally): priority only. + expect(createDefaultOrchestrator().order(["builder", "secret-guard", "pr-assistant"])).toEqual(["secret-guard", "pr-assistant", "builder"]); }); test("batch runner: dependents blocked when dependency failed; AI agents skipped without ENABLE_AI", async () => { const s = await testSettings(); const ran: string[] = []; - const res = await batchRunAll(s, async (n) => { ran.push(n); return n === "security-scanner" ? { error: "boom" } : { ok: true }; }); - expect(ran).not.toContain("secret-remover"); // requires AI (off) - expect(res["security-scanner"].error).toBe("boom"); - const s2 = await testSettings({ ENABLE_AI: "true", AI_PROVIDER: "ollama" }); - const res2 = await batchRunAll(s2, async (n) => (n === "security-scanner" ? { status: "failed", error: "x" } : {})); - expect(res2["secret-remover"]).toEqual({ status: "blocked", error: "dependency failed: security-scanner" }); + const res = await batchRunAll(s, async (n) => { ran.push(n); return n === "secret-guard" ? { error: "boom" } : { ok: true }; }); + for (const ai of ["builder", "repo-standards", "project-creator"]) expect(ran).not.toContain(ai); // requires AI (off) + expect(ran).toContain("secret-guard"); // scanning needs no AI; its AI stage is skipped inside the agent + expect(res["secret-guard"].error).toBe("boom"); + expect(res["pr-assistant"]).toEqual({ ok: true }); // one failure does not stop independent agents const s3 = await testSettings({ PR_ASSISTANT_ENABLED: "false" }); expect(Object.keys(await batchRunAll(s3, async () => ({})))).not.toContain("pr-assistant"); }); @@ -134,7 +135,7 @@ test("repository manager: owner scope, sorted by recency, info cached", async () test("run-agent: wraps results, failure semantics, unported agent errors cleanly", async () => { const s = await testSettings(); - AGENTS_BY_NAME.set("ghost", { ...AGENTS_BY_NAME.get("pr-sla")!, name: "ghost" } as any); + AGENTS_BY_NAME.set("ghost", { ...AGENTS_BY_NAME.get("branch-cleaner")!, name: "ghost" } as any); const r = await runAgent("ghost", s, { save: false }); AGENTS_BY_NAME.delete("ghost"); expect(r.error).toContain("ainda não foi portado"); @@ -144,14 +145,17 @@ test("run-agent: wraps results, failure semantics, unported agent errors cleanly expect(anyBatchFailure({ a: {}, b: { error: "x" } })).toBe(true); expect(anyBatchFailure({ a: {} })).toBe(false); await expect(createAgent("zzz", s)).rejects.toThrow("unknown agent"); - expect(isPorted("conflict-resolver")).toBe(true); + expect(isPorted("flow-watch")).toBe(true); expect(isPorted("ghost")).toBe(false); }); test("health checks: AI provider keys, telegram warning", async () => { const s = await testSettings({ ENABLE_AI: "true", AI_PROVIDER: "gemini" }); - expect(runHealthChecks(s, "code-reviewer").errors).toContain("AI_PROVIDER=gemini but GEMINI_API_KEY is missing"); - const ok = runHealthChecks(await testSettings({ ENABLE_AI: "true", AI_PROVIDER: "litellm", LITELLM_API_KEY: "k" }), "code-reviewer"); + expect(runHealthChecks(s, "builder").errors).toContain("AI_PROVIDER=gemini but GEMINI_API_KEY is missing"); + // Former names resolve to their stage: the remover stage needs AI keys, the scanner stage does not. + expect(runHealthChecks(s, "secret-remover").errors).toContain("AI_PROVIDER=gemini but GEMINI_API_KEY is missing"); + expect(runHealthChecks(s, "security-scanner").errors).toEqual([]); + const ok = runHealthChecks(await testSettings({ ENABLE_AI: "true", AI_PROVIDER: "litellm", LITELLM_API_KEY: "k" }), "builder"); expect(ok.ok).toBe(true); expect(ok.warnings[0]).toContain("Telegram"); expect(runHealthChecks(await testSettings(), "pr-sla").ok).toBe(true); }); diff --git a/ts/tests/fleet-redesign.test.ts b/ts/tests/fleet-redesign.test.ts new file mode 100644 index 00000000..66793cc2 --- /dev/null +++ b/ts/tests/fleet-redesign.test.ts @@ -0,0 +1,163 @@ +import { afterEach, expect, test } from "bun:test"; +import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { AGENT_ALIASES, AGENT_CATALOG, AGENTS_BY_NAME, resolveAgentName } from "../src/agents/catalog.ts"; +import { agentDir } from "../src/agents/core/utils.ts"; +import { FlowWatchAgent } from "../src/agents/flow_watch/agent.ts"; +import { SecretGuardAgent } from "../src/agents/secret_guard/agent.ts"; +import { BuilderAgent } from "../src/agents/builder/agent.ts"; +import { createAgentPull, KEEP_DRAFT_LABEL } from "../src/agents/core/pr-options.ts"; +import { applyGate } from "../src/agents/pr_assistant/review-gate.ts"; +import { APPROVE, mkVerdict } from "../src/agents/pr_assistant/review-verdict.ts"; +import { contractLabel, ensureContract, resetContract } from "../src/agents/core/agent-contract.ts"; +import { IntelligenceStandardizerAgent } from "../src/agents/intelligence_standardizer/agent.ts"; +import { createAgent } from "../src/agents/registry.ts"; +import { RepositoryAllowlist } from "../src/config/allowlist.ts"; +import { testSettings, tmp } from "./helpers.ts"; + +const telegram: any = { sendMessage: async () => true }; +const base = (gh: any = {}, o: any = {}) => ({ githubClient: gh, allowlist: new RepositoryAllowlist("/nonexistent.json"), telegram, targetOwner: "me", ...o }); +const fakeStages = (a: any, results: Record, ran: string[] = []) => { + a.createStage = async (st: any) => ({ run: async () => { ran.push(st.name); if (results[st.name] instanceof Error) throw results[st.name]; return results[st.name] ?? {}; } }); + return ran; +}; +afterEach(() => { for (const k of ["PR_SLA_ENABLED", "AGENT_CONTRACT_REFRESH", "REPO_STANDARDS_MAX_PRS"]) delete process.env[k]; resetContract(); }); + +test("catalog: 8 scoped agents; every stage and former name resolves to real code", async () => { + expect(AGENT_CATALOG).toHaveLength(8); + for (const a of AGENT_CATALOG) { + expect(existsSync(join(agentDir(a.name), "agent.ts"))).toBe(true); + for (const st of a.stages) expect((await import(join(agentDir(st.dir), "agent.ts")))[st.className]).toBeDefined(); + } + for (const [old, t] of Object.entries(AGENT_ALIASES)) { + const spec = AGENTS_BY_NAME.get(t.agent)!; + expect(spec).toBeDefined(); + if (t.stage) expect(spec.stages.map((s) => s.name)).toContain(t.stage); + expect(AGENTS_BY_NAME.has(old)).toBe(false); // a former name never shadows a current agent + } + expect(resolveAgentName("pr-sla")).toEqual({ agent: "flow-watch", stage: "sla" }); + expect(resolveAgentName("code-reviewer")).toEqual({ agent: "pr-assistant" }); + expect(resolveAgentName("nope")).toBeNull(); +}); + +test("registry: a former name builds the new agent restricted to its stage; AI stage still needs ENABLE_AI", async () => { + const s = await testSettings(); + const a: any = await createAgent("ci-health", s); + expect(a).toBeInstanceOf(FlowWatchAgent); expect(a.onlyStage).toBe("ci"); + await expect(createAgent("secret-remover", s)).rejects.toThrow("requires AI"); + const g: any = await createAgent("secret-guard", s); // scanning works without AI + expect(g.onlyStage).toBeNull(); expect(g.opts.ai).toBeUndefined(); +}); + +test("composite: stages run in order, toggles skip, a failed stage marks the run failed; a single stage passes through", async () => { + const a: any = new FlowWatchAgent(base()); + const ran = fakeStages(a, { ci: { count: 2 }, sla: new Error("boom") }); + const r = await a.run(); + expect(ran).toEqual(["ci", "sla"]); + expect(r.stages.ci).toEqual({ count: 2 }); expect(r.stages.sla.error).toBe("boom"); expect(r.error).toContain("sla"); + process.env.PR_SLA_ENABLED = "false"; + const b: any = new FlowWatchAgent(base()); const ran2 = fakeStages(b, {}); + const r2 = await b.run(); + expect(ran2).toEqual(["ci"]); expect(r2.skipped_stages).toEqual({ sla: "PR_SLA_ENABLED=false" }); expect(r2.error).toBeUndefined(); + const only: any = new FlowWatchAgent(base({}, { stage: "sla" })); fakeStages(only, { sla: { stale_pull_requests: [] } }); + expect(await only.run()).toEqual({ stale_pull_requests: [] }); // the former agent's exact result shape + expect(() => new FlowWatchAgent(base({}, { stage: "ghost" }))).toThrow("unknown stage"); +}); + +test("flow-watch only observes: no CI remediation tasks, no SLA nudge comments", async () => { + const a: any = new FlowWatchAgent(base()); + expect((await a.createStage(a.stages[0])).remediate).toBe(false); + const sla = await a.createStage(a.stages[1]); + let commented = 0; + sla.githubClient = { searchPrs: async () => [{}], getPrFromIssue: async () => ({ number: 1, title: "t", html_url: "u", updated_at: "2020-01-01T00:00:00Z", base: { repo: { full_name: "me/r" } } }), + commentOnPr: async () => { commented++; return {}; }, getIssueComments: async () => [] }; + const r = await sla.run(); + expect(r.count).toBe(1); expect(commented).toBe(0); expect(r.nudged).toEqual([]); +}); + +test("secret-guard: the remover gets this run's scan, never runs after a failed scan nor without AI", async () => { + const cwd = process.cwd(), d = tmp(); process.chdir(d); + try { + const scan = { repositories_with_findings: [{ repository: "me/r", findings: [] }] }; + const a: any = new SecretGuardAgent(base({}, { ai: { provider: "ollama", model: "m" } })); + let got: any = null; + a.createStage = async (st: any) => (st.name === "scan" ? { run: async () => scan } : { run: async () => { got = a.stageOptions(st).scanResults; return {}; } }); + await a.run(); + expect(got).toBe(scan); + expect(readFileSync(join(d, "results", readdirSync(join(d, "results"))[0]!), "utf8")).toContain("me/r"); // kept for `run-agent secret-remover` + const b: any = new SecretGuardAgent(base({}, { ai: { provider: "ollama", model: "m" } })); const ran = fakeStages(b, { scan: { error: "gitleaks missing" } }); + const r = await b.run(); + expect(ran).toEqual(["scan"]); expect(r.skipped_stages.remove).toBe("scan failed"); + const c: any = new SecretGuardAgent(base()); const ran3 = fakeStages(c, { scan: {} }); + expect((await c.run()).skipped_stages.remove).toBe("ENABLE_AI=false"); expect(ran3).toEqual(["scan"]); + } finally { process.chdir(cwd); } +}); + +test("builder stages open draft PRs labelled keep-draft", async () => { + const a: any = new BuilderAgent(base({}, { ai: { provider: "ollama", model: "m" }, aiClient: { generate: async () => "" } })); + for (const st of a.stages) expect((await a.createStage(st)).prOptions).toEqual({ draft: true, labels: [KEEP_DRAFT_LABEL] }); +}); + +test("createAgentPull: draft + label; falls back to a labelled regular PR where drafts are unsupported", async () => { + const calls: any[] = []; + const gh: any = { createPull: async (_r: string, p: any) => { calls.push(["pull", p.draft ?? false]); return { number: 1, base: { repo: { full_name: "me/r" } } }; }, addLabelToPr: async (_p: any, l: string) => { calls.push(["label", l]); return [true, ""]; } }; + await createAgentPull(gh, "me/r", { title: "t", body: "b", head: "h", base: "main" }, { draft: true, labels: [KEEP_DRAFT_LABEL] }, () => {}); + expect(calls).toEqual([["pull", true], ["label", KEEP_DRAFT_LABEL]]); + calls.length = 0; + let first = true; + gh.createPull = async (_r: string, p: any) => { if (first) { first = false; throw new Error("Draft pull requests are not supported in this repository."); } calls.push(["pull", p.draft ?? false]); return { number: 2, base: { repo: { full_name: "me/r" } } }; }; + await createAgentPull(gh, "me/r", { title: "t", body: "b", head: "h", base: "main" }, { draft: true, labels: [KEEP_DRAFT_LABEL] }, () => {}); + expect(calls).toEqual([["pull", false], ["label", KEEP_DRAFT_LABEL]]); + gh.createPull = async () => { throw new Error("Validation Failed"); }; + await expect(createAgentPull(gh, "me/r", { title: "t", body: "b", head: "h", base: "main" }, { draft: true, labels: [] }, () => {})).rejects.toThrow("Validation Failed"); +}); + +test("review gate never marks a keep-draft PR ready, even when the review approves", async () => { + const calls: string[] = []; + const gh: any = { createStatus: async () => {}, setDraft: async (_p: any, d: boolean) => { calls.push(`draft:${d}`); }, removeLabel: async () => {} }; + const approved = mkVerdict({ findings: [], verdict: APPROVE, summary: "ok" }); + const p = (labels: any[]) => ({ number: 1, draft: true, labels, head: { sha: "s" }, base: { repo: { full_name: "me/r" } } }) as any; + await applyGate(p([{ name: KEEP_DRAFT_LABEL }]), gh, approved, true, () => {}); + expect(calls).toEqual([]); + await applyGate(p([]), gh, approved, true, () => {}); + expect(calls).toEqual(["draft:false"]); +}); + +test("agent contract: off by default; refreshes skills + global AGENTS.md, caches, keeps the old copy on failure", async () => { + const home = tmp(); let calls = 0, fail = false; + const runner: any = async (cmd: string[], o: any) => { + calls++; + if (fail) return { code: 1, stdout: "", stderr: "network down", timedOut: false }; + if (cmd[1] === "clone") { const dst = cmd[cmd.length - 1]; mkdirSync(join(dst, ".git"), { recursive: true }); mkdirSync(join(dst, ".agents", "skills", "code-review"), { recursive: true }); + writeFileSync(join(dst, ".agents", "skills", "code-review", "SKILL.md"), "skill"); writeFileSync(join(dst, ".agents", "AGENTS.md"), "global rules"); } + expect(o.env.GITHUB_TOKEN).toBeUndefined(); // public clone: credentials never reach git + return { code: 0, stdout: cmd[1] === "rev-parse" ? "1234567890abcdef" : "", stderr: "", timedOut: false }; + }; + expect((await ensureContract(() => {}, { home, runner })).source).toBe("disabled"); + process.env.AGENT_CONTRACT_REFRESH = "true"; + const old = join(home, ".config", "opencode", "skills", "stale"); mkdirSync(old, { recursive: true }); + const c = await ensureContract(() => {}, { home, runner, now: 1 }); + expect(c).toEqual({ sha: "1234567890abcdef", source: "fresh" }); + expect(readFileSync(join(home, ".config", "opencode", "AGENTS.md"), "utf8")).toBe("global rules"); + expect(existsSync(join(home, ".config", "opencode", "skills", "code-review", "SKILL.md"))).toBe(true); + expect(existsSync(old)).toBe(false); // skills removed upstream disappear + expect(contractLabel()).toBe("juninmd/skills@1234567"); + const n = calls; await ensureContract(() => {}, { home, runner, now: 2 }); expect(calls).toBe(n); // within TTL: no git + fail = true; + const f = await ensureContract(() => {}, { home, runner, now: 2 + 3_600_001 }); + expect(f.source).toBe("cache"); expect(existsSync(join(home, ".config", "opencode", "skills", "code-review", "SKILL.md"))).toBe(true); +}); + +test("standardizer: every active repo, missing AGENTS.md first, capped per run, never a second open PR", async () => { + process.env.REPO_STANDARDS_MAX_PRS = "1"; + const repo = (n: string, o: any = {}) => ({ owner: { login: "me" }, full_name: `me/${n}`, name: n, ...o }); + const files: Record = { "me/a": ["AGENTS.md", ".agents", "CONTRIBUTING.md", "LICENSE"], "me/b": [], "me/c": [], "me/d": [] }; + const gh: any = { getUserRepos: async (o: any) => { expect(o.limit).toBeNull(); return [repo("a"), repo("arch", { archived: true }), repo("fork", { fork: true }), repo("b"), repo("c"), repo("d")]; }, + pathExists: async (r: string, p: string) => (files[r] ?? []).includes(p), getPulls: async (r: string) => (r === "me/b" ? [{ title: "[agent/x] Standardize b Quality & Intelligence" }] : []) }; + const a: any = new IntelligenceStandardizerAgent(base(gh)); const opened: string[] = []; + a.loadTaskInstructions = () => "i"; a.runOpencodeOnRepo = async (r: string) => { opened.push(r); return { pr_url: "u" }; }; + const r = await a.run(); + expect(opened).toEqual(["me/c"]); + const reason = Object.fromEntries(r.skipped.map((x: any) => [x.repository, x.reason])); + expect(reason).toEqual({ "me/b": "pr_already_open", "me/d": "run_cap_reached", "me/a": "already_standardized" }); +}); diff --git a/ts/tests/lote4.test.ts b/ts/tests/lote4.test.ts index 2649b90c..f083421a 100644 --- a/ts/tests/lote4.test.ts +++ b/ts/tests/lote4.test.ts @@ -1,7 +1,6 @@ import { describe, expect, test } from "bun:test"; import { mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; -import { CodeReviewerAgent } from "../src/agents/code_reviewer/agent.ts"; import { DependencyManagerAgent } from "../src/agents/dependency_manager/agent.ts"; import { detectEcosystems } from "../src/agents/dependency_manager/detect.ts"; import { SecretRemoverAgent } from "../src/agents/secret_remover/agent.ts"; @@ -13,35 +12,6 @@ import { tmp } from "./helpers.ts"; const telegram: any = { sendMessage: async () => true }; const base = (gh: any) => ({ githubClient: gh, allowlist: new RepositoryAllowlist("/nonexistent.json"), telegram, targetOwner: "me" }); -describe("code_reviewer", () => { - const pr = { number: 7, title: "t", base: { repo: { full_name: "me/r" } } }; - const mk = (response: string, extra: any = {}) => { - const posted: any[] = []; - const gh: any = { - getUserRepos: async () => [{ owner: { login: "me" }, full_name: "me/r" }], getPulls: async () => [pr], - getAuthenticatedLogin: async () => "bot", getIssueComments: async () => extra.comments ?? [], - getFiles: async () => [{ filename: "a.ts", status: "modified", additions: 1, deletions: 0, patch: "+x" }], - createReview: async (_p: any, o: any) => { if (extra.reviewFails) throw new Error("x"); posted.push(["review", o]); return {}; }, - commentOnPr: async (_p: any, b: string) => { posted.push(["comment", b]); return {}; }, - }; - const a = new CodeReviewerAgent({ ...base(gh), aiClient: { generate: async () => response } }); - return { a, posted }; - }; - test("posts inline review for issues with line", async () => { - const { a, posted } = mk('{"issues":[{"severity":"high","file":"a.ts","line":3,"description":"bug","suggestion":"fix"}],"summary":"s"}'); - const r = await a.run(); - expect(r.reviews_performed).toHaveLength(1); - expect(posted[0][0]).toBe("review"); expect(posted[0][1].comments[0]).toMatchObject({ path: "a.ts", line: 3 }); - expect(posted[0][1].body).toContain(""); - }); - test("falls back to comment, skips already reviewed", async () => { - const { a, posted } = mk('{"issues":[],"summary":"ok"}'); - await a.run(); expect(posted[0][0]).toBe("comment"); expect(posted[0][1]).toContain("No issues found"); - const s = mk("{}", { comments: [{ body: "", user: { login: "bot" } }] }); - expect((await s.a.run()).reviews_performed).toHaveLength(0); - }); -}); - describe("dependency_manager", () => { test("detects ecosystems from root files only", () => { const e = detectEcosystems(["package.json", "bun.lockb", "src/go.mod", "Cargo.toml"]); diff --git a/ts/tests/secret-guard-approval.test.ts b/ts/tests/secret-guard-approval.test.ts new file mode 100644 index 00000000..46a49cd0 --- /dev/null +++ b/ts/tests/secret-guard-approval.test.ts @@ -0,0 +1,119 @@ +import { expect, test } from "bun:test"; +import { join } from "node:path"; +import { writeFileSync } from "node:fs"; +import { APPROVAL_LABEL, ApprovalGate, approvalId, TelegramApprovals } from "../src/agents/secret_remover/approval.ts"; +import { FindingProcessor } from "../src/agents/secret_remover/processor.ts"; +import { PRAssistantAgent } from "../src/agents/pr_assistant/agent.ts"; +import { KEEP_DRAFT_LABEL } from "../src/agents/core/pr-options.ts"; +import { RepositoryAllowlist } from "../src/config/allowlist.ts"; +import { tmp } from "./helpers.ts"; + +const F1 = { rule_id: "aws-key", file: "a.env", line: 3, commit: "c1" }, F2 = { rule_id: "gh-pat", file: "b.ts", line: 9, commit: "c2" }; +const ID = approvalId("me/r", [F1, F2]); +const issue = (id: string, n = 5) => ({ number: n, html_url: `https://github.com/me/r/issues/${n}`, labels: [{ name: APPROVAL_LABEL }], body: `\nx` }); +const comment = (login: string, body: string, type = "User") => ({ user: { login, type }, body }); +function gh(o: { issues?: any[]; comments?: any[] } = {}) { + const calls: any[] = []; + return { calls, getOpenIssues: async () => o.issues ?? [], getIssueComments: async () => o.comments ?? [], + createIssue: async (_r: string, p: any) => { calls.push(["issue", p]); return { number: 9, html_url: "https://github.com/me/r/issues/9" }; }, + post: async (path: string, b: any) => { calls.push(["post", path, b.body]); return {}; }, patch: async (path: string, b: any) => { calls.push(["patch", path, b.state]); return {}; } } as any; +} +const tg = () => { const sent: any[] = []; return { sent, sendMessage: async (t: string, _m: string, k?: any) => { sent.push([t, k]); return true; } } as any; }; + +test("approval id is bound to the exact finding set, not to its order", () => { + expect(approvalId("me/r", [F2, F1])).toBe(ID); + expect(approvalId("me/r", [F1])).not.toBe(ID); + expect(approvalId("me/other", [F1, F2])).not.toBe(ID); + expect(ID).toMatch(/^[0-9a-f]{10}$/); +}); + +test("gate: only the owner's /aprovar (or a bot-persisted Telegram approval) approves", async () => { + const check = (comments: any[], tgApproved = new Set()) => new ApprovalGate(gh({ issues: [issue(ID)], comments }), tg(), "Me", tgApproved, () => {}).check("me/r", ID); + expect(await check([comment("me", "/aprovar")])).toEqual({ approved: true, via: "github", issue: 5 }); + expect((await check([comment("intruder", "/aprovar")])).approved).toBe(false); + expect((await check([comment("me", "pode /aprovar depois")])).approved).toBe(false); // must be the command, not a mention + expect((await check([comment("me", ``)])).approved).toBe(false); // a human cannot forge the bot marker + expect(await check([comment("juninmd-bot[bot]", ``, "Bot")])).toEqual({ approved: true, via: "telegram", issue: 5 }); + // An approval for another finding set never carries over. + const other = await new ApprovalGate(gh({ issues: [issue("ffffffffff")], comments: [comment("me", "/aprovar")] }), tg(), "me", new Set(), () => {}).check("me/r", ID); + expect(other.approved).toBe(false); + // Fail-closed on API errors. + const broken: any = { getOpenIssues: async () => { throw new Error("502"); } }; + expect((await new ApprovalGate(broken, tg(), "me", new Set(), () => {}).check("me/r", ID)).approved).toBe(false); +}); + +test("gate: a Telegram approval is persisted on the issue so the next run still sees it", async () => { + const g = gh({ issues: [issue(ID)] }); + const r = await new ApprovalGate(g, tg(), "me", new Set([ID]), () => {}).check("me/r", ID); + expect(r).toEqual({ approved: true, via: "telegram", issue: 5 }); + expect(g.calls[0][2]).toContain(`secret-guard:approved-telegram:${ID}`); +}); + +test("gate.request: one issue + one Telegram button per finding set; older requests are superseded", async () => { + const g = gh({ issues: [issue("0123456789", 4)] }), t = tg(); + const r = await new ApprovalGate(g, t, "me", new Set(), () => {}).request("me/r", ID, [F1, F2]); + expect(r).toEqual({ issue: 9, created: true }); + const created = g.calls.find((c: any) => c[0] === "issue")[1]; + expect(created.labels).toEqual([APPROVAL_LABEL]); expect(created.body).toContain(`secret-guard:${ID}`); expect(created.body).toContain("/aprovar"); + expect(created.body).not.toContain("redacted"); // no secret content, only locations + expect(g.calls.some((c: any) => c[0] === "patch" && c[1].endsWith("/issues/4"))).toBe(true); + expect(t.sent[0][1].inline_keyboard[0][0].callback_data).toBe(`sg:${ID}`); + const again = gh({ issues: [issue(ID)] }), t2 = tg(); + expect(await new ApprovalGate(again, t2, "me", new Set(), () => {}).request("me/r", ID, [F1, F2])).toEqual({ issue: 5, created: false }); + expect(t2.sent).toHaveLength(0); expect(again.calls).toHaveLength(0); +}); + +test("processor: without approval nothing is rewritten; with approval it rewrites and closes the issue", async () => { + const removed: string[] = [], notes: string[] = []; + const mkProc = (approved: boolean, gateCalls: string[]) => new FindingProcessor({} as any, tg(), {} as any, () => {}, { + check: async () => ({ approved, via: approved ? "github" : null, issue: approved ? 5 : null }), + request: async () => { gateCalls.push("request"); return { issue: 9, created: true }; }, + close: async () => { gateCalls.push("close"); }, + } as any, async (_r: string, f: any) => { removed.push(f.file); return true; }); + const items = [{ f: F1, originalLine: "x" }, { f: F2, originalLine: "y" }], notify = async (_f: any, a: string) => { notes.push(a); }; + const g1: string[] = [], acts1: any[] = []; + expect(await mkProc(false, g1).resolveRemovals("me/r", items, "/clone", "tok", notify, acts1)).toEqual({ removed: 0, awaiting: 2 }); + expect(removed).toEqual([]); expect(g1).toEqual(["request"]); expect(acts1.map((a) => a.status)).toEqual(["AWAITING_APPROVAL", "AWAITING_APPROVAL"]); + expect(notes).toEqual(["AWAITING_APPROVAL", "AWAITING_APPROVAL"]); + const g2: string[] = [], acts2: any[] = []; + expect(await mkProc(true, g2).resolveRemovals("me/r", items, "/clone", "tok", notify, acts2)).toEqual({ removed: 2, awaiting: 0 }); + expect(removed).toEqual(["a.env", "b.ts"]); expect(g2).toEqual(["close"]); expect(acts2[0].approved_via).toBe("github"); + // No gate wired: never rewrite. + const bare = new FindingProcessor({} as any, tg(), {} as any, () => {}, null, async () => { throw new Error("must not rewrite"); }); + expect((await bare.resolveRemovals("me/r", items, "/c", "t", notify, [])).awaiting).toBe(2); +}); + +test("telegram approvals: owner's private chat or listed ids only; updates acknowledged; errors approve nothing", async () => { + const cq = (id: number, data: string, chat: any, from = 1) => ({ update_id: id, callback_query: { id: `q${id}`, data, from: { id: from }, message: { chat } } }); + const calls: any[] = []; + const fetchFn: any = async (url: string, init: any) => { + const body = JSON.parse(init.body); calls.push([url.split("/").pop(), body]); + if (url.endsWith("getUpdates") && body.offset === undefined) + return { json: async () => ({ ok: true, result: [cq(10, `sg:${ID}`, { id: 42, type: "private" }), cq(11, "sg:aaaaaaaaaa", { id: -5, type: "group" }), cq(12, "other", { id: 42, type: "private" })] }) }; + return { json: async () => ({ ok: true, result: [] }) }; + }; + const ids = await new TelegramApprovals("tok", "42", [], () => {}, fetchFn).poll(); + expect([...ids]).toEqual([ID]); + expect(calls.filter((c) => c[0] === "answerCallbackQuery").map((c) => c[1].text.startsWith("Aprovado"))).toEqual([true, false]); + expect(calls.at(-1)).toEqual(["getUpdates", { offset: 13, timeout: 0, limit: 1, allowed_updates: ["callback_query"] }]); + const listed = await new TelegramApprovals("tok", "42", ["7"], () => {}, fetchFn).poll(); + expect(listed.size).toBe(0); // approver list set: chat membership alone is not enough + const down: any = async () => { throw new Error("offline"); }; + expect((await new TelegramApprovals("tok", "42", [], () => {}, down).poll()).size).toBe(0); + expect((await new TelegramApprovals(null, "42", [], () => {}, fetchFn).poll()).size).toBe(0); +}); + +test("pr-assistant: keep-draft PRs are reviewed but never merged, not even on owner /merge", async () => { + const SHA = "abcdef0123456789abcdef0123456789abcdef01", calls: any[] = []; + const p: any = { number: 7, title: "t", html_url: "u", mergeable: true, mergeable_state: "clean", created_at: "2020-01-01T00:00:00Z", user: { login: "juninmd" }, draft: true, + labels: [{ name: KEEP_DRAFT_LABEL }], head: { sha: SHA, ref: "f", repo: { full_name: "o/r" } }, base: { ref: "main", repo: { full_name: "o/r" } } }; + const gh: any = { getIssueComments: async () => [{ user: { login: "juninmd", type: "User" }, body: "/merge", created_at: "2026-11-20T10:00:00Z" }], + getCombinedStatus: async () => ({ statuses: [] }), getCheckRuns: async () => [], getPull: async () => p, addAssigneeToPr: async () => [true, ""], requestReviewerOnPr: async () => [true, ""], + mergePr: async () => { calls.push("merge"); return [true, "ok"]; }, setDraft: async () => { calls.push("ready"); } }; + const pol = join(tmp(), "a.json"); writeFileSync(pol, JSON.stringify({ defaults: { mode: "merge", merge: true } })); + const a: any = new PRAssistantAgent({ githubClient: gh, allowlist: new RepositoryAllowlist("/nonexistent.json"), telegram: tg(), autonomyPolicyPath: pol, aiClient: null, opencodeReviewActive: false, requireReview: true }); + let reviewed = 0; a.reviews.runOpencodeReview = async () => { reviewed++; return "approved"; }; + const r = { merged: [], conflicts_resolved: [], pipeline_failures: [], skipped: [] as any[], blocked: [] }; + await a.processPr(p, r); + expect(reviewed).toBe(1); expect(r.skipped[0].reason).toBe("keep_draft"); expect(calls).toEqual([]); +}); diff --git a/ts/tests/webhooks.test.ts b/ts/tests/webhooks.test.ts index e461ebaa..a337d461 100644 --- a/ts/tests/webhooks.test.ts +++ b/ts/tests/webhooks.test.ts @@ -125,7 +125,7 @@ test("admin API: disabled without token, 401, filters, detail, reprocess, bulk, expect((await get(app, "/api/overview?hours=0")).status).toBe(422); expect((await get(app, "/api/overview?hours=9999")).status).toBe(422); const fleet = await (await get(app, "/api/agents")).json(); - expect(fleet.agents.length).toBe(15); + expect(fleet.agents.length).toBe(8); }); test("admin: bad tokens throttled; responses not cacheable", async () => { From d025c4756389834e1cb89a90c936f3a1cfee304d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 13:59:58 +0000 Subject: [PATCH 2/2] fix(agents): close review gaps in approval, keep-draft and retired names - Telegram approval marker counts only from this bot's login or the owner. - Approval button is sent even when the repo has issues disabled. - Public approval issue lists rules only; consent text says the whole file is deleted from history and all branches/tags are force-pushed. - keep-draft label failure closes the PR (fail closed). - code-reviewer / conflict-resolver CronJobs become no-ops instead of a second full pr-assistant pass. - remove stage never runs on stale findings; AGENTS.md install is atomic. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Cn6JQLt2WHRBiK4sRPxupu --- AGENTS.md | 7 +++-- README.md | 5 +-- ts/src/agents/catalog.ts | 9 +++--- ts/src/agents/core/agent-contract.ts | 3 +- ts/src/agents/core/pr-options.ts | 8 ++++- ts/src/agents/registry.ts | 4 +++ ts/src/agents/secret_guard/agent.ts | 3 +- ts/src/agents/secret_remover/approval.ts | 39 ++++++++++++++++-------- ts/tests/fleet-redesign.test.ts | 14 ++++++++- ts/tests/secret-guard-approval.test.ts | 12 ++++++-- 10 files changed, 77 insertions(+), 27 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 8a2d12b0..87aec0ff 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -71,12 +71,15 @@ Prioridade: **Critical** (segurança) › **High** (PR/CI) › **Medium** › ** **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`. +`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ó arquivo, linha, regra e commit, nunca o segredo) e manda um botão **Aprovar** no Telegram. +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. diff --git a/README.md b/README.md index 578287c6..0f990652 100644 --- a/README.md +++ b/README.md @@ -33,8 +33,9 @@ Some of them run former agents as internal **stages**. 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`, and `code-reviewer` / `conflict-resolver` -(both now part of `pr-assistant`). +`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 diff --git a/ts/src/agents/catalog.ts b/ts/src/agents/catalog.ts index aa5ef2c2..d1d58ea1 100644 --- a/ts/src/agents/catalog.ts +++ b/ts/src/agents/catalog.ts @@ -50,11 +50,12 @@ export const AGENT_CATALOG: AgentSpec[] = [ export const AGENTS_BY_NAME = new Map(AGENT_CATALOG.map((s) => [s.name, s])); /** Former agent names: still accepted by the CLI so existing CronJobs keep running the same unit of work. */ -export const AGENT_ALIASES: Record = { +export const AGENT_ALIASES: Record = { "security-scanner": { agent: "secret-guard", stage: "scan" }, "secret-remover": { agent: "secret-guard", stage: "remove" }, - "code-reviewer": { agent: "pr-assistant" }, - "conflict-resolver": { agent: "pr-assistant" }, + // Retired: their work now runs inside pr-assistant's own schedule; a leftover CronJob becomes a no-op, not a second PR pass. + "code-reviewer": { agent: "pr-assistant", retired: true }, + "conflict-resolver": { agent: "pr-assistant", retired: true }, "ci-health": { agent: "flow-watch", stage: "ci" }, "pr-sla": { agent: "flow-watch", stage: "sla" }, "intelligence-standardizer": { agent: "repo-standards", stage: "agents-md" }, @@ -65,7 +66,7 @@ export const AGENT_ALIASES: Record = }; /** Resolve a CLI name (current or former) to the agent that runs it, plus the single stage a former name maps to. */ -export function resolveAgentName(name: string): { agent: string; stage?: string } | null { +export function resolveAgentName(name: string): { agent: string; stage?: string; retired?: boolean } | null { if (AGENTS_BY_NAME.has(name)) return { agent: name }; return AGENT_ALIASES[name] ?? null; } diff --git a/ts/src/agents/core/agent-contract.ts b/ts/src/agents/core/agent-contract.ts index fa6c3fdf..15cf875d 100644 --- a/ts/src/agents/core/agent-contract.ts +++ b/ts/src/agents/core/agent-contract.ts @@ -42,7 +42,8 @@ function install(src: string, home: string): void { if (existsSync(skills)) renameSync(skills, old); renameSync(fresh, skills); rmSync(old, { recursive: true, force: true }); - cpSync(join(src, ".agents", "AGENTS.md"), join(cfg, "AGENTS.md")); + cpSync(join(src, ".agents", "AGENTS.md"), join(cfg, "AGENTS.md.new")); + renameSync(join(cfg, "AGENTS.md.new"), join(cfg, "AGENTS.md")); // atomic: a starting opencode never reads a half-written file } export function ensureContract(log: Log, o: { home?: string; runner?: Runner; now?: number } = {}): Promise { diff --git a/ts/src/agents/core/pr-options.ts b/ts/src/agents/core/pr-options.ts index 4f8e9f4b..f164aa70 100644 --- a/ts/src/agents/core/pr-options.ts +++ b/ts/src/agents/core/pr-options.ts @@ -18,6 +18,12 @@ export async function createAgentPull(gh: GithubClient, repo: string, p: { title log(`Draft PRs unavailable in ${repo}; opening a regular PR guarded by '${o.labels.join(", ")}'`, "WARNING"); pr = await gh.createPull(repo, p); } - for (const label of o.labels) await gh.addLabelToPr(pr, label); + for (const label of o.labels) { + const [ok, msg] = (await gh.addLabelToPr(pr, label)) as [boolean, string]; + if (ok) continue; + // Fail closed: a builder PR without its guard label could be marked ready and merged by the bot. + await gh.closePr(pr); + throw new Error(`label '${label}' could not be added to ${repo}#${pr.number} (${msg}); PR closed`); + } return pr; } diff --git a/ts/src/agents/registry.ts b/ts/src/agents/registry.ts index a3a3858f..6908c2c5 100644 --- a/ts/src/agents/registry.ts +++ b/ts/src/agents/registry.ts @@ -42,6 +42,10 @@ export async function createAgent(name: string, s: Settings, o: { provider?: str const target = resolveAgentName(name); const spec = target ? AGENTS_BY_NAME.get(target.agent) : undefined; if (!target || !spec) throw new Error(`unknown agent: ${name}`); + if (target.retired) { + const reason = `'${name}' is retired: its work runs inside ${target.agent}; remove this schedule`; + return { name, run: async () => { console.warn(`[WARNING] ${reason}`); return { status: "skipped", reason }; } } as unknown as BaseAgent; + } const agent = target.agent, stage = spec.stages.find((st) => st.name === target.stage); if (!isPorted(agent)) throw new Error(`agent '${agent}' ainda não foi portado para Bun`); const mod = await import(join(agentDir(agent), "agent.ts")); diff --git a/ts/src/agents/secret_guard/agent.ts b/ts/src/agents/secret_guard/agent.ts index a06b8212..c8d93b06 100644 --- a/ts/src/agents/secret_guard/agent.ts +++ b/ts/src/agents/secret_guard/agent.ts @@ -11,7 +11,8 @@ export class SecretGuardAgent extends CompositeAgent { constructor(o: AgentOpts) { super("secret-guard", o); } protected skipReason(stage: StageSpec, done: Record): string | null { - if (stage.name === "remove" && done.scan && ("error" in done.scan || done.scan.status === "failed")) return "scan failed"; + if (stage.name === "remove" && !done.scan) return "scan not run (stale findings are never used)"; + if (stage.name === "remove" && ("error" in done.scan! || done.scan!.status === "failed")) return "scan failed"; return super.skipReason(stage, done); } protected stageOptions(stage: StageSpec) { return stage.name === "remove" && this.scan ? { scanResults: this.scan } : {}; } diff --git a/ts/src/agents/secret_remover/approval.ts b/ts/src/agents/secret_remover/approval.ts index d0d43d55..e0234743 100644 --- a/ts/src/agents/secret_remover/approval.ts +++ b/ts/src/agents/secret_remover/approval.ts @@ -5,6 +5,7 @@ import { createHash } from "node:crypto"; import type { GithubClient } from "../../github/client.ts"; import { TelegramNotifier } from "../../notifications/telegram.ts"; +import { configuredBotLogin, DEFAULT_BOT_LOGIN } from "../pr_assistant/bot-identity.ts"; type Log = (m: string, level?: string) => void; export const APPROVAL_LABEL = "secret-guard"; @@ -55,14 +56,18 @@ export class TelegramApprovals { } } +const CONSENT = "Aprovar apaga **o arquivo inteiro** de todo o histórico git (`git-filter-repo --invert-paths`) e faz force-push de todos os branches e tags. Não tem volta."; + +/** Public text: counts and rules only; file paths and lines go to the owner's private Telegram chat. */ function issueBody(id: string, findings: Finding[]): string { - const rows = findings.slice(0, 50).map((f) => `- \`${f.file ?? "?"}\` linha ${f.line ?? 0} · regra \`${f.rule_id ?? f.RuleID ?? "?"}\` · commit \`${String(f.commit ?? "HEAD").slice(0, 8)}\``); + const rules = [...new Set(findings.map((f) => String(f.rule_id ?? f.RuleID ?? "?")))].map((r) => `\`${r}\``).join(", "); return [marker(id), "## 🔐 Remoção de segredo do histórico aguardando aprovação", "", - `O secret-guard classificou ${findings.length} achado(s) como segredo real. Remover reescreve o histórico git do branch padrão (force-push), o que **não tem volta**.`, "", - ...rows, "", + `O secret-guard classificou ${findings.length} achado(s) como segredo real (regras: ${rules}). Os arquivos e linhas estão na mensagem privada do Telegram.`, "", + CONSENT, "", "**Para aprovar:** comente `/aprovar` aqui (só o dono do repositório conta) ou toque em **Aprovar** na mensagem do Telegram.", "Sem aprovação nada é reescrito. Rotacione o segredo de qualquer forma: removê-lo do histórico não o invalida."].join("\n"); } +const telegramList = (findings: Finding[]) => findings.slice(0, 15).map((f) => ` └ ${esc(String(f.file ?? "?"))} linha ${f.line ?? 0} · ${esc(String(f.rule_id ?? f.RuleID ?? "?"))}`).join("\n"); export class ApprovalGate { constructor(private gh: GithubClient, private telegram: TelegramNotifier, private owner: string, private telegramApproved: Set, private log: Log) {} @@ -71,6 +76,8 @@ export class ApprovalGate { return (await this.gh.getOpenIssues(repo, 100)).filter((i) => (i.labels ?? []).some((l: any) => (typeof l === "string" ? l : l.name) === APPROVAL_LABEL)); } private isOwner = (c: any) => (c.user?.login ?? "").toLowerCase() === this.owner.toLowerCase(); + /** Only this bot's own App login (or the owner, when the bot runs on the owner's PAT) can persist a Telegram approval. */ + private isSelfOrOwner = (c: any) => this.isOwner(c) || [configuredBotLogin(), DEFAULT_BOT_LOGIN].map((l) => l.toLowerCase()).includes((c.user?.login ?? "").toLowerCase()); async check(repo: string, id: string): Promise { try { @@ -82,24 +89,30 @@ export class ApprovalGate { if (!issue) return { approved: false, via: null, issue: null }; const comments = await this.gh.getIssueComments(repo, issue.number); if (comments.some((c: any) => this.isOwner(c) && APPROVE_RE.test(c.body ?? ""))) return { approved: true, via: "github", issue: issue.number }; - // A Telegram approval persisted by the bot on an earlier run (only a Bot account can author it). - if (comments.some((c: any) => c.user?.type === "Bot" && (c.body ?? "").includes(telegramMarker(id)))) return { approved: true, via: "telegram", issue: issue.number }; + // A Telegram approval persisted by this bot on an earlier run; any other account writing the marker is ignored. + if (comments.some((c: any) => this.isSelfOrOwner(c) && (c.body ?? "").includes(telegramMarker(id)))) return { approved: true, via: "telegram", issue: issue.number }; return { approved: false, via: null, issue: issue.number }; } catch (e: any) { this.log(`Approval check failed for ${repo}: ${e?.message ?? e}`, "WARNING"); return { approved: false, via: null, issue: null }; } } - /** Open (once per finding set) the approval issue and send the Telegram button. Older requests are superseded. */ + /** Open (once per finding set) the approval issue and send the Telegram button. Older requests are superseded. + * Without an issue (issues disabled, API error) the button is still sent on every run, so a real secret is never silent. */ async request(repo: string, id: string, findings: Finding[]): Promise<{ issue: number | null; created: boolean }> { + let issue: { number: number; html_url: string } | null = null; try { const open = await this.openIssues(repo), existing = open.find((i) => (i.body ?? "").includes(marker(id))); if (existing) return { issue: existing.number, created: false }; - const issue = await this.gh.createIssue(repo, { title: "🔐 secret-guard: aprovar remoção de segredo do histórico", body: issueBody(id, findings), labels: [APPROVAL_LABEL] }); - for (const old of open) await this.close(repo, old.number, `Substituída por #${issue.number} (achados mudaram).`); - await this.telegram.sendMessage( - `🔐 SECRET GUARD — APROVAÇÃO NECESSÁRIA\n──────────────────────\n📦 ${esc(repo)}\n🔥 ${findings.length} segredo(s) real(is) no histórico.\nRemover reescreve o histórico (irreversível). Nada acontece sem sua aprovação.`, - "HTML", { inline_keyboard: [[{ text: "✅ Aprovar reescrita", callback_data: `sg:${id}` }], [{ text: "🔗 Ver issue", url: issue.html_url }]] }); - return { issue: issue.number, created: true }; - } catch (e: any) { this.log(`Could not request approval for ${repo}: ${e?.message ?? e}`, "WARNING"); return { issue: null, created: false }; } + const created: any = await this.gh.createIssue(repo, { title: "🔐 secret-guard: aprovar remoção de segredo do histórico", body: issueBody(id, findings), labels: [APPROVAL_LABEL] }); + issue = { number: created.number, html_url: created.html_url }; + for (const old of open) await this.close(repo, old.number, `Substituída por #${created.number} (achados mudaram).`); + } catch (e: any) { this.log(`Could not open the approval issue for ${repo}: ${e?.message ?? e}`, "WARNING"); } + const buttons: any[][] = [[{ text: "✅ Aprovar reescrita", callback_data: `sg:${id}` }]]; + if (issue) buttons.push([{ text: "🔗 Ver issue", url: issue.html_url }]); + await this.telegram.sendMessage( + `🔐 SECRET GUARD — APROVAÇÃO NECESSÁRIA\n──────────────────────\n📦 ${esc(repo)}\n🔥 ${findings.length} segredo(s) real(is) no histórico:\n${telegramList(findings)}\n\n` + + `Aprovar apaga o arquivo inteiro de todo o histórico e faz force-push de todos os branches e tags (irreversível). Nada acontece sem sua aprovação.`, + "HTML", { inline_keyboard: buttons }).catch(() => false); + return { issue: issue?.number ?? null, created: true }; } async close(repo: string, issue: number, note: string): Promise { diff --git a/ts/tests/fleet-redesign.test.ts b/ts/tests/fleet-redesign.test.ts index 66793cc2..2bbb491b 100644 --- a/ts/tests/fleet-redesign.test.ts +++ b/ts/tests/fleet-redesign.test.ts @@ -36,7 +36,7 @@ test("catalog: 8 scoped agents; every stage and former name resolves to real cod expect(AGENTS_BY_NAME.has(old)).toBe(false); // a former name never shadows a current agent } expect(resolveAgentName("pr-sla")).toEqual({ agent: "flow-watch", stage: "sla" }); - expect(resolveAgentName("code-reviewer")).toEqual({ agent: "pr-assistant" }); + expect(resolveAgentName("code-reviewer")).toEqual({ agent: "pr-assistant", retired: true }); expect(resolveAgentName("nope")).toBeNull(); }); @@ -47,6 +47,9 @@ test("registry: a former name builds the new agent restricted to its stage; AI s await expect(createAgent("secret-remover", s)).rejects.toThrow("requires AI"); const g: any = await createAgent("secret-guard", s); // scanning works without AI expect(g.onlyStage).toBeNull(); expect(g.opts.ai).toBeUndefined(); + // Retired names: a leftover CronJob is a no-op, never a second full pr-assistant pass. + const retired = await createAgent("code-reviewer", s); + expect(await retired.run()).toMatchObject({ status: "skipped" }); }); test("composite: stages run in order, toggles skip, a failed stage marks the run failed; a single stage passes through", async () => { @@ -90,6 +93,10 @@ test("secret-guard: the remover gets this run's scan, never runs after a failed expect(ran).toEqual(["scan"]); expect(r.skipped_stages.remove).toBe("scan failed"); const c: any = new SecretGuardAgent(base()); const ran3 = fakeStages(c, { scan: {} }); expect((await c.run()).skipped_stages.remove).toBe("ENABLE_AI=false"); expect(ran3).toEqual(["scan"]); + process.env.SECURITY_SCANNER_ENABLED = "false"; + const e: any = new SecretGuardAgent(base({}, { ai: { provider: "ollama", model: "m" } })); const ran4 = fakeStages(e, {}); + expect((await e.run()).skipped_stages.remove).toContain("scan not run"); expect(ran4).toEqual([]); + delete process.env.SECURITY_SCANNER_ENABLED; } finally { process.chdir(cwd); } }); @@ -108,6 +115,11 @@ test("createAgentPull: draft + label; falls back to a labelled regular PR where gh.createPull = async (_r: string, p: any) => { if (first) { first = false; throw new Error("Draft pull requests are not supported in this repository."); } calls.push(["pull", p.draft ?? false]); return { number: 2, base: { repo: { full_name: "me/r" } } }; }; await createAgentPull(gh, "me/r", { title: "t", body: "b", head: "h", base: "main" }, { draft: true, labels: [KEEP_DRAFT_LABEL] }, () => {}); expect(calls).toEqual([["pull", false], ["label", KEEP_DRAFT_LABEL]]); + // Fail closed: label refused -> the PR is closed and the run errors, never an unguarded PR. + gh.createPull = async () => ({ number: 3, base: { repo: { full_name: "me/r" } } }); gh.addLabelToPr = async () => [false, "403"]; gh.closePr = async (p: any) => { calls.push(["close", p.number]); return [true, ""]; }; + calls.length = 0; + await expect(createAgentPull(gh, "me/r", { title: "t", body: "b", head: "h", base: "main" }, { draft: true, labels: [KEEP_DRAFT_LABEL] }, () => {})).rejects.toThrow("PR closed"); + expect(calls).toEqual([["close", 3]]); gh.createPull = async () => { throw new Error("Validation Failed"); }; await expect(createAgentPull(gh, "me/r", { title: "t", body: "b", head: "h", base: "main" }, { draft: true, labels: [] }, () => {})).rejects.toThrow("Validation Failed"); }); diff --git a/ts/tests/secret-guard-approval.test.ts b/ts/tests/secret-guard-approval.test.ts index 46a49cd0..469dad18 100644 --- a/ts/tests/secret-guard-approval.test.ts +++ b/ts/tests/secret-guard-approval.test.ts @@ -32,7 +32,8 @@ test("gate: only the owner's /aprovar (or a bot-persisted Telegram approval) app expect(await check([comment("me", "/aprovar")])).toEqual({ approved: true, via: "github", issue: 5 }); expect((await check([comment("intruder", "/aprovar")])).approved).toBe(false); expect((await check([comment("me", "pode /aprovar depois")])).approved).toBe(false); // must be the command, not a mention - expect((await check([comment("me", ``)])).approved).toBe(false); // a human cannot forge the bot marker + expect((await check([comment("intruder", ``)])).approved).toBe(false); // nobody else can forge the marker + expect((await check([comment("github-actions[bot]", ``, "Bot")])).approved).toBe(false); // nor another bot expect(await check([comment("juninmd-bot[bot]", ``, "Bot")])).toEqual({ approved: true, via: "telegram", issue: 5 }); // An approval for another finding set never carries over. const other = await new ApprovalGate(gh({ issues: [issue("ffffffffff")], comments: [comment("me", "/aprovar")] }), tg(), "me", new Set(), () => {}).check("me/r", ID); @@ -55,12 +56,19 @@ test("gate.request: one issue + one Telegram button per finding set; older reque expect(r).toEqual({ issue: 9, created: true }); const created = g.calls.find((c: any) => c[0] === "issue")[1]; expect(created.labels).toEqual([APPROVAL_LABEL]); expect(created.body).toContain(`secret-guard:${ID}`); expect(created.body).toContain("/aprovar"); - expect(created.body).not.toContain("redacted"); // no secret content, only locations + expect(created.body).not.toContain("a.env"); expect(created.body).toContain("aws-key"); // public issue: rules only, locations go to Telegram + expect(created.body).toContain("arquivo inteiro"); // consent states what really happens + expect(t.sent[0][0]).toContain("a.env"); expect(g.calls.some((c: any) => c[0] === "patch" && c[1].endsWith("/issues/4"))).toBe(true); expect(t.sent[0][1].inline_keyboard[0][0].callback_data).toBe(`sg:${ID}`); const again = gh({ issues: [issue(ID)] }), t2 = tg(); expect(await new ApprovalGate(again, t2, "me", new Set(), () => {}).request("me/r", ID, [F1, F2])).toEqual({ issue: 5, created: false }); expect(t2.sent).toHaveLength(0); expect(again.calls).toHaveLength(0); + // Issues disabled: no issue, but the owner still gets the button (a real secret is never silent). + const noIssues = gh(); noIssues.createIssue = async () => { throw new Error("410 Issues are disabled"); }; + const t3 = tg(); + expect(await new ApprovalGate(noIssues, t3, "me", new Set(), () => {}).request("me/r", ID, [F1])).toEqual({ issue: null, created: true }); + expect(t3.sent[0][1].inline_keyboard).toEqual([[{ text: "✅ Aprovar reescrita", callback_data: `sg:${ID}` }]]); }); test("processor: without approval nothing is rewritten; with approval it rewrites and closes the issue", async () => {