mddd-cli 1.0.7 → 1.0.9

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 +1 -4
  2. package/package.json +1 -1
  3. package/readme.md +327 -152
package/bin/cli.js CHANGED
@@ -4,9 +4,6 @@ import { Command } from 'commander';
4
4
  import fs from 'fs';
5
5
  import path from 'path';
6
6
  import pc from 'picocolors';
7
- import { createRequire } from 'module';
8
- const require = createRequire(import.meta.url);
9
- const pkg = require('./package.json');
10
7
 
11
8
  const program = new Command();
12
9
 
@@ -34,7 +31,7 @@ function findClosestMacro(currentDir) {
34
31
  program
35
32
  .name('md')
36
33
  .description('Manager for co-located specifications for Mermaid Diagram Driven Development (MDDD)')
37
- .version(pkg.version);
34
+ .version('1.0.8');
38
35
 
39
36
  // ==========================================
40
37
  // COMMAND: md init
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mddd-cli",
3
- "version": "1.0.7",
3
+ "version": "1.0.9",
4
4
  "description": "Official CLI for modular, co-located, and versioned Mermaid Diagram Driven Development (MDDD).",
5
5
  "main": "bin/cli.js",
6
6
  "type": "module",
package/readme.md CHANGED
@@ -7,332 +7,507 @@
7
7
  ---
8
8
 
9
9
  <p align="center">
10
- <a href="#português">🇧🇷 Português</a> •
11
- <a href="#english">🇺🇸 English</a>
10
+ <a href="#english">🇺🇸 English</a> •
11
+ <a href="#português">🇧🇷 Português</a>
12
12
  </p>
13
13
 
14
14
  ---
15
15
 
16
- <a id="português"></a>
16
+ <a id="english"></a>
17
17
 
18
- # 🇧🇷 Português
18
+ # 🇺🇸 English
19
19
 
20
- Uma CLI agnóstica, ultra-leve e cirúrgica para implementar **MDDD (Mermaid Diagram Driven Development)** de forma modular, colocalizada e estritamente versionada.
20
+ An agnostic, ultra-lightweight, and surgical CLI for implementing **MDDD (Mermaid Diagram Driven Development)** in a modular, co-located, and strictly versioned way.
21
21
 
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.
22
+ This tool automates the creation and connection of visual specification files (Markdown + Mermaid + Decision Matrices). 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 assets as the **Single Source of Truth** before touching production code.
23
23
 
24
24
  ---
25
25
 
26
- ## 📌 O Conceito: MDDD
26
+ ## 📌 The Concept: MDDD vs. Text-Based Specs
27
27
 
28
- No **Mermaid Diagram Driven Development**, invertemos o ciclo tradicional de desenvolvimento orientado por chat de IA:
28
+ Unlike traditional specification frameworks that generate dozens of text files and "deltas" that pollute your repository, MDDD introduces a **Visual-First & Flow-Centric** paradigm:
29
29
 
30
- 1. **Desenho (`/md-new`):** A IA e você criam a regra de negócio visualmente dentro do arquivo colocalizado `.spec.md`.
31
- 2. **Aprovação:** Você revisa o fluxo visual direto no preview do Markdown do seu editor de código.
32
- 3. **Edição (`/md-edit`):** Ajustes de escopo alteram o diagrama primeiro e incrementam a versão semântica do arquivo.
33
- 4. **Implementação (`/md-impl`):** A IA lê a especificação assinada e versionada para escrever o código definitivo e os testes unitários.
30
+ 1. **A Real Architectural Map:** Instead of flat text maps, MDDD allows you to connect micro-specifications into a macro system view. It behaves like a geographical map of your entire software architecture.
31
+ 2. **Engineered for High Complexity & Massive CRUDs:** Complex states, multi-role validation, and heavy business rules are structured inside **Decision Matrices** in markdown tables. This eliminates visual layout saturation and handles complex behaviors with mathematical precision.
32
+ 3. **Zero Asset Bloat (Git Native):** Requirements are versioned directly in place. AIs leveraging CLI capabilities or **MCP (Model Context Protocol)** can instantly query the Git history to understand evolutionary changes, meaning zero temporary files or architectural clutter.
34
33
 
35
34
  ---
36
35
 
37
- ## Pré-visualização dos Diagramas Mermaid
36
+ ## ⚖️ MDDD vs. OpenSpec (SDD)
37
+
38
+ | Feature / Paradigm | OpenSpec (Specification Driven Development) | MDDD (Mermaid Diagram Driven Development) |
39
+ | :--- | :--- | :--- |
40
+ | **Logic Structure** | Textual paragraphs, verbose rules, and conversational scenarios. | Binary/Factual Decision Matrices + Strict Structural Topologies. |
41
+ | **AI Context Consumption** | High token overhead due to massive text-based behavioral descriptions. | Ultra-low token footprint using concise matrix truth tables. |
42
+ | **Scalability** | Adding rules creates massive text blocks prone to prompt fragmentation. | Adding rules scales horizontally by appending precise factor columns. |
43
+ | **Ambiguity Control** | High risk of LLM hallucination when interpreting nested "if/else" phrasing. | Mathematical precision; deterministic processing via matrix rows. |
44
+ | **Tool Footprint** | Massive boilerplate with a bloat of internal files and complex folder structures. | Ultra-lightweight: a single, highly readable CLI file easily audited by any human. |
45
+
46
+ ### 🚀 Why MDDD Decision Matrices Outperform OpenSpec:
47
+ * **Predictable Tokens:** For an LLM, reading an MDDD matrix table is identical to processing a binary truth table. It matches primitive factor columns (`Active Tenant?`, `Global Kill Switch?`) and instantly resolves whether the outcome is `ALLOW` or `DENY` without token-wasting lexical processing.
48
+ * **Infinite Columns = Infinite Variables:** If your system gains a new architectural constraint (e.g., `Is Environment Production?` or `IP Whitelisted?`), you simply append a new column to the matrix. The business logic scales horizontally without bloating or breaking Mermaid visual flows.
49
+ * **A True Replacement for OpenSpec:** OpenSpec requires writing multiple paragraphs and descriptive test scenarios to cover complex constraint combinations. MDDD completely handles this in a single, deterministic table row—slashing prompt context overhead and completely eliminating AI hallucinations.
50
+
51
+ ---
52
+
53
+ ## 🛠️ The MDDD Pipeline
38
54
 
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" />
55
+ | Phase | Actor | Action / Trigger | What Happens |
56
+ | :--- | :--- | :--- | :--- |
57
+ | **1. Input** | Human | `md-new` / `md-audit` | The user proposes a feature using natural language, points the AI directly to a Jira/GitHub Issue/Task, or asks AI to audit a legacy file. |
58
+ | **2. Conception** | AI | Autogeneration | The AI assesses the scope and builds the `.spec.md` file complete with flowcharts, lifecycles, and required **Decision Matrices**. |
59
+ | **3. Alignment** | Human | Interactive Review | The user reviews the specification within the editor. Refinements are handled iteratively by chatting with the AI. |
60
+ | **4. Planning** | AI | Task Breakdown | Once the spec is approved, the AI extracts a granular, atomic checklist of development steps directly within the file. |
61
+ | **5. Execution** | Human | `md-impl` | The user fires the execution trigger. The AI implements production code and tests strictly adhering to the specs, updating the semantic versioning on completion. |
41
62
 
42
- ### Exemplo de matriz de decisão
43
- <img width="1237" height="702" alt="image" src="https://github.com/user-attachments/assets/e8ffc227-9b2a-44d5-ad66-116dffedc8ba" />
63
+ ---
64
+
65
+ ## ✅ Mermaid Diagram Preview
44
66
 
45
- 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:
67
+ To preview Mermaid diagrams directly in your editor during the MDDD workflow, you can use extensions that render ````mermaid```` blocks in Markdown files:
68
+
69
+ ### Architectural Diagram
70
+
71
+ ```mermaid
72
+ sequenceDiagram
73
+ autonumber
74
+ actor U as Merchant User
75
+ actor A as Platform Admin
76
+ participant Core as Platform Core (Orchestrator)
77
+ participant Registry as Micro-App Registry
78
+ participant Sandbox as Execution Sandbox (Isolated Context)
79
+ participant TenantDB as Tenant Multi-Database
80
+ participant Billing as Metered Billing Engine
81
+
82
+ Note over U, Core: Scenario: Merchant attempts to execute a premium custom micro-app.
83
+
84
+ U->>Core: Request App Execution (TenantID, AppID)
85
+ Core->>Registry: Fetch Micro-App Manifest & Scope Permissions
86
+ Registry-->>Core: Return Manifest (Required API Scopes, Tier Level)
87
+
88
+ Note over Core, TenantDB: Dynamic Security & Multitenancy Validation
89
+ Core->>TenantDB: Check Tenant Subscription & Feature Flags
90
+ TenantDB-->>Core: Tenant Authorized (Active License)
91
+
92
+ Core->>Billing: Track Execution Event (Metered Usage API)
93
+ activate Billing
94
+ Billing->>Billing: Log Token/Compute Usage
95
+ deactivate Billing
96
+
97
+ Note over Core, Sandbox: Initializing Containerized Sandbox
98
+ Core->>Sandbox: Inject Security Token & Restricted SDK Proxies
99
+ Core->>Sandbox: Boot Micro-App Frontend/Backend Bundle
100
+
101
+ activate Sandbox
102
+ Sandbox->>Sandbox: Execute Micro-App Lifecycle (onInit)
103
+ Sandbox->>Core: Restricted API Call (Write Tenant Data)
104
+ Core->>TenantDB: Persist Changes securely within Tenant Isolation
105
+ Sandbox-->>U: Render Isolated UI Fragment / Micro-Frontend
106
+ deactivate Sandbox
107
+
108
+ Note over A, Core: Platform Admin can hot-swap or deprecate apps globally.
109
+ A->>Core: Deprecate App Version (Global Flag)
110
+ Core->>Registry: Update Status to "DEPRECATED"
111
+
112
+ ```
113
+
114
+ ### Micro-App Runtime & Lifecycle Decision Matrix
115
+
116
+ | Active Tenant? | Premium App? | Active Billing Tier? | User Has Role Admin? | App Whitelisted? | Global Kill Switch? | Proposed Action | Decision (Outcome) | Transition State (New Status) |
117
+ | --- | --- | --- | --- | --- | --- | --- | --- | --- |
118
+ | ❌ NO | - | - | - | - | - | `BOOT_APP` | ❌ **DENY** | - |
119
+ | ✅ YES | ❌ NO | **FREE** | ❌ NO | ✅ YES | ❌ NO | `BOOT_APP` | ✅ **ALLOW** | `ACTIVE_RUNTIME` |
120
+ | ✅ YES | ✅ YES | **FREE** | - | - | ❌ NO | `INSTALL_APP` | ❌ **DENY** | - (Trigger Upsell) |
121
+ | ✅ YES | ✅ YES | **ENTERPRISE** | ✅ YES | ✅ YES | ❌ NO | `INSTALL_APP` | ✅ **ALLOW** | `INSTALLED` |
122
+ | ✅ YES | - | - | ❌ NO | - | ❌ NO | `CONFIG_API` | ❌ **DENY** | - |
123
+ | ✅ YES | - | - | ✅ YES | - | ❌ NO | `CONFIG_API` | ✅ **ALLOW** | `CONFIGURED` |
124
+ | ✅ YES | - | - | - | - | ✅ YES | `BOOT_APP` | ❌ **DENY** | `MUTED_ISOLATION` |
125
+ | ✅ YES | - | - | - | - | ✅ YES | `HOT_RELOAD` | ❌ **DENY** | - |
126
+ | ❌ NO | - | - | - | - | - | `PURGE_DATA` | ❌ **DENY** | - |
127
+
128
+ ---
46
129
 
47
130
  ### VS Code
48
- - **Markdown Preview Mermaid Support** — Adiciona suporte a diagramas Mermaid no preview nativo do Markdown.
49
- - **Mermaid Editor** — Editor visual com preview lado a lado e exportação.
50
- - **bierner.markdown-mermaid** — Extensão oficial que estende o preview de Markdown para renderizar Mermaid.
131
+
132
+ * **Markdown Preview Mermaid Support** — Adds Mermaid diagram support to the native Markdown preview.
133
+ * **Mermaid Editor** — Visual editor with side-by-side preview and export.
134
+ * **bierner.markdown-mermaid** — Official extension that extends the Markdown preview to render Mermaid.
51
135
 
52
136
  ### JetBrains (IntelliJ, WebStorm, GoLand, etc.)
53
- - Suporte nativo a Mermaid a partir do **2024.1** — Basta abrir o arquivo `.spec.md` e usar o preview de Markdown integrado.
54
137
 
55
- ### Outros Editores
56
- - **Neovim/Vim:** Utilize plugins como `iamcco/markdown-preview.nvim` (com `markdown-preview` configurado para Mermaid).
57
- - **Sublime Text:** Pacote `Mermaid` no Package Control que adiciona preview e snippets.
58
- - **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.
138
+ * Native Mermaid support starting from **2024.1** — Just open the `.spec.md` file and use the built-in Markdown preview.
139
+
140
+ ### Other Editors
59
141
 
60
- > 💡 **Dica:** Quanto melhor a visualização dos diagramas, mais fácil validar os fluxos de negócio antes de implementar.
142
+ * **Neovim/Vim:** Use plugins like `iamcco/markdown-preview.nvim` (with `markdown-preview` configured for Mermaid).
143
+ * **Sublime Text:** `Mermaid` package from Package Control that adds preview and snippets.
144
+ * **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.
145
+
146
+ > 💡 **Tip:** The better you can visualize the diagrams, the easier it is to validate business flows before implementation.
61
147
 
62
148
  ---
63
149
 
64
- ## 📥 Instalação
150
+ ## 📥 Installation
65
151
 
66
- Como o pacote está publicado no NPM, a instalação é global e simples:
152
+ Since the package is published on NPM, installation is global and simple:
67
153
 
68
154
  ```bash
69
- # Instalação global
155
+ # Global installation
70
156
  npm install -g mddd-cli
157
+
71
158
  ```
72
159
 
73
- > **Nota:** Certifique-se de ter o **Node.js v18 ou superior** instalado em sua máquina.
160
+ > **Note:** Make sure you have **Node.js v18 or higher** installed on your machine.
74
161
 
75
162
  ---
76
163
 
77
- ## 🚀 Guia de Uso Rápido
164
+ ## 🚀 Quick Start Guide
78
165
 
79
- O fluxo MDDD é baseado em comandos de CLI para gerenciar a estrutura e comandos de barra (`/`) para orquestrar a IA no chat.
166
+ The MDDD workflow is based on CLI commands to manage the structure and slash commands (`/`) to orchestrate the AI in the chat.
80
167
 
81
- ### 1. Inicialize seu projeto
168
+ ### 1. Initialize your project
82
169
 
83
- Na raiz do seu projeto, execute:
170
+ In your project root, run:
84
171
 
85
172
  ```bash
86
173
  md init
174
+
87
175
  ```
88
176
 
89
- Isso criará o arquivo `system_prompt.md` na raiz, contendo as instruções globais que guiarão a IA no entendimento da metodologia MDDD.
177
+ This will create the `system_prompt.md` and `SKILL.md` files in the root directory, containing the global instructions that will guide the AI in understanding the MDDD methodology and interacting with Git logs.
90
178
 
91
- ### 2. Crie uma nova especificação (Feature)
179
+ ### 2. Create a new specification (Feature)
92
180
 
93
- Ao iniciar uma nova funcionalidade, crie o contrato visual dela:
181
+ When starting a new feature, create its visual contract:
94
182
 
95
183
  ```bash
96
- # Para uma funcionalidade simples (micro)
97
- md new src/feature-name
184
+ # For a single feature
185
+ md-new path/feature-name
186
+
187
+ # For a feature connecting to an existing flow
188
+ md-new path/feature-name --parent path/to/parent
98
189
 
99
- # Para um módulo completo (macro)
100
- md new src/feature-name --macro
101
190
  ```
102
191
 
103
- Isso gerará o arquivo `feature-name.spec.md` com a estrutura de Mermaid, Matriz de Decisão e Versionamento.
192
+ This will generate the `feature-name.spec.md` file containing the semantic version structure, Mermaid placeholders, Decision Matrix matrices, and the implementation checklist.
104
193
 
105
- ### 3. Auditoria de Legado
194
+ ### 3. Legacy Audit
106
195
 
107
- Precisa refatorar um código existente? Audite-o:
196
+ Need to refactor existing code? Audit it:
108
197
 
109
198
  ```bash
110
- md audit src/path/to/legacy-file.dart
199
+ md-audit path/to/legacy-file
200
+
111
201
  ```
112
202
 
113
203
  ---
114
204
 
115
- ## 🤖 Comandos de Barra (Gatilhos para IAs)
205
+ ## 🤖 SKILLS (AI Triggers)
116
206
 
117
- Após rodar o `md init`, a sua IA passará a entender estes atalhos quando você os digitar no chat:
207
+ After running `md init`, your AI will understand these shortcuts when you type them in the chat:
118
208
 
119
- | Comando | Descrição |
120
- | :---------- | :------------------------------------------------------------------------------- |
121
- | `/md-new` | Inicia o modo de desenho para nova feature (gera diagrama e tabela). |
122
- | `/md-edit` | Solicita alteração em um `.spec.md` existente (incrementa versão semântica). |
123
- | `/md-audit` | Analisa código legado e propõe refatoração visual (Mermaid). |
124
- | `/md-impl` | Gera código e testes baseando-se estritamente no diagrama do `.spec.md`. |
209
+ | Skill | Description |
210
+ | --- | --- |
211
+ | `md-new` | Starts design mode for a new feature from natural language or issue link (generates diagrams/matrices). |
212
+ | `md-edit` | Requests changes to an existing `.spec.md` file (increments semantic version). |
213
+ | `md-audit` | Analyzes legacy code and proposes visual refactoring (Mermaid). |
214
+ | `md-impl` | Generates code and tests strictly based on the `.spec.md` layout, managing version history. |
125
215
 
126
216
  ---
127
217
 
128
- ## 🏗️ Arquitetura de Especificação Colocalizada (Co-location)
218
+ ## 🏗️ Co-located Specification Architecture
129
219
 
130
- As especificações visuais não ficam centralizadas em pastas distantes. Elas vivem no **mesmo diretório** do componente, tela ou feature que descrevem.
220
+ Visual specifications are not centralized in distant folders. They live in the **same directory** as the component, screen, or feature they describe, mapping out your software natively.
131
221
 
132
222
  ```
133
223
  src/
134
224
  └── home/
135
- ├── home.spec.md # 🌎 MACRO: Visão global do módulo (stateDiagram-v2)
225
+ ├── home.spec.md # 🌎 Global module map (stateDiagram-v2 connecting nodes)
136
226
  ├── guest/
137
- │ ├── guest.spec.md # 🔬 MICRO: Fluxo de tela (graph LR) + Matriz de Decisão
138
- │ └── guest_page.dart # 💻 Código produtivo gerado pela IA
227
+ │ ├── guest.spec.md # 🔬 Screen flow (graph LR) + Decision Matrix
228
+ │ └── guest_page.dart # 💻 Production code generated by AI
139
229
  └── consumer/
140
- └── consumer.spec.md # 🔬 MICRO: Fluxo de tela (graph LR) + Matriz de Decisão
230
+ └── consumer.spec.md # 🔬 Screen flow (graph LR) + Decision Matrix
231
+
141
232
  ```
142
233
 
143
234
  ---
144
235
 
145
- ## 📦 Comandos da CLI
236
+ ## 📦 CLI Commands
146
237
 
147
- | Comando | Descrição |
148
- | :------------ | :---------------------------------------------------------------------------------------------------- |
149
- | `md init` | Inicializa o prompt de sistema universal e as skills para guiar qualquer IA no projeto. |
150
- | `md new` | Cria uma nova especificação `.spec.md` colocalizada com versionamento automático. |
151
- | `md edit` | Sinaliza uma alteração pendente em um arquivo de especificação existente. |
152
- | `md audit` | Audita um arquivo de código existente para criar uma especificação retroativa ou sugerir refatoração. |
153
- | `md impl` | Prepara o ecossistema para implementar código produtivo e testes com base no `.spec.md`. |
238
+ | Command | Description |
239
+ | --- | --- |
240
+ | `md init` | Configures the `system_prompt.md` file and the SKILL.md files which instructs the AI how to behave. Run this everytime you update MDDD-CLI NPM Package. |
241
+
242
+ Other commands are made for IA-only. You should only tell IA which skill you want to use and the destination file.
154
243
 
155
244
  ---
156
245
 
157
- ## 🧪 Tecnologias
246
+ ## 🧪 Technologies
158
247
 
159
- - **Node.js** >= 18
160
- - **Commander.js** — Interface CLI robusta e declarativa
161
- - **Picocolors** — Saída colorida e leve no terminal
162
- - **Mermaid.js** — Diagramação visual como fonte da verdade
248
+ * **Node.js** >= 18
249
+ * **Commander.js** — Robust and declarative CLI interface
250
+ * **Picocolors** — Colorful and lightweight terminal output
251
+ * **Mermaid.js** — Visual diagramming as the source of truth
163
252
 
164
253
  ---
165
254
 
166
- ## 💬 Precisa de ajuda?
255
+ ## 💬 Need help?
167
256
 
168
- Se encontrar qualquer problema, abra uma [Issue no GitHub](https://github.com/JulioCRFilho/mermaid-diagram-driven-development/issues).
257
+ If you encounter any issues, open a [GitHub Issue](https://github.com/JulioCRFilho/mermaid-diagram-driven-development/issues).
169
258
 
170
259
  ---
171
260
 
172
- ## 📄 Licença
261
+ ## 📄 License
173
262
 
174
- Distribuído sob a licença MIT. Veja o arquivo [LICENSE](LICENSE) para mais informações.
263
+ Distributed under the MIT license. See the [LICENSE](https://www.google.com/search?q=LICENSE) file for more information.
175
264
 
176
265
  ---
177
266
 
178
- ---
267
+ # 🇧🇷 Português
179
268
 
180
- <a id="english"></a>
269
+ Uma CLI agnóstica, ultra-leve e cirúrgica para implementar **MDDD (Mermaid Diagram Driven Development)** de forma modular, colocalizada e estritamente versionada.
181
270
 
182
- # 🇺🇸 English
271
+ Esta ferramenta automatiza a criação e a conexão de arquivos de especificação visual (Markdown + Mermaid + Matrizes de Decisão). O objetivo é envelopar as regras de negócio em arquivos `.spec.md` para que qualquer ferramenta de IA (**Cursor, Windsurf, Claude Code, GitHub Copilot**, etc.) use esses assets como a **Fonte Única da Verdade** antes de tocar no código produtivo.
183
272
 
184
- An agnostic, ultra-lightweight, and surgical CLI for implementing **MDDD (Mermaid Diagram Driven Development)** in a modular, co-located, and strictly versioned way.
273
+ ---
274
+
275
+ ## 📌 O Conceito: MDDD vs. Especificações em Texto
185
276
 
186
- 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.
277
+ Ao contrário de frameworks tradicionais de especificação que geram dezenas de arquivos de texto e "deltas" que poluem o seu repositório, o MDDD introduz um paradigma **Visual-First & Focado em Fluxo**:
278
+
279
+ 1. **Um Mapa Real da Arquitetura:** Em vez de mapas em formato de texto chapado, o MDDD permite conectar micro-especificações em uma visão macro do sistema. Ele se comporta como um mapa geográfico real de toda a sua arquitetura de software.
280
+ 2. **Projetado para Alta Complexidade e CRUDs Gigantes:** Estados complexos, validações de múltiplos perfis e regras de negócio densas são estruturadas dentro de **Matrizes de Decisão** em tabelas markdown. Isso elimina a saturação visual dos layouts e resolve comportamentos complexos com precisão matemática.
281
+ 3. **Poluição Zero de Arquivos (Nativo do Git):** Os requisitos mudam e são versionados diretamente no próprio local original. As IAs que utilizam recursos de terminal ou **MCP (Model Context Protocol)** podem consultar o histórico do Git instantaneamente para entender as mudanças evolutivas, significando zero arquivos temporários ou lixo arquitetural.
187
282
 
188
283
  ---
189
284
 
190
- ## 📌 The Concept: MDDD
285
+ ## ⚖️ MDDD vs. OpenSpec (SDD)
286
+
287
+ | Funcionalidade / Paradigma | OpenSpec (Specification Driven Development) | MDDD (Mermaid Diagram Driven Development) |
288
+ | --- | --- | --- |
289
+ | **Estrutura Lógica** | Parágrafos textuais, regras verbosas e cenários conversacionais. | Matrizes de Decisão Binárias/Factuais + Topologias Estruturais Estritas. |
290
+ | **Consumo de Contexto da IA** | Alto consumo de tokens devido a descrições comportamentais massivas em texto. | Consumo ultra-baixo de tokens através de tabelas de verdade concisas em matrizes. |
291
+ | **Escalabilidade** | Adicionar regras cria blocos de texto massivos propensos a fragmentação de prompt. | Adicionar regras escala horizontalmente anexando colunas precisas de fatores. |
292
+ | **Controle de Ambiguidade** | Alto risco de alucinação de LLM ao interpretar frases aninhadas de "se/senão". | Precisão matemática pura; processamento determinístico via linhas de matriz. |
293
+ | **Pegada da Ferramenta** | Boilerplate massivo com poluição de arquivos internos e estruturas complexas de pastas. | Ultra-leve: um único arquivo CLI altamente legível e facilmente auditável por qualquer humano. |
191
294
 
192
- In **Mermaid Diagram Driven Development**, we invert the traditional AI chat-driven development cycle:
295
+ ### 🚀 Por que as Matrizes de Decisão MDDD Superam o OpenSpec:
193
296
 
194
- 1. **Design (`/md-new`):** The AI and you create the business rule visually inside the co-located `.spec.md` file.
195
- 2. **Approval:** You review the visual flow directly in your code editor's Markdown preview.
196
- 3. **Editing (`/md-edit`):** Scope adjustments alter the diagram first and increment the file's semantic version.
197
- 4. **Implementation (`/md-impl`):** The AI reads the signed and versioned specification to write the definitive code and unit tests.
297
+ * **Tokens Previsíveis:** Para uma LLM, ler essa tabela é idêntico a processar uma matriz binária de verdade. Ela bate o olho nas colunas de fatores primitivos (`Tenant Ativo?`, `Kill Switch Global Ativo?`) e sabe exatamente se a combinação resulta em `ALLOW` ou `DENY` sem gastar processamento léxico ou tokens desnecessários.
298
+ * **Infinitas Colunas = Infinitas Variáveis:** Se o seu sistema ganhar uma nova regra arquitetural (ex: `Ambiente é Produção?` ou `IP em White-list?`), basta adicionar uma nova coluna na matriz. A lógica de negócio expande horizontalmente sem poluir ou quebrar os fluxos visuais do Mermaid.
299
+ * **Substituição Real do OpenSpec:** O OpenSpec precisa escrever parágrafos descritivos e cenários de teste para cobrir combinações complexas de restrições. O MDDD resolve isso em uma única linha de tabela determinística, economizando o contexto do prompt e eliminando completamente alucinações da IA.
198
300
 
199
301
  ---
200
302
 
201
- ## Mermaid Diagram Preview
303
+ ## 🛠️ O Pipeline MDDD
202
304
 
203
- To preview Mermaid diagrams directly in your editor during the MDDD workflow, you can use extensions that render ````mermaid```` blocks in Markdown files:
305
+ | Etapa | Ator | Ação / Gatilho | O que acontece |
306
+ | --- | --- | --- | --- |
307
+ | **1. Entrada** | Humano | `md-new` / `md-audit` | O usuário propõe uma funcionalidade em linguagem natural, aponta a IA diretamente para uma Issue/Task do Jira ou GitHub, ou pede para a IA auditar um arquivo legado. |
308
+ | **2. Concepção** | IA | Autogeração | A IA avalia o escopo e constrói o arquivo `.spec.md` completo com diagramas de fluxo, ciclos de vida e as **Matrizes de Decisão** necessárias. |
309
+ | **3. Alinhamento** | Humano | Revisão Interativa | O usuário revisa a especificação dentro do editor. Os refinamentos são feitos de forma iterativa conversando com a IA. |
310
+ | **4. Planning** | IA | Quebra de Tarefas | Com a spec aprovada, a IA extrai um checklist granular e atômico dos passos de desenvolvimento diretamente dentro do arquivo. |
311
+ | **5. Execução** | Humano | `md-impl` | O usuário dispara o gatilho de execução. A IA implementa o código produtivo e os testes baseando-se estritamente nas specs, atualizando o versionamento semântico ao concluir. |
204
312
 
205
- ### Flutter App Initialization Diagram Example
206
- <img width="1316" height="444" alt="image" src="https://github.com/user-attachments/assets/5cacc283-e517-4468-a8cd-d67442a75bf2" />
313
+ ---
207
314
 
208
- ### Decision Matrix Example
209
- <img width="1237" height="702" alt="image" src="https://github.com/user-attachments/assets/e8ffc227-9b2a-44d5-ad66-116dffedc8ba" />
315
+ ## Pré-visualização dos Diagramas Mermaid
316
+
317
+ Para visualizar diagramas Mermaid diretamente no seu editor durante o fluxo MDDD, você pode usar extensões que renderizam blocos `mermaid` em arquivos Markdown:
318
+
319
+ ### Diagrama Arquitetural
320
+
321
+ ```mermaid
322
+ sequenceDiagram
323
+ autonumber
324
+ actor U as Usuário Merchant (Lojista)
325
+ actor A as Admin da Plataforma
326
+ participant Core as Core da Plataforma (Orquestrador)
327
+ participant Registry as Registro de Micro-Apps
328
+ participant Sandbox as Sandbox de Execução (Contexto Isolado)
329
+ participant TenantDB as Multi-Banco do Tenant
330
+ participant Billing as Motor de Tarifação (Uso Medido)
331
+
332
+ Note over U, Core: Cenário: Lojista tenta executar um micro-app customizado premium.
333
+
334
+ U->>Core: Requisita Execução do App (TenantID, AppID)
335
+ Core->>Registry: Busca Manifesto do Micro-App & Permissões de Escopo
336
+ Registry-->>Core: Retorna Manifesto (Escopos de API Requeridos, Nível de Tier)
337
+
338
+ Note over Core, TenantDB: Validação Dinâmica de Segurança & Multitenancy
339
+ Core->>TenantDB: Checa Assinatura do Tenant & Feature Flags
340
+ TenantDB-->>Core: Tenant Autorizado (Licença Ativa)
341
+
342
+ Core->>Billing: Rastreia Evento de Execução (API de Uso Medido)
343
+ activate Billing
344
+ Billing->>Billing: Registra Consumo de Tokens/Processamento
345
+ deactivate Billing
346
+
347
+ Note over Core, Sandbox: Initializing Sandbox em Container
348
+ Core->>Sandbox: Injeta Token de Segurança & Proxies de SDK Restritos
349
+ Core->>Sandbox: Inicializa o Bundle Frontend/Backend do Micro-App
350
+
351
+ activate Sandbox
352
+ Sandbox->>Sandbox: Executa Ciclo de Vida do Micro-App (onInit)
353
+ Sandbox->>Core: Chamada de API Restrita (Escrita de Dados do Tenant)
354
+ Core->>TenantDB: Persiste Mudanças com Segurança no Isolamento do Tenant
355
+ Sandbox-->>U: Renderiza Fragmento de UI Isolado / Micro-Frontend
356
+ deactivate Sandbox
357
+
358
+ Note over A, Core: Admin da Plataforma pode substituir a quente ou depreciar apps globalmente.
359
+ A->>Core: Deprecia Versão do App (Flag Global)
360
+ Core->>Registry: Atualiza Status para "DEPRECATED"
361
+
362
+ ```
363
+
364
+ ### Matriz de Decisão de Ciclo de Vida & Runtime de Micro-Apps
365
+
366
+ | Tenant Ativo? | App Premium? | Tier de Faturamento Ativo? | Usuário é Admin? | App em White-list? | Kill Switch Global Ativo? | Ação Proposta | Decisão (Resultado) | Estado de Transição (Novo Status) |
367
+ | --- | --- | --- | --- | --- | --- | --- | --- | --- |
368
+ | ❌ NÃO | - | - | - | - | - | `BOOT_APP` | ❌ **DENY (Negar)** | - |
369
+ | ✅ SIM | ❌ NÃO | **FREE** | ❌ NÃO | ✅ SIM | ❌ NÃO | `BOOT_APP` | ✅ **ALLOW (Permitir)** | `ACTIVE_RUNTIME` |
370
+ | ✅ SIM | ✅ SIM | **FREE** | - | - | ❌ NÃO | `INSTALL_APP` | ❌ **DENY (Negar)** | - (Dispara Upsell) |
371
+ | ✅ SIM | ✅ SIM | **ENTERPRISE** | ✅ SIM | ✅ SIM | ❌ NÃO | `INSTALL_APP` | ✅ **ALLOW (Permitir)** | `INSTALLED` |
372
+ | ✅ SIM | - | - | ❌ NÃO | - | ❌ NÃO | `CONFIG_API` | ❌ **DENY (Negar)** | - |
373
+ | ✅ SIM | - | - | ✅ SIM | - | ❌ NÃO | `CONFIG_API` | ✅ **ALLOW (Permitir)** | `CONFIGURED` |
374
+ | ✅ SIM | - | - | - | - | ✅ SIM | `BOOT_APP` | ❌ **DENY (Negar)** | `MUTED_ISOLATION` |
375
+ | ✅ SIM | - | - | - | - | ✅ SIM | `HOT_RELOAD` | ❌ **DENY (Negar)** | - |
376
+ | ❌ NÃO | - | - | - | - | - | `PURGE_DATA` | ❌ **DENY (Negar)** | - |
377
+
378
+ ---
210
379
 
211
380
  ### VS Code
212
- - **Markdown Preview Mermaid Support** — Adds Mermaid diagram support to the native Markdown preview.
213
- - **Mermaid Editor** — Visual editor with side-by-side preview and export.
214
- - **bierner.markdown-mermaid** — Official extension that extends the Markdown preview to render Mermaid.
381
+
382
+ * **Markdown Preview Mermaid Support** — Adiciona suporte a diagramas Mermaid no preview nativo do Markdown.
383
+ * **Mermaid Editor** — Editor visual com preview lado a lado e exportação.
384
+ * **bierner.markdown-mermaid** — Extensão oficial que estende o preview de Markdown para renderizar Mermaid.
215
385
 
216
386
  ### JetBrains (IntelliJ, WebStorm, GoLand, etc.)
217
- - Native Mermaid support starting from **2024.1** — Just open the `.spec.md` file and use the built-in Markdown preview.
218
387
 
219
- ### Other Editors
220
- - **Neovim/Vim:** Use plugins like `iamcco/markdown-preview.nvim` (with `markdown-preview` configured for Mermaid).
221
- - **Sublime Text:** `Mermaid` package from Package Control that adds preview and snippets.
222
- - **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.
388
+ * Suporte nativo a Mermaid a partir do **2024.1** — Basta abrir o arquivo `.spec.md` e usar o preview de Markdown integrado.
223
389
 
224
- > 💡 **Tip:** The better you can visualize the diagrams, the easier it is to validate business flows before implementation.
390
+ ### Outros Editores
391
+
392
+ * **Neovim/Vim:** Utilize plugins como `iamcco/markdown-preview.nvim` (com `markdown-preview` configurado para Mermaid).
393
+ * **Sublime Text:** Pacote `Mermaid` no Package Control que adiciona preview e snippets.
394
+ * **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.
395
+
396
+ > 💡 **Dica:** Quanto melhor você conseguir visualizar os diagramas, mais fácil será validar os fluxos de negócio antes da implementação.
225
397
 
226
398
  ---
227
399
 
228
- ## 📥 Installation
400
+ ## 📥 Instalação
229
401
 
230
- Since the package is published on NPM, installation is global and simple:
402
+ Como o pacote está publicado no NPM, a instalação é global e simples:
231
403
 
232
404
  ```bash
233
- # Global installation
405
+ # Instalação global
234
406
  npm install -g mddd-cli
407
+
235
408
  ```
236
409
 
237
- > **Note:** Make sure you have **Node.js v18 or higher** installed on your machine.
410
+ > **Note:** Certifique-se de ter o **Node.js v18 ou superior** instalado em sua máquina.
238
411
 
239
412
  ---
240
413
 
241
- ## 🚀 Quick Start Guide
414
+ ## 🚀 Guia de Uso Rápido
242
415
 
243
- The MDDD workflow is based on CLI commands to manage the structure and slash commands (`/`) to orchestrate the AI in the chat.
416
+ O fluxo MDDD é baseado em comandos de CLI para gerenciar a estrutura e comandos de barra (`/`) para orquestrar a IA no chat.
244
417
 
245
418
  ### 1. Initialize your project
246
419
 
247
- In your project root, run:
420
+ Na raiz do seu projeto, execute:
248
421
 
249
422
  ```bash
250
423
  md init
424
+
251
425
  ```
252
426
 
253
- 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.
427
+ Isso criará os arquivos `system_prompt.md` e `SKILL.md` no diretório raiz, contendo as instruções globais que guiarão a IA no entendimento da metodologia MDDD e na interação com os logs do Git.
254
428
 
255
- ### 2. Create a new specification (Feature)
429
+ ### 2. Crie uma nova especificação (Feature)
256
430
 
257
- When starting a new feature, create its visual contract:
431
+ Ao iniciar uma nova funcionalidade, crie o seu contrato visual:
258
432
 
259
433
  ```bash
260
- # For a simple feature (micro)
261
- md new src/feature-name
434
+ # Para uma funcionalidade única
435
+ md-new caminho/nome-da-feature
436
+
437
+ # Para uma funcionalidade conectando a um fluxo existente
438
+ md-new caminho/nome-da-feature --parent caminho/para/pai
262
439
 
263
- # For a complete module (macro)
264
- md new src/feature-name --macro
265
440
  ```
266
441
 
267
- This will generate the `feature-name.spec.md` file with the Mermaid structure, Decision Matrix, and Versioning.
442
+ Isso gerará o arquivo `nome-da-feature.spec.md` contendo a estrutura de versão semântica, placeholders do Mermaid, tabelas de Matrizes de Decisão e o checklist de tarefas de implementação.
268
443
 
269
- ### 3. Legacy Audit
444
+ ### 3. Auditoria de Legado
270
445
 
271
- Need to refactor existing code? Audit it:
446
+ Precisa refatorar um código existente? Audite-o:
272
447
 
273
448
  ```bash
274
- md audit src/path/to/legacy-file.dart
449
+ md-audit caminho/para/arquivo-legado
450
+
275
451
  ```
276
452
 
277
453
  ---
278
454
 
279
- ## 🤖 Slash Commands (AI Triggers)
455
+ ## 🤖 SKILLS (Gatilhos para IA)
280
456
 
281
- After running `md init`, your AI will understand these shortcuts when you type them in the chat:
457
+ Após rodar o `md init`, a sua IA passará a entender estes atalhos quando você os digitar no chat:
282
458
 
283
- | Command | Description |
284
- | :---------- | :------------------------------------------------------------------------------------ |
285
- | `/md-new` | Starts design mode for a new feature (generates diagram and table). |
286
- | `/md-edit` | Requests changes to an existing `.spec.md` file (increments semantic version). |
287
- | `/md-audit` | Analyzes legacy code and proposes visual refactoring (Mermaid). |
288
- | `/md-impl` | Generates code and tests strictly based on the `.spec.md` diagram. |
459
+ | Skill | Descrição |
460
+ | --- | --- |
461
+ | `md-new` | Inicia o modo de desenho para uma nova feature a partir de texto ou link de issue (gera diagramas/matrizes). |
462
+ | `md-edit` | Solicita alterações em um arquivo `.spec.md` existente (incrementa a versão semântica). |
463
+ | `md-audit` | Analisa código legado e propõe refatoração visual (Mermaid). |
464
+ | `md-impl` | Gera código e testes baseando-se estritamente na estrutura do `.spec.md`, gerenciando o histórico de versões. |
289
465
 
290
466
  ---
291
467
 
292
- ## 🏗️ Co-located Specification Architecture
468
+ ## 🏗️ Arquitetura de Especificação Colocalizada (Co-location)
293
469
 
294
- Visual specifications are not centralized in distant folders. They live in the **same directory** as the component, screen, or feature they describe.
470
+ As especificações visuais não ficam centralizadas em pastas distantes. Elas vivem no **mesmo diretório** do componente, tela ou feature que descrevem, mapeando o software de forma nativa.
295
471
 
296
472
  ```
297
473
  src/
298
474
  └── home/
299
- ├── home.spec.md # 🌎 MACRO: Global module view (stateDiagram-v2)
475
+ ├── home.spec.md # 🌎 Mapa global do módulo (stateDiagram-v2 conectando nós)
300
476
  ├── guest/
301
- │ ├── guest.spec.md # 🔬 MICRO: Screen flow (graph LR) + Decision Matrix
302
- │ └── guest_page.dart # 💻 Production code generated by AI
477
+ │ ├── guest.spec.md # 🔬 Fluxo de tela (graph LR) + Matriz de Decisão
478
+ │ └── guest_page.dart # 💻 Código produtivo gerado pela IA
303
479
  └── consumer/
304
- └── consumer.spec.md # 🔬 MICRO: Screen flow (graph LR) + Decision Matrix
480
+ └── consumer.spec.md # 🔬 Fluxo de tela (graph LR) + Matriz de Decisão
481
+
305
482
  ```
306
483
 
307
484
  ---
308
485
 
309
- ## 📦 CLI Commands
486
+ ## 📦 Comandos da CLI
487
+
488
+ | Comando | Description |
489
+ | --- | --- |
490
+ | `md init` | Configura os arquivos `system_prompt.md` e `SKILL.md` que instruem a IA sobre como se comportar. Execute isto sempre que atualizar o pacote NPM do MDDD-CLI. |
310
491
 
311
- | Command | Description |
312
- | :------------ | :----------------------------------------------------------------------------------------------------- |
313
- | `md init` | Initializes the universal system prompt and skills to guide any AI in the project. |
314
- | `md new` | Creates a new co-located `.spec.md` specification with automatic versioning. |
315
- | `md edit` | Signals a pending change in an existing specification file. |
316
- | `md audit` | Audits an existing code file to create a retroactive specification or suggest refactoring. |
317
- | `md impl` | Prepares the ecosystem to implement production code and tests based on the `.spec.md`. |
492
+ Outros comandos foram feitos exclusivamente para o uso da IA. Você só precisa dizer à IA qual skill deseja usar e o arquivo de destino.
318
493
 
319
494
  ---
320
495
 
321
- ## 🧪 Technologies
496
+ ## 🧪 Tecnologias
322
497
 
323
- - **Node.js** >= 18
324
- - **Commander.js** — Robust and declarative CLI interface
325
- - **Picocolors** — Colorful and lightweight terminal output
326
- - **Mermaid.js** — Visual diagramming as the source of truth
498
+ * **Node.js** >= 18
499
+ * **Commander.js** — Interface CLI robusta e declarativa
500
+ * **Picocolors** — Saída colorida e leve no terminal
501
+ * **Mermaid.js** — Diagramação visual como fonte da verdade
327
502
 
328
503
  ---
329
504
 
330
- ## 💬 Need help?
505
+ ## 💬 Precisa de ajuda?
331
506
 
332
- If you encounter any issues, open a [GitHub Issue](https://github.com/JulioCRFilho/mermaid-diagram-driven-development/issues).
507
+ Se encontrar qualquer problema, abra uma [Issue no GitHub](https://github.com/JulioCRFilho/mermaid-diagram-driven-development/issues).
333
508
 
334
509
  ---
335
510
 
336
- ## 📄 License
511
+ ## 📄 Licença
337
512
 
338
- Distributed under the MIT license. See the [LICENSE](LICENSE) file for more information.
513
+ Distribuído sob a licença MIT. Veja o arquivo [LICENSE](https://www.google.com/search?q=LICENSE) para mais informações.