mddd-cli 4.1.2 → 4.2.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 CHANGED
@@ -17,7 +17,7 @@ const program = new Command();
17
17
  program
18
18
  .name('md')
19
19
  .description('Manager for co-located specifications for Mermaid Diagram Driven Development (MDDD)')
20
- .version('4.1.2');
20
+ .version('4.2.0');
21
21
 
22
22
  // ==========================================
23
23
  // COMMAND: md init
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mddd-cli",
3
- "version": "4.1.2",
3
+ "version": "4.2.0",
4
4
  "description": "Official CLI for modular, co-located, and versioned Mermaid Diagram Driven Development (MDDD).",
5
5
  "type": "module",
6
6
  "exports": "./bin/cli.js",
@@ -8,7 +8,6 @@
8
8
  "md": "./bin/cli.js"
9
9
  },
10
10
  "files": [
11
- "bin",
12
11
  "src",
13
12
  "system_prompt.md"
14
13
  ],
@@ -23,6 +22,8 @@
23
22
  "mermaid",
24
23
  "md",
25
24
  "ai",
25
+ "sdd",
26
+ "spec-driven",
26
27
  "diagram-driven",
27
28
  "architecture",
28
29
  "cli",
@@ -39,7 +40,7 @@
39
40
  },
40
41
  "homepage": "https://github.com/JulioCRFilho/mermaid-diagram-driven-development#readme",
41
42
  "dependencies": {
42
- "@mermaid-js/parser": "^1.1.1",
43
+ "@mermaid-js/mermaid-cli": "github:mermaid-js/mermaid-cli",
43
44
  "commander": "^12.0.0",
44
45
  "picocolors": "^1.0.0"
45
46
  }
@@ -5,23 +5,8 @@ import { fileURLToPath } from 'node:url';
5
5
  import path from 'node:path';
6
6
  import pc from 'picocolors';
7
7
 
8
- import mdNewContent from '../skills/md-new/content.js';
9
- import mdEditContent from '../skills/md-edit/content.js';
10
- import mdAuditContent from '../skills/md-audit/content.js';
11
- import mdImplContent from '../skills/md-impl/content.js';
12
8
  import { GITHUB_WORKFLOW_CONTENT } from '../workflows/mddd-preview.yml.js';
13
9
 
14
- /**
15
- * Build the SKILLS map from co-located modules.
16
- * @type {Record<string, string>}
17
- */
18
- const SKILLS = {
19
- 'md-new': mdNewContent,
20
- 'md-edit': mdEditContent,
21
- 'md-audit': mdAuditContent,
22
- 'md-impl': mdImplContent,
23
- };
24
-
25
10
  /**
26
11
  * Resolve and read system_prompt.md from the project root.
27
12
  * @returns {string}
@@ -41,8 +26,15 @@ function readSystemPrompt() {
41
26
  export async function execute(initService) {
42
27
  const systemPrompt = readSystemPrompt();
43
28
 
29
+ // Descobre o caminho absoluto real da pasta interna de templates de skills da CLI
30
+ const currentFile = fileURLToPath(import.meta.url);
31
+ const cliSkillsSourceDir = path.resolve(path.dirname(currentFile), '..', 'skills');
32
+
44
33
  await initService.createSystemPrompt(systemPrompt);
45
- await initService.createSkills(SKILLS, (msg) => console.log(msg));
34
+
35
+ // Passa o caminho da pasta de origem em vez do mapa de strings antigas
36
+ await initService.createSkills(cliSkillsSourceDir, (msg) => console.log(msg));
37
+
46
38
  await initService.createGitHubWorkflow(GITHUB_WORKFLOW_CONTENT, (msg) => console.log(msg));
47
39
 
48
40
  console.log(pc.green('\n🚀 Universal [system_prompt.md] and SKILLS generated successfully in the project root!'));
@@ -1,56 +1,22 @@
1
- import { parse } from '@mermaid-js/parser';
1
+ import { exec } from 'node:child_process';
2
2
  import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { promisify } from 'node:util';
5
+
6
+ const execAsync = promisify(exec);
3
7
 
4
8
  function extractMermaidBlocks(text) {
5
9
  const regex = /```mermaid\s*([\s\S]*?)\s*```/g;
6
10
  const blocks = [];
7
11
  let match;
8
-
9
12
  while ((match = regex.exec(text)) !== null) {
10
13
  if (match[1].trim()) {
11
14
  blocks.push(match[1].trim());
12
15
  }
13
16
  }
14
-
15
17
  return blocks;
16
18
  }
17
19
 
18
- /**
19
- * Normaliza quebras de linha, remove TODOS os tipos de espaços Unicode fantasmas
20
- * e elimina comentários/linhas vazias do topo antes do tipo de diagrama.
21
- * @param {string} code
22
- * @returns {string}
23
- */
24
- function cleanDiagramCode(code) {
25
- // 1. Unifica todas as quebras de linha possíveis (\r\n ou \r isolado) para \n
26
- const uniformLines = code.replace(/\r\n|\r/g, '\n');
27
-
28
- // 2. Divide em linhas para processar o topo do arquivo
29
- const lines = uniformLines.split('\n');
30
- const cleanedLines = [];
31
- let foundTypeDeclaration = false;
32
-
33
- for (const line of lines) {
34
- // Substitui todos os tipos conhecidos de espaços em branco Unicode invisíveis por espaços comuns
35
- // (\u00A0 é o NBSP, \u2000-\u200A são variantes de espaçamento tipográfico)
36
- let normalizedLine = line.replace(/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g, ' ');
37
-
38
- const trimmed = normalizedLine.trim();
39
-
40
- // Ignora linhas vazias ou comentários iniciais até achar a declaração do diagrama
41
- if (!foundTypeDeclaration && (trimmed === '' || trimmed.startsWith('%%'))) {
42
- continue;
43
- }
44
-
45
- foundTypeDeclaration = true;
46
-
47
- // Mantém a linha com os espaços normais restaurados (importante para a indentação dos blocos do Mermaid)
48
- cleanedLines.push(normalizedLine);
49
- }
50
-
51
- return cleanedLines.join('\n').trim();
52
- }
53
-
54
20
  export async function validateMermaidSyntax(input) {
55
21
  let content = input;
56
22
 
@@ -65,28 +31,49 @@ export async function validateMermaidSyntax(input) {
65
31
  if (diagramsToValidate.length === 0) {
66
32
  return {
67
33
  valid: false,
68
- error: "Nenhum bloco de código '```mermaid' estruturado foi encontrado."
34
+ error: "Nenhum bloco '```mermaid' encontrado no arquivo."
69
35
  };
70
36
  }
71
37
  }
72
38
 
39
+ const tempInputPath = path.join(process.cwd(), `.temp_validate_${Date.now()}.mmd`);
40
+ const tempOutputPath = path.join(process.cwd(), `.temp_validate_${Date.now()}.svg`);
41
+
73
42
  try {
74
- const cleanedDiagrams = [];
75
-
43
+ const validatedDiagrams = [];
44
+
76
45
  for (const diagramCode of diagramsToValidate) {
77
- const readyCode = cleanDiagramCode(diagramCode);
78
- await parse(readyCode); // Se tiver espaço fantasma aqui, o parser agora aceita!
79
- cleanedDiagrams.push(readyCode);
46
+ fs.writeFileSync(tempInputPath, diagramCode, 'utf-8');
47
+
48
+ // AJUSTE AQUI: Explicitamos o pacote (-p) e chamamos o executável real (mmdc)
49
+ await execAsync(`npx -p @mermaid-js/mermaid-cli mmdc -i "${tempInputPath}" -o "${tempOutputPath}"`);
50
+
51
+ if (fs.existsSync(tempOutputPath)) {
52
+ fs.unlinkSync(tempOutputPath);
53
+ }
54
+
55
+ validatedDiagrams.push(diagramCode);
80
56
  }
81
-
57
+
58
+ if (fs.existsSync(tempInputPath)) {
59
+ fs.unlinkSync(tempInputPath);
60
+ }
61
+
82
62
  return {
83
63
  valid: true,
84
- diagrams: cleanedDiagrams
64
+ diagrams: validatedDiagrams
85
65
  };
66
+
86
67
  } catch (error) {
68
+ if (fs.existsSync(tempInputPath)) fs.unlinkSync(tempInputPath);
69
+ if (fs.existsSync(tempOutputPath)) fs.unlinkSync(tempOutputPath);
70
+
71
+ // Captura o erro real de compilação enviado pelo compilador do Mermaid
72
+ const errorMessage = error.stderr || error.message || 'Erro de validação desconhecido no Mermaid.';
73
+
87
74
  return {
88
75
  valid: false,
89
- error: error.message || 'Erro de sintaxe desconhecido no Mermaid.'
76
+ error: errorMessage.trim()
90
77
  };
91
78
  }
92
79
  }
@@ -1,3 +1,4 @@
1
+ import fs from 'node:fs';
1
2
  import path from 'node:path';
2
3
 
3
4
  /**
@@ -24,31 +25,37 @@ export class InitService {
24
25
  }
25
26
 
26
27
  /**
27
- * Creates all skill folders and SKILL.md files.
28
- * @param {Record<string, string>} skills - Map of skill name to skill content
28
+ * Copies all real skill folders and files to .agents/skills/.
29
+ * @param {string} sourceSkillsDir - Absolute path to the CLI source skills template folder
29
30
  * @param {(message: string) => void} logger
30
- * @returns {Promise<string[]>} Array of file paths created
31
+ * @returns {Promise<void>}
31
32
  */
32
- async createSkills(skills, logger) {
33
+ async createSkills(sourceSkillsDir, logger) {
33
34
  const agentsDir = '.agents';
34
- const skillsDir = path.join(agentsDir, 'skills');
35
+ const targetSkillsDir = path.join(agentsDir, 'skills');
35
36
 
37
+ // Garante a existência da árvore de diretórios base no destino
36
38
  this.#fs.ensureDir(agentsDir);
37
- this.#fs.ensureDir(skillsDir);
39
+ this.#fs.ensureDir(targetSkillsDir);
38
40
 
39
- const created = [];
41
+ if (!fs.existsSync(sourceSkillsDir)) {
42
+ throw new Error(`Source skills template directory not found at: ${sourceSkillsDir}`);
43
+ }
40
44
 
41
- for (const [skillName, content] of Object.entries(skills)) {
42
- const skillFolder = path.join(skillsDir, skillName);
43
- this.#fs.ensureDir(skillFolder);
45
+ // Copia de forma real, recursiva e idêntica todas as pastas de skills
46
+ // Mantém estruturas complexas como a da sua skill 'mermaid-diagrams' (com subpastas references/, readme.md, etc)
47
+ fs.cpSync(sourceSkillsDir, targetSkillsDir, {
48
+ recursive: true,
49
+ force: true
50
+ });
44
51
 
45
- const skillFile = path.join(skillFolder, 'SKILL.md');
46
- await this.#fs.writeFile(skillFile, content);
47
- created.push(skillFile);
48
- logger(`✅ Skill successfully encapsulated: ${skillFile}`);
52
+ // Lista as pastas copiadas apenas para dar um feedback limpo no console
53
+ const copiedSkills = fs.readdirSync(targetSkillsDir);
54
+ for (const skillName of copiedSkills) {
55
+ if (fs.statSync(path.join(targetSkillsDir, skillName)).isDirectory()) {
56
+ logger(`✅ Skill successfully encapsulated: ${path.join(targetSkillsDir, skillName)}`);
57
+ }
49
58
  }
50
-
51
- return created;
52
59
  }
53
60
 
54
61
  /**
package/system_prompt.md CHANGED
@@ -1,6 +1,7 @@
1
1
  # Mermaid Diagram Driven Development (MDDD) Protocol
2
2
 
3
3
  You are a Mermaid Diagram processing system. Your cognitive processing is guided by visual topologies and truth tables, eliminating text-based specification ambiguity.
4
+ Consume the mermaid-diagrams skill to learn how to produce it.
4
5
 
5
6
  ```mermaid
6
7
  %% @spec-version v2.0.0
package/bin/cli.spec.md DELETED
@@ -1,73 +0,0 @@
1
- # CLI Module | v4.2.1 (Stable)
2
-
3
- ## 1. Flow Contract (Mermaid)
4
-
5
- ### 1.1 Topologia Atual (As-Is)
6
-
7
- ```mermaid
8
- %% @spec-version v4.2.1
9
- graph TD
10
- subgraph "CLI Entry (bin/cli.js)"
11
- A[bin/cli.js: Commander Router] --> B[delegate to ./commands/init.js]
12
- end
13
-
14
- subgraph "Commands Layer"
15
- B --> C[InitService.createSystemPrompt]
16
- B --> D[InitService.createSkills]
17
- end
18
-
19
- subgraph "Shared Services"
20
- C --> E[FileSystemService.writeFile]
21
- D --> E
22
- E --> F[fs/promises]
23
- end
24
-
25
- subgraph "External Dependencies"
26
- F --> G["@mermaid-js/mermaid-cli"]
27
- end
28
- ```
29
-
30
- O diagrama acima reflete a arquitetura final e estável pós-refatoração: separação clara entre CLI Entry, Commands Layer e Shared Services, com injeção de dependência do `FileSystemService`. O `@mermaid-js/mermaid-cli` é uma dependência externa instalada junto com o pacote para renderização de diagramas Mermaid.
31
-
32
- ## 2. Decision Matrix
33
-
34
- | Código Atual | Co-located `.spec.md` Exists? | Design Assessment | Ação de Implementação | Manipulação de Código Permitida? | Versão Inicial |
35
- | :--- | :---: | :---: | :--- | :---: | :---: |
36
- | `bin/cli.js` (37 linhas) | ✅ YES | Clean / CLI Entry | Delega para `src/commands/init.js` | ✅ **ALLOW** | `v1.0.0` |
37
- | `src/commands/init.js` | ✅ YES | Modular / Co-located | Contém prompts + delega para `InitService` | ✅ **ALLOW** | `v3.0.0` |
38
- | `src/services/InitService.js` | ✅ YES | Clean / Service | Orquestra criação de system_prompt e skills | ✅ **ALLOW** | `v3.0.0` |
39
- | `src/services/FileSystemService.js` | ✅ YES | Clean / Service | Abstrai `fs/promises` com DI | ✅ **ALLOW** | `v3.0.0` |
40
- | `@mermaid-js/mermaid-cli` | N/A | External Dependency | Renderização de diagramas Mermaid via CLI | ✅ **ALLOW** | `v4.2.0` |
41
-
42
- ### Fatores Primitivos de Qualidade
43
-
44
- | Fator | Valor | Impacto |
45
- | :--- | :---: | :--- |
46
- | CLI Entry desacoplado? | ✅ YES | `bin/cli.js` com 37 linhas, apenas Commander + delegação |
47
- | Lógica de template co-localizada? | ✅ YES | `SYSTEM_PROMPT_CONTENT` e `SKILLS` em `src/commands/init.js` |
48
- | Separação CLI/Business? | ✅ YES | Camadas bem definidas: CLI → Commands → Services |
49
- | Serviços com injeção de dependência? | ✅ YES | `FileSystemService` aceita mock no construtor |
50
- | Código testável? | ⚠️ PARCIAL | Serviços são testáveis; `bin/cli.js` não exporta funções |
51
- | Escopo reduzido? | ✅ YES | Apenas comando `init` — comandos removidos foram eliminados |
52
-
53
- ## 3. Audit History
54
-
55
- <details>
56
- <summary>Click to expand</summary>
57
-
58
- | Data | Auditor | Versão | Resumo das Mudanças |
59
- | :--- | :--- | :---: | :--- |
60
- | 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. |
61
- | 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. |
62
- | 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. |
63
- | 2026-05-28 | Cline (Agent-Actor) | v4.0.0 | **MAJOR Mutation (v3.0.0 → v4.0.0):** Refatoração concluída e estabilizada. Diagrama As-Is e To-Be unificados em um único diagrama estável refletindo a arquitetura real: `bin/cli.js` (37 linhas) → `src/commands/init.js` → `src/services/InitService.js` + `src/services/FileSystemService.js`. Título alterado de "Refactoring Plan" para "CLI Module (Stable)". Matriz de decisão e fatores de qualidade atualizados para refletir o estado modular final. |
64
- | 2026-05-28 | Cline (md-audit) | v4.1.0 | **MINOR Mutation (v4.0.0 → v4.1.0):** Criados specs faltantes `src/services/FileSystemService.spec.md` e `src/services/InitService.spec.md` via `md-audit`. A Matriz de Decisão, que já declarava ✅ `YES` para ambos, agora reflete a realidade do filesystem. Nenhuma alteração em código de produção. |
65
- | 2026-05-30 | Cline (Agent-Actor) | v4.2.0 | **MINOR Mutation (v4.1.0 → v4.2.0):** Adicionado `@mermaid-js/mermaid-cli@^11.15.0` como dependência no `package.json`. Diagrama atualizado para incluir o subgraph "External Dependencies" com referência ao mermaid-cli. Matriz de decisão estendida com linha para a dependência externa. |
66
- | 2026-05-30 | Cline (Agent-Actor) | v4.2.1 | **PATCH Mutation (v4.2.0 → v4.2.1):** Adicionado `system_prompt.md` ao campo `"files"` no `package.json` para resolver erro `ENOENT` ao executar `md init` com instalação global via npm. |
67
-
68
- ### Análise de Qualidade
69
-
70
- - **Acoplamento**: ✅ **BAIXO** — CLI Entry com 37 linhas delega para Commands Layer; Services são independentes com DI.
71
- - **Coesão**: ✅ **ALTA** — Cada módulo tem responsabilidade única e bem definida.
72
- - **Testabilidade**: ⚠️ **PARCIAL** — `InitService` e `FileSystemService` são testáveis via injeção de dependência; `bin/cli.js` permanece sem exportações para teste unitário.
73
- - **Manutenibilidade**: ✅ **ALTA** — Arquitetura limpa com 3 camadas claras e escopo reduzido a apenas `init`.
@@ -1,54 +0,0 @@
1
- export default `[ROLE: SECURITY & QUALITY AUDITOR] [STRICT CONTRACT]
2
-
3
- \`\`\`mermaid
4
- %% @spec-version v1.3.2
5
- stateDiagram-v2
6
- [*] --> Evaluation: Quality Assessment.
7
- Evaluation --> MakeSpec: Co-located .spec.md.
8
-
9
- state MakeSpec {
10
- [*] --> SpecExists: Check for existing .spec.md.
11
- SpecNotFound --> CreateSpec: Create .spec.md from "src/templates/spec-template.md".
12
- SpecExists --> Break: Audit only.
13
- Break --> [*]
14
- }
15
-
16
- CreateSpec --> RenderTopology: Create new co-located .spec.md.
17
-
18
- state RenderTopology {
19
- [*] --> CheckCode: Analyze current code structure and dependencies
20
- CheckCode --> EvaluatedCodeIsClean: Map exact architecture as-is (v1.0.0 - stable)
21
- CheckCode --> EvaluatedCodeIsChaotic: Draw BOTH current chaotic logic AND ideal target refactored graph (v1.0.0 - draft)
22
- }
23
-
24
- RenderTopology --> CheckDiagram: Use "npx md validate <path/to/spec.md>" to validate diagram syntax
25
-
26
- state CheckDiagram {
27
- [*] --> DiagramValid: Proceed to next step
28
- DiagramInvalid --> RenderTopology: Re-render until valid
29
- }
30
-
31
- CheckDiagram --> DiscoveryAnalysis: Identify potential vulnerabilities and code quality issues
32
- DiscoveryAnalysis --> WriteToAuditTag: Document findings and recommendations in the .spec.md file
33
- WriteToAuditTag: Inject payloads inside <details> block
34
- WriteToAuditTag --> EnforceImmutability: Lock Production Code File
35
- EnforceImmutability --> [*]
36
- \`\`\`
37
-
38
- \`\`\`mermaid
39
- %% @spec-version v1.3.0
40
- %% Decision Matrix for EvaluatedCodeIsClean vs EvaluatedCodeIsChaotic
41
- flowchart TD
42
- M[Measure Cyclomatic Complexity] --> A{Aggregate Results}
43
- C[Measure Module Coupling] --> A
44
- H[Measure Module Cohesion LCOM] --> A
45
- V[Count Lint/Code Violations] --> A
46
-
47
- A -->|Complexity < 10 AND Coupling < 3 AND Cohesion > 0.9 AND Violations == 0| Clean[EvaluatedCodeIsClean]
48
- A -->|Complexity >= 10 OR Coupling >= 3 OR Cohesion <= 0.9 OR Violations > 0| Chaotic[EvaluatedCodeIsChaotic]
49
-
50
- style Clean fill:#1b5e20,color:#fff
51
- style Chaotic fill:#b71c1c,color:#fff
52
- \`\`\`
53
-
54
- `;
@@ -1,74 +0,0 @@
1
- export default `[ROLE: ARCHITECT] [STRICT CONTRACT]
2
-
3
- \`\`\`mermaid
4
- %% @spec-version v1.3.1
5
- stateDiagram-v2
6
- [*] --> Read TargetSpec: Read Target .spec.md
7
- Read TargetSpec --> ParseVersion: Parse Current SPEC_VERSION
8
- ParseVersion --> ApplyAdjustments: Apply requested Mermaid/Matrix Adjustments
9
- ApplyAdjustments --> EvaluateScope: Evaluate Mutation Scope
10
-
11
- state EvaluateScope {
12
- [*] --> TypoFix: Typo / Label Fix
13
- [*] --> NewNode: New Node / Flow Path / Factor
14
- [*] --> BreakingChange: Breaking Overhaul / Restructure
15
- }
16
-
17
- EvaluateScope --> IncrementVersion: Increment Version Based on Scope
18
-
19
- state IncrementVersion {
20
- [*] --> IncrementPatch: Increment Patch: Bump Z in X.Y.Z
21
- [*] --> IncrementMinor: Increment Minor: Bump Y in X.Y.Z
22
- [*] --> IncrementMajor: Increment Major: Bump X in X.Y.Z
23
- }
24
-
25
- IncrementVersion --> CheckDiagram: Use "npx md validate <path/to/spec.md>" to validate diagram syntax
26
-
27
- state CheckDiagram {
28
- [*] --> TryRender
29
- TryRender --> DiagramValid: Render succeeded
30
- TryRender --> IncrementRetry: Render failed
31
- IncrementRetry --> TryRender: Retry count < 5
32
- IncrementRetry --> RenderFailed: Retry count >= 5
33
- }
34
-
35
- CheckDiagram --> WriteToFile: Write validated .spec.md to target path
36
- WriteToFile --> VerifyWrite
37
- state VerifyWrite {
38
- [*] --> WriteSuccess: File written successfully
39
- [*] --> WriteError: File write failed (permissions / disk / path)
40
- }
41
- WriteError --> AwaitHumanReview: Error: manual intervention required
42
-
43
- WriteSuccess --> DiscoveryAnalysis: Identify potential vulnerabilities and code quality issues
44
- DiscoveryAnalysis --> AwaitHumanReview: Flag discovered issues for human review
45
- RenderFailed --> AwaitHumanReview: Error: Mermaid CLI validation failed after 5 attempts
46
-
47
- state AwaitHumanReview {
48
- [*] --> Approved: Resume CI/CD pipeline
49
- [*] --> ChangesRequested: Loop back to ApplyAdjustments
50
- [*] --> Aborted: Terminate session
51
- }
52
-
53
- AwaitHumanReview --> [*]: Pause Code & Test Generation
54
- \`\`\`
55
-
56
- \`\`\`mermaid
57
- %% @spec-version v1.3.0
58
- %% Decision Matrix for EvaluateScope: TypoFix vs NewNode vs BreakingChange
59
- flowchart TD
60
- M[Mutation Request Contains...] --> A{Evaluate Factors}
61
-
62
- T[Only label / text changes] --> A
63
- N[New states / flows / factors added] --> A
64
- B[Existing states / flows removed or restructured] --> A
65
-
66
- A -->|"T == true AND N == false AND B == false"| Patch[TypoFix → IncrementPatch]
67
- A -->|"N == true AND B == false"| Minor[NewNode → IncrementMinor]
68
- A -->|"B == true"| Major[BreakingChange → IncrementMajor]
69
-
70
- style Patch fill:#1b5e20,color:#fff
71
- style Minor fill:#0d47a1,color:#fff
72
- style Major fill:#b71c1c,color:#fff
73
- \`\`\`
74
- `;
@@ -1,87 +0,0 @@
1
- export default `[ROLE: SOFTWARE ENGINEER] [STRICT CONTRACT]
2
-
3
- \`\`\`mermaid
4
- %% @spec-version v1.3.1
5
- stateDiagram-v2
6
- state ImplWorkflow {
7
- [*] --> IngestSpec: [Inherits Parent Context] Ingest Signed .spec.md
8
- IngestSpec --> ParseVersion: Parse Matrix Rows & Version Header
9
- ParseVersion --> VerifyRequest: Verify Code/Chat Request Against Decision Matrix
10
- VerifyRequest -->|Matches 100%| CheckTarget: Check File Target State
11
- VerifyRequest -->|Human Asks to Skip/Add Extraneous Scope| TriggerDefense: Trigger Prompt Injection Defense
12
-
13
- CheckTarget -->|New File| GenerateCode: Generate Full Structural Code from Scratch
14
- CheckTarget -->|Existing File| IdempotentOverwrite: Idempotent Overwrite - Read & Output Full File
15
-
16
- GenerateCode --> GenerateTests: Generate Truth-Table Unit Tests
17
- IdempotentOverwrite --> DataLossCheck: Check for Data Loss Risk
18
- DataLossCheck -->|No Risk| GenerateTests
19
- DataLossCheck -->|Risk Detected| AlertUser: Alert User & Pause Generation
20
-
21
- GenerateTests --> RunTests: Run Generated Tests
22
- RunTests -->|All Pass| PromoteSpec: Promote .spec.md from draft to stable
23
- RunTests -->|Any Fail| FixCode: Fix Code/Tests & Retry
24
-
25
- PromoteSpec --> UpdateVersion: Update SPEC_VERSION to vSameVersion - stable
26
- UpdateVersion --> AppendHistory: Append Audit History: impl complete
27
- AppendHistory --> PersistSpec: Persist Updated .spec.md to Disk
28
- PersistSpec --> AwaitHumanReview: Pause for User Approval Before Lock
29
- }
30
-
31
- state AwaitHumanReview {
32
- [*] --> LockApproved: User approves immutability lock
33
- [*] --> ChangesRequested: User requests changes → loop back to GenerateCode/IdempotentOverwrite
34
- [*] --> Aborted: Terminate session without lock
35
- }
36
-
37
- LockApproved --> LockCodeImmutability: Lock Code Immutability for Stable Version
38
-
39
- state LockCodeImmutability {
40
- [*] --> SetGitHook: Install pre-commit hook blocking edits to stable files
41
- SetGitHook --> SetSpecFlag: Set .spec.md immutable flag (SPEC_IMMUTABLE: true)
42
- SetGitHook --> SetFilePermissions: chmod 444 on production code files
43
- SetFilePermissions --> VerifyLock: Verify git diff shows no modifications
44
- VerifyLock --> LockComplete: Lock verified & confirmed
45
- LockComplete --> [*]
46
- }
47
-
48
- LockCodeImmutability --> [*]
49
-
50
- TriggerDefense --> RefuseCoding: Refuse Coding & Demand Spec Refinement via md-edit
51
- RefuseCoding --> [*]
52
- \`\`\`
53
-
54
- \`\`\`mermaid
55
- %% @spec-version v1.3.1
56
- %% Decision Matrix for CheckTarget: NewFile vs ExistingFile
57
- flowchart TD
58
- R[Check Target Path...] --> A{Evaluate Factors}
59
-
60
- P[Path does not exist on disk] --> A
61
- E[Path exists on disk] --> A
62
-
63
- A -->|"P == true"| NewFile[CheckTarget → NewFile]
64
- A -->|"E == true"| ExistingFile[CheckTarget → ExistingFile]
65
-
66
- style NewFile fill:#0d47a1,color:#fff
67
- style ExistingFile fill:#e65100,color:#fff
68
- \`\`\`
69
-
70
- \`\`\`mermaid
71
- %% @spec-version v1.3.1
72
- %% Decision Matrix for DataLossCheck: No Risk vs Risk Detected
73
- flowchart TD
74
- M[Evaluate Data Loss Risk Factors...] --> A{Aggregate Risk Conditions}
75
-
76
- FF[File exists on disk AND will be overwritten] --> A
77
- C[Code changes detected outside spec scope] --> A
78
- B[No recent git backup / uncommitted changes] --> A
79
- V[User confirmation flag not set] --> A
80
-
81
- A -->|"FF == true OR C == true OR B == true OR V == true"| Risk[Risk Detected → Alert User]
82
- A -->|"FF == false AND C == false AND B == false AND V == false"| NoRisk[No Risk → Proceed to GenerateTests]
83
-
84
- style NoRisk fill:#1b5e20,color:#fff
85
- style Risk fill:#b71c1c,color:#fff
86
- \`\`\`
87
- `;
@@ -1,45 +0,0 @@
1
- export default `[ROLE: ARCHITECT] [STRICT CONTRACT]
2
-
3
- \`\`\`mermaid
4
- %% @spec-version v1.3.1
5
- stateDiagram-v2
6
- [*] --> TargetVerification
7
-
8
- state TargetVerification {
9
- [*] --> CheckFileExistence: Does .spec.md already exist at target path?
10
- FileExists --> Break: Existing .specs are immutable. Switch to edit mode.
11
- FileNotFound --> EvaluateContext: File Does Not Exist
12
- }
13
-
14
- state EvaluateContext {
15
- [*] --> DeepAnalysis: Evaluate target context and goal
16
- DeepAnalysis --> DiagramTypeInference: Infer appropriate diagram type and template
17
- DiagramTypeInference --> InferNodes: Identify key nodes and relationships to be represented
18
- }
19
-
20
- EvaluateContext --> GenerateBlueprint: Create .spec.md from "src/templates/spec-template.md".
21
- GenerateBlueprint --> FormatSpecOutput: Format blueprint into target .spec.md structure
22
- FormatSpecOutput --> CheckDiagram: Use "npx md validate <path/to/spec.md>" to validate diagram syntax
23
-
24
- state CheckDiagram {
25
- [*] --> DiagramValid: Proceed to next step
26
- DiagramInvalid --> GenerateBlueprint: Re-generate blueprint with adjustments until valid
27
- }
28
-
29
- CheckDiagram --> WriteToFile: Write validated .spec.md to target path
30
- WriteToFile --> InitializeVersion: Set initial SPEC_VERSION
31
-
32
- state InitializeVersion {
33
- [*] --> SetDraftVersion: Set SPEC_VERSION to v1.0.0-draft
34
- }
35
-
36
- InitializeVersion --> AppendCreationAudit: Record creation metadata
37
-
38
- state AppendCreationAudit {
39
- [*] --> LogCreation: Append audit entry: "Created via md-new" with timestamp
40
- }
41
-
42
- AppendCreationAudit --> AwaitHumanReview: Pause for user to review and adjust generated diagram
43
- AwaitHumanReview --> [*]
44
- \`\`\`
45
- `;