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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ jobs:
with:
components: rustfmt, clippy, llvm-tools-preview
- uses: taiki-e/install-action@cargo-llvm-cov
- uses: taiki-e/install-action@cargo-mutants
- name: Require branch rebased on master
run: |
git fetch --no-tags origin master
Expand All @@ -32,5 +31,3 @@ jobs:
run: cargo clippy --all-targets --all-features -- -D warnings
- run: cargo test --all-targets --all-features
- run: cargo llvm-cov --workspace --all-features --fail-under-lines 95.01
- run: cargo mutants --baseline run --copy-target true --minimum-test-timeout 60 --no-shuffle -j 4
- run: bash scripts/check-mutation-score.sh
19 changes: 19 additions & 0 deletions .github/workflows/mutation.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: Mutation testing

on:
workflow_dispatch:

permissions:
contents: read

jobs:
mutation:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: dtolnay/rust-toolchain@stable
- uses: taiki-e/install-action@cargo-mutants
- run: cargo mutants --baseline run --copy-target true --minimum-test-timeout 60 --no-shuffle -j 4
- run: bash scripts/check-mutation-score.sh
164 changes: 83 additions & 81 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -1,81 +1,83 @@
# AGENTS.md

## Objetivo do repositório

Este repositório contém o `risk-gate`, um software escrito em Rust e executado
como etapa de GitHub Actions. A finalidade do software é analisar o risco de um
Pull Request, aplicar gates de validação compatíveis com o risco encontrado e
publicar um relatório auditável no PR.

O produto não é um linter genérico nem um serviço externo. A configuração é
versionada junto com o projeto analisado no arquivo `.risk-gate.yaml`.

## Regras obrigatórias para agentes

1. Implemente o produto em Rust. Não introduza uma implementação paralela em
Python, Node.js ou Elixir. Ferramentas auxiliares podem usar outra linguagem
somente quando isso for explicitamente necessário e permanecerem fora do
runtime principal.
2. Preserve uma arquitetura de biblioteca + CLI. A biblioteca deve concentrar
parsing, descoberta de linguagens, AST, mapeamento, cálculo de risco,
regras e relatório; a CLI deve adaptar isso ao GitHub Actions.
3. Toda decisão de risco deve ser determinística, explicável e testável sem
acesso à rede. O acesso ao GitHub deve ser uma borda substituível.
4. O arquivo `.risk-gate.yaml` é parte do contrato público. Mudanças
incompatíveis exigem atualização da especificação, dos exemplos e dos
testes de contrato.
5. Nunca trate uma validação não executada, interrompida, com comando ausente
ou com saída inconclusiva como sucesso.
6. Não publique, aprove, faça merge ou altere configurações do GitHub fora do
escopo explícito da execução. O comentário do relatório deve ser idempotente
e atualizado por uma marca estável.
7. Não esconda falhas por meio de `instantMerge`. Essa opção somente impede que
o gate bloqueie o merge; ela não converte validações falhas em sucesso nem
altera o relatório.
8. Comandos de validação são configuração não confiável do repositório. Execute
com diretório de trabalho, ambiente e timeout explícitos, registre o resultado
e evite interpolação insegura de valores vindos de eventos do GitHub.
9. Separe sempre os estados `SUCCESS`, `PARTIAL` e `FAILED`. Um comentário,
uma árvore AST parcial ou uma permissão ausente não prova sucesso completo.
10. Antes de declarar uma integração concluída, prove o caminho real: evento do
PR, leitura da configuração, diff, análise, execução dos gates, comentário
e código de saída da Action.

## Escopo inicial de linguagens

O modelo de AST deve ser independente de linguagem. A primeira entrega deve
suportar Python, JavaScript, TypeScript e Elixir, usando parsers concretos
atrás de uma interface comum. A árvore deve cobrir todo o projeto incluído no
escopo da execução, não apenas arquivos alterados. Arquivos sem parser devem
ser reportados como não analisados; nunca devem desaparecer silenciosamente.

## Modelo de risco

Os níveis ordenados, do menor para o maior, são:

`minimal < low < normal < high < danger`

O risco do PR é o maior risco aplicável aos módulos alcançados por arquivos
alterados no diff. Alterações sem correspondência no `riskMap` usam o risco
`normal` por padrão, para que uma área nova não passe despercebida. O fallback
deve ser configurável somente quando isso estiver especificado e validado.

## Fluxo esperado

`configuração -> árvore AST completa -> módulos/path map -> diff do PR -> risco
máximo -> gateRules -> validações -> comentário no PR -> exit code`

Cada etapa deve expor dados suficientes para diagnóstico e testes. Consulte os
documentos em `specs/` antes de alterar contratos e `docs/` para exemplos de
operação.

## Qualidade mínima

Antes de concluir uma mudança, execute os checks Rust disponíveis (`cargo fmt
--check`, `cargo clippy --all-targets --all-features -- -D warnings` e `cargo
test`, quando o projeto já os tiver). Adicione testes unitários para regras de
risco e testes de integração para configuração, diff, gates e relatório.

Toda alteração deve atualizar a documentação afetada. Não invente uma
capacidade do GitHub Actions que não esteja coberta por teste ou marcada como
limitação.
# Agent Instructions

## Repository purpose

This repository contains risk-gate, a Rust application executed as a GitHub
Actions step. It analyzes Pull Request risk, applies validation gates that
match the detected risk, and publishes an auditable PR report.

The product is not a generic linter or an external service. Configuration is
versioned with the analyzed project in .risk-gate.yaml.

## Mandatory rules for agents

1. Implement the product in Rust. Do not introduce a parallel implementation
in Python, Node.js, or Elixir. Helper tools may use another language only
when explicitly necessary and kept outside the product runtime.
2. Preserve the library plus CLI architecture. The library owns parsing,
language discovery, AST construction, mapping, risk calculation, gates, and
reporting; the CLI adapts those capabilities to GitHub Actions.
3. Every risk decision must be deterministic, explainable, and testable without
network access. GitHub access must remain replaceable at the boundary.
4. .risk-gate.yaml is part of the public contract. Incompatible changes require
updates to the specification, examples, and tests.
5. Never treat a validation that was not executed, was interrupted, has a
missing command, or produced inconclusive output as success.
6. Do not publish, approve, merge, or change GitHub settings outside the
explicit scope of the task. Reports must be idempotent and updated through
a stable marker.
7. Do not hide failures through instantMerge. This option only prevents the
gate from blocking the merge; it does not turn failed validations into
success or alter the report.
8. Validation commands are untrusted repository configuration. Run them with
explicit working directory, environment, and timeout; record the result and
avoid unsafe interpolation of GitHub event values.
9. Always distinguish SUCCESS, PARTIAL, and FAILED. A comment, partial AST, or
missing permission does not prove complete success.
10. Before declaring an integration complete, prove the real path: PR event,
configuration loading, diff, analysis, gate execution, comment, and Action
exit code.
11. All documentation, comments, CLI messages, reports, examples, and other
user-facing project text must be written in English. Preserve exact
identifiers, YAML keys, API fields, exit codes, and code literals.

## AST and language model

The AST model must be language-independent. The first supported languages are
Python, JavaScript, TypeScript, and Elixir behind a common interface. The tree
must cover the complete project included in the execution scope, not only
changed files. Files without a parser must be reported as unanalyzed and must
never disappear silently.

## Risk model

The ordered levels, from lowest to highest, are:

minimal < low < normal < high < danger

PR risk is the highest risk applicable to modules reached by changed files.
Changes that do not match riskMap use normal by default so that new areas are
not silently overlooked. A fallback may be configurable only when it is
specified and validated.

The execution flow is:

configuration -> complete AST -> module/path map -> PR diff -> maximum risk -> gateRules -> validations -> PR comment -> exit code

Every stage must expose enough data for diagnosis and testing. Read specs/
before changing contracts and docs/ for operational examples.

## Minimum quality

Before completing a change, run the available Rust checks:

~~~bash
cargo fmt --all -- --check
cargo clippy --all-targets --all-features -- -D warnings
cargo test --all-targets --all-features
~~~

Add unit tests for risk rules and integration tests for configuration, diff,
gates, and reporting. Every change must update affected documentation. Do not
invent GitHub Actions capabilities that are not covered by tests or explicitly
marked as limitations.
14 changes: 7 additions & 7 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# Changelog

## Unreleased
## 0.1.0

- Implementa análise AST para Python, JavaScript, TypeScript e Elixir.
- Adiciona classificação por `riskMap`, gates por risco, validações e aprovações
de equipes/usuários do GitHub.
- Publica relatório idempotente no PR e aplica limites de arquivos, nós AST e
tamanho de comentário.
- Automatiza cobertura mínima de 95%, mutação e checksum do binário de release.
- Implements AST analysis for Python, JavaScript, TypeScript, and Elixir.
- Adds riskMap classification, risk-based gates, validations, and GitHub team
or user approvals.
- Publishes an idempotent PR report and applies file, AST-node, and comment
size limits.
- Automates coverage above 95%, mutation testing, and release binary checksums.
Loading
Loading