mddd-cli 2.1.3 → 3.0.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/bin/cli.js +1 -84
- package/bin/cli.spec.md +13 -100
- package/package.json +6 -5
- package/readme.md +43 -112
- package/src/commands/init.js +237 -0
- package/src/services/FileSystemService.js +100 -0
- package/src/services/InitService.js +52 -0
package/bin/cli.js
CHANGED
|
@@ -3,28 +3,12 @@
|
|
|
3
3
|
import { Command } from 'commander';
|
|
4
4
|
import pc from 'picocolors';
|
|
5
5
|
import { FileSystemService } from '../src/services/FileSystemService.js';
|
|
6
|
-
import { ParentLinker } from '../src/services/ParentLinker.js';
|
|
7
6
|
import { InitService } from '../src/services/InitService.js';
|
|
8
|
-
import { SpecGenerator } from '../src/services/SpecGenerator.js';
|
|
9
|
-
import { SpecValidator } from '../src/services/SpecValidator.js';
|
|
10
|
-
import { SpecEditor } from '../src/services/SpecEditor.js';
|
|
11
|
-
import { AuditService } from '../src/services/AuditService.js';
|
|
12
|
-
import { ImplValidator } from '../src/services/ImplValidator.js';
|
|
13
7
|
import * as initCmd from '../src/commands/init.js';
|
|
14
|
-
import * as newCmd from '../src/commands/new.js';
|
|
15
|
-
import * as editCmd from '../src/commands/edit.js';
|
|
16
|
-
import * as auditCmd from '../src/commands/audit.js';
|
|
17
|
-
import * as implCmd from '../src/commands/impl.js';
|
|
18
8
|
|
|
19
9
|
// ─── Services ────────────────────────────────────────────────────────────────
|
|
20
10
|
const fs = new FileSystemService();
|
|
21
|
-
const parentLinker = new ParentLinker(fs);
|
|
22
11
|
const initService = new InitService(fs);
|
|
23
|
-
const specGenerator = new SpecGenerator(fs);
|
|
24
|
-
const specValidator = new SpecValidator(fs);
|
|
25
|
-
const specEditor = new SpecEditor(fs);
|
|
26
|
-
const auditService = new AuditService(fs);
|
|
27
|
-
const implValidator = new ImplValidator(fs);
|
|
28
12
|
|
|
29
13
|
// ─── CLI Setup ───────────────────────────────────────────────────────────────
|
|
30
14
|
const program = new Command();
|
|
@@ -32,7 +16,7 @@ const program = new Command();
|
|
|
32
16
|
program
|
|
33
17
|
.name('md')
|
|
34
18
|
.description('Manager for co-located specifications for Mermaid Diagram Driven Development (MDDD)')
|
|
35
|
-
.version('
|
|
19
|
+
.version('3.0.0');
|
|
36
20
|
|
|
37
21
|
// ==========================================
|
|
38
22
|
// COMMAND: md init
|
|
@@ -49,72 +33,5 @@ program
|
|
|
49
33
|
}
|
|
50
34
|
});
|
|
51
35
|
|
|
52
|
-
// ==========================================
|
|
53
|
-
// COMMAND: md new <targetPath>
|
|
54
|
-
// ==========================================
|
|
55
|
-
program
|
|
56
|
-
.command('new')
|
|
57
|
-
.description('Creates a new co-located specification in Markdown, injects the version header, and links to the parent flow')
|
|
58
|
-
.argument('<targetPath>', 'Path to the feature directory (e.g., src/home/guest)')
|
|
59
|
-
.option('-m, --macro', 'Defines if the new file will be a module macro containing a stateDiagram-v2')
|
|
60
|
-
.option('-p, --parent <parentFile>', 'Path to an existing specification file (.spec.md) to connect this new flow')
|
|
61
|
-
.action(async (targetPath, options) => {
|
|
62
|
-
try {
|
|
63
|
-
await newCmd.execute(specGenerator, parentLinker, fs, targetPath, options);
|
|
64
|
-
} catch (err) {
|
|
65
|
-
console.error(pc.red(`❌ ${err.message}`));
|
|
66
|
-
process.exit(1);
|
|
67
|
-
}
|
|
68
|
-
});
|
|
69
|
-
|
|
70
|
-
// ==========================================
|
|
71
|
-
// COMMAND: md edit <specFilePath> <instruction...>
|
|
72
|
-
// ==========================================
|
|
73
|
-
program
|
|
74
|
-
.command('edit')
|
|
75
|
-
.description('Signals a pending change in an existing Mermaid specification file')
|
|
76
|
-
.argument('<specFilePath>', 'Path to the specification file (.spec.md)')
|
|
77
|
-
.argument('<instruction...>', 'The change instruction or flow adjustment')
|
|
78
|
-
.action(async (specFilePath, instruction) => {
|
|
79
|
-
try {
|
|
80
|
-
await editCmd.execute(specEditor, specFilePath, instruction);
|
|
81
|
-
} catch (err) {
|
|
82
|
-
console.error(pc.red(`❌ ${err.message}`));
|
|
83
|
-
process.exit(1);
|
|
84
|
-
}
|
|
85
|
-
});
|
|
86
|
-
|
|
87
|
-
// ==========================================
|
|
88
|
-
// COMMAND: md audit <codeFilePath>
|
|
89
|
-
// ==========================================
|
|
90
|
-
program
|
|
91
|
-
.command('audit')
|
|
92
|
-
.description('Audits an existing code file to create a retroactive specification or suggest refactoring')
|
|
93
|
-
.argument('<codeFilePath>', 'Path to the existing code file (e.g., src/services/user.go)')
|
|
94
|
-
.action(async (codeFilePath) => {
|
|
95
|
-
try {
|
|
96
|
-
await auditCmd.execute(auditService, specGenerator, codeFilePath);
|
|
97
|
-
} catch (err) {
|
|
98
|
-
console.error(pc.red(`❌ ${err.message}`));
|
|
99
|
-
process.exit(1);
|
|
100
|
-
}
|
|
101
|
-
});
|
|
102
|
-
|
|
103
|
-
// ==========================================
|
|
104
|
-
// COMMAND: md impl <specFilePath>
|
|
105
|
-
// ==========================================
|
|
106
|
-
program
|
|
107
|
-
.command('impl')
|
|
108
|
-
.description('Prepares the ecosystem to implement productive code and tests based on the specification file')
|
|
109
|
-
.argument('<specFilePath>', 'Path to the specification file (.spec.md)')
|
|
110
|
-
.action(async (specFilePath) => {
|
|
111
|
-
try {
|
|
112
|
-
await implCmd.execute(implValidator, specFilePath);
|
|
113
|
-
} catch (err) {
|
|
114
|
-
console.error(pc.red(`❌ ${err.message}`));
|
|
115
|
-
process.exit(1);
|
|
116
|
-
}
|
|
117
|
-
});
|
|
118
|
-
|
|
119
36
|
// ─── Parse ───────────────────────────────────────────────────────────────────
|
|
120
37
|
program.parse(process.argv);
|
package/bin/cli.spec.md
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
# Refactoring Plan: cli |
|
|
1
|
+
# Refactoring Plan: cli | v3.0.0
|
|
2
2
|
|
|
3
3
|
## 1. Flow Contract (Mermaid)
|
|
4
4
|
|
|
5
5
|
### 1.1 Topologia Atual (As-Is)
|
|
6
6
|
|
|
7
7
|
```mermaid
|
|
8
|
-
%% @spec-version
|
|
8
|
+
%% @spec-version v3.0.0
|
|
9
9
|
graph TD
|
|
10
10
|
subgraph "CLI Entry (cli.js)"
|
|
11
11
|
A[index.js#!/usr/bin/env node] --> B[Commander: program.parse]
|
|
@@ -13,10 +13,6 @@ graph TD
|
|
|
13
13
|
|
|
14
14
|
subgraph "Command Routing"
|
|
15
15
|
B --> C[md init]
|
|
16
|
-
B --> D[md new <path>]
|
|
17
|
-
B --> E[md edit <spec> <instruction>]
|
|
18
|
-
B --> F[md audit <codeFile>]
|
|
19
|
-
B --> G[md impl <spec>]
|
|
20
16
|
end
|
|
21
17
|
|
|
22
18
|
subgraph "md init Action"
|
|
@@ -24,100 +20,27 @@ graph TD
|
|
|
24
20
|
C --> I[Write system_prompt.md]
|
|
25
21
|
C --> J[Write 4 embedded SKILL.md files]
|
|
26
22
|
end
|
|
27
|
-
|
|
28
|
-
subgraph "md new Action"
|
|
29
|
-
D --> K[Normalize path]
|
|
30
|
-
K --> L{folder exists?}
|
|
31
|
-
L -->|NO| M[mkdir -p]
|
|
32
|
-
L -->|YES| N[skip mkdir]
|
|
33
|
-
M --> O[Build .spec.md template]
|
|
34
|
-
N --> O
|
|
35
|
-
O --> P{--macro flag?}
|
|
36
|
-
P -->|YES| Q[stateDiagram-v2 template]
|
|
37
|
-
P -->|NO| R[graph LR + Decision Matrix template]
|
|
38
|
-
Q --> S[Write file]
|
|
39
|
-
R --> S
|
|
40
|
-
S --> T{--parent or findClosestMacro?}
|
|
41
|
-
T -->|Found| U[Append link to parent .spec.md]
|
|
42
|
-
T -->|Not Found| V[Done]
|
|
43
|
-
end
|
|
44
|
-
|
|
45
|
-
subgraph "Utility Functions"
|
|
46
|
-
X[findClosestMacro] --> Y[walk dir up]
|
|
47
|
-
Y --> Z{find *.spec.md?}
|
|
48
|
-
Z -->|Found| AA[return path]
|
|
49
|
-
Z -->|Not Found| AB[return null]
|
|
50
|
-
end
|
|
51
|
-
|
|
52
|
-
subgraph "md edit Action"
|
|
53
|
-
E --> AC[validate file exists]
|
|
54
|
-
AC --> AD[print placeholder message]
|
|
55
|
-
end
|
|
56
|
-
|
|
57
|
-
subgraph "md audit Action"
|
|
58
|
-
F --> AE[validate file exists]
|
|
59
|
-
AE --> AF{spec exists?}
|
|
60
|
-
AF -->|NO| AG[write template spec]
|
|
61
|
-
AF -->|YES| AH[print found message]
|
|
62
|
-
AG --> AI[print 'AI will analyze' message]
|
|
63
|
-
AH --> AI
|
|
64
|
-
end
|
|
65
|
-
|
|
66
|
-
subgraph "md impl Action"
|
|
67
|
-
G --> AJ[validate file exists]
|
|
68
|
-
AJ --> AK[print placeholder message]
|
|
69
|
-
end
|
|
70
23
|
```
|
|
71
24
|
|
|
72
25
|
### 1.2 Topologia Aprovada (To-Be → Refactoring Target)
|
|
73
26
|
|
|
74
27
|
```mermaid
|
|
75
|
-
%% @spec-version
|
|
28
|
+
%% @spec-version v3.0.0
|
|
76
29
|
graph TD
|
|
77
30
|
subgraph "CLI Entry (cli.js)"
|
|
78
31
|
A[bin/cli.js] --> B[Commander Router]
|
|
79
32
|
B --> C[delegate to ./commands/init.js]
|
|
80
|
-
B --> D[delegate to ./commands/new.js]
|
|
81
|
-
B --> E[delegate to ./commands/edit.js]
|
|
82
|
-
B --> F[delegate to ./commands/audit.js]
|
|
83
|
-
B --> G[delegate to ./commands/impl.js]
|
|
84
33
|
end
|
|
85
34
|
|
|
86
35
|
subgraph "Commands Layer"
|
|
87
36
|
C --> H[InitService.createSystemPrompt]
|
|
88
37
|
C --> I[InitService.createSkills]
|
|
89
|
-
D --> J[SpecGenerator.create]
|
|
90
|
-
D --> K[ParentLinker.link]
|
|
91
|
-
E --> L[SpecValidator.validate]
|
|
92
|
-
E --> M[SpecEditor.prepareInstruction]
|
|
93
|
-
F --> N[AuditService.run]
|
|
94
|
-
F --> O[SpecGenerator.createIfMissing]
|
|
95
|
-
G --> P[ImplValidator.validate]
|
|
96
38
|
end
|
|
97
39
|
|
|
98
40
|
subgraph "Shared Services"
|
|
99
41
|
H --> Q[FileSystemService]
|
|
100
42
|
I --> Q
|
|
101
|
-
J --> Q
|
|
102
|
-
K --> Q
|
|
103
|
-
L --> Q
|
|
104
|
-
N --> Q
|
|
105
|
-
O --> Q
|
|
106
|
-
P --> Q
|
|
107
43
|
Q --> R[fs/promises]
|
|
108
|
-
|
|
109
|
-
subgraph "Template Engine"
|
|
110
|
-
S[TemplateFactory] --> T[MacroTemplate: stateDiagram-v2]
|
|
111
|
-
S --> U[MicroTemplate: graph LR + DecisionMatrix]
|
|
112
|
-
S --> V[AuditTemplate: graph LR + AuditHistory]
|
|
113
|
-
end
|
|
114
|
-
end
|
|
115
|
-
|
|
116
|
-
subgraph "Tests (Unit)"
|
|
117
|
-
W[SpecGenerator.test.js]
|
|
118
|
-
X[ParentLinker.test.js]
|
|
119
|
-
Y[AuditService.test.js]
|
|
120
|
-
Z[TemplateFactory.test.js]
|
|
121
44
|
end
|
|
122
45
|
```
|
|
123
46
|
|
|
@@ -126,7 +49,7 @@ graph TD
|
|
|
126
49
|
| Código Atual | Co-located .spec.md Exists? | Design Assessment | Ação de Auditoria | Manipulação de Código Permitida? | Versão Inicial |
|
|
127
50
|
| :--- | :---: | :---: | :--- | :---: | :---: |
|
|
128
51
|
| `bin/cli.js` (421 linhas) | ❌ NO | Caótico / Acoplado | Auto-gerar Spec + Mapear Lógica Atual E Proposta | ❌ **FORBIDDEN (Immutability)** | `v1.0.0` |
|
|
129
|
-
| `src/commands
|
|
52
|
+
| `src/commands/init.js` + `src/services/InitService.js` + `src/services/FileSystemService.js` (refatorado) | ✅ YES (this spec) | Refatorado / Modular | Aprovado com diagrama To-Be como alvo de implementação | ✅ **ALLOW (Refactoring)** | `v3.0.0` |
|
|
130
53
|
|
|
131
54
|
### Fatores Primitivos de Acoplamento
|
|
132
55
|
|
|
@@ -134,10 +57,10 @@ graph TD
|
|
|
134
57
|
| :--- | :---: | :--- |
|
|
135
58
|
| Arquivo único monolítico? | ✅ YES | Acoplamento extremo; todas as responsabilidades no mesmo closure |
|
|
136
59
|
| Lógica de template embutida? | ✅ YES | 4 skills + 2 templates inline no código (string templates >20KB) |
|
|
137
|
-
| Duplicação entre `new` e `audit`? |
|
|
138
|
-
| Tratamento de erros inconsistente? |
|
|
139
|
-
| Sem separação CLI/Business? |
|
|
140
|
-
| Lógica de crawling de diretório isolada? | ❌
|
|
60
|
+
| Duplicação entre `new` e `audit`? | ❌ N/A (removido) | Comandos `new`, `edit`, `audit` e `impl` foram removidos do escopo |
|
|
61
|
+
| Tratamento de erros inconsistente? | ❌ N/A (removido) | Comandos `edit`/`audit`/`impl` removidos |
|
|
62
|
+
| Sem separação CLI/Business? | ❌ NO | `init` permanece com separação CLI/Business via `src/commands/init.js` |
|
|
63
|
+
| Lógica de crawling de diretório isolada? | ❌ N/A (removido) | `findClosestMacro` removido junto com comando `new` |
|
|
141
64
|
| Código testável? | ❌ NO | Sem módulos exportados; dependência direta de `fs`, `path` sem injeção |
|
|
142
65
|
|
|
143
66
|
## 3. Audit History
|
|
@@ -149,23 +72,13 @@ graph TD
|
|
|
149
72
|
| :--- | :--- | :---: | :--- |
|
|
150
73
|
| 2026-05-27 | MDDD-Audit Agent (Cline) | v1.0.0 | Auditoria inicial. Código classificado como **Caótico/Acoplado**. Diagrama As-Is documenta a topologia real (monolítica). Diagrama To-Be propõe separação em Commands Layer + Shared Services + Template Engine + Testes. Decisão de imutabilidade: código de produção não foi modificado. |
|
|
151
74
|
| 2026-05-27 | Cline (Agent-Actor) | v2.0.0 | **MAJOR Mutation (v1.0.0 → v2.0.0):** Aprovada refatoração estrutural do monolito `bin/cli.js` (421 linhas) para arquitetura modular: Commands Layer (`src/commands/*.js`) + Shared Services (`src/services/*.js`) + Template Engine (`src/services/TemplateFactory.js`) + Unit Tests. Removida restrição FORBIDDEN (Immutability). Diagrama To-Be promovido a alvo de implementação oficial. |
|
|
75
|
+
| 2026-05-27 | Cline (Agent-Actor) | v3.0.0 | **MAJOR Mutation (v2.0.0 → v3.0.0):** Removidos comandos `new`, `edit`, `audit` e `impl` do escopo do CLI. Diagramas As-Is e To-Be simplificados para refletir apenas o comando `init` restante. Matriz de decisão e fatores de acoplamento atualizados. |
|
|
152
76
|
|
|
153
77
|
### Análise de Qualidade
|
|
154
78
|
|
|
155
|
-
- **Acoplamento**: ⚠️ **
|
|
156
|
-
- **Coesão**:
|
|
157
|
-
- **Testabilidade**:
|
|
158
|
-
- **Manutenibilidade**:
|
|
159
|
-
- **Segurança**: ✅ Usa `EACCES`/`EPERM` handler no `findClosestMacro`.
|
|
160
|
-
|
|
161
|
-
### Recomendações de Refatoração
|
|
162
|
-
|
|
163
|
-
1. **Separar em módulos**: `src/commands/init.js`, `src/commands/new.js`, `src/commands/edit.js`, `src/commands/audit.js`, `src/commands/impl.js`
|
|
164
|
-
2. **Extrair Template Engine**: `src/services/TemplateFactory.js` com templates parametrizados
|
|
165
|
-
3. **Extrair FileSystemService**: `src/services/FileSystemService.js` com injeção de dependência para testabilidade
|
|
166
|
-
4. **Criar ParentLinker**: `src/services/ParentLinker.js` com crawler testável
|
|
167
|
-
5. **Adicionar testes unitários**: Coverage mínimo de 80% para todas as funções extraídas
|
|
168
|
-
6. **Exportar funções**: Usar `export` em vez de closures anônimas no `.action()`
|
|
169
|
-
7. **Migrar para `fs/promises`**: Substituir `readdirSync`/`writeFileSync` por `async/await` para melhor gerenciamento de concorrência
|
|
79
|
+
- **Acoplamento**: ⚠️ **MÉDIO** - O comando `init` restante ainda reside em `bin/cli.js` mas delega para `src/commands/init.js`.
|
|
80
|
+
- **Coesão**: ✅ **ALTA** - Escopo reduzido a apenas inicialização do ambiente MDDD.
|
|
81
|
+
- **Testabilidade**: ⚠️ **MÉDIA** - Serviços são injetados via construtor, mas `bin/cli.js` não exporta funções para teste unitário isolado.
|
|
82
|
+
- **Manutenibilidade**: ✅ **ALTA** - Código simplificado com apenas um comando e clara separação de responsabilidades.
|
|
170
83
|
|
|
171
84
|
</details>
|
package/package.json
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mddd-cli",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "3.0.0",
|
|
4
4
|
"description": "Official CLI for modular, co-located, and versioned Mermaid Diagram Driven Development (MDDD).",
|
|
5
|
-
"main": "bin/cli.js",
|
|
6
5
|
"type": "module",
|
|
6
|
+
"exports": "./bin/cli.js",
|
|
7
7
|
"bin": {
|
|
8
|
-
"md": "bin/cli.js"
|
|
8
|
+
"md": "./bin/cli.js"
|
|
9
9
|
},
|
|
10
10
|
"files": [
|
|
11
|
-
"bin
|
|
11
|
+
"bin",
|
|
12
|
+
"src"
|
|
12
13
|
],
|
|
13
14
|
"engines": {
|
|
14
15
|
"node": ">=18.0.0"
|
|
@@ -40,4 +41,4 @@
|
|
|
40
41
|
"commander": "^12.0.0",
|
|
41
42
|
"picocolors": "^1.0.0"
|
|
42
43
|
}
|
|
43
|
-
}
|
|
44
|
+
}
|
package/readme.md
CHANGED
|
@@ -57,11 +57,11 @@ Unlike traditional specification frameworks that generate dozens of text files a
|
|
|
57
57
|
|
|
58
58
|
| Phase | Actor | Action / Trigger | What Happens |
|
|
59
59
|
| :--- | :--- | :--- | :--- |
|
|
60
|
-
| **1. Input** | Human |
|
|
60
|
+
| **1. Input** | Human | Feature Request | 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. |
|
|
61
61
|
| **2. Conception** | AI | Autogeneration | The AI assesses the scope and builds the `.spec.md` file complete with flowcharts, lifecycles, and required **Decision Matrices**. |
|
|
62
62
|
| **3. Alignment** | Human | Interactive Review | The user reviews the specification within the editor. Refinements are handled iteratively by chatting with the AI. |
|
|
63
63
|
| **4. Planning** | AI | Task Breakdown | Once the spec is approved, the AI extracts a granular, atomic checklist of development steps directly within the file. |
|
|
64
|
-
| **5. Execution** |
|
|
64
|
+
| **5. Execution** | AI | Code Generation | The AI implements production code and tests strictly adhering to the specs, updating the semantic versioning on completion. |
|
|
65
65
|
|
|
66
66
|
---
|
|
67
67
|
|
|
@@ -69,7 +69,7 @@ Unlike traditional specification frameworks that generate dozens of text files a
|
|
|
69
69
|
|
|
70
70
|
To preview Mermaid diagrams directly in your editor during the MDDD workflow, you can use extensions that render ````mermaid```` blocks in Markdown files:
|
|
71
71
|
|
|
72
|
-
### Architectural Diagram
|
|
72
|
+
### Architectural Diagram Example
|
|
73
73
|
|
|
74
74
|
```mermaid
|
|
75
75
|
sequenceDiagram
|
|
@@ -114,7 +114,7 @@ sequenceDiagram
|
|
|
114
114
|
|
|
115
115
|
```
|
|
116
116
|
|
|
117
|
-
### Micro-App Runtime & Lifecycle Decision Matrix
|
|
117
|
+
### Micro-App Runtime & Lifecycle Decision Matrix Example
|
|
118
118
|
|
|
119
119
|
| Active Tenant? | Premium App? | Active Billing Tier? | User Has Role Admin? | App Whitelisted? | Global Kill Switch? | Proposed Action | Decision (Outcome) | Transition State (New Status) |
|
|
120
120
|
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
|
@@ -130,7 +130,7 @@ sequenceDiagram
|
|
|
130
130
|
|
|
131
131
|
---
|
|
132
132
|
|
|
133
|
-
### VS Code
|
|
133
|
+
### VS Code and derivated
|
|
134
134
|
|
|
135
135
|
* **Markdown Preview Mermaid Support** — Adds Mermaid diagram support to the native Markdown preview.
|
|
136
136
|
* **Mermaid Editor** — Visual editor with side-by-side preview and export.
|
|
@@ -166,7 +166,7 @@ npm install -g mddd-cli
|
|
|
166
166
|
|
|
167
167
|
## 🚀 Quick Start Guide
|
|
168
168
|
|
|
169
|
-
The MDDD workflow is based on
|
|
169
|
+
The MDDD workflow is based on skills to orchestrate the AI in the chat.
|
|
170
170
|
|
|
171
171
|
### 1. Initialize your project
|
|
172
172
|
|
|
@@ -177,31 +177,22 @@ md init
|
|
|
177
177
|
|
|
178
178
|
```
|
|
179
179
|
|
|
180
|
-
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.
|
|
180
|
+
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. You can rename `system_prompt.md` to any .rules file you need (.cursorrules, .clinerules, etc.).
|
|
181
181
|
|
|
182
|
-
### 2.
|
|
182
|
+
### 2. Audit legacy files or make new ones.
|
|
183
183
|
|
|
184
|
-
|
|
184
|
+
- Tell AI to `md-audit` the file you want to review. If it's clean and concise, AI will create the spec based on it. If it's not, then AI will propose a refactoring with the "to-be" spec.
|
|
185
185
|
|
|
186
|
-
|
|
187
|
-
# For a single feature
|
|
188
|
-
md new path/feature-name
|
|
189
|
-
|
|
190
|
-
# For a feature connecting to an existing flow
|
|
191
|
-
md new path/feature-name --parent path/to/parent
|
|
192
|
-
|
|
193
|
-
```
|
|
194
|
-
|
|
195
|
-
This will generate the `feature-name.spec.md` file containing the semantic version structure, Mermaid placeholders, Decision Matrix matrices, and the implementation checklist.
|
|
186
|
+
- Tell AI to `md-new` a specification you need, connect to a Jira/Task, to a Figma/Design or simple tell AI what you need.
|
|
196
187
|
|
|
197
|
-
### 3.
|
|
188
|
+
### 3. Implement the specification.
|
|
198
189
|
|
|
199
|
-
|
|
190
|
+
Tell AI to `md-impl` pointing to a .spec file. It will read all the specification, create the task list and start working on it.
|
|
200
191
|
|
|
201
|
-
|
|
202
|
-
md audit path/to/legacy-file
|
|
192
|
+
### 4. Edit existing specifications.
|
|
203
193
|
|
|
204
|
-
|
|
194
|
+
If you need to add a new feature or modify an existing one, just tell AI to `md-edit` the .spec file with the modifications you want.
|
|
195
|
+
Review it until you get exactly the specification you need and then tell AI to `md-impl` it.
|
|
205
196
|
|
|
206
197
|
---
|
|
207
198
|
|
|
@@ -241,12 +232,6 @@ src/
|
|
|
241
232
|
| Command | Description |
|
|
242
233
|
| --- | --- |
|
|
243
234
|
| `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. |
|
|
244
|
-
| `md new <targetPath>` | Creates a new `.spec.md` file at the target directory. Supports `--macro` for module-level specs and `--parent` for explicit parent linking. |
|
|
245
|
-
| `md edit <specFilePath> <instruction...>` | Signals a pending change to an existing `.spec.md` file. The AI then applies the changes and increments semantic version. |
|
|
246
|
-
| `md audit <codeFilePath>` | Audits a code file to create a retroactive `.spec.md` or suggest refactoring. |
|
|
247
|
-
| `md impl <specFilePath>` | Prepares the ecosystem to implement production code and tests based on a signed `.spec.md`. |
|
|
248
|
-
|
|
249
|
-
> **💡 Note for AI agents:** These commands are designed to be invoked by AI tools (Cursor, Windsurf, Claude Code, GitHub Copilot). As a human, simply tell the AI which skill to use and the target file.
|
|
250
235
|
|
|
251
236
|
### Project Architecture
|
|
252
237
|
|
|
@@ -254,36 +239,17 @@ The CLI codebase follows a clean modular architecture, as documented in `bin/cli
|
|
|
254
239
|
|
|
255
240
|
```
|
|
256
241
|
bin/
|
|
257
|
-
├── cli.js # Thin Commander router (<
|
|
258
|
-
└── cli.spec.md # Co-located spec (
|
|
242
|
+
├── cli.js # Thin Commander router (< 30 lines)
|
|
243
|
+
└── cli.spec.md # Co-located spec (v3.0.0)
|
|
259
244
|
|
|
260
245
|
src/
|
|
261
|
-
├── commands/ # Command layer
|
|
262
|
-
│
|
|
263
|
-
│ ├── new.js
|
|
264
|
-
│ ├── edit.js
|
|
265
|
-
│ ├── audit.js
|
|
266
|
-
│ └── impl.js
|
|
246
|
+
├── commands/ # Command layer
|
|
247
|
+
│ └── init.js
|
|
267
248
|
└── services/ # Shared services with DI
|
|
268
249
|
├── FileSystemService.js
|
|
269
|
-
|
|
270
|
-
├── ParentLinker.js
|
|
271
|
-
├── InitService.js
|
|
272
|
-
├── SpecGenerator.js
|
|
273
|
-
├── SpecValidator.js
|
|
274
|
-
├── SpecEditor.js
|
|
275
|
-
├── AuditService.js
|
|
276
|
-
└── ImplValidator.js
|
|
277
|
-
|
|
278
|
-
tests/ # Unit tests
|
|
279
|
-
├── SpecGenerator.test.js
|
|
280
|
-
├── ParentLinker.test.js
|
|
281
|
-
├── AuditService.test.js
|
|
282
|
-
└── TemplateFactory.test.js
|
|
250
|
+
└── InitService.js
|
|
283
251
|
```
|
|
284
252
|
|
|
285
|
-
All 21 unit tests pass with mocked file system (zero real I/O), ensuring full coverage of the core services.
|
|
286
|
-
|
|
287
253
|
---
|
|
288
254
|
|
|
289
255
|
## 🧪 Technologies
|
|
@@ -313,7 +279,7 @@ Distributed under the MIT license. See the [LICENSE](https://www.google.com/sear
|
|
|
313
279
|
|
|
314
280
|
Uma CLI agnóstica, ultra-leve e cirúrgica para implementar **MDDD (Mermaid Diagram Driven Development)** de forma modular, colocalizada e estritamente versionada.
|
|
315
281
|
|
|
316
|
-
Esta ferramenta automatiza a criação e a conexão de arquivos de especificação visual (Markdown + Mermaid + Matrizes de Decisão)
|
|
282
|
+
Esta ferramenta automatiza a criação e a conexão de arquivos de especificação visual (Markdown + Mermaid + Matrizes de Decisão) através do comando `md init`. 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.
|
|
317
283
|
|
|
318
284
|
---
|
|
319
285
|
|
|
@@ -352,11 +318,11 @@ Ao contrário de frameworks tradicionais de especificação que geram dezenas de
|
|
|
352
318
|
|
|
353
319
|
| Etapa | Ator | Ação / Gatilho | O que acontece |
|
|
354
320
|
| --- | --- | --- | --- |
|
|
355
|
-
| **1. Entrada** | Humano |
|
|
321
|
+
| **1. Entrada** | Humano | Solicitação de Funcionalidade | 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. |
|
|
356
322
|
| **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. |
|
|
357
323
|
| **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. |
|
|
358
324
|
| **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. |
|
|
359
|
-
| **5. Execução** |
|
|
325
|
+
| **5. Execução** | IA | Geração de Código | A IA implementa o código produtivo e os testes baseando-se estritamente nas specs, atualizando o versionamento semântico ao concluir. |
|
|
360
326
|
|
|
361
327
|
---
|
|
362
328
|
|
|
@@ -364,7 +330,7 @@ Ao contrário de frameworks tradicionais de especificação que geram dezenas de
|
|
|
364
330
|
|
|
365
331
|
Para visualizar diagramas Mermaid diretamente no seu editor durante o fluxo MDDD, você pode usar extensões que renderizam blocos `mermaid` em arquivos Markdown:
|
|
366
332
|
|
|
367
|
-
### Diagrama Arquitetural
|
|
333
|
+
### Exemplo de Diagrama Arquitetural
|
|
368
334
|
|
|
369
335
|
```mermaid
|
|
370
336
|
sequenceDiagram
|
|
@@ -409,7 +375,7 @@ sequenceDiagram
|
|
|
409
375
|
|
|
410
376
|
```
|
|
411
377
|
|
|
412
|
-
### Matriz de Decisão de Ciclo de Vida & Runtime de Micro-Apps
|
|
378
|
+
### Exemplo de Matriz de Decisão de Ciclo de Vida & Runtime de Micro-Apps
|
|
413
379
|
|
|
414
380
|
| 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) |
|
|
415
381
|
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
|
@@ -425,7 +391,7 @@ sequenceDiagram
|
|
|
425
391
|
|
|
426
392
|
---
|
|
427
393
|
|
|
428
|
-
### VS Code
|
|
394
|
+
### VS Code e derivados
|
|
429
395
|
|
|
430
396
|
* **Markdown Preview Mermaid Support** — Adiciona suporte a diagramas Mermaid no preview nativo do Markdown.
|
|
431
397
|
* **Mermaid Editor** — Editor visual com preview lado a lado e exportação.
|
|
@@ -461,9 +427,9 @@ npm install -g mddd-cli
|
|
|
461
427
|
|
|
462
428
|
## 🚀 Guia de Uso Rápido
|
|
463
429
|
|
|
464
|
-
O fluxo MDDD é baseado em
|
|
430
|
+
O fluxo MDDD é baseado em skills para orquestrar a IA no chat.
|
|
465
431
|
|
|
466
|
-
### 1.
|
|
432
|
+
### 1. Inicialize seu projeto
|
|
467
433
|
|
|
468
434
|
Na raiz do seu projeto, execute:
|
|
469
435
|
|
|
@@ -472,31 +438,21 @@ md init
|
|
|
472
438
|
|
|
473
439
|
```
|
|
474
440
|
|
|
475
|
-
Isso criará os arquivos `system_prompt.md` e `SKILL.md` no diretório raiz, contendo as instruções globais que guiarão a IA
|
|
441
|
+
Isso criará os arquivos `system_prompt.md` e `SKILL.md` no diretório raiz, contendo as instruções globais que guiarão a IA na compreensão da metodologia MDDD e na interação com os logs do Git. Você pode renomear `system_prompt.md` para qualquer arquivo .rules que precisar (.cursorrules, .clinerules, etc.).
|
|
476
442
|
|
|
477
|
-
### 2.
|
|
443
|
+
### 2. Auditar arquivos legados ou criar novos.
|
|
478
444
|
|
|
479
|
-
|
|
445
|
+
* Diga à IA para executar `md-audit` no arquivo que você deseja revisar. Se ele estiver limpo e conciso, a IA criará a especificação com base nele. Caso contrário, a IA proporá uma refatoração com a especificação ideal ("to-be").
|
|
446
|
+
* Diga à IA para executar `md-new` para uma especificação que você precisa, conectar a um Jira/Tarefa, a um Figma/Design ou simplesmente diga à IA o que você precisa.
|
|
480
447
|
|
|
481
|
-
|
|
482
|
-
# Para uma funcionalidade única
|
|
483
|
-
md new caminho/nome-da-feature
|
|
484
|
-
|
|
485
|
-
# Para uma funcionalidade conectando a um fluxo existente
|
|
486
|
-
md new caminho/nome-da-feature --parent caminho/para/pai
|
|
487
|
-
|
|
488
|
-
```
|
|
489
|
-
|
|
490
|
-
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.
|
|
448
|
+
### 3. Implementar a especificação.
|
|
491
449
|
|
|
492
|
-
|
|
450
|
+
Diga à IA para executar `md-impl` apontando para um arquivo .spec. Ela lerá toda a especificação, criará a lista de tarefas e começará a trabalhar nela.
|
|
493
451
|
|
|
494
|
-
|
|
452
|
+
### 4. Editar especificações existentes.
|
|
495
453
|
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
```
|
|
454
|
+
Se você precisar adicionar uma nova funcionalidade ou modificar uma existente, basta dizer à IA para executar `md-edit` no arquivo .spec com as modificações desejadas.
|
|
455
|
+
Revise até obter exatamente a especificação de que precisa e, em seguida, diga à IA para executá-lo com `md-impl`.
|
|
500
456
|
|
|
501
457
|
---
|
|
502
458
|
|
|
@@ -536,12 +492,6 @@ src/
|
|
|
536
492
|
| Comando | Descrição |
|
|
537
493
|
| --- | --- |
|
|
538
494
|
| `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. |
|
|
539
|
-
| `md new <targetPath>` | Cria um novo arquivo `.spec.md` no diretório alvo. Suporta `--macro` para specs de módulo e `--parent` para vinculação explícita ao pai. |
|
|
540
|
-
| `md edit <specFilePath> <instruction...>` | Sinaliza uma alteração pendente em um `.spec.md` existente. A IA então aplica as mudanças e incrementa a versão semântica. |
|
|
541
|
-
| `md audit <codeFilePath>` | Audita um arquivo de código para criar um `.spec.md` retroativo ou sugerir refatoração. |
|
|
542
|
-
| `md impl <specFilePath>` | Prepara o ecossistema para implementar código produtivo e testes com base em um `.spec.md` assinado. |
|
|
543
|
-
|
|
544
|
-
> **💡 Nota para agentes de IA:** Estes comandos foram projetados para serem invocados por ferramentas de IA (Cursor, Windsurf, Claude Code, GitHub Copilot). Como humano, basta dizer à IA qual skill usar e o arquivo de destino.
|
|
545
495
|
|
|
546
496
|
### Arquitetura do Projeto
|
|
547
497
|
|
|
@@ -549,36 +499,17 @@ O código-fonte da CLI segue uma arquitetura modular limpa, conforme documentado
|
|
|
549
499
|
|
|
550
500
|
```
|
|
551
501
|
bin/
|
|
552
|
-
├── cli.js # Router Commander enxuto (<
|
|
553
|
-
└── cli.spec.md # Spec colocalizada (
|
|
502
|
+
├── cli.js # Router Commander enxuto (< 30 linhas)
|
|
503
|
+
└── cli.spec.md # Spec colocalizada (v3.0.0)
|
|
554
504
|
|
|
555
505
|
src/
|
|
556
|
-
├── commands/ # Camada de comandos
|
|
557
|
-
│
|
|
558
|
-
│ ├── new.js
|
|
559
|
-
│ ├── edit.js
|
|
560
|
-
│ ├── audit.js
|
|
561
|
-
│ └── impl.js
|
|
506
|
+
├── commands/ # Camada de comandos
|
|
507
|
+
│ └── init.js
|
|
562
508
|
└── services/ # Serviços compartilhados com DI
|
|
563
509
|
├── FileSystemService.js
|
|
564
|
-
|
|
565
|
-
├── ParentLinker.js
|
|
566
|
-
├── InitService.js
|
|
567
|
-
├── SpecGenerator.js
|
|
568
|
-
├── SpecValidator.js
|
|
569
|
-
├── SpecEditor.js
|
|
570
|
-
├── AuditService.js
|
|
571
|
-
└── ImplValidator.js
|
|
572
|
-
|
|
573
|
-
tests/ # Testes unitários
|
|
574
|
-
├── SpecGenerator.test.js
|
|
575
|
-
├── ParentLinker.test.js
|
|
576
|
-
├── AuditService.test.js
|
|
577
|
-
└── TemplateFactory.test.js
|
|
510
|
+
└── InitService.js
|
|
578
511
|
```
|
|
579
512
|
|
|
580
|
-
Todos os 21 testes unitários passam com sistema de arquivos mockado (zero I/O real), garantindo cobertura total dos serviços principais.
|
|
581
|
-
|
|
582
513
|
---
|
|
583
514
|
|
|
584
515
|
## 🧪 Tecnologias
|
|
@@ -599,4 +530,4 @@ Se encontrar qualquer problema, abra uma [Issue no GitHub](https://github.com/Ju
|
|
|
599
530
|
|
|
600
531
|
## 📄 Licença
|
|
601
532
|
|
|
602
|
-
Distribuído sob a licença MIT. Veja o arquivo [LICENSE](https://www.google.com/search?q=LICENSE) para mais informações.
|
|
533
|
+
Distribuído sob a licença MIT. Veja o arquivo [LICENSE](https://www.google.com/search?q=LICENSE) para mais informações.
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import pc from 'picocolors';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* PROMPT SYSTEM CONTENT: the full MDDD universal system prompt text.
|
|
5
|
+
* (Embedded here to maintain co-location; refactored from the monolithic cli.js)
|
|
6
|
+
*/
|
|
7
|
+
export const SYSTEM_PROMPT_CONTENT = `# Mermaid Diagram Driven Development (MDDD) Protocol
|
|
8
|
+
|
|
9
|
+
You are an engineering agent operating strictly under MDDD. Your cognitive processing is guided by visual topologies and truth tables, completely eliminating text-based specification ambiguity.
|
|
10
|
+
|
|
11
|
+
\`\`\`mermaid
|
|
12
|
+
%% @spec-version v1.0.0
|
|
13
|
+
stateDiagram-v2
|
|
14
|
+
[*] --> ReadSpecification: User Trigger Fired
|
|
15
|
+
ReadSpecification --> CheckDecisionMatrix: Evaluate Primitive Factors
|
|
16
|
+
CheckDecisionMatrix --> HaltWithConflict: Constraint Violation / Feature Creep
|
|
17
|
+
CheckDecisionMatrix --> ExecuteAction: Strict Match Confirmed
|
|
18
|
+
ExecuteAction --> MutateState: Apply File/Code Changes
|
|
19
|
+
MutateState --> UpdateVersionHeader: Apply Semantic Version Rules
|
|
20
|
+
UpdateVersionHeader --> [*]
|
|
21
|
+
\`\`\`
|
|
22
|
+
|
|
23
|
+
## 1. Co-location Architecture Tree
|
|
24
|
+
|
|
25
|
+
src/
|
|
26
|
+
└── [domain]/
|
|
27
|
+
├── [domain_name].spec.md # 🌎 Macro Module Domain
|
|
28
|
+
└── [feature_name]/
|
|
29
|
+
├── [feature_name].spec.md # 🔬 Micro Flow Contract + Decision Matrix
|
|
30
|
+
└── [feature_name].* # 💻 Target Production Code File (Any Extension)
|
|
31
|
+
|
|
32
|
+
## 2. Parent Interaction Logic
|
|
33
|
+
|
|
34
|
+
\`\`\`mermaid
|
|
35
|
+
graph TD
|
|
36
|
+
A[Create/Change Sub-Feature] --> B[Open Indicated Parent File]
|
|
37
|
+
B --> C[Locate Bifurcation Node in Parent Mermaid]
|
|
38
|
+
C --> D[Modify Parent Graph: Point Arrow to New State]
|
|
39
|
+
D --> E[Child File: Inherit Parent Context in Entry Node]
|
|
40
|
+
\`\`\`
|
|
41
|
+
|
|
42
|
+
## 3. Core Behavioral Framework Matrix
|
|
43
|
+
|
|
44
|
+
| User Context | Target Spec Header | Human Request Path | Diagram Change Impact | AI Core Rule / Mandate / Ironclad Clause |
|
|
45
|
+
| :---: | :---: | :---: | :---: | :--- |
|
|
46
|
+
| | - | **MISSING** | - | - | Never remove, omit, or bypass the version tag from files. |
|
|
47
|
+
| | Code Change Needed | **SIGNED** | Contradicts Matrix | - | 🛑 **HALT**: Refuse code generation. Demand \`md edit\` to align design first. |
|
|
48
|
+
| | Feature Writing | - | Continuous Text Block | - | 📊 **STRUCTURE**: Convert text into tables of primitive factors (yes/no/rigid values). |
|
|
49
|
+
| | Command Executed | \`SPEC_VERSION\` | - | Typo / Label Only | Increment Patch (\`X.Y.Z\` -> \`X.Y.Z+1\`) |
|
|
50
|
+
| | Command Executed | \`SPEC_VERSION\` | - | New State / Arrow / Matrix Column | Increment Minor (\`X.Y.Z\` -> \`X.Y+1.0\`) |
|
|
51
|
+
| | Command Executed | \`SPEC_VERSION\` | - | Structural Breaking / Flow Overhaul | Increment Major (\`X.Y.Z\` -> \`X+1.0.0\`) |
|
|
52
|
+
|
|
53
|
+
## 4. Anti-Hallucination Guardrails
|
|
54
|
+
1. **No Spec, No Code:** You are strictly forbidden from writing a single line of production code or unit tests if the corresponding \`.spec.md\` file does not exist or does not contain a populated Decision Matrix.
|
|
55
|
+
2. **Implicit Logic Ban:** If a business condition, validation check, or outcome branch is not explicitly listed as a row or column in the Decision Matrix, it does not exist. Do not assume, extrapolate, or invent fallback behaviors.
|
|
56
|
+
3. **Strict State Isolation:** When handling a micro feature, you cannot introduce global states or modify sibling domains unless instructed via explicit macro architectural mapping updates.
|
|
57
|
+
4. **Idempotent Full-File Output Mandate:** You are completely forbidden from using code placeholders, truncating files, or emitting partial snippets (e.g., "// rest of class unchanged", "/* TODO */"). Every code generation action must output the entire, clean, compile-ready file from scratch, ensuring perfect context preservation.`;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Skills content map: skill name -> SKILL.md content.
|
|
61
|
+
*/
|
|
62
|
+
export const SKILLS = {
|
|
63
|
+
'md-new': `[ROLE: ARCHITECT] [STRICT CONTRACT]
|
|
64
|
+
|
|
65
|
+
\`\`\`mermaid
|
|
66
|
+
%% @spec-version v1.1.0
|
|
67
|
+
stateDiagram-v2
|
|
68
|
+
[*] --> TargetVerification
|
|
69
|
+
TargetVerification --> StopAndSwitchToEdit: .spec.md File Already Exists
|
|
70
|
+
TargetVerification --> EvaluateContext: File Does Not Exist
|
|
71
|
+
|
|
72
|
+
state EvaluateContext {
|
|
73
|
+
[*] --> CheckDirectoryDepth
|
|
74
|
+
CheckDirectoryDepth --> InferMacro: Target is Domain Root (e.g., src/domain)
|
|
75
|
+
CheckDirectoryDepth --> InferMicro: Target is Sub-Feature (e.g., src/domain/feature)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
InferMacro --> ExecCliNew: Apply stateDiagram-v2 Template
|
|
79
|
+
InferMicro --> ExecCliNew: Apply graph LR + Matrix Template
|
|
80
|
+
|
|
81
|
+
ExecCliNew --> AwaitHumanReview: Run "md new [path]" & Populate Blueprint
|
|
82
|
+
AwaitHumanReview --> [*]: Pause Code & Test Generation
|
|
83
|
+
\`\`\`
|
|
84
|
+
|
|
85
|
+
### Operational Execution Matrix
|
|
86
|
+
|
|
87
|
+
| File Exists? | Path Depth Type | Parent Indicated? | CLI Execution Syntax | Target Payload Blueprint | Next AI Action |
|
|
88
|
+
| :---: | :---: | :---: | :--- | :--- | :---: |
|
|
89
|
+
| ✅ YES | - | - | *None* (Aborted) | *None* | 🛑 **STOP** (Call md-edit instead) |
|
|
90
|
+
| ❌ NO | Domain Root | ❌ NO | \`md new [domain_path]\` | \`stateDiagram-v2\` Placeholder Domain Map | ⏳ **AWAIT_VISUAL_APPROVAL** |
|
|
91
|
+
| ❌ NO | Sub-Feature | ❌ NO | \`md new [feature_path]\` | \`graph LR\` + Auto-scanned parent link reference | ⏳ **AWAIT_VISUAL_APPROVAL** |
|
|
92
|
+
| ❌ NO | Sub-Feature | ✅ YES | \`md new [feature_path] -p[parent]\` | \`graph LR\` + Explicit link injected to designated Parent | ⏳ **AWAIT_VISUAL_APPROVAL** |
|
|
93
|
+
|
|
94
|
+
### Automation & Inference Ironclad Rules
|
|
95
|
+
1. **Deterministic Inference:** You must strictly follow the directory depth. If the target path is a top-level domain folder inside your source root, treat it as a Module Macro. If it is nested inside a domain, it is a Micro Feature. Never ask the user to declare this.
|
|
96
|
+
2. **Implicit Parent Binding:** When creating a Sub-Feature without an explicit \`-p\` parameter, acknowledge that the CLI tool will automatically scan and mutate the nearest parent macro file via recursive climbing. You must read the updated parent immediately after execution to synchronize your internal context map.
|
|
97
|
+
3. Agnostic Blueprint Initialization: When generating the initial blueprint files, you must scan the neighboring files in the target domain directory to identify the current programming language and framework conventions. Adapt your placeholder references to strictly pair with the localized file architecture.`,
|
|
98
|
+
|
|
99
|
+
'md-edit': `[ROLE: ARCHITECT] [STRICT CONTRACT]
|
|
100
|
+
|
|
101
|
+
\`\`\`mermaid
|
|
102
|
+
%% @spec-version v1.1.0
|
|
103
|
+
graph LR
|
|
104
|
+
A[Read Target .spec.md] --> B[Parse Current SPEC_VERSION]
|
|
105
|
+
B --> C[Apply Mermaid/Matrix Adjustments]
|
|
106
|
+
C --> D{Evaluate Mutation Scope}
|
|
107
|
+
|
|
108
|
+
D -->|Typo / Label Fix| E[Increment Patch: Bump Z in X.Y.Z]
|
|
109
|
+
D -->|New Node / Flow Path / Factor| F[Increment Minor: Bump Y in X.Y.Z]
|
|
110
|
+
D -->|Breaking Overhaul / Restructure| G[Increment Major: Bump X in X.Y.Z]
|
|
111
|
+
|
|
112
|
+
E --> H[Validate Mermaid Syntax]
|
|
113
|
+
F --> H
|
|
114
|
+
G --> H
|
|
115
|
+
|
|
116
|
+
H -->|Syntax Valid| I[Save Contract & Halt]
|
|
117
|
+
H -->|Syntax Invalid| J[🛑 HALT: Abort & Ask Human]
|
|
118
|
+
\`\`\`
|
|
119
|
+
|
|
120
|
+
### Evolution Versioning Matrix
|
|
121
|
+
|
|
122
|
+
| Structural Change Type | Adds Factor Column? | Adds Transition Node/Arrow? | Label / Typo Corrections Only? | Semantic Version Modification | Target AI State |
|
|
123
|
+
| :--- | :---: | :---: | :---: | :---: | :---: |
|
|
124
|
+
| Complete Business Overhaul | - | - | - | **MAJOR Mutation (X.Y.Z -> X+1.0.0)** | ⏳ **AWAIT_USER_VALIDATION** |
|
|
125
|
+
| New Context Conditional Branch | ✅ YES | - | - | **MINOR Mutation (X.Y.Z -> X.Y+1.0)** | ⏳ **AWAIT_USER_VALIDATION** |
|
|
126
|
+
| New UI Flow Step / Lifecycle State | ❌ NO | ✅ YES | - | **MINOR Mutation (X.Y.Z -> X.Y+1.0)** | ⏳ **AWAIT_USER_VALIDATION** |
|
|
127
|
+
| Visual Spacing / Text Refinement | ❌ NO | ❌ NO | ✅ YES | **PATCH Mutation (X.Y.Z -> X.Y.Z+1)** | ⏳ **AWAIT_USER_VALIDATION** |
|
|
128
|
+
|
|
129
|
+
### Mutation Integrity Ironclad Rules
|
|
130
|
+
1. **Incremental SemVer Locking:** You must read the existing \`SPEC_VERSION\` from the file header before modifying it. Never reset, guess, or overwrite the version to a lower state. Bumping Minor explicitly drops the patch version to zero (\`X.Y.Z\` -> \`X.Y+1.0\`). Bumping Major explicitly drops both minor and patch to zero (\`X.Y.Z\` -> \`X+1.0.0\`).
|
|
131
|
+
2. **Strict Syntax Guard:** Before writing the modifications to disk, execute an internal mental compilation of the Mermaid syntax. If any arrow (\`-->\`), state connector, or label syntax breaks the official Mermaid spec, immediately halt execution and report the error to the user without modifying the file.
|
|
132
|
+
3. **Audit History Log Requirement:** Every time you perform an edit, you must append a new row to the markdown table inside the \`<details><summary>Click to expand</summary>...</details>\` block at the bottom of the file, containing the current date, your agent identity, the new version number, and a concise summary of the changes made.
|
|
133
|
+
4. **Node ID Immutability:** When adding new transitions or nodes to an existing graph, you are strictly forbidden from altering, renaming, or refactoring the identifiers (IDs) of existing states/nodes unless explicitly requested by the user.`,
|
|
134
|
+
|
|
135
|
+
'md-audit': `[ROLE: SECURITY & QUALITY AUDITOR] [STRICT CONTRACT]
|
|
136
|
+
|
|
137
|
+
\`\`\`mermaid
|
|
138
|
+
%% @spec-version v1.1.0
|
|
139
|
+
stateDiagram-v2
|
|
140
|
+
[*] --> AnalyzeLegacyCode: Evaluate Coupling & Scope Leaks
|
|
141
|
+
AnalyzeLegacyCode --> FileSystemCheck
|
|
142
|
+
|
|
143
|
+
state FileSystemCheck {
|
|
144
|
+
[*] --> CheckCoLocation
|
|
145
|
+
CheckCoLocation --> CreateMissingSpec: Target Co-located .spec.md Missing
|
|
146
|
+
CheckCoLocation --> AppendToExisting: Target Co-located .spec.md Exists
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
CreateMissingSpec --> RenderTopology: Initialize New .spec.md
|
|
150
|
+
AppendToExisting --> InjectAuditBlock: Target Existing File Preservation Map
|
|
151
|
+
|
|
152
|
+
state RenderTopology {
|
|
153
|
+
[*] --> CodeIsClean: Map exact architecture as-is (v1.0.0)
|
|
154
|
+
[*] --> CodeIsChaotic: Draw BOTH current real logic AND ideal target refactored graph
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
RenderTopology --> WriteToAuditTag: Inject payloads inside <details> block
|
|
158
|
+
InjectAuditBlock --> WriteToAuditTag: Append to existing <details> block without overwriting business specs
|
|
159
|
+
WriteToAuditTag --> EnforceImmutability: Lock Production Code File
|
|
160
|
+
EnforceImmutability --> [*]
|
|
161
|
+
\`\`\`
|
|
162
|
+
|
|
163
|
+
### Reverse Engineering & Auto-Repair Decision Matrix
|
|
164
|
+
|
|
165
|
+
| Source File State | Co-located .spec.md Exists? | Code Design Assessment | Target Output Destination | Code File Manipulation Allowed? | Initial Compiled Version |
|
|
166
|
+
| :--- | :---: | :---: | :--- | :---: | :---: |
|
|
167
|
+
| Legacy Code Active | ✅ YES | Clean / Modular | Append to existing \`<details><summary>Audit History</summary>\` | ❌ **FORBIDDEN (Immutability)** | Retain Current |
|
|
168
|
+
| Legacy Code Active | ✅ YES | Chaotic / Coupled | Append to existing \`<details><summary>Audit History</summary>\` | ❌ **FORBIDDEN (Immutability)** | Retain Current |
|
|
169
|
+
| Legacy Code Active | ❌ NO | Clean / Modular | Auto-generate Spec File + Map Current Logic | ❌ **FORBIDDEN (Immutability)** | \`v1.0.0\` |
|
|
170
|
+
| Legacy Code Active | ❌ NO | Chaotic / Coupled | Auto-generate Spec File + Map Current AND Proposed Logic | ❌ **FORBIDDEN (Immutability)** | \`v1.0.0\` |
|
|
171
|
+
|
|
172
|
+
### Missing Spec Auto-Repair Blueprint Requirements
|
|
173
|
+
* **Enforce Section Injections:** Every generated specification file must structurally enforce:
|
|
174
|
+
1. \`SPEC_VERSION: v1.0.0\` metadata header at the very top.
|
|
175
|
+
2. \`stateDiagram-v2\` or \`graph LR\` derived exactly from code logic behaviors.
|
|
176
|
+
3. \`Decision Matrix\` tables filled if the code contains conditional execution branches.
|
|
177
|
+
4. An isolated \`<details><summary>Audit History</summary>...</details>\` block at the bottom containing the specific code review analytics.
|
|
178
|
+
|
|
179
|
+
### Quality Assurance & Immutability Ironclad Rules
|
|
180
|
+
1. **Absolute Immutability Command:** Under no circumstances are you allowed to patch, alter, or modify the target production code file during the \`md-audit\` cycle. Your execution scope is strictly limited to observation and documentation within the Markdown specification file.
|
|
181
|
+
2. **Preservation Guarantee:** When appending an audit report to an existing \`.spec.md\` file, you must read the file completely and guarantee that the business requirements, main diagrams, and current decision matrices are left untouched. You are only allowed to inject rows inside the \`<details>\` audit history block.
|
|
182
|
+
3. **Chaotic Code Double-Mapping:** If you evaluate the legacy code as chaotic or highly coupled, you must not replace the current reality with your ideal version. You are required to draw the current graph (flawed as it is) to serve as a baseline, and then provide a separate, clearly labeled Mermaid graph showing the suggested refactored topology.
|
|
183
|
+
|
|
184
|
+
**Rule:** ALWAYS GENERATE THE .SPEC.MD FILE OR UPDATE THE EXISTING ONE.
|
|
185
|
+
`,
|
|
186
|
+
|
|
187
|
+
'md-impl': `[ROLE: SOFTWARE ENGINEER] [STRICT CONTRACT]
|
|
188
|
+
|
|
189
|
+
\`\`\`mermaid
|
|
190
|
+
%% @spec-version v1.1.0
|
|
191
|
+
graph TD
|
|
192
|
+
A[Ingest Signed .spec.md] --> B[Parse Matrix Rows & Version Header]
|
|
193
|
+
B --> C{Verify Code/Chat Request}
|
|
194
|
+
|
|
195
|
+
C -->|Matches Decision Matrix Rows 100%| D[Check File Target State]
|
|
196
|
+
C -->|Human Asks to Skip/Add Extraneous Scope| E[Trigger Prompt Injection Defense]
|
|
197
|
+
|
|
198
|
+
D -->|New File| F[Generate Full Structural Code from Scratch]
|
|
199
|
+
D -->|Existing File| G[Idempotent Overwrite: Read & Output Full File]
|
|
200
|
+
|
|
201
|
+
F --> H[Generate Truth-Table Unit Tests]
|
|
202
|
+
G --> H
|
|
203
|
+
|
|
204
|
+
H --> I[Verify 100% Branch Coverage Alignment]
|
|
205
|
+
I --> [*]
|
|
206
|
+
|
|
207
|
+
E --> J[Refuse Coding & Demand Spec Refinement via md-edit]
|
|
208
|
+
J --> [*]
|
|
209
|
+
\`\`\`
|
|
210
|
+
|
|
211
|
+
### Injection Defense & Execution Guard Matrix
|
|
212
|
+
|
|
213
|
+
| Spec Contract Signed? | Chat Prompt Code Alignment | Human Requests Bypassing Spec Matrix? | Core AI Action Authorized | Error Response Pattern |
|
|
214
|
+
| :---: | :---: | :---: | :--- | :--- |
|
|
215
|
+
| ❌ NO | - | - | ❌ **DENY GENERATION** | Demand invocation of \`md-new\` or \`md-audit\` |
|
|
216
|
+
| ✅ YES | ❌ Out-of-bounds | - | ❌ **DENY GENERATION** | "Please use the md-edit command to update the diagram..." |
|
|
217
|
+
| ✅ YES | - | ✅ YES (Feature Creep) | ❌ **DENY GENERATION** | "Please use the md-edit command to update the diagram..." |
|
|
218
|
+
| ✅ YES | ✅ 100% Rigid Match| ❌ NO | ✅ **ALLOW SOLID CODEGEN** | Complete compliance code + 100% matrix row unit tests |
|
|
219
|
+
|
|
220
|
+
### Production Implementation & Codegen Ironclad Rules
|
|
221
|
+
1. **The Matrix Test Alignment Mandate:** Your unit test suite must match the Decision Matrix row by row. For every single row present in the specification's truth table, you are strictly required to build at least one explicit, dedicated unit test case mapping those precise primitive factors to that exact outcome.
|
|
222
|
+
2. **Anti-Placeholder Clause:** You are absolutely forbidden from generating incomplete code structures, omitting code sections, or using placeholders like \`// TODO\`, \`// implementation goes here\`, or \`// rest of the class remains unchanged\`. You must always output the complete, compile-ready, and production-grade file layout.
|
|
223
|
+
3. **Strict SOLID Compliance:** Every piece of logic generated under this cycle must follow strict Clean Architecture principles and SOLID patterns. If the specification implies a new conditional branch, you must implement it using polymorphism or structured strategies rather than compounding nested \`if-else\` or pattern-matching anti-patterns unless explicitly dictated by the diagram topology.`,
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Executes the `md init` command.
|
|
228
|
+
* @param {import('../services/InitService.js').InitService} initService
|
|
229
|
+
* @returns {Promise<void>}
|
|
230
|
+
*/
|
|
231
|
+
export async function execute(initService) {
|
|
232
|
+
await initService.createSystemPrompt(SYSTEM_PROMPT_CONTENT);
|
|
233
|
+
await initService.createSkills(SKILLS, (msg) => console.log(msg));
|
|
234
|
+
|
|
235
|
+
console.log(pc.green('\n🚀 Universal [system_prompt.md] and SKILLS generated successfully in the project root!'));
|
|
236
|
+
console.log(pc.green('Run the "md init" command whenever you update the MDDD-CLI NPM package.'));
|
|
237
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import { existsSync, mkdirSync, readdirSync } from 'node:fs';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* @typedef {Object} FileSystemOperations
|
|
7
|
+
* @property {(path: string) => Promise<string>} readFile
|
|
8
|
+
* @property {(path: string, content: string) => Promise<void>} writeFile
|
|
9
|
+
* @property {(path: string, content: string) => Promise<void>} appendFile
|
|
10
|
+
* @property {(path: string) => boolean} existsSync
|
|
11
|
+
* @property {(path: string) => void} mkdirSyncRecursive
|
|
12
|
+
* @property {(path: string) => string[]} readdirSync
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Shared file system service with dependency injection support for testability.
|
|
17
|
+
*/
|
|
18
|
+
export class FileSystemService {
|
|
19
|
+
/** @type {FileSystemOperations} */
|
|
20
|
+
#fs;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @param {Partial<FileSystemOperations>} [fsMock] - Optional mock for testing
|
|
24
|
+
*/
|
|
25
|
+
constructor(fsMock) {
|
|
26
|
+
this.#fs = {
|
|
27
|
+
readFile: fsMock?.readFile || fs.readFile.bind(fs),
|
|
28
|
+
writeFile: fsMock?.writeFile || fs.writeFile.bind(fs),
|
|
29
|
+
appendFile: fsMock?.appendFile || fs.appendFile.bind(fs),
|
|
30
|
+
existsSync: fsMock?.existsSync || existsSync,
|
|
31
|
+
mkdirSyncRecursive: fsMock?.mkdirSyncRecursive || ((p) => mkdirSync(p, { recursive: true })),
|
|
32
|
+
readdirSync: fsMock?.readdirSync || readdirSync,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Checks if a path exists synchronously.
|
|
38
|
+
* @param {string} path
|
|
39
|
+
* @returns {boolean}
|
|
40
|
+
*/
|
|
41
|
+
existsSync(path) {
|
|
42
|
+
return this.#fs.existsSync(path);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Creates a directory recursively.
|
|
47
|
+
* @param {string} path
|
|
48
|
+
*/
|
|
49
|
+
mkdirSyncRecursive(path) {
|
|
50
|
+
this.#fs.mkdirSyncRecursive(path);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Creates a directory if it doesn't exist.
|
|
55
|
+
* @param {string} path
|
|
56
|
+
*/
|
|
57
|
+
ensureDir(path) {
|
|
58
|
+
if (!this.#fs.existsSync(path)) {
|
|
59
|
+
this.#fs.mkdirSyncRecursive(path);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Reads a file as UTF-8 string.
|
|
65
|
+
* @param {string} path
|
|
66
|
+
* @returns {Promise<string>}
|
|
67
|
+
*/
|
|
68
|
+
async readFile(path) {
|
|
69
|
+
return this.#fs.readFile(path);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Writes a string to a file.
|
|
74
|
+
* @param {string} path
|
|
75
|
+
* @param {string} content
|
|
76
|
+
* @returns {Promise<void>}
|
|
77
|
+
*/
|
|
78
|
+
async writeFile(path, content) {
|
|
79
|
+
return this.#fs.writeFile(path, content);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Appends content to a file.
|
|
84
|
+
* @param {string} path
|
|
85
|
+
* @param {string} content
|
|
86
|
+
* @returns {Promise<void>}
|
|
87
|
+
*/
|
|
88
|
+
async appendFile(path, content) {
|
|
89
|
+
return this.#fs.appendFile(path, content);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Synchronous readdir for directory crawling.
|
|
94
|
+
* @param {string} dir
|
|
95
|
+
* @returns {string[]}
|
|
96
|
+
*/
|
|
97
|
+
readdirSync(dir) {
|
|
98
|
+
return this.#fs.readdirSync(dir);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Handles the `md init` business logic: system prompt and skills creation.
|
|
5
|
+
*/
|
|
6
|
+
export class InitService {
|
|
7
|
+
/** @type {import('./FileSystemService.js').FileSystemService} */
|
|
8
|
+
#fs;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @param {import('./FileSystemService.js').FileSystemService} fsService
|
|
12
|
+
*/
|
|
13
|
+
constructor(fsService) {
|
|
14
|
+
this.#fs = fsService;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Creates the universal system prompt file.
|
|
19
|
+
* @param {string} promptContent - The full MDDD system prompt content
|
|
20
|
+
* @returns {Promise<void>}
|
|
21
|
+
*/
|
|
22
|
+
async createSystemPrompt(promptContent) {
|
|
23
|
+
await this.#fs.writeFile('system_prompt.md', promptContent);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Creates all skill folders and SKILL.md files.
|
|
28
|
+
* @param {Record<string, string>} skills - Map of skill name to skill content
|
|
29
|
+
* @returns {Promise<{console: (message: string) => void}>} Array of file paths created
|
|
30
|
+
*/
|
|
31
|
+
async createSkills(skills, logger) {
|
|
32
|
+
const agentsDir = '.agents';
|
|
33
|
+
const skillsDir = path.join(agentsDir, 'skills');
|
|
34
|
+
|
|
35
|
+
this.#fs.ensureDir(agentsDir);
|
|
36
|
+
this.#fs.ensureDir(skillsDir);
|
|
37
|
+
|
|
38
|
+
const created = [];
|
|
39
|
+
|
|
40
|
+
for (const [skillName, content] of Object.entries(skills)) {
|
|
41
|
+
const skillFolder = path.join(skillsDir, skillName);
|
|
42
|
+
this.#fs.ensureDir(skillFolder);
|
|
43
|
+
|
|
44
|
+
const skillFile = path.join(skillFolder, 'SKILL.md');
|
|
45
|
+
await this.#fs.writeFile(skillFile, content);
|
|
46
|
+
created.push(skillFile);
|
|
47
|
+
logger(`✅ Skill successfully encapsulated: ${skillFile}`);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
return created;
|
|
51
|
+
}
|
|
52
|
+
}
|