wrxn-reversa 1.3.7 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -49,7 +49,7 @@ The installer will:
49
49
  2. Ask which agents to install — all selected by default
50
50
  3. Collect project name, language, and preferences
51
51
  4. Copy agents to `.agents/skills/` (and `.claude/skills/` for Claude Code)
52
- 5. Create the engine entry file (`CLAUDE.md`, `AGENTS.md`, etc.)
52
+ 5. Write the routing card for each engine (`.claude/rules/reversa.md`, `.agents/rules/reversa.md`, or a marked block in `AGENTS.md`, etc.)
53
53
  6. Create the `.reversa/` structure with state, configuration, and plan
54
54
  7. Generate SHA-256 manifest for safe updates
55
55
 
@@ -63,7 +63,7 @@ The installer will:
63
63
  > [!IMPORTANT]
64
64
  > ### 🔒 Guaranteed immutability of the legacy project
65
65
  >
66
- > The installer only creates new files (`CLAUDE.md`, `AGENTS.md`, `.agents/skills/`, etc.) and **never modifies or deletes any existing file** in your project. During analysis, agents operate under a strict and inviolable directive: **all writes are restricted to `.reversa/` and `_reversa_sdd/`** — no other file in your project is touched.
66
+ > The installer creates new files (`.claude/rules/reversa.md`, `.agents/rules/reversa.md`, `.agents/skills/`, etc.). In an existing instruction file such as `AGENTS.md` it only adds a marked Reversa block, and only if you choose "Merge"; it **never deletes any existing file** in your project. During analysis, agents operate under a strict and inviolable directive: **all writes are restricted to `.reversa/` and `_reversa_sdd/`** — no other file in your project is touched.
67
67
 
68
68
  > [!CAUTION]
69
69
  > ### 💾 Back up your project before starting
@@ -416,13 +416,13 @@ Every statement in the specs is marked with:
416
416
 
417
417
  | Engine | File created | Skills path | Activation |
418
418
  |--------|-------------|-------------|------------|
419
- | Claude Code ⭐ | `CLAUDE.md` | `.claude/skills/reversa-*/` and `.agents/skills/reversa-*/` | `/reversa` |
419
+ | Claude Code ⭐ | `.claude/rules/reversa.md` | `.claude/skills/reversa-*/` and `.agents/skills/reversa-*/` | `/reversa` |
420
420
  | Codex ⭐ | `AGENTS.md` | `.agents/skills/reversa-*/` | `reversa` |
421
- | Cursor ⭐ | `.cursorrules` | `.agents/skills/reversa-*/` | `/reversa` |
421
+ | Cursor ⭐ | `.cursor/rules/reversa.mdc` | `.agents/skills/reversa-*/` | `/reversa` |
422
422
  | Gemini CLI | `GEMINI.md` | `.agents/skills/reversa-*/` | `/reversa` |
423
423
  | Windsurf | `.windsurfrules` | `.agents/skills/reversa-*/` | `/reversa` |
424
424
  | Antigravity | `AGENTS.md` | `.agents/skills/reversa-*/` | `/reversa` |
425
- | Kiro | (none) | `.kiro/skills/reversa-*/` and `.agents/skills/reversa-*/` | `/reversa` |
425
+ | Kiro | `.kiro/steering/reversa.md` | `.kiro/skills/reversa-*/` and `.agents/skills/reversa-*/` | `/reversa` |
426
426
  | Opencode | `AGENTS.md` | `.agents/skills/reversa-*/` | `reversa` |
427
427
  | Hermes | `AGENTS.md` | `.agents/skills/reversa-*/` | `reversa` |
428
428
  | Cline | `.clinerules` | `.agents/skills/reversa-*/` | `/reversa` |
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: reversa
3
- description: Ponto de entrada principal do Reversa. Orquestra a análise completa de um sistema legado, gerando especificações executáveis por agentes de IA. Use quando o usuário digitar "/reversa", "reversa", "iniciar análise" ou "engenharia reversa". É o primeiro skill a ser chamado em qualquer sessão.
3
+ description: 'Orquestrador da extração (engenharia reversa) de um sistema legado: Scout, Archaeologist, Detective, Architect, Writer e Reviewer geram specs executáveis em `_reversa_sdd/`; inicia ou retoma a análise pelo `.reversa/state.json`. Use com "/reversa", "reversa", "iniciar análise", "engenharia reversa", "documentar o legado", "extrair specs do código". Não é a porta dos outros fluxos: feature vai para /reversa-forward, bug para /reversa-debugger; na dúvida, /reversa-router.'
4
4
  license: MIT
5
5
  compatibility: Claude Code, Codex, Cursor, Gemini CLI e demais agentes compatíveis com Agent Skills.
6
6
  metadata:
@@ -1,3 +1,3 @@
1
1
  interface:
2
2
  display_name: "Reversa"
3
- short_description: "Ponto de entrada principal do Reversa"
3
+ short_description: "Extração do legado em specs executáveis"
@@ -68,6 +68,7 @@ Este arquivo persiste o estado completo da análise entre sessões. O Reversa l
68
68
  | `engines` | string[] | Engines configuradas (ex: `["claude-code", "codex"]`) |
69
69
  | `agents` | string[] | Agentes instalados |
70
70
  | `created_files` | string[] | Todos os arquivos criados pelo Reversa (para uninstall seguro) |
71
+ | `entry_blocks` | object | Arquivo → `{ mode: created \| merged \| skipped, sha256 }`: blocos do Reversa em arquivos compartilhados (`AGENTS.md`, `GEMINI.md`…) |
71
72
 
72
73
  ## Fases válidas
73
74
 
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  name: reversa-agents-help
3
- description: Explica com analogias o que cada agente do Reversa faz e quando usá-lo. Ative com /reversa-agents-help.
3
+ description: Guia humano do Reversa, com analogias para o que cada agente faz e quando usá-lo, para quem está começando. Para descobrir o próximo passo do projeto, o caminho é o /reversa-router. Ativação: /reversa-agents-help.
4
+ disable-model-invocation: true
4
5
  license: MIT
5
6
  compatibility: Claude Code, Codex, Cursor, Gemini CLI e demais agentes compatíveis com Agent Skills.
6
7
  metadata:
@@ -1,3 +1,5 @@
1
1
  interface:
2
2
  display_name: "Reversa Agents Help"
3
3
  short_description: "Explica com analogias o que cada agente do Reversa faz e…"
4
+ policy:
5
+ allow_implicit_invocation: false
@@ -0,0 +1,140 @@
1
+ ---
2
+ name: reversa-router
3
+ description: 'Roteador do Reversa: lê o estado de todos os fluxos, diz onde o projeto está, casa o pedido com o fluxo certo e mostra a cadeia completa de skills com o próximo comando. Use com "/reversa-router", "o que eu faço agora", "onde eu parei", "qual o próximo passo", "por onde começo", "qual agente do reversa uso", "what next", "which reversa skill". Não executa etapas: encaminha.'
4
+ license: MIT
5
+ compatibility: Claude Code, Codex, Cursor, Gemini CLI e demais agentes compatíveis com Agent Skills.
6
+ metadata:
7
+ author: sandeco
8
+ version: "1.0.0"
9
+ framework: reversa
10
+ role: router
11
+ ---
12
+
13
+ Você é o roteador do Reversa. Sua missão: descobrir onde o projeto está, casar o pedido do usuário com um fluxo, mostrar a cadeia completa desse fluxo com a posição atual marcada e encaminhar para a porta de entrada. Você não executa etapas, não escreve arquivos e não decide pelo usuário.
14
+
15
+ ## Regras que valem a sessão inteira
16
+
17
+ 1. O disco manda. Estágio vem dos artefatos e dos arquivos de estado, nunca da memória da conversa.
18
+ 2. Etapas user-invoked não se ativam pelo nome: leia `<skills>/reversa-<x>/SKILL.md` na íntegra, até a última seção. `<skills>` é a pasta-mãe deste skill; se não souber qual é, use `.agents/skills/` (sempre instalado).
19
+ 3. Depois de resumo ou compactação da conversa, ou na dúvida sobre o passo atual, refaça o Passo 1 antes de responder.
20
+ 4. Uma pergunta por vez. Todo menu termina com "Outro (descreva)".
21
+ 5. Leia `.reversa/state.json` para `user_name`, `chat_language`, `output_folder` (padrão `_reversa_sdd`) e `forward_folder` (padrão `_reversa_forward`). Use os valores reais no lugar dos padrões abaixo.
22
+
23
+ ## Passo 1: mapa de situação (só leitura, em silêncio)
24
+
25
+ | Verifique | Significa |
26
+ |---|---|
27
+ | `.reversa/state.json` → `phase`, `doc_level`, `newproject_progress` | extração em curso ou concluída; projeto novo em curso |
28
+ | `.reversa/plan.md` (tarefas ✅) | quanto da extração rodou |
29
+ | `_reversa_sdd/architecture.md` + `domain.md` | âncora de legado (extração feita) |
30
+ | `_reversa_sdd/prd.md` + `_reversa_sdd/sdd/*.md` | âncora greenfield |
31
+ | `.reversa/active-requirements.json` + pasta da feature | feature ativa e estágio físico (tabela do `reversa-forward`); `paused-features` |
32
+ | `.reversa/forward-autonomous.json` | fila autônoma em curso |
33
+ | `.reversa/active-ideation.json` | sessão de brainstorm (`current-stage`) |
34
+ | `_reversa_sdd/migration/.state.json` | migração (`currentAgent`, aprovações) |
35
+ | `_reversa_sdd/reconstruction-plan.md` | reconstrução em curso |
36
+ | `_reversa_docs/.state.json` | mini-site |
37
+ | `_reversa_sdd/_pricing/` | precificação (advisor, profile, product, size, estimate) |
38
+ | `_reversa_bugs/*/bugs/*/bug.md` com `status` diferente de `resolved` | bugs abertos |
39
+ | `_reversa_refactor/*/opportunities/` com `state: proposed` | refatorações pendentes |
40
+
41
+ Resuma em até 5 linhas o que existe e o que está em andamento.
42
+
43
+ ## Passo 2: casar a intenção
44
+
45
+ 1. Com pedido explícito, case com a tabela "Fluxos". Pedido de criar ou mudar código num projeto com âncora vai para F4, F6, F7 ou F8, nunca direto para o código.
46
+ 2. Sem pedido, ou com "o que faço agora": proponha continuar o que está em andamento (Passo 1). Havendo mais de um, liste-os num menu.
47
+ 3. Nada em andamento e nenhum pedido: mostre F1, F2, F3, F4, F8 e F9 numa linha cada e pergunte.
48
+
49
+ ## Passo 3: pré-condições
50
+
51
+ Se a porta exige artefato que não existe, encaminhe antes para o fluxo que o produz e diga por quê. Exemplos: migrar sem extração → F1 primeiro; preço por feature sem `actions.md` → F4 até o to-do; `/reversa-add` sem `legacy-impact.md` → F4.
52
+
53
+ ## Passo 4: apresentação (formato fixo)
54
+
55
+ > Fluxo: **<nome do fluxo>**
56
+ > Cadeia: `<etapa> → **<etapa atual>** → <etapa> → …` (opcionais com `?`, checkpoints humanos com 🛑)
57
+ > Estado: <uma frase a partir do Passo 1>
58
+ > Próximo: **`<comando>`**, porque <motivo curto>
59
+ >
60
+ > Digite **CONTINUAR** para seguir, ou o nome de outro comando da cadeia.
61
+
62
+ ## Ao receber CONTINUAR
63
+
64
+ 1. Se o próximo for uma porta de entrada model-invoked (`reversa`, `reversa-autonomous`, `reversa-brainstorm`, `reversa-new`, `reversa-forward`, `reversa-forward-autonomous`, `reversa-debugger`, `reversa-refactor`, `reversa-migrate`, `reversa-docs`, `reversa-pricing`, `impeccable`): invoque-o pela ferramenta de skills da engine (Claude Code: ferramenta Skill; Codex: `$nome`; OMP: `skill://nome`). Sem essa ferramenta, leia o `SKILL.md` pela regra 2.
65
+ 2. Se for skill user-invoked (qualquer outra): leia o `SKILL.md` pela regra 2 e siga.
66
+ 3. O skill encaminhado assume a conversa. Você só volta se o usuário pedir `/reversa-router` de novo.
67
+
68
+ ## Fluxos (cadeia canônica)
69
+
70
+ **F1 Extração do legado.** Porta `/reversa`; sem paradas `/reversa-autonomous`. Exige código no projeto.
71
+ Scout → Soul Extractor? → 🛑 nível de documentação → 🛑 organização das specs → Archaeologist (um módulo por vez, pausa oferecida após 3) → Detective → Architect → Writer (🛑 plano, um arquivo por vez) → Reviewer → Visor? → Data Master? → Design System? → verificação de regressão (só em re-extração).
72
+ Estado: `state.json`, `plan.md`. Saída: F4, F10, F11, F12 ou F13. Re-extração com entregas não convergidas: o `/reversa` oferece `/reversa-sync` antes.
73
+
74
+ **F2 Ideação.** Porta `/reversa-brainstorm`. Exige nada.
75
+ Framer → Explorer → Challenger → 🛑 Arbiter → Pre-Spec.
76
+ Estado: `active-ideation.json`, `_reversa_sdd/brainstorms/<NNN>-*/`. Saída: greenfield F3; legado `/reversa-requirements` com `pre-spec.md` (F4); reconstruir em outra stack F10.
77
+
78
+ **F3 Projeto novo.** Porta `/reversa-new` (guiado) ou `/reversa-new expresso "<ideia>"`.
79
+ Guiado: brief → Ideator → Researcher → Drafter → Spec SDD, com CONTINUAR entre eles. Expresso: entrevista única → INICIAR → os mesmos quatro → requirements → plan → to-do → coding (clarify pulado).
80
+ Estado: `state.json#newproject_progress`. Saída: guiado F4; expresso `/reversa-sync`, depois F1 (specs 🟢 do código novo) ou F12.
81
+
82
+ **F4 Feature (ciclo forward).** Porta `/reversa-forward`; atalho `/reversa-requirements <ideia>`. Coding exige âncora (`architecture.md` + `domain.md`, ou `prd.md` + `sdd/`).
83
+ requirements → clarify? (se houver `[DÚVIDA]`) → quality? → plan → to-do → audit? → coding → add?* → sync?
84
+ Estado: `active-requirements.json`, `_reversa_forward/<NNN>-*/` (`progress.jsonl`, `legacy-impact.md`, `regression-watch.md`). Saída: nova feature (F4), `/reversa-resume` para uma pausada, F13 por feature, F1 de tempos em tempos (re-extração).
85
+
86
+ **F5 Fila sem parar.** Porta `/reversa-forward-autonomous`. Exige specs e política de edição liberada, se a fila chegar ao coding.
87
+ entrevista → pré-checagem → INICIAR → para cada feature, a cadeia F4 até o alvo (sync, coding ou to-do), com clarify pulado e audit/quality desligados por padrão.
88
+ Estado: `.reversa/forward-autonomous.json`. Saída: relatório final.
89
+
90
+ **F6 Ajuste curto na entrega.** Porta `/reversa-add`. Exige feature ativa com `legacy-impact.md`.
91
+ trava de tamanho → trava de pertencimento → emenda em `## Emendas` → código → sync?
92
+ Recusa: F4.
93
+
94
+ **F7 Delta pequeno novo.** Porta `/reversa-code-express`. Exige âncora; delta de até 3 módulos e 12 ações, sem mexer em schema, contrato público ou auth que já existem.
95
+ entrevista curta → spec fina → código → rastros de impacto, sem parada no meio → sync?
96
+ Recusa: F4.
97
+
98
+ **F8 Bug.** Porta `/reversa-debugger`. Exige nada; sem specs, o bug leva `spec-gap`.
99
+ Completo: contexto → relatos e evidências → registro → views → `/reversa-debugger-fix <ID>`: mitigação? → reprodução → causa raiz (`/reversa-debugger-debate`? só com aceite) → 🛑 `fix/plan.html` → 🛑 gate 1 testes falhando → 🛑 gate 2 change set → veredito de spec (adendo) → fechamento → `/reversa-debugger-graph`.
100
+ Expresso (um defeito pequeno com pedido de conserto): registro mínimo → correção na mesma passada.
101
+ Feature que vive quebrando: `/reversa-depth-inspection` → achados viram bugs → fix.
102
+ Estado: `_reversa_bugs/<contexto>/bugs/<ID>/bug.md`.
103
+
104
+ **F9 Refatoração.** Porta `/reversa-refactor`. Melhor com `soul.md` e specs.
105
+ contexto → inventário → ROI → 🛑 escolha → especialista (`restructure`, `modularize`, `decouple`, `optimize`, `simplify`, `standardize` ou `prune`): rede de segurança → 🛑 gate do diff → prova → volta ao `/reversa-refactor`. Vários verbos no mesmo alvo: restructure e simplify antes, modularize e decouple depois, standardize e prune por último.
106
+ Estado: `_reversa_refactor/<contexto>/`.
107
+
108
+ **F10 Migração.** Porta `/reversa-migrate`. Exige F1 concluído.
109
+ brief → 🛑 Paradigm Advisor → 🛑 Curator → 🛑 Strategist → Designer (🛑 topologia, arquitetura) → Screen Translator (🛑 modo, geração) → Inspector → `handoff.md`.
110
+ Estado: `_reversa_sdd/migration/.state.json`. Saída: `handoff.md` no agente que vai construir o sistema novo, ou F11 com fonte "migração". O ciclo forward não constrói o sistema-alvo: ele ancora no legado.
111
+
112
+ **F11 Reconstrução.** Porta `/reversa-reconstructor`. Exige `_reversa_sdd/` (copiada para a pasta nova).
113
+ fonte (original ou migração) → plano bottom-up → uma tarefa por CONTINUAR.
114
+ Estado: `_reversa_sdd/reconstruction-plan.md`.
115
+
116
+ **F12 Mini-site.** Porta `/reversa-docs`. Exige extração (sem ela, o site sai mínimo).
117
+ 🛑 plano → vendor → Mapper → Analyst → Storyteller → Publisher.
118
+ Estado: `_reversa_docs/.state.json`.
119
+
120
+ **F13 Preço.** Porta `/reversa-pricing`.
121
+ advisor → profile (research?) → produto: product | serviço, por feature: F4 até o to-do → size → estimate.
122
+ Estado: `_reversa_sdd/_pricing/`.
123
+
124
+ **F14 Front-end.** Porta `/impeccable`.
125
+ `init` (uma vez por projeto) → `<comando> <alvo>`. Sem argumento, menu contextual.
126
+ Estado: `PRODUCT.md`, `DESIGN.md`.
127
+
128
+ **F15 Avulsos.** `/reversa-resume` (trocar a feature ativa), `/reversa-principles` (regras duráveis do projeto), `/reversa-sync` (convergir uma entrega na extração), `/reversa-extract-soul` (alma do sistema, logo após o Scout), `/reversa-n8n` (workflow N8N → specs → `/reversa`), `/reversa-agents-help` (agentes explicados com analogias).
129
+
130
+ ## Sessão longa e delegação
131
+
132
+ 1. Fluxo numa sessão só: o orquestrador lê cada etapa no contexto atual. Depois de compactação, as instruções da etapa somem; releia o estado e o `SKILL.md` da etapa (regra 3).
133
+ 2. Etapa delegada a subagente ou a outro agente: na mensagem de delegação vão o caminho do `SKILL.md`, a feature ou o contexto ativo, os arquivos de estado e onde ele pode escrever. Quem recebe lê o `SKILL.md`; quando o trabalho volta, refaça o Passo 1 a partir do disco.
134
+ 3. Checkpoints 🛑 ficam na sessão que conversa com o usuário. Não delegue etapa com 🛑.
135
+ 4. Nunca rode em paralelo duas etapas que gravam o mesmo estado (`state.json`, `active-requirements.json`, a mesma pasta de feature). Features diferentes em paralelo exigem worktrees separados.
136
+ 5. Paralelismo já previsto pelo Reversa: as lentes do `/reversa-depth-inspection` e os debatedores do `/reversa-debugger-debate`, com aceite explícito para harness externo.
137
+
138
+ ## Regra absoluta
139
+
140
+ Este skill só lê. Nunca apague, modifique ou sobrescreva arquivos do projeto. Toda escrita é do skill para o qual você encaminhou.
@@ -0,0 +1,3 @@
1
+ interface:
2
+ display_name: "Reversa Router"
3
+ short_description: "Diz onde o projeto está e qual skill do Reversa vem a seguir"
@@ -1,7 +1,7 @@
1
1
  import { writeFileSync } from 'fs';
2
2
  import { join, resolve } from 'path';
3
3
  import { checkExistingInstallation } from '../installer/validator.js';
4
- import { detectEngines, ENGINES } from '../installer/detector.js';
4
+ import { detectEngines, ENGINES, entryTargets } from '../installer/detector.js';
5
5
  import { Writer } from '../installer/writer.js';
6
6
  import { loadManifest, saveManifest, buildManifest } from '../installer/manifest.js';
7
7
  import { applyOrangeTheme, ORANGE_PREFIX } from '../installer/orange-prompts.js';
@@ -62,15 +62,13 @@ export default async function addEngine(args) {
62
62
  const selectedEngines = ENGINES.filter(e => selected.includes(e.id));
63
63
  const writer = new Writer(projectRoot);
64
64
 
65
- const seenEntryFiles = new Set();
65
+ for (const target of entryTargets(selectedEngines)) {
66
+ await writer.installEntryTarget(target, {
67
+ outputFolder: state.output_folder,
68
+ forwardFolder: state.forward_folder,
69
+ }, state.entry_blocks ?? {});
70
+ }
66
71
  for (const engine of selectedEngines) {
67
- if (engine.entryFile && !seenEntryFiles.has(engine.entryFile)) {
68
- seenEntryFiles.add(engine.entryFile);
69
- await writer.installEntryFile(engine, {
70
- outputFolder: state.output_folder,
71
- forwardFolder: state.forward_folder,
72
- });
73
- }
74
72
  for (const agent of installedAgents) {
75
73
  await writer.installSkill(agent, engine.skillsDir);
76
74
  if (engine.universalSkillsDir && engine.universalSkillsDir !== engine.skillsDir) {
@@ -1,6 +1,6 @@
1
1
  import { join, resolve } from 'path';
2
2
  import { writeFileSync, existsSync } from 'fs';
3
- import { detectEngines, ENGINES } from '../installer/detector.js';
3
+ import { detectEngines, ENGINES, entryTargets } from '../installer/detector.js';
4
4
  import { checkExistingInstallation } from '../installer/validator.js';
5
5
  import { runInstallPrompts, MIGRATION_AGENT_IDS, TRANSLATOR_AGENT_IDS, FORWARD_AGENT_IDS, PRICING_AGENT_IDS, DOCS_AGENT_IDS, IDEATION_AGENT_IDS, NEW_PROJECT_AGENT_IDS, BUGS_AGENT_IDS, REFACTOR_AGENT_IDS, FRONTEND_AGENT_IDS } from '../installer/prompts.js';
6
6
  import { Writer } from '../installer/writer.js';
@@ -83,16 +83,16 @@ export default async function install(args) {
83
83
  // Stop spinner before possible interactive conflict prompts
84
84
  spinner.stop();
85
85
 
86
- // Instalar entry file de cada engine (deduplica arquivos compartilhados)
87
- const seenEntryFiles = new Set();
88
- for (const engine of selectedEngines) {
89
- if (!engine.entryFile) continue;
90
- if (seenEntryFiles.has(engine.entryFile)) continue;
91
- seenEntryFiles.add(engine.entryFile);
92
- await writer.installEntryFile(engine, {
86
+ // Cartão de roteamento em cada destino (deduplica arquivos compartilhados)
87
+ const records = existing.installed ? existing.state?.entry_blocks ?? {} : {};
88
+ for (const target of entryTargets(selectedEngines)) {
89
+ await writer.installEntryTarget(target, {
93
90
  outputFolder: answers.output_folder,
94
91
  forwardFolder: answers.forward_folder,
95
- });
92
+ }, records);
93
+ }
94
+ if (answers.engines.includes('aider')) {
95
+ console.log(' Aider: add "read: CONVENTIONS.md" to .aider.conf.yml so Aider loads the Reversa card.');
96
96
  }
97
97
 
98
98
  spinner.start('Creating .reversa/ structure...');
@@ -1,9 +1,10 @@
1
- import { rmSync, unlinkSync } from 'fs';
1
+ import { readFileSync, rmSync, unlinkSync, writeFileSync } from 'fs';
2
2
  import { dirname, join, resolve } from 'path';
3
3
  import { checkExistingInstallation } from '../installer/validator.js';
4
- import { loadManifest, hashFile, indexManifest, isUnder, normalizeRel } from '../installer/manifest.js';
4
+ import { loadManifest, hashFile, hashContent, indexManifest, isUnder, normalizeRel } from '../installer/manifest.js';
5
5
  import { isSafeRel, pathState, walkTree, pruneEmpty } from '../installer/reconcile.js';
6
6
  import { ENGINES } from '../installer/detector.js';
7
+ import { findBlock, removeRange } from '../installer/entry-block.js';
7
8
 
8
9
  const STATE = '.reversa/state.json';
9
10
  const MANIFEST = '.reversa/_config/files-manifest.json';
@@ -56,11 +57,32 @@ export default async function uninstall() {
56
57
  }
57
58
  };
58
59
  inspect('.reversa', true);
60
+ // Blocos com marcas em arquivos compartilhados: sai só o bloco.
61
+ const blocks = [];
62
+ const blockFiles = new Set();
63
+ for (const [rel, record] of Object.entries(state.entry_blocks ?? {})) {
64
+ if (!isSafeRel(rel)) continue;
65
+ blockFiles.add(normalizeRel(rel));
66
+ if (pathState(projectRoot, rel) !== 'file') continue;
67
+ const text = readFileSync(join(projectRoot, rel), 'utf8');
68
+ const found = findBlock(text);
69
+ if (found.status !== 'ok' || found.edited) {
70
+ if (found.status !== 'none') kept.add(rel);
71
+ continue;
72
+ }
73
+ const next = removeRange(text, found);
74
+ blocks.push({ rel, hash: hashContent(text), next: next.trim() === '' && record?.mode === 'created' ? null : next });
75
+ }
59
76
  for (const rel of roots) {
77
+ if (blockFiles.has(rel)) continue;
60
78
  if (!isSafeRel(rel) || isUnder(rel, '.git')) kept.add(rel);
61
79
  else if (!isUnder(rel, '.reversa')) inspect(rel, SKILL_ROOTS.has(normalizeRel(dirname(rel))) && !index.has(rel));
62
80
  }
63
81
 
82
+ for (const { rel, next } of blocks) {
83
+ console.log(next === null ? ` Remove ${rel}` : ` Remove Reversa block from ${rel} (your text stays)`);
84
+ }
85
+
64
86
  for (const rel of toRemove) console.log(` Remove ${rel}`);
65
87
  for (const rel of kept) console.log(chalk.yellow(` Keep ${rel}`));
66
88
  if (safeOutput && pathState(projectRoot, outputRel) === 'dir') {
@@ -83,6 +105,20 @@ export default async function uninstall() {
83
105
 
84
106
  let removed = 0;
85
107
  let errors = 0;
108
+ for (const { rel, hash, next } of blocks) {
109
+ try {
110
+ if (pathState(projectRoot, rel) !== 'file' || hashFile(join(projectRoot, rel)) !== hash) {
111
+ console.log(chalk.yellow(` Kept ${rel} (changed since preview)`));
112
+ continue;
113
+ }
114
+ if (next === null) unlinkSync(join(projectRoot, rel));
115
+ else writeFileSync(join(projectRoot, rel), next, 'utf8');
116
+ removed++;
117
+ } catch (err) {
118
+ console.error(chalk.red(` Error updating ${rel}: ${err.message}`));
119
+ errors++;
120
+ }
121
+ }
86
122
  for (const rel of toRemove) {
87
123
  try {
88
124
  if (pathState(projectRoot, rel) !== 'file' || !isOwned(rel)) {
@@ -4,7 +4,7 @@ import { checkExistingInstallation } from '../installer/validator.js';
4
4
  import { loadManifest, saveManifest, buildManifest, indexManifest, isUnder, normalizeRel } from '../installer/manifest.js';
5
5
  import { isSafeRel, pathState } from '../installer/reconcile.js';
6
6
  import { Writer } from '../installer/writer.js';
7
- import { ENGINES } from '../installer/detector.js';
7
+ import { ENGINES, entryTargets } from '../installer/detector.js';
8
8
  import { listAllAgents } from '../installer/prompts.js';
9
9
  import { renderImpeccableNotice, IMPECCABLE_AGENT_ID } from '../installer/bundled.js';
10
10
  import { applyOrangeTheme, ORANGE_PREFIX } from '../installer/orange-prompts.js';
@@ -66,11 +66,9 @@ export default async function update() {
66
66
  const allAgents = listAllAgents();
67
67
  const installedEngines = ENGINES.filter(engine => state.engines?.includes(engine.id));
68
68
  const roots = new Set();
69
- const entries = new Map();
70
69
  for (const engine of installedEngines) {
71
70
  roots.add(normalizeRel(engine.skillsDir));
72
71
  if (engine.universalSkillsDir) roots.add(normalizeRel(engine.universalSkillsDir));
73
- if (engine.entryFile && !entries.has(engine.entryFile)) entries.set(engine.entryFile, engine);
74
72
  }
75
73
  const writer = new Writer(projectRoot);
76
74
  const plan = { writes: [], kept: [], removals: [] };
@@ -90,11 +88,16 @@ export default async function update() {
90
88
  add(writer.planForwardAssets(index));
91
89
  add(writer.planPolicyAssets());
92
90
  const options = { outputFolder: state.output_folder, forwardFolder: state.forward_folder };
93
- for (const engine of entries.values()) add(writer.planEntryFile(engine, options, index));
91
+ add(writer.planEntryTargets(entryTargets(installedEngines), options, index, state.entry_blocks ?? {}));
94
92
 
95
- for (const { rel, reason } of plan.kept) console.log(chalk.yellow(` Keep ${rel} (${reason})`));
96
- for (const { rel, reason } of plan.writes) console.log(` ${reason === 'restore' ? 'Restore' : reason === 'new' ? 'Add' : 'Refresh'} ${rel}`);
97
- for (const { rel } of plan.removals) console.log(` Remove obsolete ${rel}`);
93
+ const LABELS = { restore: 'Restore', new: 'Add', migrate: 'Migrate', refresh: 'Refresh' };
94
+ for (const { rel, reason } of plan.kept) {
95
+ console.log(chalk.yellow(reason === 'edited block'
96
+ ? ` Keep ${rel} (edited block; proposal in .reversa/_config/entry-blocks/)`
97
+ : ` Keep ${rel} (${reason})`));
98
+ }
99
+ for (const { rel, reason } of plan.writes) console.log(` ${LABELS[reason] ?? 'Refresh'} ${rel}`);
100
+ for (const { rel, legacy } of plan.removals) console.log(` Remove ${legacy ? '' : 'obsolete '}${rel}`);
98
101
  console.log(` ${plan.writes.length} file(s) to write; ${plan.removals.length} to remove.`);
99
102
 
100
103
  const { default: inquirer } = await import('inquirer');
@@ -118,7 +121,8 @@ export default async function update() {
118
121
  }
119
122
  }
120
123
 
121
- const removed = writer.applyPlan(plan, index);
124
+ const { written, removed } = writer.applyPlan(plan, index);
125
+ for (const { dropKey } of written) if (dropKey) delete manifest[dropKey];
122
126
  for (const { key } of removed) delete manifest[key];
123
127
  for (const [key, hash] of Object.entries(buildManifest(projectRoot, writer.manifestPaths))) {
124
128
  const oldKey = index.get(normalizeRel(key))?.key ?? key;
@@ -129,9 +133,10 @@ export default async function update() {
129
133
  state.package_name = name;
130
134
  state.version = version;
131
135
  state.created_files = [...new Set([...(state.created_files ?? []), ...writer.createdFiles])];
136
+ state.entry_blocks = { ...(state.entry_blocks ?? {}), ...writer.entryBlocks };
132
137
  writeFileSync(join(projectRoot, VERSION), version, 'utf8');
133
138
  writeFileSync(join(projectRoot, STATE), JSON.stringify(state, null, 2), 'utf8');
134
- console.log(chalk.hex('#ffa203')(` Update complete (${writer.manifestPaths.length} written, ${removed.length} removed).\n`));
139
+ console.log(chalk.hex('#ffa203')(` Update complete (${written.length} written, ${removed.length} removed).\n`));
135
140
 
136
141
  if (allAgents.includes(IMPECCABLE_AGENT_ID)) {
137
142
  const hasSlashEngine = installedEngines.some(e => e.id !== 'codex' && e.id !== 'hermes');
@@ -2,135 +2,47 @@ import { existsSync } from 'fs';
2
2
  import { join } from 'path';
3
3
  import { execFileSync } from 'child_process';
4
4
 
5
+ const SHARED = '.agents/skills';
6
+ const AGENTS_BLOCK = { file: 'AGENTS.md', kind: 'block' };
7
+ const engine = (id, name, star, entry, skillsDir = SHARED) => (
8
+ { id, name, star, entry, skillsDir, universalSkillsDir: SHARED }
9
+ );
10
+
11
+ // entry: onde fica o cartão de roteamento do Reversa.
12
+ // kind 'owned' = arquivo só do Reversa; 'block' = bloco com marcas num arquivo do usuário.
5
13
  export const ENGINES = [
6
- {
7
- id: 'claude-code',
8
- name: 'Claude Code',
9
- star: true,
10
- entryFile: 'CLAUDE.md',
11
- entryTemplate: 'CLAUDE.md',
12
- skillsDir: '.claude/skills',
13
- universalSkillsDir: '.agents/skills',
14
- },
15
- {
16
- id: 'codex',
17
- name: 'Codex',
18
- star: true,
19
- entryFile: 'AGENTS.md',
20
- entryTemplate: 'AGENTS.md',
21
- skillsDir: '.agents/skills',
22
- universalSkillsDir: '.agents/skills',
23
- },
24
- {
25
- id: 'cursor',
26
- name: 'Cursor',
27
- star: true,
28
- entryFile: '.cursorrules',
29
- entryTemplate: 'cursorrules',
30
- skillsDir: '.agents/skills',
31
- universalSkillsDir: '.agents/skills',
32
- },
33
- {
34
- id: 'gemini-cli',
35
- name: 'Gemini CLI',
36
- star: false,
37
- entryFile: 'GEMINI.md',
38
- entryTemplate: 'GEMINI.md',
39
- skillsDir: '.agents/skills',
40
- universalSkillsDir: '.agents/skills',
41
- },
42
- {
43
- id: 'windsurf',
44
- name: 'Windsurf',
45
- star: false,
46
- entryFile: '.windsurfrules',
47
- entryTemplate: 'windsurf',
48
- skillsDir: '.agents/skills',
49
- universalSkillsDir: '.agents/skills',
50
- },
51
- {
52
- id: 'antigravity',
53
- name: 'Antigravity',
54
- star: false,
55
- entryFile: 'AGENTS.md',
56
- entryTemplate: 'AGENTS.md',
57
- skillsDir: '.agents/skills',
58
- universalSkillsDir: '.agents/skills',
59
- },
60
- {
61
- id: 'kiro',
62
- name: 'Kiro',
63
- star: false,
64
- entryFile: null,
65
- entryTemplate: null,
66
- skillsDir: '.kiro/skills',
67
- universalSkillsDir: '.agents/skills',
68
- },
69
- {
70
- id: 'opencode',
71
- name: 'Opencode',
72
- star: false,
73
- entryFile: 'AGENTS.md',
74
- entryTemplate: 'AGENTS.md',
75
- skillsDir: '.agents/skills',
76
- universalSkillsDir: '.agents/skills',
77
- },
78
- {
79
- id: 'hermes',
80
- name: 'Hermes',
81
- star: false,
82
- entryFile: 'AGENTS.md',
83
- entryTemplate: 'AGENTS.md',
84
- skillsDir: '.agents/skills',
85
- universalSkillsDir: '.agents/skills',
86
- },
87
- {
88
- id: 'cline',
89
- name: 'Cline',
90
- star: false,
91
- entryFile: '.clinerules',
92
- entryTemplate: 'clinerules',
93
- skillsDir: '.agents/skills',
94
- universalSkillsDir: '.agents/skills',
95
- },
96
- {
97
- id: 'roo-code',
98
- name: 'Roo Code',
99
- star: false,
100
- entryFile: '.roorules',
101
- entryTemplate: 'roorules',
102
- skillsDir: '.agents/skills',
103
- universalSkillsDir: '.agents/skills',
104
- },
105
- {
106
- id: 'github-copilot',
107
- name: 'GitHub Copilot',
108
- star: false,
109
- entryFile: '.github/copilot-instructions.md',
110
- entryTemplate: 'copilot-instructions',
111
- skillsDir: '.agents/skills',
112
- universalSkillsDir: '.agents/skills',
113
- },
114
- {
115
- id: 'aider',
116
- name: 'Aider',
117
- star: false,
118
- entryFile: 'CONVENTIONS.md',
119
- entryTemplate: 'CONVENTIONS.md',
120
- skillsDir: '.agents/skills',
121
- universalSkillsDir: '.agents/skills',
122
- },
123
- {
124
- id: 'amazon-q',
125
- name: 'Amazon Q Developer',
126
- star: false,
127
- entryFile: '.amazonq/rules/reversa.md',
128
- entryTemplate: 'amazonq',
129
- skillsDir: '.agents/skills',
130
- universalSkillsDir: '.agents/skills',
131
- },
14
+ engine('claude-code', 'Claude Code', true,
15
+ { file: '.claude/rules/reversa.md', kind: 'owned', compact: true, legacyFile: 'CLAUDE.md' }, '.claude/skills'),
16
+ engine('codex', 'Codex', true, AGENTS_BLOCK),
17
+ engine('cursor', 'Cursor', true,
18
+ { file: '.cursor/rules/reversa.mdc', kind: 'owned', frontmatter: 'alwaysApply', legacyFile: '.cursorrules' }),
19
+ engine('gemini-cli', 'Gemini CLI', false, { file: 'GEMINI.md', kind: 'block' }),
20
+ engine('windsurf', 'Windsurf', false, { file: '.windsurfrules', kind: 'block' }),
21
+ engine('antigravity', 'Antigravity', false, AGENTS_BLOCK),
22
+ engine('kiro', 'Kiro', false, { file: '.kiro/steering/reversa.md', kind: 'owned' }, '.kiro/skills'),
23
+ engine('opencode', 'Opencode', false, AGENTS_BLOCK),
24
+ engine('hermes', 'Hermes', false, AGENTS_BLOCK),
25
+ engine('cline', 'Cline', false, { file: '.clinerules', kind: 'block' }),
26
+ engine('roo-code', 'Roo Code', false, { file: '.roorules', kind: 'block' }),
27
+ engine('github-copilot', 'GitHub Copilot', false, { file: '.github/copilot-instructions.md', kind: 'block' }),
28
+ engine('aider', 'Aider', false, { file: 'CONVENTIONS.md', kind: 'block' }),
29
+ engine('amazon-q', 'Amazon Q Developer', false, { file: '.amazonq/rules/reversa.md', kind: 'owned' }),
132
30
  ];
133
31
 
32
+ // Gravado em toda instalação: OMP e outros harnesses que leem .agents/rules/.
33
+ export const SHARED_RULE = { file: '.agents/rules/reversa.md', kind: 'owned', frontmatter: 'alwaysApply' };
34
+
35
+ // Destinos únicos do cartão para um conjunto de engines.
36
+ export function entryTargets(engines) {
37
+ const targets = new Map([[SHARED_RULE.file, SHARED_RULE]]);
38
+ for (const { entry } of engines) {
39
+ const seen = targets.get(entry.file);
40
+ if (!seen) targets.set(entry.file, entry);
41
+ else if (entry.compact && !seen.compact) targets.set(entry.file, { ...seen, compact: true });
42
+ }
43
+ return [...targets.values()];
44
+ }
45
+
134
46
  function commandExists(cmd) {
135
47
  if (!/^[a-zA-Z0-9_-]+$/.test(cmd)) return false;
136
48
  try {
@@ -0,0 +1,89 @@
1
+ import { readFileSync } from 'fs';
2
+ import { fileURLToPath } from 'url';
3
+ import { hashContent } from './manifest.js';
4
+ import { renderPolicyBlock } from './policy.js';
5
+ import { getPackageInfo } from '../utils/package-info.js';
6
+
7
+ const CARD = fileURLToPath(new URL('../../templates/engines/card.md', import.meta.url));
8
+ const BEGIN = '<!-- reversa:begin';
9
+ const END_MARKER = '<!-- reversa:end -->';
10
+ // Última frase da política: fecha todo bloco gravado antes das marcas (até 1.3.7).
11
+ const LEGACY_END = 'alterações nesse arquivo são ato exclusivo do usuário.';
12
+
13
+ const count = (text, needle) => text.split(needle).length - 1;
14
+ const normalize = text => text.replace(/\r\n/g, '\n');
15
+ // Índice logo depois de uma quebra de linha em `at`, se houver.
16
+ const skipNewline = (text, at) => text.startsWith('\r\n', at) ? at + 2 : text[at] === '\n' ? at + 1 : at;
17
+
18
+ export const cardHash = card => hashContent(normalize(card));
19
+
20
+ // Cartão de roteamento renderizado para um destino (ver ENGINES.entry).
21
+ export function renderCard(target, { outputFolder, forwardFolder } = {}) {
22
+ let card = readFileSync(CARD, 'utf8')
23
+ .replace('{{REVERSA_POLICY}}', renderPolicyBlock({ outputFolder, forwardFolder }));
24
+ if (!card.endsWith('\n')) card += '\n';
25
+ if (target.compact) {
26
+ card += '\n## Compact Instructions\n\nAo compactar, preserve: skill Reversa ativo, etapa atual, último checkpoint gravado e o próximo passo combinado com o usuário.\n';
27
+ }
28
+ if (target.frontmatter === 'alwaysApply') card = `---\nalwaysApply: true\n---\n\n${card}`;
29
+ return card;
30
+ }
31
+
32
+ export function renderBlock(card) {
33
+ return `${BEGIN} v=${getPackageInfo().version} sha256=${cardHash(card)} -->\n${card}${END_MARKER}\n`;
34
+ }
35
+
36
+ // { status: 'none' } | { status: 'invalid' } | { status: 'ok', start, end, inner, edited }
37
+ export function findBlock(text) {
38
+ const begins = count(text, BEGIN);
39
+ const ends = count(text, END_MARKER);
40
+ if (begins === 0 && ends === 0) return { status: 'none' };
41
+ const start = text.indexOf(BEGIN);
42
+ const endMarker = text.indexOf(END_MARKER);
43
+ if (begins !== 1 || ends !== 1 || endMarker < start) return { status: 'invalid' };
44
+ const lineEnd = text.indexOf('\n', start);
45
+ if (lineEnd < 0 || lineEnd > endMarker) return { status: 'invalid' };
46
+ const inner = text.slice(lineEnd + 1, endMarker);
47
+ const sha = /sha256=([0-9a-f]{64})/.exec(text.slice(start, lineEnd))?.[1];
48
+ return {
49
+ status: 'ok',
50
+ start,
51
+ end: skipNewline(text, endMarker + END_MARKER.length),
52
+ inner,
53
+ edited: sha !== cardHash(inner),
54
+ };
55
+ }
56
+
57
+ // Bloco gravado sem marcas pelas versões antigas: do título até a última frase da política.
58
+ export function findLegacyBlock(text) {
59
+ let start = -1;
60
+ if (text.startsWith('# Reversa\n') || text.startsWith('# Reversa\r\n')) {
61
+ start = 0;
62
+ } else {
63
+ for (const needle of ['\n\n---\n\n# Reversa', '\r\n\r\n---\r\n\r\n# Reversa', '\n\n## Política de edição do legado (Reversa)']) {
64
+ const n = count(text, needle);
65
+ if (n > 1) return null;
66
+ if (n === 1) {
67
+ start = text.indexOf(needle);
68
+ break;
69
+ }
70
+ }
71
+ }
72
+ if (start < 0) return null;
73
+ const endAt = text.indexOf(LEGACY_END, start);
74
+ if (endAt < 0) return null;
75
+ return { start, end: skipNewline(text, endAt + LEGACY_END.length) };
76
+ }
77
+
78
+ export function upsertBlock(text, block, range) {
79
+ if (range) return text.slice(0, range.start) + block + text.slice(range.end);
80
+ if (text === '') return block;
81
+ return text + (text.endsWith('\n') ? '\n' : '\n\n') + block;
82
+ }
83
+
84
+ export function removeRange(text, { start, end }) {
85
+ let before = text.slice(0, start);
86
+ const after = text.slice(end);
87
+ if (after === '' && before.endsWith('\n\n')) before = before.slice(0, -1);
88
+ return before + after;
89
+ }
@@ -30,6 +30,7 @@ const DISCOVERY_CORE = [
30
30
  'reversa-data-master',
31
31
  'reversa-design-system',
32
32
  'reversa-agents-help',
33
+ 'reversa-router',
33
34
  'reversa-reconstructor',
34
35
  ];
35
36
 
@@ -4,12 +4,12 @@ import {
4
4
  readdirSync, statSync, chmodSync,
5
5
  copyFileSync, unlinkSync,
6
6
  } from 'fs';
7
- import { join, dirname, resolve } from 'path';
7
+ import { join, dirname, resolve, basename } from 'path';
8
8
  import { fileURLToPath } from 'url';
9
9
  import { askMergeStrategy } from './prompts.js';
10
10
  import { readJsonSafe } from '../utils/json-safe.js';
11
11
  import { getPackageInfo } from '../utils/package-info.js';
12
- import { renderPolicyBlock } from './policy.js';
12
+ import { renderCard, renderBlock, cardHash, findBlock, findLegacyBlock, upsertBlock, removeRange } from './entry-block.js';
13
13
  import { hashFile, hashContent, normalizeRel, isUnder } from './manifest.js';
14
14
  import { isSafeRel, pathState, walkTree, classifyTarget, matchesBaseline, pruneEmpty } from './reconcile.js';
15
15
 
@@ -23,6 +23,7 @@ export class Writer {
23
23
  this.projectRoot = projectRoot;
24
24
  this.createdFiles = []; // dirs + files — used by uninstall via state.json
25
25
  this.manifestPaths = []; // files only — used to build SHA-256 manifest
26
+ this.entryBlocks = {}; // arquivo → { mode, sha256 } dos blocos com marcas
26
27
  }
27
28
 
28
29
  // Normalises an absolute path to project-relative
@@ -104,37 +105,64 @@ export class Writer {
104
105
  }
105
106
  }
106
107
 
107
- // Texto do arquivo de entrada de uma engine, ou null se ela não tem template.
108
- _renderEntry(engine, { outputFolder, forwardFolder } = {}) {
109
- if (!engine.entryFile || !engine.entryTemplate) return null;
110
- const templatePath = join(TEMPLATES_DIR, 'engines', engine.entryTemplate);
111
- if (!existsSync(templatePath)) return null;
112
- return readFileSync(templatePath, 'utf8')
113
- .replace('{{REVERSA_POLICY}}', renderPolicyBlock({ outputFolder, forwardFolder }));
114
- }
115
-
116
- // Instala o arquivo de entrada de uma engine (CLAUDE.md, AGENTS.md, etc.)
117
- async installEntryFile(engine, opts = {}) {
118
- const content = this._renderEntry(engine, opts);
119
- if (content === null) return;
120
-
121
- const destPath = join(this.projectRoot, engine.entryFile);
108
+ // Grava o cartão de roteamento num destino (ver ENGINES.entry).
109
+ // records: state.entry_blocks já gravado (guarda a resposta "Skip").
110
+ async installEntryTarget(target, opts = {}, records = {}) {
111
+ const card = renderCard(target, opts);
112
+ const destPath = join(this.projectRoot, target.file);
113
+ const exists = existsSync(destPath);
114
+
115
+ if (target.kind === 'owned') {
116
+ if (!exists) {
117
+ this._mkdir(dirname(destPath));
118
+ writeFileSync(destPath, card, 'utf8');
119
+ this._register(destPath);
120
+ } else if (readFileSync(destPath, 'utf8') !== card) {
121
+ console.log(` Kept existing ${target.file} (not written by this install)`);
122
+ }
123
+ return;
124
+ }
122
125
 
123
- if (!existsSync(destPath)) {
126
+ const block = renderBlock(card);
127
+ const sha256 = cardHash(card);
128
+ if (!exists) {
124
129
  this._mkdir(dirname(destPath));
125
- writeFileSync(destPath, content, 'utf8');
126
- this._register(destPath);
130
+ writeFileSync(destPath, block, 'utf8');
131
+ this.entryBlocks[target.file] = { mode: 'created', sha256 };
132
+ if (!this.createdFiles.includes(target.file)) this.createdFiles.push(target.file);
127
133
  return;
128
134
  }
129
135
 
130
- // Arquivo já existe — perguntar ao usuário (apenas merge ou skip)
131
- const strategy = await askMergeStrategy(engine.entryFile);
136
+ const text = readFileSync(destPath, 'utf8');
137
+ const found = findBlock(text);
138
+ if (found.status === 'ok' && !found.edited) {
139
+ writeFileSync(destPath, upsertBlock(text, block, found), 'utf8');
140
+ this.entryBlocks[target.file] = { mode: records[target.file]?.mode ?? 'merged', sha256 };
141
+ return;
142
+ }
143
+ if (found.status !== 'none') {
144
+ console.log(` Kept ${target.file}: Reversa block was edited or its markers are damaged`);
145
+ return;
146
+ }
147
+ if (records[target.file]?.mode === 'skipped') return;
132
148
 
133
- if (strategy === 'merge') {
134
- appendFileSync(destPath, '\n\n---\n\n' + content, 'utf8');
135
- // Não registra em createdFiles — arquivo pré-existente
149
+ const strategy = await askMergeStrategy(target.file);
150
+ if (strategy !== 'merge') {
151
+ this.entryBlocks[target.file] = { mode: 'skipped' };
152
+ return;
136
153
  }
137
- // 'skip' → não faz nada
154
+ const merged = upsertBlock(text, block);
155
+ if (basename(target.file) === 'AGENTS.md') {
156
+ const bytes = Buffer.byteLength(merged);
157
+ if (bytes > 32768) {
158
+ console.log(" Not merged into AGENTS.md: the result would exceed Codex's 32 KiB project_doc_max_bytes limit.");
159
+ this.entryBlocks[target.file] = { mode: 'skipped' };
160
+ return;
161
+ }
162
+ if (bytes > 28672) console.log(" Warning: AGENTS.md will be close to Codex's 32 KiB limit.");
163
+ }
164
+ writeFileSync(destPath, merged, 'utf8');
165
+ this.entryBlocks[target.file] = { mode: 'merged', sha256 };
138
166
  }
139
167
 
140
168
  // Cria a estrutura interna .reversa/
@@ -384,17 +412,81 @@ export class Writer {
384
412
  return plan;
385
413
  }
386
414
 
387
- // Arquivo de entrada de uma engine. Só entra no plano se foi o Reversa que
388
- // o criou (está no manifest): um arquivo mesclado ou pulado no install não
389
- // tem registro e não é tocado.
390
- planEntryFile(engine, opts, index) {
415
+ // Cartão de roteamento em cada destino. Arquivo próprio: mesma regra dos
416
+ // demais arquivos instalados. Arquivo compartilhado: só o bloco com marcas
417
+ // muda, e só se ninguém o editou. Texto do usuário fora do bloco nunca muda.
418
+ planEntryTargets(targets, opts, index, records = {}) {
391
419
  const plan = this._emptyPlan();
392
- const content = this._renderEntry(engine, opts);
393
- if (content === null || !index.has(normalizeRel(engine.entryFile))) return plan;
394
- this._planContent(plan, engine.entryFile, content, index);
420
+ for (const target of targets) {
421
+ const card = renderCard(target, opts);
422
+ if (target.kind === 'owned') this._planContent(plan, target.file, card, index);
423
+ else this._planBlock(plan, target.file, card, index, records);
424
+ if (target.legacyFile) this._planLegacy(plan, target.legacyFile, index);
425
+ }
395
426
  return plan;
396
427
  }
397
428
 
429
+ _planBlock(plan, rel, card, index, records) {
430
+ const block = renderBlock(card);
431
+ const sha256 = cardHash(card);
432
+ const state = pathState(this.projectRoot, rel);
433
+ const dropKey = index.get(rel)?.key;
434
+ if (state === 'missing') {
435
+ if (records[rel]?.mode === 'created' || index.has(rel)) {
436
+ plan.writes.push({ rel, reason: 'restore', content: block, block: { mode: 'created', sha256 }, dropKey });
437
+ }
438
+ return;
439
+ }
440
+ if (state !== 'file') {
441
+ plan.kept.push({ rel, reason: 'conflict' });
442
+ return;
443
+ }
444
+ const text = readFileSync(join(this.projectRoot, rel), 'utf8');
445
+ const baseline = hashContent(text);
446
+ const found = findBlock(text);
447
+ if (found.status === 'ok' && !found.edited) {
448
+ if (found.inner === card) return;
449
+ plan.writes.push({
450
+ rel, reason: 'refresh', content: upsertBlock(text, block, found), baseline,
451
+ block: { mode: records[rel]?.mode ?? 'merged', sha256 }, dropKey,
452
+ });
453
+ } else if (found.status === 'ok') {
454
+ plan.kept.push({ rel, reason: 'edited block' });
455
+ const proposal = `.reversa/_config/entry-blocks/${rel.replaceAll('/', '__')}.new`;
456
+ const current = pathState(this.projectRoot, proposal) === 'file'
457
+ ? hashFile(join(this.projectRoot, proposal)) : undefined;
458
+ if (current !== hashContent(block)) {
459
+ plan.writes.push({ rel: proposal, reason: 'new', content: block, baseline: current, block: {} });
460
+ }
461
+ } else if (found.status === 'invalid') {
462
+ plan.kept.push({ rel, reason: 'damaged markers' });
463
+ } else {
464
+ const legacy = findLegacyBlock(text);
465
+ if (!legacy) return;
466
+ plan.writes.push({
467
+ rel, reason: 'migrate', content: upsertBlock(text, block, legacy), baseline,
468
+ block: { mode: index.has(rel) && legacy.start === 0 ? 'created' : 'merged', sha256 }, dropKey,
469
+ });
470
+ }
471
+ }
472
+
473
+ // Arquivo usado antes do cartão (CLAUDE.md, .cursorrules): sai só o texto do Reversa.
474
+ _planLegacy(plan, rel, index) {
475
+ if (pathState(this.projectRoot, rel) !== 'file') return;
476
+ const text = readFileSync(join(this.projectRoot, rel), 'utf8');
477
+ const found = findBlock(text);
478
+ const range = found.status === 'ok' && !found.edited ? found
479
+ : found.status === 'none' ? findLegacyBlock(text) : null;
480
+ if (!range) return;
481
+ const rest = removeRange(text, range);
482
+ const entry = index.get(rel);
483
+ if (rest.trim() === '' && entry) {
484
+ plan.removals.push({ rel, key: entry.key, hash: hashContent(text), ownerDir: rel, legacy: true });
485
+ } else {
486
+ plan.writes.push({ rel, reason: 'migrate', content: rest, baseline: hashContent(text), block: {}, dropKey: entry?.key });
487
+ }
488
+ }
489
+
398
490
  // Config da política e hooks: criados quando ausentes, nunca sobrescritos.
399
491
  planPolicyAssets() {
400
492
  const plan = this._emptyPlan();
@@ -418,9 +510,11 @@ export class Writer {
418
510
 
419
511
  // Executa as escritas e remoções de um plano e registra o que escreveu.
420
512
  applyPlan(plan, index) {
513
+ const written = [];
421
514
  const removed = [];
422
515
  for (const write of plan.writes) {
423
- const hash = write.reason === 'refresh' ? index.get(write.rel).hash : undefined;
516
+ const hash = 'baseline' in write ? write.baseline
517
+ : write.reason === 'refresh' ? index.get(write.rel).hash : undefined;
424
518
  if (!matchesBaseline(this.projectRoot, write.rel, hash)) {
425
519
  console.log(` Kept ${write.rel} (changed since preview)`);
426
520
  continue;
@@ -433,7 +527,11 @@ export class Writer {
433
527
  } else {
434
528
  writeFileSync(dest, write.content, 'utf8');
435
529
  }
436
- if (write.ownerDir) {
530
+ written.push(write);
531
+ if (write.block) {
532
+ // Blocos com marcas e textos migrados ficam fora do manifest.
533
+ if (write.block.mode) this.entryBlocks[write.rel] = write.block;
534
+ } else if (write.ownerDir) {
437
535
  // Skills: o diretório vai para created_files, os arquivos para o manifest.
438
536
  this._register(join(this.projectRoot, write.ownerDir));
439
537
  const rel = this._rel(dest);
@@ -457,7 +555,7 @@ export class Writer {
457
555
  dir = dir.slice(0, dir.lastIndexOf('/'));
458
556
  }
459
557
  }
460
- return removed;
558
+ return { written, removed };
461
559
  }
462
560
 
463
561
  // Adiciona _reversa_sdd/ e .reversa/config.user.toml ao .gitignore
@@ -487,6 +585,7 @@ export class Writer {
487
585
  if (!existsSync(statePath)) return;
488
586
  const state = readJsonSafe(statePath);
489
587
  state.created_files = [...new Set([...(state.created_files ?? []), ...this.createdFiles])];
588
+ state.entry_blocks = { ...(state.entry_blocks ?? {}), ...this.entryBlocks };
490
589
  writeFileSync(statePath, JSON.stringify(state, null, 2), 'utf8');
491
590
  }
492
591
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wrxn-reversa",
3
- "version": "1.3.7",
3
+ "version": "1.4.0",
4
4
  "description": "Transform legacy systems into executable specifications for AI coding agents",
5
5
  "bin": {
6
6
  "wrxn-reversa": "bin/reversa.js"
@@ -0,0 +1,40 @@
1
+ # Reversa
2
+
3
+ > Framework Reversa instalado neste projeto. Skills em `.agents/skills/` (no Claude Code, também em `.claude/skills/`).
4
+ > Como chamar: Claude Code e Cursor `/nome` · Codex `$nome` ou `nome` · OMP `/skill:nome`. `reversa` sozinho é `/reversa`.
5
+
6
+ Escopo: estas regras valem dentro de um fluxo Reversa ou quando o usuário pede um skill Reversa; fora disso, siga as demais instruções do projeto.
7
+
8
+ ## Roteamento
9
+
10
+ Antes de agir, case o pedido do usuário com uma linha da tabela e entre pela porta indicada. A cadeia completa de cada fluxo está no `/reversa-router`: use-o quando não tiver certeza do fluxo ou quando o usuário perguntar "onde eu parei" ou "o que faço agora".
11
+
12
+ | Pedido do usuário | Porta de entrada | Exige antes |
13
+ |---|---|---|
14
+ | Entender ou documentar o legado, gerar specs | `/reversa` (sem paradas: `/reversa-autonomous`) | código no projeto |
15
+ | Ideia ainda bruta, pensar antes de construir | `/reversa-brainstorm` | nada |
16
+ | Projeto novo a partir de uma ideia | `/reversa-new` (até o código: `/reversa-new expresso`) | nada |
17
+ | Nova feature, evoluir o sistema | `/reversa-forward` | specs em `_reversa_sdd/` (sem elas, modo greenfield) |
18
+ | Várias features sem parar (`/goal`) | `/reversa-forward-autonomous` | specs e `.reversa/reversa-config.json` liberado |
19
+ | Ajuste curto no que a feature ativa entregou | `/reversa-add` | feature ativa já codificada |
20
+ | Mudança pequena e nova numa base já extraída | `/reversa-code-express` | âncora em `_reversa_sdd/` |
21
+ | Bug: relatar, rastrear, corrigir | `/reversa-debugger`, depois `/reversa-debugger-fix <ID>` | nada (melhor com specs) |
22
+ | Melhorar código sem mudar comportamento | `/reversa-refactor` | melhor com `soul.md` e specs |
23
+ | Migrar o legado para outra stack | `/reversa-migrate` | extração concluída |
24
+ | Reimplementar do zero a partir das specs | `/reversa-reconstructor` | extração ou migração concluída |
25
+ | Mini-site HTML da documentação | `/reversa-docs` | extração concluída |
26
+ | Quanto cobrar pelo software ou por uma feature | `/reversa-pricing` | por feature: forward até o to-do |
27
+ | Design de interface (front-end) | `/impeccable` | nada |
28
+ | Explicação dos agentes com analogias | `/reversa-agents-help` | nada |
29
+
30
+ ## Regras permanentes (valem também depois de qualquer resumo da conversa)
31
+
32
+ 1. **Código de produto num projeto com `_reversa_sdd/`.** Antes de criar ou mudar comportamento, ofereça em uma linha a porta certa (`/reversa-forward`, `/reversa-add`, `/reversa-code-express` ou `/reversa-debugger`). Se o usuário pedir para fazer direto, faça, mas leia antes as specs da área em `_reversa_sdd/` e siga os padrões registrados lá.
33
+ 2. **Etapas internas não se ativam pelo nome.** `reversa-scout`, `reversa-plan`, `reversa-coding` e as demais etapas são lidas: abra `.claude/skills/<etapa>/SKILL.md` (ou `.agents/skills/<etapa>/SKILL.md`) na íntegra e siga. Nunca execute uma etapa só a partir do nome dela.
34
+ 3. **CONTINUAR** depois de uma sugestão `/reversa-<x>`: leia o `SKILL.md` de `reversa-<x>` pela regra 2 e siga.
35
+ 4. **Reancoragem.** Se a conversa foi resumida ou compactada, ou se você não sabe em que etapa está, releia do disco o estado do fluxo (`.reversa/state.json`, `.reversa/active-requirements.json`, `.reversa/forward-autonomous.json`, `.reversa/active-ideation.json`, `_reversa_sdd/migration/.state.json`) e o `SKILL.md` da etapa antes de responder. O disco manda, não a memória da conversa.
36
+ 5. **Delegação.** Ao passar uma etapa a um subagente ou a outro agente (outro painel, Codex): entregue o caminho do `SKILL.md`, a feature ou o contexto ativo e os arquivos de estado. Quem recebe lê o `SKILL.md` e grava o resultado em disco; quem delegou relê o estado quando o trabalho volta. Checkpoints 🛑 (aprovação humana) ficam na sessão que conversa com o usuário. Nunca rode em paralelo duas etapas que gravam o mesmo arquivo de estado ou a mesma pasta de feature; features diferentes em paralelo pedem worktrees separados. Quem recebe devolve a lista de arquivos gravados e as perguntas pendentes; só quem delegou atualiza `.reversa/state.json` e `.reversa/plan.md`.
37
+
38
+ ## Regra não-negociável
39
+
40
+ {{REVERSA_POLICY}}
@@ -1,26 +0,0 @@
1
- # Reversa
2
-
3
- > Framework de Engenharia Reversa instalado neste projeto.
4
-
5
- ## Como usar
6
-
7
- Use o fluxo adequado no chat:
8
-
9
- - `reversa` — descobrir e documentar um sistema existente
10
- - `reversa-new` — criar PRD e specs para um projeto novo
11
- - `reversa-forward` — implementar ou evoluir código a partir das specs
12
- - `reversa-migrate` — planejar a migração de um sistema legado
13
- - `reversa-docs` — gerar o mini-site visual da documentação
14
- - `impeccable` — design de front-end: criticar, auditar e polir interfaces (Impeccable, Apache 2.0)
15
- - `reversa-agents-help` — consultar o catálogo completo de agentes
16
-
17
- ## Comportamento ao ativar
18
-
19
- Quando o usuário digitar `reversa` sozinho em uma mensagem:
20
-
21
- 1. Ative o skill `reversa` disponível em `.agents/skills/reversa/SKILL.md`
22
- 2. Leia o SKILL.md na íntegra e siga exatamente as instruções do Reversa
23
-
24
- ## Regra não-negociável
25
-
26
- {{REVERSA_POLICY}}
@@ -1,27 +0,0 @@
1
- # Reversa
2
-
3
- > Framework de Engenharia Reversa instalado neste projeto.
4
-
5
- ## Como usar
6
-
7
- Use o fluxo adequado no chat:
8
-
9
- - `/reversa` — descobrir e documentar um sistema existente
10
- - `/reversa-new` — criar PRD e specs para um projeto novo
11
- - `/reversa-forward` — implementar ou evoluir código a partir das specs
12
- - `/reversa-migrate` — planejar a migração de um sistema legado
13
- - `/reversa-docs` — gerar o mini-site visual da documentação
14
- - `/impeccable` — design de front-end: criticar, auditar e polir interfaces (Impeccable, Apache 2.0)
15
- - `/reversa-agents-help` — consultar o catálogo completo de agentes
16
-
17
- ## Comportamento ao ativar
18
-
19
- Quando o usuário digitar `/reversa` ou a palavra `reversa` sozinha em uma mensagem:
20
-
21
- 1. Ative o skill `reversa` disponível em `.claude/skills/reversa/SKILL.md`
22
- 2. Se não encontrar em `.claude/skills/`, tente `.agents/skills/reversa/SKILL.md`
23
- 3. Leia o SKILL.md na íntegra e siga exatamente as instruções do Reversa
24
-
25
- ## Regra não-negociável
26
-
27
- {{REVERSA_POLICY}}
@@ -1,26 +0,0 @@
1
- # Reversa
2
-
3
- > Framework de Engenharia Reversa instalado neste projeto.
4
-
5
- ## Como usar
6
-
7
- Use o fluxo adequado no chat:
8
-
9
- - `reversa` — descobrir e documentar um sistema existente
10
- - `reversa-new` — criar PRD e specs para um projeto novo
11
- - `reversa-forward` — implementar ou evoluir código a partir das specs
12
- - `reversa-migrate` — planejar a migração de um sistema legado
13
- - `reversa-docs` — gerar o mini-site visual da documentação
14
- - `impeccable` — design de front-end: criticar, auditar e polir interfaces (Impeccable, Apache 2.0)
15
- - `reversa-agents-help` — consultar o catálogo completo de agentes
16
-
17
- ## Comportamento ao ativar
18
-
19
- Quando o usuário escrever `reversa` sozinho:
20
-
21
- 1. Ative o skill `reversa` disponível em `.agents/skills/reversa/SKILL.md`
22
- 2. Leia o SKILL.md na íntegra e siga exatamente as instruções do Reversa
23
-
24
- ## Regra não-negociável
25
-
26
- {{REVERSA_POLICY}}
@@ -1,26 +0,0 @@
1
- # Reversa
2
-
3
- > Framework de Engenharia Reversa instalado neste projeto.
4
-
5
- ## Como usar
6
-
7
- Use o fluxo adequado no chat:
8
-
9
- - `/reversa` — descobrir e documentar um sistema existente
10
- - `/reversa-new` — criar PRD e specs para um projeto novo
11
- - `/reversa-forward` — implementar ou evoluir código a partir das specs
12
- - `/reversa-migrate` — planejar a migração de um sistema legado
13
- - `/reversa-docs` — gerar o mini-site visual da documentação
14
- - `/impeccable` — design de front-end: criticar, auditar e polir interfaces (Impeccable, Apache 2.0)
15
- - `/reversa-agents-help` — consultar o catálogo completo de agentes
16
-
17
- ## Comportamento ao ativar
18
-
19
- Quando o usuário digitar `/reversa` ou a palavra `reversa` sozinha em uma mensagem:
20
-
21
- 1. Ative o skill `reversa` disponível em `.agents/skills/reversa/SKILL.md`
22
- 2. Leia o SKILL.md na íntegra e siga exatamente as instruções do Reversa
23
-
24
- ## Regra não-negociável
25
-
26
- {{REVERSA_POLICY}}
@@ -1,7 +0,0 @@
1
- # Reversa — Framework de Engenharia Reversa
2
-
3
- Quando o usuário digitar "/reversa" ou "reversa" sozinho em uma mensagem:
4
- 1. Ative o skill "reversa" em .agents/skills/reversa/SKILL.md
5
- 2. Leia o SKILL.md na íntegra e siga exatamente as instruções do Reversa
6
-
7
- {{REVERSA_POLICY}}
@@ -1,7 +0,0 @@
1
- # Reversa — Framework de Engenharia Reversa
2
-
3
- Quando o usuário digitar "/reversa" ou "reversa" sozinho em uma mensagem:
4
- 1. Ative o skill "reversa" em .agents/skills/reversa/SKILL.md
5
- 2. Leia o SKILL.md na íntegra e siga exatamente as instruções do Reversa
6
-
7
- {{REVERSA_POLICY}}
@@ -1,26 +0,0 @@
1
- # Reversa
2
-
3
- > Framework de Engenharia Reversa instalado neste projeto.
4
-
5
- ## Como usar
6
-
7
- Use o fluxo adequado no chat:
8
-
9
- - `/reversa` — descobrir e documentar um sistema existente
10
- - `/reversa-new` — criar PRD e specs para um projeto novo
11
- - `/reversa-forward` — implementar ou evoluir código a partir das specs
12
- - `/reversa-migrate` — planejar a migração de um sistema legado
13
- - `/reversa-docs` — gerar o mini-site visual da documentação
14
- - `/impeccable` — design de front-end: criticar, auditar e polir interfaces (Impeccable, Apache 2.0)
15
- - `/reversa-agents-help` — consultar o catálogo completo de agentes
16
-
17
- ## Comportamento ao ativar
18
-
19
- Quando o usuário digitar `/reversa` ou a palavra `reversa` sozinha em uma mensagem:
20
-
21
- 1. Ative o skill `reversa` disponível em `.agents/skills/reversa/SKILL.md`
22
- 2. Leia o SKILL.md na íntegra e siga exatamente as instruções do Reversa
23
-
24
- ## Regra não-negociável
25
-
26
- {{REVERSA_POLICY}}
@@ -1,7 +0,0 @@
1
- # Reversa — Framework de Engenharia Reversa
2
-
3
- Quando o usuário digitar "/reversa" ou "reversa" sozinho em uma mensagem:
4
- 1. Ative o skill "reversa" em .agents/skills/reversa/SKILL.md
5
- 2. Leia o SKILL.md na íntegra e siga exatamente as instruções do Reversa
6
-
7
- {{REVERSA_POLICY}}
@@ -1,7 +0,0 @@
1
- # Reversa — Framework de Engenharia Reversa
2
-
3
- Quando o usuário digitar "/reversa" ou "reversa" sozinho em uma mensagem:
4
- 1. Ative o skill "reversa" em .agents/skills/reversa/SKILL.md
5
- 2. Leia o SKILL.md na íntegra e siga exatamente as instruções do Reversa
6
-
7
- {{REVERSA_POLICY}}
@@ -1,7 +0,0 @@
1
- # Reversa — Framework de Engenharia Reversa
2
-
3
- Quando o usuário digitar "/reversa" ou "reversa" sozinho em uma mensagem:
4
- 1. Ative o skill "reversa" em .agents/skills/reversa/SKILL.md
5
- 2. Leia o SKILL.md na íntegra e siga exatamente as instruções do Reversa
6
-
7
- {{REVERSA_POLICY}}