# RuleWalk

**See exactly what a business rule does to real data, step by step — before you trust it.**

A business rule lives in a requirements doc, a policy email, or a JavaScript function.
RuleWalk takes that rule, traces it through real or synthetic data, and produces a
single self-contained HTML file: expandable cards that show the record count, the
before/after sample, and a plain-language explanation at every stage of the pipeline.

No runtime dependencies. No server. One JSON in, one HTML out.

<br>

<div align="center">
  <img src="docs/screenshots/hero-overview.png" width="760" alt="RuleWalk — five-step pipeline overview with type badges and record count flows" />
  <br><br>
  <sub>Five-step pipeline rendered as a walkthrough — type badges, record counts, and pass/reject tallies at a glance</sub>
</div>

---

## What it is — and what it isn't

**RuleWalk** is a communication and audit tool. It proves rule *behavior* with data:
which records pass a filter and why, which fields a transform adds, what the final
output looks like after the full chain runs. The result is a shareable, offline HTML
artifact anyone can open in a browser to follow the rule step by step.

It is not a production rule engine, not a testing framework, and not a monitoring tool.
It is a desk-check companion: given a rule and a dataset, it answers the question
*what actually happens to each record when this rule runs?*

---

## Using with Claude Code

Install globally and link the skill — one time, any project:

```bash
npm install -g rulewalk
rulewalk install-skill
```

Restart Claude Code. From that point on, just describe a rule or paste code in any
conversation and RuleWalk activates automatically:

```
Explain this business rule: orders pending for more than 3 days, excluding cancelled ones.
```

```
Trace this filter function: src/billing/collection-queue.js
```

```
Walk me through what this pipeline does to the data.
```

Claude identifies the steps, generates the pipeline IR, validates it, and delivers
the HTML — you review the walkthrough, not the wiring.

---

## Quick start (CLI)

```bash
npx rulewalk doctor                                         # verify environment (Node ≥ 18)
npx rulewalk demo                                           # generate a working example
npx rulewalk validate  my-rule.pipeline.json                # validate an IR
npx rulewalk deliver   my-rule.pipeline.json  my-rule.html  # validate → render
```

> **Running from source:** clone the repo and replace `npx rulewalk` with
> `node rulewalk/bin/rulewalk.mjs`.

---

## How it works

1. **Extract** — identify each step in the rule (filter, transform, group, lookup,
   action) from a business document or a code function.
2. **Data** — use a sample you provide, or generate synthetic records that cover every
   branch the rule exercises.
3. **IR** — write a typed `pipeline.json` (schema v2) recording counts, samples, and
   conditions for each step.
4. **Validate** — check the JSON Schema *and* the count chain: every step's
   `output_count` must equal the next step's `input_count`. Exit non-zero if anything
   is off; the HTML is never written for an invalid pipeline.
5. **Render** — inject the IR into a self-contained HTML template. The output works
   offline, with no external fonts, no CDN, no network requests of any kind.

For `source_type: "code"`, step 1 is static analysis — RuleWalk reads the function
to extract conditions and field references. It never executes your code.

---

## What the artifact shows

Each pipeline step renders as an expandable card:

- **Count** — records entering and leaving the step (`16 → 9`)
- **Rule text** — plain-language description of what the step does
- **Condition** — the exact condition in source syntax (JS expression, formula, SQL
  clause), never translated to pseudo-code
- **Before/after sample** — records that passed, and records that were rejected with
  an individual reason per record
- **Confidence badge** — signals how certain RuleWalk is about the extracted rule:
  - *(no badge)* `confirmed` — rule is unambiguous and directly traceable to the source
  - `~assumed` (amber left border + badge) — source implies the rule but with
    uncertainty: magic numbers, thresholds with no comment or config reference
  - `≈approx` (orange) — rule was inferred or constructed by RuleWalk to fill a gap
    not present in the source; always accompanied by a note explaining what was invented
- **Data provenance** — a note on every sample indicating whether the data is real
  (`data_origin: "provided"`) or synthetic (`data_origin: "synthetic"`)

The HTML file is fully self-contained and can be committed to a repository, attached
to a PR, or sent by email — no server, no login, no dependencies.

---

## Screenshots

<div align="center">
  <img src="docs/screenshots/filter-detail.png" width="680" alt="Filter step expanded — 12 active products passed in green, 4 discontinued rejected in red with individual reasons" />
  <br><br>
  <sub>Filter step: 16 → 12 products. Each rejected record shows its individual reason — no silent drops.</sub>
</div>

<br>

<table>
<tr>
<td align="center" width="50%">
  <img src="docs/screenshots/enrich-steps.png" width="100%" alt="Transform calculates days_to_stockout; Lookup joins supplier name and email" />
  <br>
  <sub><b>Transform + Lookup</b> — <code>days_to_stockout</code> calculated from stock and sales rate, then enriched with supplier contact from a reference table</sub>
</td>
<td align="center" width="50%">
  <img src="docs/screenshots/confidence-assumed.png" width="100%" alt="~assumed confidence badge with amber left border and explanation note on undocumented threshold" />
  <br>
  <sub><b>Confidence signal</b> — amber <code>~assumed</code> badge flags steps where the source has undocumented thresholds or magic numbers</sub>
</td>
</tr>
</table>

---

## Examples

Three ready-to-open examples live in [`examples/`](examples/):

| Example | What it demonstrates |
|---------|---------------------|
| `pedidos-pendentes` | Two-step filter extracted from a business document |
| `triagem-leads` | All five step types in one pipeline (filter → transform → group → lookup → action) |
| `collection-queue` | Code analysis with `confidence: assumed` on undocumented magic numbers |

See [`examples/README.md`](examples/README.md) for the full coverage breakdown of
what each example proves.

---

## Intentionally outside scope

RuleWalk is a documentation and audit tool. It deliberately does not:

- **Execute code.** Analysis is always static. No `eval`, no subprocess, no sandbox.
  For `source_type: "code"`, RuleWalk reads the function and reasons about it — it
  never runs it.
- **Connect to live data sources.** No database connectors, no API clients, no file
  watchers. Data is either a sample you provide or is synthesized to cover all rule
  branches.
- **Run in production.** RuleWalk produces an HTML artifact for human review, not a
  deployable rule engine. It has no scheduler, no trigger, no persistence layer.
- **Assert rule correctness.** RuleWalk shows what a rule *does*, not whether it is
  *right*. Correctness is a judgment call for the human who reads the walkthrough.

---

## Developing locally

> This section is for contributors working on the RuleWalk source code.
> If you just want to use RuleWalk, install it as a plugin (see above) — no
> manual linking is needed.

To use the skill from Claude Code while iterating on the source, link the skill
directory directly to the repo — changes are picked up immediately with no manual sync.

**Windows (junction — no elevation required):**

```powershell
# Remove the installed copy if it exists
Remove-Item -Recurse -Force "$env:USERPROFILE\.claude\skills\rulewalk"

# Create a junction pointing to the repo
New-Item -ItemType Junction `
  -Path  "$env:USERPROFILE\.claude\skills\rulewalk" `
  -Target "D:\projetos\RuleWalk\rulewalk"
```

**macOS / Linux (symlink):**

```bash
rm -rf ~/.claude/skills/rulewalk
ln -s /path/to/RuleWalk/rulewalk ~/.claude/skills/rulewalk
```

After this, `~/.claude/skills/rulewalk` is a pointer to `rulewalk/` inside the repo.
Every edit to `SKILL.md`, `bin/rulewalk.mjs`, `schema/`, or `templates/` is live
in the skill immediately.

---

## License

MIT — see [LICENSE](LICENSE).

---
---

## 🇧🇷 Português

**Veja exatamente o que uma regra de negócio faz com dados reais, passo a passo — antes de confiar nela.**

Uma regra de negócio vive num documento de requisitos, num e-mail de política ou numa
função JavaScript. RuleWalk pega essa regra, a percorre com dados reais ou sintéticos
e produz um único arquivo HTML auto-contido: cards expansíveis que mostram a contagem
de registros, a amostra antes/depois e uma explicação em linguagem natural em cada
etapa do pipeline.

Sem dependências em tempo de execução. Sem servidor. Um JSON de entrada, um HTML de saída.

---

### O que é — e o que não é

**RuleWalk** é uma ferramenta de comunicação e auditoria. Ela prova o *comportamento*
de uma regra com dados: quais registros passam por um filtro e por quê, quais campos
um transform adiciona, como fica o resultado final depois que toda a cadeia roda. O
resultado é um arquivo HTML compartilhável, offline, que qualquer pessoa pode abrir
no navegador para acompanhar a regra passo a passo.

Não é uma engine de regra de produção, não é um framework de teste e não é uma
ferramenta de monitoramento. É um companheiro de teste de mesa: dado uma regra e um
conjunto de dados, ela responde à pergunta *o que realmente acontece com cada registro
quando essa regra executa?*

---

### Usando com o Claude Code

Instale globalmente e vincule a skill — uma vez, vale para qualquer projeto:

```bash
npm install -g rulewalk
rulewalk install-skill
```

Reinicie o Claude Code. A partir daí, basta descrever uma regra ou colar um código
em qualquer conversa e o RuleWalk ativa automaticamente:

```
Explica essa regra de negócio: pedidos pendentes há mais de 3 dias, excluindo cancelados.
```

```
Rastreia essa função de filtro: src/billing/collection-queue.js
```

```
Mostra o que acontece com os registros nesse pipeline.
```

O Claude identifica os steps, gera o IR do pipeline, valida e entrega o HTML — você
revisa o walkthrough, não a fiação.

---

### Início rápido (CLI)

```bash
npx rulewalk doctor                                         # verificar ambiente (Node ≥ 18)
npx rulewalk demo                                           # gerar exemplo funcional
npx rulewalk validate  minha-regra.pipeline.json            # validar um IR
npx rulewalk deliver   minha-regra.pipeline.json  minha-regra.html  # validar → renderizar
```

> **Rodando do código-fonte:** clone o repositório e substitua `npx rulewalk` por
> `node rulewalk/bin/rulewalk.mjs`.

---

### Como funciona

1. **Extrair** — identificar cada step da regra (filter, transform, group, lookup,
   action) a partir de um documento de negócio ou de uma função no código.
2. **Dados** — usar uma amostra que você fornece, ou gerar registros sintéticos que
   cobrem todos os ramos que a regra exercita.
3. **IR** — escrever um `pipeline.json` tipado (schema v2) registrando contagens,
   amostras e condições para cada step.
4. **Validar** — checar o JSON Schema *e* a cadeia de contagens: o `output_count` de
   cada step deve ser igual ao `input_count` do próximo. Sai com código não-zero se
   algo estiver errado; o HTML nunca é escrito para um pipeline inválido.
5. **Renderizar** — injetar o IR num template HTML auto-contido. O resultado funciona
   offline, sem fontes externas, sem CDN, sem requisição de rede alguma.

Para `source_type: "code"`, o passo 1 é análise estática — RuleWalk lê a função para
extrair condições e referências de campo. Ele nunca executa o seu código.

---

### O que o artefato mostra

Cada step do pipeline é renderizado como um card expansível:

- **Contagem** — registros que entram e saem do step (`16 → 9`)
- **Texto da regra** — descrição em linguagem natural do que o step faz
- **Condição** — a condição exata na sintaxe da fonte (expressão JS, fórmula, cláusula
  SQL), nunca traduzida para pseudo-código
- **Amostra antes/depois** — registros que passaram, e registros que foram rejeitados
  com uma razão individual por registro
- **Badge de confidence** — sinaliza o grau de certeza do RuleWalk sobre a regra extraída:
  - *(sem badge)* `confirmed` — regra inequívoca, diretamente rastreável à fonte
  - `~assumed` (borda âmbar + badge) — a fonte implica a regra mas com incerteza:
    magic numbers, thresholds sem comentário ou referência de configuração
  - `≈approx` (laranja) — regra inferida ou construída pelo RuleWalk para preencher
    uma lacuna não presente na fonte; sempre acompanhada de uma nota explicando o que
    foi inventado
- **Proveniência do dado** — nota em cada amostra indicando se o dado é real
  (`data_origin: "provided"`) ou sintético (`data_origin: "synthetic"`)

O arquivo HTML é completamente auto-contido e pode ser commitado num repositório,
anexado a um PR ou enviado por e-mail — sem servidor, sem login, sem dependências.

---

### Capturas de tela

<div align="center">
  <img src="docs/screenshots/filter-detail.png" width="680" alt="Step de filtro expandido — 12 produtos ativos passaram em verde, 4 descontinuados rejeitados em vermelho com razão individual" />
  <br><br>
  <sub>Step de filtro: 16 → 12 produtos. Cada registro rejeitado exibe sua razão individual — sem descartes silenciosos.</sub>
</div>

<br>

<table>
<tr>
<td align="center" width="50%">
  <img src="docs/screenshots/enrich-steps.png" width="100%" alt="Transform calcula days_to_stockout; Lookup adiciona nome e e-mail do fornecedor" />
  <br>
  <sub><b>Transform + Lookup</b> — <code>days_to_stockout</code> calculado a partir do estoque e taxa de vendas; enriquecido com contato do fornecedor via lookup</sub>
</td>
<td align="center" width="50%">
  <img src="docs/screenshots/confidence-assumed.png" width="100%" alt="Badge ~assumed com borda âmbar e nota explicando o threshold sem documentação" />
  <br>
  <sub><b>Sinal de confidence</b> — badge âmbar <code>~assumed</code> sinaliza steps com thresholds sem documentação ou magic numbers na fonte</sub>
</td>
</tr>
</table>

---

### Exemplos

Três exemplos prontos para abrir estão em [`examples/`](examples/):

| Exemplo | O que demonstra |
|---------|----------------|
| `pedidos-pendentes` | Dois filtros extraídos de um documento de negócio |
| `triagem-leads` | Todos os cinco tipos de step num pipeline (filter → transform → group → lookup → action) |
| `collection-queue` | Análise de código com `confidence: assumed` em magic numbers sem documentação |

Veja [`examples/README.md`](examples/README.md) para o detalhamento completo do que
cada exemplo prova.

---

### Fora do escopo (intencionalmente)

RuleWalk é uma ferramenta de documentação e auditoria. Ela deliberadamente não:

- **Executa código.** A análise é sempre estática. Sem `eval`, sem subprocess, sem
  sandbox. Para `source_type: "code"`, o RuleWalk lê a função e raciocina sobre ela —
  nunca a executa.
- **Conecta a fontes de dados ao vivo.** Sem conectores de banco, sem clientes de API,
  sem file watchers. Os dados são uma amostra que você fornece ou são sintetizados para
  cobrir todos os ramos da regra.
- **Roda em produção.** RuleWalk produz um artefato HTML para revisão humana, não uma
  engine de regra deployável. Não tem agendador, trigger nem camada de persistência.
- **Afirma a correção da regra.** RuleWalk mostra o que uma regra *faz*, não se ela
  está *certa*. A correção é um julgamento de quem lê o walkthrough.

---

### Desenvolvimento local

> Esta seção é para colaboradores trabalhando no código-fonte do RuleWalk.
> Se você só quer usar o RuleWalk, instale como plugin (veja acima) — nenhum
> link manual é necessário.

Para usar a skill no Claude Code enquanto itera no código-fonte, crie um link direto
para o repositório — mudanças ficam disponíveis imediatamente, sem sincronização manual.

**Windows (junction — sem necessidade de elevação):**

```powershell
Remove-Item -Recurse -Force "$env:USERPROFILE\.claude\skills\rulewalk"

New-Item -ItemType Junction `
  -Path  "$env:USERPROFILE\.claude\skills\rulewalk" `
  -Target "D:\projetos\RuleWalk\rulewalk"
```

**macOS / Linux (symlink):**

```bash
rm -rf ~/.claude/skills/rulewalk
ln -s /path/to/RuleWalk/rulewalk ~/.claude/skills/rulewalk
```

Após isso, `~/.claude/skills/rulewalk` aponta diretamente para `rulewalk/` no
repositório. Qualquer edição em `SKILL.md`, `bin/rulewalk.mjs`, `schema/` ou
`templates/` entra em vigor na skill imediatamente.

---

### Licença

MIT — veja [LICENSE](LICENSE).
