mddd-cli 1.0.1 → 1.0.3

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.
Files changed (3) hide show
  1. package/bin/cli.js +28 -36
  2. package/package.json +1 -1
  3. package/readme.md +284 -23
package/bin/cli.js CHANGED
@@ -130,64 +130,56 @@ program
130
130
  .option('-m, --macro', 'Define se o novo arquivo será um macro de módulo contendo stateDiagram-v2')
131
131
  .option('-p, --parent <parentFile>', 'Caminho de um arquivo spec (.spec.md) existente para conectar este novo fluxo')
132
132
  .action((targetPath, options) => {
133
+ // Garante que o diretório base exista
133
134
  if (!fs.existsSync(targetPath)) {
134
135
  fs.mkdirSync(targetPath, { recursive: true });
135
136
  }
136
137
 
138
+ // Correção: Extrai o nome da feature para o arquivo
139
+ // Se targetPath terminar em /routing, folderName será 'routing'.
140
+ // O arquivo será 'routing.spec.md'.
137
141
  const folderName = path.basename(targetPath);
138
- const isMacro = options.macro;
139
-
140
- // Extensão universal .spec.md para absolutamente tudo
141
142
  const finalFile = path.join(targetPath, `${folderName}.spec.md`);
142
143
 
144
+ // Segurança: Verifica se o caminho final existe e é um diretório
145
+ if (fs.existsSync(finalFile) && fs.lstatSync(finalFile).isDirectory()) {
146
+ console.log(pc.red(`❌ Erro: Já existe um diretório com o nome ${finalFile}. Não é possível criar o arquivo spec.`));
147
+ process.exit(1);
148
+ }
149
+
143
150
  if (fs.existsSync(finalFile)) {
144
151
  console.log(pc.yellow(`⚠️ A especificação já existe em: ${finalFile}`));
145
152
  return;
146
153
  }
147
154
 
148
- // Geração dos templates otimizados para Cline/MDDD
149
- let template = '';
155
+ const isMacro = options.macro;
150
156
  const version = 'v1.0.0';
151
-
152
- if (isMacro) {
153
- template = `\n# Macro Módulo: ${folderName} | ${version}\n\n` +
154
- `\`\`\`mermaid\n%% @spec-version ${version}\nstateDiagram-v2\n [*] --> Inicial_${folderName}\n\`\`\`\n\n` +
155
- `## 3. Histórico de Auditoria\n<details>\n<summary>Clique para expandir</summary>\n\n\n\n</details>\n`;
156
- } else {
157
- template = `\n# Especificação: ${folderName} | ${version}\n\n` +
158
- `## 1. Contrato de Fluxo (Mermaid)\n\`\`\`mermaid\n%% @spec-version ${version}\ngraph LR\n A([Início]) --> B[Processo]\n\`\`\`\n\n` +
159
- `## 2. Matriz de Decisão\n| Condição | Ação | Próximo Estado |\n| :--- | :--- | :--- |\n| | | |\n\n` +
160
- `## 3. Histórico de Auditoria\n<details>\n<summary>Clique para expandir</summary>\n\n\n\n</details>\n`;
161
- }
157
+ let template = isMacro
158
+ ? `\n# Macro Módulo: ${folderName} | ${version}\n\n` +
159
+ `\`\`\`mermaid\n%% @spec-version ${version}\nstateDiagram-v2\n [*] --> Inicial_${folderName}\n\`\`\`\n\n` +
160
+ `## 3. Histórico de Auditoria\n<details>\n<summary>Clique para expandir</summary>\n\n\n\n</details>\n`
161
+ : `\n# Especificação: ${folderName} | ${version}\n\n` +
162
+ `## 1. Contrato de Fluxo (Mermaid)\n\`\`\`mermaid\n%% @spec-version ${version}\ngraph LR\n A([Início]) --> B[Processo]\n\`\`\`\n\n` +
163
+ `## 2. Matriz de Decisão\n| Condição | Ação | Próximo Estado |\n| :--- | :--- | :--- |\n| | | |\n\n` +
164
+ `## 3. Histórico de Auditoria\n<details>\n<summary>Clique para expandir</summary>\n\n\n\n</details>\n`;
162
165
 
163
166
  fs.writeFileSync(finalFile, template);
164
- console.log(pc.green(`✅ Novo arquivo Markdown criado com controle de versão (v1.0.0): ${finalFile}`));
165
-
166
- // Lógica de Vinculação entre os arquivos Markdown
167
- let macroPath = null;
168
- if (options.parent) {
169
- if (fs.existsSync(options.parent)) {
170
- macroPath = options.parent;
171
- console.log(pc.cyan('🎯 Usando o arquivo pai explícito enviado por parâmetro.'));
172
- } else {
173
- console.log(pc.red(`❌ O arquivo pai indicado não foi encontrado: ${options.parent}`));
174
- process.exit(1);
175
- }
176
- } else if (!isMacro) {
177
- macroPath = findClosestMacro(targetPath);
178
- }
167
+ console.log(pc.green(`✅ Novo arquivo Markdown criado: ${finalFile}`));
168
+
169
+ // Lógica de Vinculação
170
+ let macroPath = options.parent || (!isMacro ? findClosestMacro(targetPath) : null);
179
171
 
180
172
  if (macroPath) {
173
+ if (!fs.existsSync(macroPath)) {
174
+ console.log(pc.red(`❌ Arquivo pai não encontrado: ${macroPath}`));
175
+ process.exit(1);
176
+ }
181
177
  const relativePath = path.relative(path.dirname(macroPath), finalFile);
182
- const cleanLinkPath = relativePath.replace(/\\/g, '/'); // Normaliza barras para padrão POSIX/Web
183
-
184
- // Como o pai é um arquivo Markdown, injetamos uma seção de navegação limpa no fim do documento
178
+ const cleanLinkPath = relativePath.replace(/\\/g, '/');
185
179
  const injection = `\n\n%% Conexão automática para sub-fluxo\n- [Ir para as regras de ${folderName}](file://./${cleanLinkPath})\n`;
186
180
 
187
181
  fs.appendFileSync(macroPath, injection);
188
182
  console.log(pc.blue(`🔗 Vinculado com sucesso no arquivo pai: ${macroPath}`));
189
- } else if (!isMacro) {
190
- console.log(pc.yellow('⚠️ Aviso: Nenhum arquivo macro (*.spec.md) acima na árvore foi encontrado para auto-vinculação.'));
191
183
  }
192
184
  });
193
185
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mddd-cli",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "description": "CLI oficial para Mermaid Diagram Driven Development (MDDD) modular, colocalizado e versionado.",
5
5
  "main": "bin/cli.js",
6
6
  "type": "module",
package/readme.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # Mermaid Diagram Driven Development (MDDD) CLI 🚀
2
2
 
3
+ ![npm](https://img.shields.io/npm/v/mddd-cli)
4
+ ![npm](https://img.shields.io/npm/l/mddd-cli)
5
+ ![Node](https://img.shields.io/node/v/mddd-cli)
6
+
7
+ ---
8
+
9
+ <p align="center">
10
+ <a href="#português">🇧🇷 Português</a> •
11
+ <a href="#english">🇺🇸 English</a>
12
+ </p>
13
+
14
+ ---
15
+
16
+ <a id="português"></a>
17
+
18
+ # 🇧🇷 Português
19
+
3
20
  Uma CLI agnóstica, ultra-leve e cirúrgica para implementar **MDDD (Mermaid Diagram Driven Development)** de forma modular, colocalizada e estritamente versionada.
4
21
 
5
22
  Esta ferramenta automatiza a criação e a conexão de arquivos de especificação visual (Markdown + Mermaid). O objetivo é envelopar as regras de negócio em arquivos `.spec.md` para que qualquer IA de mercado (**Cursor, Windsurf, Claude Code, GitHub Copilot**, etc.) use esses diagramas como a **Fonte Única da Verdade** antes de tocar no código produtivo.
@@ -17,6 +34,30 @@ No **Mermaid Diagram Driven Development**, invertemos o ciclo tradicional de des
17
34
 
18
35
  ---
19
36
 
37
+ ## ✅ Pré-visualização dos Diagramas Mermaid
38
+
39
+ ### Exemplo diagrama de inicialização de um app Flutter
40
+ <img width="1316" height="444" alt="image" src="https://github.com/user-attachments/assets/5cacc283-e517-4468-a8cd-d67442a75bf2" />
41
+
42
+ Para visualizar os diagramas Mermaid diretamente no seu editor durante o fluxo MDDD, você pode utilizar extensões que renderizam blocos ````mermaid```` em arquivos Markdown:
43
+
44
+ ### VS Code
45
+ - **Markdown Preview Mermaid Support** — Adiciona suporte a diagramas Mermaid no preview nativo do Markdown.
46
+ - **Mermaid Editor** — Editor visual com preview lado a lado e exportação.
47
+ - **bierner.markdown-mermaid** — Extensão oficial que estende o preview de Markdown para renderizar Mermaid.
48
+
49
+ ### JetBrains (IntelliJ, WebStorm, GoLand, etc.)
50
+ - Suporte nativo a Mermaid a partir do **2024.1** — Basta abrir o arquivo `.spec.md` e usar o preview de Markdown integrado.
51
+
52
+ ### Outros Editores
53
+ - **Neovim/Vim:** Utilize plugins como `iamcco/markdown-preview.nvim` (com `markdown-preview` configurado para Mermaid).
54
+ - **Sublime Text:** Pacote `Mermaid` no Package Control que adiciona preview e snippets.
55
+ - **Markdown Editors:** Ferramentas como [Typora](https://typora.io), [Obsidian](https://obsidian.md) e [Notion](https://notion.so) já possuem suporte nativo a Mermaid — basta colar o arquivo `.spec.md` e o diagrama será renderizado automaticamente.
56
+
57
+ > 💡 **Dica:** Quanto melhor a visualização dos diagramas, mais fácil validar os fluxos de negócio antes de implementar.
58
+
59
+ ---
60
+
20
61
  ## 📥 Instalação
21
62
 
22
63
  Como o pacote está publicado no NPM, a instalação é global e simples:
@@ -24,40 +65,68 @@ Como o pacote está publicado no NPM, a instalação é global e simples:
24
65
  ```bash
25
66
  # Instalação global
26
67
  npm install -g mddd-cli
27
- Nota: Certifique-se de ter o Node.js v18 ou superior instalado em sua máquina.
68
+ ```
28
69
 
29
- 🚀 Guia de Uso Rápido
30
- O fluxo MDDD é baseado em comandos de CLI para gerenciar a estrutura e comandos de barra (/) para orquestrar a IA no chat.
70
+ > **Nota:** Certifique-se de ter o **Node.js v18 ou superior** instalado em sua máquina.
31
71
 
32
- 1. Inicialize seu projeto
33
- Na raiz do seu projeto, execute: md init
34
- Isso criará o arquivo system_prompt.md na raiz, contendo as instruções globais que guiarão a IA no entendimento da metodologia MDDD.
72
+ ---
73
+
74
+ ## 🚀 Guia de Uso Rápido
75
+
76
+ O fluxo MDDD é baseado em comandos de CLI para gerenciar a estrutura e comandos de barra (`/`) para orquestrar a IA no chat.
77
+
78
+ ### 1. Inicialize seu projeto
79
+
80
+ Na raiz do seu projeto, execute:
81
+
82
+ ```bash
83
+ md init
84
+ ```
85
+
86
+ Isso criará o arquivo `system_prompt.md` na raiz, contendo as instruções globais que guiarão a IA no entendimento da metodologia MDDD.
87
+
88
+ ### 2. Crie uma nova especificação (Feature)
35
89
 
36
- 2. Crie uma nova especificação (Feature)
37
- Ao iniciar uma nova funcionalidade, crie o contrato visual dela:
38
- # Para uma funcionalidade simples (micro)
90
+ Ao iniciar uma nova funcionalidade, crie o contrato visual dela:
91
+
92
+ ```bash
93
+ # Para uma funcionalidade simples (micro)
39
94
  md new src/feature-name
40
95
 
41
96
  # Para um módulo completo (macro)
42
97
  md new src/feature-name --macro
98
+ ```
99
+
100
+ Isso gerará o arquivo `feature-name.spec.md` com a estrutura de Mermaid, Matriz de Decisão e Versionamento.
101
+
102
+ ### 3. Auditoria de Legado
43
103
 
44
- Isso gerará o arquivo feature-name.spec.md com a estrutura de Mermaid, Matriz de Decisão e Versionamento.
104
+ Precisa refatorar um código existente? Audite-o:
45
105
 
46
- 3. Auditoria de Legado
47
- Precisa refatorar um código existente? Audite-o:
106
+ ```bash
48
107
  md audit src/path/to/legacy-file.dart
108
+ ```
109
+
110
+ ---
111
+
112
+ ## 🤖 Comandos de Barra (Gatilhos para IAs)
49
113
 
50
- 🤖 Comandos de Barra (Gatilhos para IAs)
51
- Após rodar o md init, a sua IA passará a entender estes atalhos quando você os digitar no chat:
52
- Comando Descrição
53
- /md-new Inicia o modo de desenho para nova feature (gera diagrama e tabela).
54
- /md-edit Solicita alteração em um .spec.md existente (incrementa versão semântica).
55
- /md-audit Analisa código legado e propõe refatoração visual (Mermaid).
56
- /md-impl Gera código e testes baseando-se estritamente no diagrama do .spec.md.
114
+ Após rodar o `md init`, a sua IA passará a entender estes atalhos quando você os digitar no chat:
57
115
 
58
- 🏗️ Arquitetura de Especificação Colocalizada (Co-location)
59
- As especificações visuais não ficam centralizadas em pastas distantes. Elas vivem no mesmo diretório do componente, tela ou feature que descrevem.
116
+ | Comando | Descrição |
117
+ | :---------- | :------------------------------------------------------------------------------- |
118
+ | `/md-new` | Inicia o modo de desenho para nova feature (gera diagrama e tabela). |
119
+ | `/md-edit` | Solicita alteração em um `.spec.md` existente (incrementa versão semântica). |
120
+ | `/md-audit` | Analisa código legado e propõe refatoração visual (Mermaid). |
121
+ | `/md-impl` | Gera código e testes baseando-se estritamente no diagrama do `.spec.md`. |
60
122
 
123
+ ---
124
+
125
+ ## 🏗️ Arquitetura de Especificação Colocalizada (Co-location)
126
+
127
+ As especificações visuais não ficam centralizadas em pastas distantes. Elas vivem no **mesmo diretório** do componente, tela ou feature que descrevem.
128
+
129
+ ```
61
130
  src/
62
131
  └── home/
63
132
  ├── home.spec.md # 🌎 MACRO: Visão global do módulo (stateDiagram-v2)
@@ -66,6 +135,198 @@ src/
66
135
  │ └── guest_page.dart # 💻 Código produtivo gerado pela IA
67
136
  └── consumer/
68
137
  └── consumer.spec.md # 🔬 MICRO: Fluxo de tela (graph LR) + Matriz de Decisão
138
+ ```
139
+
140
+ ---
141
+
142
+ ## 📦 Comandos da CLI
143
+
144
+ | Comando | Descrição |
145
+ | :------------ | :---------------------------------------------------------------------------------------------------- |
146
+ | `md init` | Inicializa o prompt de sistema universal e as skills para guiar qualquer IA no projeto. |
147
+ | `md new` | Cria uma nova especificação `.spec.md` colocalizada com versionamento automático. |
148
+ | `md edit` | Sinaliza uma alteração pendente em um arquivo de especificação existente. |
149
+ | `md audit` | Audita um arquivo de código existente para criar uma especificação retroativa ou sugerir refatoração. |
150
+ | `md impl` | Prepara o ecossistema para implementar código produtivo e testes com base no `.spec.md`. |
151
+
152
+ ---
153
+
154
+ ## 🧪 Tecnologias
155
+
156
+ - **Node.js** >= 18
157
+ - **Commander.js** — Interface CLI robusta e declarativa
158
+ - **Picocolors** — Saída colorida e leve no terminal
159
+ - **Mermaid.js** — Diagramação visual como fonte da verdade
160
+
161
+ ---
162
+
163
+ ## 💬 Precisa de ajuda?
164
+
165
+ Se encontrar qualquer problema, abra uma [Issue no GitHub](https://github.com/JulioCRFilho/mermaid-diagram-driven-development/issues).
166
+
167
+ ---
168
+
169
+ ## 📄 Licença
170
+
171
+ Distribuído sob a licença MIT. Veja o arquivo [LICENSE](LICENSE) para mais informações.
172
+
173
+ ---
174
+
175
+ ---
176
+
177
+ <a id="english"></a>
178
+
179
+ # 🇺🇸 English
180
+
181
+ An agnostic, ultra-lightweight, and surgical CLI for implementing **MDDD (Mermaid Diagram Driven Development)** in a modular, co-located, and strictly versioned way.
182
+
183
+ This tool automates the creation and connection of visual specification files (Markdown + Mermaid). The goal is to encapsulate business rules within `.spec.md` files so that any AI tool (**Cursor, Windsurf, Claude Code, GitHub Copilot**, etc.) uses these diagrams as the **Single Source of Truth** before touching production code.
184
+
185
+ ---
186
+
187
+ ## 📌 The Concept: MDDD
188
+
189
+ In **Mermaid Diagram Driven Development**, we invert the traditional AI chat-driven development cycle:
190
+
191
+ 1. **Design (`/md-new`):** The AI and you create the business rule visually inside the co-located `.spec.md` file.
192
+ 2. **Approval:** You review the visual flow directly in your code editor's Markdown preview.
193
+ 3. **Editing (`/md-edit`):** Scope adjustments alter the diagram first and increment the file's semantic version.
194
+ 4. **Implementation (`/md-impl`):** The AI reads the signed and versioned specification to write the definitive code and unit tests.
195
+
196
+ ---
197
+
198
+ ## ✅ Mermaid Diagram Preview
199
+
200
+ To preview Mermaid diagrams directly in your editor during the MDDD workflow, you can use extensions that render ````mermaid```` blocks in Markdown files:
201
+
202
+ ### Exemplo diagrama de inicialização de um app Flutter
203
+ <img width="1316" height="444" alt="image" src="https://github.com/user-attachments/assets/5cacc283-e517-4468-a8cd-d67442a75bf2" />
204
+
205
+ ### VS Code
206
+ - **Markdown Preview Mermaid Support** — Adds Mermaid diagram support to the native Markdown preview.
207
+ - **Mermaid Editor** — Visual editor with side-by-side preview and export.
208
+ - **bierner.markdown-mermaid** — Official extension that extends the Markdown preview to render Mermaid.
209
+
210
+ ### JetBrains (IntelliJ, WebStorm, GoLand, etc.)
211
+ - Native Mermaid support starting from **2024.1** — Just open the `.spec.md` file and use the built-in Markdown preview.
212
+
213
+ ### Other Editors
214
+ - **Neovim/Vim:** Use plugins like `iamcco/markdown-preview.nvim` (with `markdown-preview` configured for Mermaid).
215
+ - **Sublime Text:** `Mermaid` package from Package Control that adds preview and snippets.
216
+ - **Markdown Editors:** Tools like [Typora](https://typora.io), [Obsidian](https://obsidian.md), and [Notion](https://notion.so) already have native Mermaid support — just paste the `.spec.md` file and the diagram will render automatically.
217
+
218
+ > 💡 **Tip:** The better you can visualize the diagrams, the easier it is to validate business flows before implementation.
219
+
220
+ ---
221
+
222
+ ## 📥 Installation
223
+
224
+ Since the package is published on NPM, installation is global and simple:
225
+
226
+ ```bash
227
+ # Global installation
228
+ npm install -g mddd-cli
229
+ ```
230
+
231
+ > **Note:** Make sure you have **Node.js v18 or higher** installed on your machine.
232
+
233
+ ---
234
+
235
+ ## 🚀 Quick Start Guide
236
+
237
+ The MDDD workflow is based on CLI commands to manage the structure and slash commands (`/`) to orchestrate the AI in the chat.
238
+
239
+ ### 1. Initialize your project
240
+
241
+ In your project root, run:
242
+
243
+ ```bash
244
+ md init
245
+ ```
246
+
247
+ This will create the `system_prompt.md` file in the root directory, containing the global instructions that will guide the AI in understanding the MDDD methodology.
248
+
249
+ ### 2. Create a new specification (Feature)
250
+
251
+ When starting a new feature, create its visual contract:
252
+
253
+ ```bash
254
+ # For a simple feature (micro)
255
+ md new src/feature-name
256
+
257
+ # For a complete module (macro)
258
+ md new src/feature-name --macro
259
+ ```
260
+
261
+ This will generate the `feature-name.spec.md` file with the Mermaid structure, Decision Matrix, and Versioning.
262
+
263
+ ### 3. Legacy Audit
264
+
265
+ Need to refactor existing code? Audit it:
266
+
267
+ ```bash
268
+ md audit src/path/to/legacy-file.dart
269
+ ```
270
+
271
+ ---
272
+
273
+ ## 🤖 Slash Commands (AI Triggers)
274
+
275
+ After running `md init`, your AI will understand these shortcuts when you type them in the chat:
276
+
277
+ | Command | Description |
278
+ | :---------- | :------------------------------------------------------------------------------------ |
279
+ | `/md-new` | Starts design mode for a new feature (generates diagram and table). |
280
+ | `/md-edit` | Requests changes to an existing `.spec.md` file (increments semantic version). |
281
+ | `/md-audit` | Analyzes legacy code and proposes visual refactoring (Mermaid). |
282
+ | `/md-impl` | Generates code and tests strictly based on the `.spec.md` diagram. |
283
+
284
+ ---
285
+
286
+ ## 🏗️ Co-located Specification Architecture
287
+
288
+ Visual specifications are not centralized in distant folders. They live in the **same directory** as the component, screen, or feature they describe.
289
+
290
+ ```
291
+ src/
292
+ └── home/
293
+ ├── home.spec.md # 🌎 MACRO: Global module view (stateDiagram-v2)
294
+ ├── guest/
295
+ │ ├── guest.spec.md # 🔬 MICRO: Screen flow (graph LR) + Decision Matrix
296
+ │ └── guest_page.dart # 💻 Production code generated by AI
297
+ └── consumer/
298
+ └── consumer.spec.md # 🔬 MICRO: Screen flow (graph LR) + Decision Matrix
299
+ ```
300
+
301
+ ---
302
+
303
+ ## 📦 CLI Commands
304
+
305
+ | Command | Description |
306
+ | :------------ | :----------------------------------------------------------------------------------------------------- |
307
+ | `md init` | Initializes the universal system prompt and skills to guide any AI in the project. |
308
+ | `md new` | Creates a new co-located `.spec.md` specification with automatic versioning. |
309
+ | `md edit` | Signals a pending change in an existing specification file. |
310
+ | `md audit` | Audits an existing code file to create a retroactive specification or suggest refactoring. |
311
+ | `md impl` | Prepares the ecosystem to implement production code and tests based on the `.spec.md`. |
312
+
313
+ ---
314
+
315
+ ## 🧪 Technologies
316
+
317
+ - **Node.js** >= 18
318
+ - **Commander.js** — Robust and declarative CLI interface
319
+ - **Picocolors** — Colorful and lightweight terminal output
320
+ - **Mermaid.js** — Visual diagramming as the source of truth
321
+
322
+ ---
323
+
324
+ ## 💬 Need help?
325
+
326
+ If you encounter any issues, open a [GitHub Issue](https://github.com/JulioCRFilho/mermaid-diagram-driven-development/issues).
327
+
328
+ ---
329
+
330
+ ## 📄 License
69
331
 
70
- 💬 Precisa de ajuda?
71
- Se encontrar qualquer problema, abra uma Issue no GitHub.
332
+ Distributed under the MIT license. See the [LICENSE](LICENSE) file for more information.