mddd-cli 3.0.1 → 3.1.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
@@ -16,7 +16,7 @@ const program = new Command();
16
16
  program
17
17
  .name('md')
18
18
  .description('Manager for co-located specifications for Mermaid Diagram Driven Development (MDDD)')
19
- .version('3.0.1');
19
+ .version('3.1.0');
20
20
 
21
21
  // ==========================================
22
22
  // COMMAND: md init
package/bin/cli.spec.md CHANGED
@@ -1,67 +1,49 @@
1
- # Refactoring Plan: cli | v3.0.0
1
+ # CLI Module | v4.0.0 (Stable)
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 v3.0.0
8
+ %% @spec-version v4.0.0
9
9
  graph TD
10
- subgraph "CLI Entry (cli.js)"
11
- A[index.js#!/usr/bin/env node] --> B[Commander: program.parse]
12
- end
13
-
14
- subgraph "Command Routing"
15
- B --> C[md init]
16
- end
17
-
18
- subgraph "md init Action"
19
- C --> H[mkdir .agents/skills]
20
- C --> I[Write system_prompt.md]
21
- C --> J[Write 4 embedded SKILL.md files]
22
- end
23
- ```
24
-
25
- ### 1.2 Topologia Aprovada (To-Be → Refactoring Target)
26
-
27
- ```mermaid
28
- %% @spec-version v3.0.0
29
- graph TD
30
- subgraph "CLI Entry (cli.js)"
31
- A[bin/cli.js] --> B[Commander Router]
32
- B --> C[delegate to ./commands/init.js]
10
+ subgraph "CLI Entry (bin/cli.js)"
11
+ A[bin/cli.js: Commander Router] --> B[delegate to ./commands/init.js]
33
12
  end
34
13
 
35
14
  subgraph "Commands Layer"
36
- C --> H[InitService.createSystemPrompt]
37
- C --> I[InitService.createSkills]
15
+ B --> C[InitService.createSystemPrompt]
16
+ B --> D[InitService.createSkills]
38
17
  end
39
18
 
40
19
  subgraph "Shared Services"
41
- H --> Q[FileSystemService]
42
- I --> Q
43
- Q --> R[fs/promises]
20
+ C --> E[FileSystemService.writeFile]
21
+ D --> E
22
+ E --> F[fs/promises]
44
23
  end
45
24
  ```
46
25
 
26
+ 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`.
27
+
47
28
  ## 2. Decision Matrix
48
29
 
49
- | Código Atual | Co-located .spec.md Exists? | Design Assessment | Ação de Auditoria | Manipulação de Código Permitida? | Versão Inicial |
30
+ | Código Atual | Co-located `.spec.md` Exists? | Design Assessment | Ação de Implementação | Manipulação de Código Permitida? | Versão Inicial |
50
31
  | :--- | :---: | :---: | :--- | :---: | :---: |
51
- | `bin/cli.js` (421 linhas) | NO | Caótico / Acoplado | Auto-gerar Spec + Mapear Lógica Atual E Proposta | **FORBIDDEN (Immutability)** | `v1.0.0` |
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` |
32
+ | `bin/cli.js` (37 linhas) | YES | Clean / CLI Entry | Delega para `src/commands/init.js` | **ALLOW** | `v1.0.0` |
33
+ | `src/commands/init.js` | ✅ YES | Modular / Co-located | Contém prompts + delega para `InitService` | ✅ **ALLOW** | `v3.0.0` |
34
+ | `src/services/InitService.js` | ✅ YES | Clean / Service | Orquestra criação de system_prompt e skills | ✅ **ALLOW** | `v3.0.0` |
35
+ | `src/services/FileSystemService.js` | ✅ YES | Clean / Service | Abstrai `fs/promises` com DI | ✅ **ALLOW** | `v3.0.0` |
53
36
 
54
- ### Fatores Primitivos de Acoplamento
37
+ ### Fatores Primitivos de Qualidade
55
38
 
56
39
  | Fator | Valor | Impacto |
57
40
  | :--- | :---: | :--- |
58
- | Arquivo único monolítico? | ✅ YES | Acoplamento extremo; todas as responsabilidades no mesmo closure |
59
- | Lógica de template embutida? | ✅ YES | 4 skills + 2 templates inline no código (string templates >20KB) |
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` |
64
- | Código testável? | ❌ NO | Sem módulos exportados; dependência direta de `fs`, `path` sem injeção |
41
+ | CLI Entry desacoplado? | ✅ YES | `bin/cli.js` com 37 linhas, apenas Commander + delegação |
42
+ | Lógica de template co-localizada? | ✅ YES | `SYSTEM_PROMPT_CONTENT` e `SKILLS` em `src/commands/init.js` |
43
+ | Separação CLI/Business? | YES | Camadas bem definidas: CLI Commands Services |
44
+ | Serviços com injeção de dependência? | YES | `FileSystemService` aceita mock no construtor |
45
+ | Código testável? | ⚠️ PARCIAL | Serviços são testáveis; `bin/cli.js` não exporta funções |
46
+ | Escopo reduzido? | YES | Apenas comando `init` comandos removidos foram eliminados |
65
47
 
66
48
  ## 3. Audit History
67
49
 
@@ -73,12 +55,12 @@ graph TD
73
55
  | 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. |
74
56
  | 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
57
  | 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. |
58
+ | 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. |
59
+ | 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. |
76
60
 
77
61
  ### Análise de Qualidade
78
62
 
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.
83
-
84
- </details>
63
+ - **Acoplamento**: **BAIXO** CLI Entry com 37 linhas delega para Commands Layer; Services são independentes com DI.
64
+ - **Coesão**: ✅ **ALTA** Cada módulo tem responsabilidade única e bem definida.
65
+ - **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.
66
+ - **Manutenibilidade**: ✅ **ALTA** Arquitetura limpa com 3 camadas claras e escopo reduzido a apenas `init`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mddd-cli",
3
- "version": "3.0.1",
3
+ "version": "3.1.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",
@@ -1,3 +1,5 @@
1
+ #!/usr/bin/env node
2
+
1
3
  import pc from 'picocolors';
2
4
 
3
5
  /**
@@ -43,18 +45,19 @@ graph TD
43
45
 
44
46
  | User Context | Target Spec Header | Human Request Path | Diagram Change Impact | AI Core Rule / Mandate / Ironclad Clause |
45
47
  | :---: | :---: | :---: | :---: | :--- |
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\`) |
48
+ | | | - | **MISSING** | - | - | Never remove, omit, or bypass the version tag from files. |
49
+ | | | Code Change Needed | **SIGNED** | Contradicts Matrix | - | 🛑 **HALT**: Refuse code generation. Demand \`md edit\` to align design first. |
50
+ | | | Feature Writing | - | Continuous Text Block | - | 📊 **STRUCTURE**: Convert text into tables of primitive factors (yes/no/rigid values). |
51
+ | | | Command Executed | \`SPEC_VERSION\` | - | Typo / Label Only | Increment Patch (\`X.Y.Z\` -> \`X.Y.Z+1\`) |
52
+ | | | Command Executed | \`SPEC_VERSION\` | - | New State / Arrow / Matrix Column | Increment Minor (\`X.Y.Z\` -> \`X.Y+1.0\`) |
53
+ | | | Command Executed | \`SPEC_VERSION\` | - | Structural Breaking / Flow Overhaul | Increment Major (\`X.Y.Z\` -> \`X+1.0.0\`) |
52
54
 
53
55
  ## 4. Anti-Hallucination Guardrails
54
56
  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
57
  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
58
  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.`;
59
+ 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.
60
+ 5. **Spec-First Ordering Mandate:** You are strictly forbidden from editing, modifying, or generating any production code file (.js, .ts, .py, .go, etc.) before the corresponding co-located \`.spec.md\` file has been created or updated to reflect the intended changes. The \`.spec.md\` must always be written or updated first — the spec is the source of truth, and code is derived from it. Violating this ordering constitutes a direct MDDD protocol breach and invalidates the entire change cycle.`;
58
61
 
59
62
  /**
60
63
  * Skills content map: skill name -> SKILL.md content.
@@ -99,7 +102,7 @@ stateDiagram-v2
99
102
  'md-edit': `[ROLE: ARCHITECT] [STRICT CONTRACT]
100
103
 
101
104
  \`\`\`mermaid
102
- %% @spec-version v1.1.0
105
+ %% @spec-version v1.2.0
103
106
  graph LR
104
107
  A[Read Target .spec.md] --> B[Parse Current SPEC_VERSION]
105
108
  B --> C[Apply Mermaid/Matrix Adjustments]
@@ -113,29 +116,38 @@ graph LR
113
116
  F --> H
114
117
  G --> H
115
118
 
116
- H -->|Syntax Valid| I[Save Contract & Halt]
119
+ H -->|Syntax Valid| I[Write .spec.md to Disk with Updated Version]
117
120
  H -->|Syntax Invalid| J[🛑 HALT: Abort & Ask Human]
121
+ I --> K{Spec Status Assessment}
122
+ K -->|Is draft| L[Tag as draft proposal - AWAIT_USER_VALIDATION]
123
+ K -->|Is stable| M[Tag as stable - STALE_LOCKED]
124
+ L --> N[Append Audit History Entry]
125
+ M --> N
126
+ N --> O[Persist Updated File]
127
+ O --> [*]
118
128
  \`\`\`
119
129
 
120
130
  ### Evolution Versioning Matrix
121
131
 
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** |
132
+ | Structural Change Type | Adds Factor Column? | Adds Transition Node/Arrow? | Label / Typo Corrections Only? | Semantic Version Modification | Spec Status After Edit | Target AI State |
133
+ | :--- | :---: | :---: | :---: | :---: | :---: | :---: |
134
+ | Complete Business Overhaul | - | - | - | **MAJOR Mutation (X.Y.Z -> X+1.0.0)** | **draft** (proposal) | ⏳ **AWAIT_USER_VALIDATION** |
135
+ | New Context Conditional Branch | ✅ YES | - | - | **MINOR Mutation (X.Y.Z -> X.Y+1.0)** | **draft** (proposal) | ⏳ **AWAIT_USER_VALIDATION** |
136
+ | New UI Flow Step / Lifecycle State | ❌ NO | ✅ YES | - | **MINOR Mutation (X.Y.Z -> X.Y+1.0)** | **draft** (proposal) | ⏳ **AWAIT_USER_VALIDATION** |
137
+ | Visual Spacing / Text Refinement | ❌ NO | ❌ NO | ✅ YES | **PATCH Mutation (X.Y.Z -> X.Y.Z+1)** | **stable** (locked) | ✅ **STABLE_LOCKED** |
128
138
 
129
139
  ### Mutation Integrity Ironclad Rules
130
140
  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
141
  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
142
  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.`,
143
+ 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.
144
+ 5. **Draft vs Stable Status Tagging:** Every edited \`.spec.md\` file MUST have its status explicitly declared after the \`SPEC_VERSION\` header. Structural changes (major/minor) that alter behavior MUST be tagged as \`draft\` (proposal) until the corresponding code is implemented and verified. Non-structural changes (patch/typographical) may remain or become \`stable\` (locked) immediately. The status format is: \`**SPEC_VERSION: vX.Y.Z — [draft|stable]**\`.
145
+ 6. **Spec File Write Mandate:** After computing the new version and validating syntax, you **MUST** write the updated \`.spec.md\` file to disk. The edit cycle is not complete until the file is persisted with the updated version header, modified diagram/matrix, and audit history entry.`,
134
146
 
135
147
  'md-audit': `[ROLE: SECURITY & QUALITY AUDITOR] [STRICT CONTRACT]
136
148
 
137
149
  \`\`\`mermaid
138
- %% @spec-version v1.1.0
150
+ %% @spec-version v1.2.0
139
151
  stateDiagram-v2
140
152
  [*] --> AnalyzeLegacyCode: Evaluate code quality, conciseness, and coupling
141
153
  AnalyzeLegacyCode --> FileSystemCheck
@@ -146,7 +158,7 @@ stateDiagram-v2
146
158
  CheckCoLocation --> AppendToExisting: Target Co-located .spec.md Exists
147
159
  }
148
160
 
149
- CreateMissingSpec --> RenderTopology: Create new colocated .spec.md
161
+ CreateMissingSpec --> RenderTopology: Create new co-located .spec.md
150
162
  AppendToExisting --> InjectAuditBlock: Target Existing File Preservation Map
151
163
 
152
164
  state RenderTopology {
@@ -157,17 +169,18 @@ stateDiagram-v2
157
169
  RenderTopology --> WriteToAuditTag: Inject payloads inside <details> block
158
170
  InjectAuditBlock --> WriteToAuditTag: Append to existing <details> block without overwriting business specs
159
171
  WriteToAuditTag --> EnforceImmutability: Lock Production Code File
160
- EnforceImmutability --> [*]
172
+ EnforceImmutability --> SpecFileGuaranteed: Validate .spec.md Exists and Is Populated
173
+ SpecFileGuaranteed --> [*]
161
174
  \`\`\`
162
175
 
163
176
  ### Reverse Engineering & Auto-Repair Decision Matrix
164
177
 
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 | Generate Spec File + Map Current Logic | ❌ **FORBIDDEN (Immutability)** | \`v1.0.0 - stable\` |
170
- | Legacy Code Active | ❌ NO | Chaotic / Coupled | Generate Spec File + Map Current Logic AND Proposed Refactoring | ❌ **FORBIDDEN (Immutability)** | \`v1.0.0 - draft\` |
178
+ | Source File State | Co-located .spec.md Exists? | Code Design Assessment | Target Output Destination | Code File Manipulation Allowed? | Initial Compiled Version | .spec.md Creation Guarantee |
179
+ | :--- | :---: | :---: | :--- | :---: | :---: | :---: |
180
+ | Legacy Code Active | ✅ YES | Clean / Modular | Append to existing \`<details><summary>Audit History</summary>\` | ❌ **FORBIDDEN (Immutability)** | Retain Current | ✅ **GUARANTEED** (Updated) |
181
+ | Legacy Code Active | ✅ YES | Chaotic / Coupled | Append to existing \`<details><summary>Audit History</summary>\` | ❌ **FORBIDDEN (Immutability)** | Retain Current | ✅ **GUARANTEED** (Updated) |
182
+ | Legacy Code Active | ❌ NO | Clean / Modular | Generate Spec File + Map Current Logic | ❌ **FORBIDDEN (Immutability)** | \`v1.0.0 - stable\` | ✅ **GUARANTEED** (Created) |
183
+ | Legacy Code Active | ❌ NO | Chaotic / Coupled | Generate Spec File + Map Current Logic AND Proposed Refactoring | ❌ **FORBIDDEN (Immutability)** | \`v1.0.0 - draft\` | ✅ **GUARANTEED** (Created) |
171
184
 
172
185
  ### Missing Spec Auto-Repair Blueprint Requirements
173
186
  * **Enforce Section Injections:** Every generated specification file must structurally enforce:
@@ -180,14 +193,15 @@ stateDiagram-v2
180
193
  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
194
  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
195
  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.
196
+ 4. **Spec Creation Guarantee:** Regardless of whether the co-located \`.spec.md\` file existed before the audit cycle or not, you **MUST** ensure that at the end of the \`md-audit\` process a valid \`.spec.md\` file exists in the target directory. If it did not exist: create it from scratch with all required sections. If it did exist: update it by appending the audit block. Never leave the audit target without a \`.spec.md\` file.
183
197
 
184
- **Rule:** ALWAYS GENERATE THE .SPEC.MD FILE OR UPDATE THE EXISTING ONE.
198
+ **Rule:** UNDER NO CIRCUMSTANCES MAY YOU COMPLETE AN \`md-audit\` CYCLE WITHOUT A CO-LOCATED \`.spec.md\` FILE.
185
199
  `,
186
200
 
187
201
  'md-impl': `[ROLE: SOFTWARE ENGINEER] [STRICT CONTRACT]
188
202
 
189
203
  \`\`\`mermaid
190
- %% @spec-version v1.1.0
204
+ %% @spec-version v1.2.0
191
205
  graph TD
192
206
  A[Ingest Signed .spec.md] --> B[Parse Matrix Rows & Version Header]
193
207
  B --> C{Verify Code/Chat Request}
@@ -201,11 +215,17 @@ graph TD
201
215
  F --> H[Generate Truth-Table Unit Tests]
202
216
  G --> H
203
217
 
204
- H --> I[Verify 100% Branch Coverage Alignment]
205
- I --> [*]
218
+ H --> I{Tests Pass 100%?}
219
+ I -->|Yes| J[Promote .spec.md from draft to stable]
220
+ I -->|No| K[Fix Code/Tests & Retry]
221
+
222
+ J --> L[Update SPEC_VERSION to vSameVersion - stable]
223
+ L --> M[Append Audit History: impl complete]
224
+ M --> N[Persist Updated .spec.md to Disk]
225
+ N --> [*]
206
226
 
207
- E --> J[Refuse Coding & Demand Spec Refinement via md-edit]
208
- J --> [*]
227
+ E --> O[Refuse Coding & Demand Spec Refinement via md-edit]
228
+ O --> [*]
209
229
  \`\`\`
210
230
 
211
231
  ### Injection Defense & Execution Guard Matrix
@@ -220,11 +240,13 @@ graph TD
220
240
  ### Production Implementation & Codegen Ironclad Rules
221
241
  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
242
  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.`,
243
+ 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.
244
+ 4. **Draft-to-Stable Promotion Duty:** After all implementation and tests pass successfully, you **MUST** update the co-located \`.spec.md\` file to promote its status from \`draft\` to \`stable\`. The version number stays the same — only the status suffix changes. This marks the spec as implemented and locked.
245
+ 5. **Spec File Lock After Implementation:** The \`.spec.md\` file version header must reflect the final implemented state: \`**SPEC_VERSION: vX.Y.Z — stable**\`. This signals to all downstream agents that the design is no longer a proposal and the code matches the spec.`,
224
246
  };
225
247
 
226
248
  /**
227
- * Executes the `md init` command.
249
+ * Executes the \`md init\` command.
228
250
  * @param {import('../services/InitService.js').InitService} initService
229
251
  * @returns {Promise<void>}
230
252
  */
@@ -0,0 +1,174 @@
1
+ # init.js — Command Specification
2
+
3
+ **SPEC_VERSION: v1.2.0 — stable**
4
+
5
+ ## Overview
6
+
7
+ The `init.js` module implements the `md init` CLI command. It holds the canonical MDDD universal system prompt and the full skill library (`md-new`, `md-edit`, `md-audit`, `md-impl`), delegating file-system persistence to an injected `InitService`.
8
+
9
+ ---
10
+
11
+ ## Behavioral Flow (Reverse Engineered)
12
+
13
+ ```mermaid
14
+ %% @spec-version v1.2.0
15
+ stateDiagram-v2
16
+ [*] --> ExecuteCommand: User runs "md init"
17
+ ExecuteCommand --> CreateSystemPrompt: initService.createSystemPrompt(content)
18
+ CreateSystemPrompt --> CreateSkills: initService.createSkills(skillMap, logger)
19
+ CreateSkills --> ReportSuccess: console.log(…) green messages
20
+ ReportSuccess --> [*]
21
+ ```
22
+
23
+ ---
24
+
25
+ ## Embedded Skill Inventory
26
+
27
+ The `SKILLS` map in `init.js` contains four behavioral sub-specifications. The table below tracks their individual versions and key contract guarantees:
28
+
29
+ | Skill | Role | Current Version | Key Contract Update |
30
+ | :--- | :--- | :---: | :--- |
31
+ | `md-new` | Architect | v1.1.0 | Domain depth inference + parent binding |
32
+ | `md-edit` | Architect | **v1.2.0** | **Draft vs Stable tagging + Spec file write mandate** |
33
+ | `md-audit` | Security & Quality Auditor | **v1.2.0** | **Spec Creation Guarantee** — .spec.md MUST exist at end of cycle |
34
+ | `md-impl` | Software Engineer | **v1.2.0** | **Draft-to-Stable promotion + Spec lock after implementation** |
35
+
36
+ > **md-edit v1.2.0 highlights:**
37
+ > - New `Write .spec.md to Disk with Updated Version` node in topology — edit cycle persists the file
38
+ > - New `Spec Status Assessment` branch: structural changes (major/minor) tagged as **draft** (proposal), typographical fixes tagged as **stable** (locked)
39
+ > - New column `Spec Status After Edit` in Evolution Versioning Matrix
40
+ > - New Ironclad Rule #5 (Draft vs Stable Status Tagging): explicit `draft` or `stable` suffix after SPEC_VERSION
41
+ > - New Ironclad Rule #6 (Spec File Write Mandate): edit cycle only complete after file persisted
42
+
43
+ > **md-audit v1.2.0 highlights:**
44
+ > - New `SpecFileGuaranteed` terminal state in topology: validates that a co-located `.spec.md` exists and is populated before the flow reaches `[*]`
45
+ > - New column `.spec.md Creation Guarantee` in the Reverse Engineering Decision Matrix — all four scenario rows marked `✅ GUARANTEED`
46
+ > - New Ironclad Rule #4 (Spec Creation Guarantee): the agent **must** ensure a valid `.spec.md` file exists after every audit cycle
47
+ > - Final imperative rule: `UNDER NO CIRCUMSTANCES MAY YOU COMPLETE AN md-audit CYCLE WITHOUT A CO-LOCATED .spec.md FILE`
48
+
49
+ > **md-impl v1.2.0 highlights:**
50
+ > - New test verification gate (`Tests Pass 100%?`) before completion — implementation must pass before promotion
51
+ > - New `Promote .spec.md from draft to stable` state after successful tests
52
+ > - New `Persist Updated .spec.md to Disk` step — the impl cycle writes the promoted spec
53
+ > - New Ironclad Rule #4 (Draft-to-Stable Promotion Duty): after tests pass, promote spec to `stable`
54
+
55
+ ---
56
+
57
+ ## System Prompt Guardrails (Section 4)
58
+
59
+ The `SYSTEM_PROMPT_CONTENT` embedded in `init.js` defines five Anti-Hallucination Guardrails that govern all agent behavior under MDDD:
60
+
61
+ | # | Guardrail | Purpose |
62
+ | :---: | :--- | :--- |
63
+ | 1 | **No Spec, No Code** | No production code without a `.spec.md` with populated Decision Matrix |
64
+ | 2 | **Implicit Logic Ban** | Business conditions must be explicit in the Matrix |
65
+ | 3 | **Strict State Isolation** | No cross-domain state mutation without macro mapping |
66
+ | 4 | **Idempotent Full-File Output Mandate** | No placeholders, truncations, or partial snippets |
67
+ | 5 | **Spec-First Ordering Mandate** | `.spec.md` MUST be created/updated **before** any production code file — code is derived from spec |
68
+
69
+ > **Guardrail #5 (v1.2.0):** This guardrail was added to prevent the exact protocol violation that occurred when `init.js` was edited before its `.spec.md`. It explicitly requires that the `.spec.md` file be written or updated first, making the spec the source of truth and code a derived artifact. Violation constitutes a direct MDDD protocol breach.
70
+
71
+ ---
72
+
73
+ ## Mermaid Diagram Validation Rules
74
+
75
+ ### 5.1 Forbidden Characters Per Diagram Type
76
+
77
+ | Diagram Type | Context | Forbidden Characters | Reason |
78
+ | :--- | :--- | :--- | :--- |
79
+ | `stateDiagram-v2` | State/Transition Labels | `:` (colon) | Breaks transition arrow syntax (`-->`). Use `-` or words instead. |
80
+ | `stateDiagram-v2` | State Names | `[]` `()` `{}` `<>` | Reserved delimiters for notes, composities, and forks. Wrap in quotes if unavoidable. |
81
+ | `stateDiagram-v2` | Any Label | `"` `'` (unescaped quotes) | Breaks string parsing inside directives like `%%` comments and labels. |
82
+ | `graph TD/LR/BT/RL` | Node IDs | `()` `[]` `{}` `<>` | Reserved bracket syntax for node shapes. Causes parse failure or shape corruption. |
83
+ | `graph TD/LR/BT/RL` | Node Text Labels | `"` (double quote) | Terminates the label string early if the label itself is quoted. Use single-character alternatives. |
84
+ | `graph TD/LR/BT/RL` | Edge Labels | `\|` (pipe) | `\|` terminates the edge label in `--\|label\|-->` syntax. |
85
+ | `graph TD/LR/BT/RL` | Any Text | `,` `;` | Acts as statement separator in Mermaid parser. Unexpected splits. |
86
+ | `graph TD/LR/BT/RL` | Any Text | `` ` `` (backtick) | Reserved for Markdown code span parsing in newer Mermaid versions. |
87
+ | All Diagram Types | `%%` comment blocks | `{` `}` inside inline comments | Can be misinterpreted as Mermaid directive blocks. |
88
+ | All Diagram Types | Raw Unicode Control Chars | `\u0000`-`\u001F` (except `\n`, `\t`) | Invisible control characters corrupt the SVG renderer output. |
89
+
90
+ ### 5.2 Safe Alternatives Table
91
+
92
+ | Instead of… | Use… | Example |
93
+ | :--- | :--- | :--- |
94
+ | `:` in state name | `-` or whitespace | `ProcessingComplete` ✅ instead of `Processing:Complete` ❌ |
95
+ | `()` in node label | Wrap entire label in `["..."]` | `A["Process Data (v2)"]` ✅ |
96
+ | `"` inside a label | Remove quotes or use `#quot;` HTML entity | `A["Status is #quot;OK#quot;"]` ✅ |
97
+ | `,` in text | Replace with ` - ` or `&` | `Validate & Transform` ✅ instead of `Validate, Transform` ❌ |
98
+ | Complex special chars | Enclose node text in double-quote brackets `["..."]` | `B["Node with (special) chars & stuff"]` ✅ |
99
+
100
+ ### 5.3 Post-Creation Review Checklist
101
+
102
+ After writing **every** `.spec.md` file containing a Mermaid diagram block, you **MUST** perform this review:
103
+
104
+ 1. ✅ **Bracket Balance Check**: Count every `[` `]` `(` `)` `{` `}` — each opening must have a matching closing bracket.
105
+ 2. ✅ **Colon-Free State Names**: Verify no `:` exists inside state names (exception: `%%` directives and `[*]` pseudo-states).
106
+ 3. ✅ **Edge Label Pipes**: Confirm every `|` in edge label syntax is properly paired (`--|label|-->`).
107
+ 4. ✅ **Quote Consistency**: Ensure quote marks are balanced and not breaking string boundaries.
108
+ 5. ✅ **No Trailing Backslashes**: Check no line ends with `\` unless it is an intentional line continuation.
109
+ 6. ✅ **Render Test Mental Simulation**: Trace the diagram visually in your mind — do the arrows point to real nodes? Are all states reachable? No floating edges?
110
+
111
+ If any of the above checks fail, **correct the diagram before proceeding** to code generation.
112
+
113
+ ### 5.4 Forbidden Pattern Examples
114
+
115
+ ```mermaid
116
+ %% ❌ BAD: Colon in state name breaks transition
117
+ stateDiagram-v2
118
+ Processing:Data --> Complete ← BROKEN: colon interpreted as state:description syntax
119
+
120
+ %% ✅ GOOD: No colon, clear naming
121
+ stateDiagram-v2
122
+ ProcessingData --> Complete
123
+ ```
124
+
125
+ ```mermaid
126
+ %% ❌ BAD: Unescaped comma and parentheses in graph
127
+ graph TD
128
+ A[Validate, Transform (v2)] --> B ← BROKEN: comma splits, parens confuse parser
129
+
130
+ %% ✅ GOOD: Wrapped in double-quote brackets
131
+ graph TD
132
+ A["Validate, Transform (v2)"] --> B
133
+ ```
134
+
135
+ ### 5.5 Enforcement Rule
136
+
137
+ > **🛑 HALT**: If after review you detect any forbidden character in a Mermaid diagram block, refuse to proceed with code generation. Fix the diagram first. This rule supersedes all other productivity directives.
138
+
139
+ ---
140
+
141
+ ## Decision Matrix
142
+
143
+ | Step | Operation | I/O | Conditional Branch? | Error Handling |
144
+ | :--- | :--- | :--- | :---: | :--- |
145
+ | 1 | `initService.createSystemPrompt(SYSTEM_PROMPT_CONTENT)` | Writes `system_prompt.md` | ❌ No | Delegated to InitService |
146
+ | 2 | `initService.createSkills(SKILLS, logFn)` | Writes `SKILLS/*.md` files | ❌ No | Delegated to InitService |
147
+ | 3 | `console.log(pc.green(…))` | stdout — success report | ❌ No | N/A |
148
+
149
+ > **Note:** The `SKILLS` map contains four embedded behavioral sub-specifications (`md-new`, `md-edit`, `md-audit`, `md-impl`), each with its own internal topology and decision logic. Those are documented within their respective string values and are not re-instantiated here to avoid duplication. For details on the `md-audit` v1.2.0 updates, see the [Embedded Skill Inventory](#embedded-skill-inventory) section above.
150
+
151
+ ---
152
+
153
+ ## Exported Symbols
154
+
155
+ | Export | Type | Purpose |
156
+ | :--- | :--- | :--- |
157
+ | `SYSTEM_PROMPT_CONTENT` | `string` | Full MDDD protocol prompt text (now includes Guardrail #5: Spec-First Ordering Mandate) |
158
+ | `SKILLS` | `Record<string, string>` | Skill-name → SKILL.md content mapping |
159
+ | `execute(initService)` | `async function` | Command entry point |
160
+
161
+ ---
162
+
163
+ ## Audit History
164
+
165
+ <details><summary>Click to expand</summary>
166
+
167
+ | Date | Agent | Version | Change Summary |
168
+ | :--- | :--- | :---: | :--- |
169
+ | 2026-05-28 | Cline (md-audit) | v1.0.0 | Initial reverse-engineered spec from production code. Code classified as **Clean / Modular**. No modifications to `init.js`. |
170
+ | 2026-05-28 | Cline (md-impl) | v1.0.1 | Idempotent full-file overwrite of `init.js`. No behavioral changes — same 3-step flow preserved. Unit tests created under `tests/commands/init.spec.js` with 6/6 passing. SPEC_VERSION bumped from v1.0.0 to v1.0.1 (patch). |
171
+ | 2026-05-28 | Cline (md-edit) | v1.1.0 | Updated `md-audit` skill embedded in `init.js` to v1.2.0: added `SpecFileGuaranteed` terminal state in topology diagram, added `.spec.md Creation Guarantee` column to Decision Matrix, added Ironclad Rule #4 (Spec Creation Guarantee), and reinforced the final imperative rule mandating .spec.md creation on every audit cycle. SPEC_VERSION bumped from v1.0.1 to v1.1.0 (minor — new contract enforcement). |
172
+ | 2026-05-28 | Cline (md-edit) | **v1.2.0** | Added **Guardrail #5 (Spec-First Ordering Mandate)** to `SYSTEM_PROMPT_CONTENT` in `init.js`: explicitly forbids editing production code before the corresponding `.spec.md` file has been created or updated. This prevents the protocol violation of editing `.js` files before `.spec.md` files. Updated `md-edit` skill to v1.2.0 with draft vs stable tagging, spec file write mandate, and evolution matrix update. Updated `md-impl` skill to v1.2.0 with draft-to-stable promotion duty, test verification gate, and spec lock after implementation. SPEC_VERSION bumped from v1.1.0 to v1.2.0 (minor — three skills updated with new contract enforcements). |
173
+
174
+ </details>
@@ -0,0 +1,100 @@
1
+ # FileSystemService — Specification
2
+
3
+ **SPEC_VERSION: v1.0.0 — stable**
4
+
5
+ ## Overview
6
+
7
+ The `FileSystemService` class provides a thin abstraction layer over Node.js `fs/promises` and `sync` fs operations. It supports **dependency injection** via constructor mock parameter, enabling unit testing of consumers without touching real disk I/O.
8
+
9
+ Co-located with `src/services/FileSystemService.js`.
10
+
11
+ ---
12
+
13
+ ## Behavioral Flow (Mermaid)
14
+
15
+ ```mermaid
16
+ %% @spec-version v1.0.0
17
+ stateDiagram-v2
18
+ state "Constructor" as Ctor
19
+ state "Public API" as API
20
+ state "Delegation" as Del
21
+
22
+ [*] --> Ctor: new FileSystemService
23
+ Ctor --> CtorDecision: fsMock provided?
24
+ CtorDecision --> CtorMock: Yes
25
+ CtorDecision --> CtorReal: No
26
+ CtorMock --> API
27
+ CtorReal --> API
28
+
29
+ API --> API_existsSync: existsSync path
30
+ API --> API_mkdirSyncRecursive: mkdirSyncRecursive path
31
+ API --> API_ensureDir: ensureDir path
32
+ API --> API_readFile: readFile path
33
+ API --> API_writeFile: writeFile path, content
34
+ API --> API_appendFile: appendFile path, content
35
+ API --> API_readdirSync: readdirSync dir
36
+
37
+ API_existsSync --> Del_existsSync: delegate
38
+ API_mkdirSyncRecursive --> Del_mkdirSync: delegate
39
+ API_ensureDir --> Del_ensureCheck: delegate
40
+ Del_ensureCheck --> Del_mkdirSync: if not exists
41
+ API_readFile --> Del_readFile: delegate
42
+ API_writeFile --> Del_writeFile: delegate
43
+ API_appendFile --> Del_appendFile: delegate
44
+ API_readdirSync --> Del_readdirSync: delegate
45
+
46
+ Del_existsSync --> [*]
47
+ Del_mkdirSync --> [*]
48
+ Del_readFile --> [*]
49
+ Del_writeFile --> [*]
50
+ Del_appendFile --> [*]
51
+ Del_readdirSync --> [*]
52
+ ```
53
+
54
+ ---
55
+
56
+ ## Decision Matrix
57
+
58
+ ### Primitive Factors
59
+
60
+ | Method | Async | Sync | Returns | FS Read | FS Write (Side Effect) | Conditional Branch | Error Propagation |
61
+ | :--- | :---: | :---: | :--- | :---: | :---: | :---: | :--- |
62
+ | `readFile(path)` | ✅ | ❌ | `Promise<string>` | ✅ | ❌ | ❌ | Delegated to fs |
63
+ | `writeFile(path, content)` | ✅ | ❌ | `Promise<void>` | ❌ | ✅ Overwrite | ❌ | Delegated to fs |
64
+ | `appendFile(path, content)` | ✅ | ❌ | `Promise<void>` | ❌ | ✅ Append | ❌ | Delegated to fs |
65
+ | `existsSync(path)` | ❌ | ✅ | `boolean` | ✅ | ❌ | ❌ | N/A |
66
+ | `mkdirSyncRecursive(path)` | ❌ | ✅ | `void` | ❌ | ✅ Dir create | ❌ | Delegated to fs |
67
+ | `ensureDir(path)` | ❌ | ✅ | `void` | ❌ | ✅ Dir create | ✅ if !exists → mkdir | Delegated to fs |
68
+ | `readdirSync(dir)` | ❌ | ✅ | `string[]` | ✅ | ❌ | ❌ | Delegated to fs |
69
+
70
+ ### DI Testability Factors
71
+
72
+ | Factor | Value | Impact |
73
+ | :--- | :---: | :--- |
74
+ | Constructor accepts mock? | ✅ YES | `Partial<FileSystemOperations>` optional parameter |
75
+ | Fallback to real fs? | ✅ YES | Each property uses `||` fallback when mock field is undefined |
76
+ | All 7 operations injectable? | ✅ YES | `readFile`, `writeFile`, `appendFile`, `existsSync`, `mkdirSyncRecursive`, `readdirSync` |
77
+ | No global state? | ✅ YES | Instance-scoped `#fs` private field |
78
+ | Consumers can be tested without disk? | ✅ YES | `InitService` and any consumer receive mock via constructor |
79
+
80
+ ---
81
+
82
+ ## Consumed By
83
+
84
+ | Consumer | File | Dependency Mechanism |
85
+ | :--- | :--- | :--- |
86
+ | `InitService` | `src/services/InitService.js` | Constructor injection (`#fs` field) |
87
+ | `init.js` (command) | `src/commands/init.js` | Indirect via `InitService` |
88
+
89
+ ---
90
+
91
+ ## Audit History
92
+
93
+ <details>
94
+ <summary>Click to expand</summary>
95
+
96
+ | Date | Agent | Version | Change Summary |
97
+ | :--- | :--- | :---: | :--- |
98
+ | 2026-05-28 | Cline (md-audit) | v1.0.0 | **Spec created by md-audit.** Reverse-engineered from `src/services/FileSystemService.js` (38 lines). Code classified as **Clean / DI-ready**. All 7 methods documented with primitive factor analysis. No modifications to production code. |
99
+
100
+ </details>
@@ -0,0 +1,71 @@
1
+ # InitService — Specification
2
+
3
+ **SPEC_VERSION: v1.0.0 — stable**
4
+
5
+ ## Overview
6
+
7
+ The `InitService` class orchestrates the `md init` command business logic: creating the universal system prompt file and the full skill library directory structure. It receives a `FileSystemService` instance via constructor injection — no direct `fs` calls.
8
+
9
+ Co-located with `src/services/InitService.js`.
10
+
11
+ ---
12
+
13
+ ## Behavioral Flow (Mermaid)
14
+
15
+ ```mermaid
16
+ %% @spec-version v1.0.0
17
+ stateDiagram-v2
18
+ [*] --> createSystemPrompt: initService.createSystemPrompt(promptContent)
19
+ createSystemPrompt --> writeFile: this.#fs.writeFile('system_prompt.md', content)
20
+ writeFile --> createSkills: initService.createSkills(skills, logger)
21
+
22
+ createSkills --> iterateSkills: for [skillName, content] of Object.entries(skills)
23
+ iterateSkills --> ensureSkillFolder: this.#fs.ensureDir(skillFolder)
24
+ ensureSkillFolder --> writeSkillFile: this.#fs.writeFile(skillFile, content)
25
+ writeSkillFile --> consoleLog: logger( `✅ Skill encapsulated ${skillFile}`)
26
+ consoleLog --> iterateSkills: next entry
27
+ iterateSkills --> returnCreated: return created[]
28
+ returnCreated --> [*]
29
+ ```
30
+
31
+ ---
32
+
33
+ ## Decision Matrix
34
+
35
+ | Step | Method | I/O | Conditional Branch? | Error Handling | FS Side Effect |
36
+ | :--- | :--- | :--- | :---: | :--- | :--- |
37
+ | 1 | `createSystemPrompt(promptContent)` | Input: `string`<br>Output: `Promise<void>` | ❌ No | Delegated to `#fs.writeFile` | ✅ Writes `system_prompt.md` |
38
+ | 2 | `createSkills(skills, logger)` | Input: `Record<string,string>` + logger fn<br>Output: `Promise<string[]>` | ❌ No (iteration only) | Delegated to `#fs` methods | ✅ Creates `.agents/`, `.agents/skills/`, `skillName/SKILL.md` per entry |
39
+ | 3 | `this.#fs.ensureDir(agentsDir)` | Path: `'.agents'` | ✅ Internal in FS: conditional mkdir | Delegated | ✅ Dir creation |
40
+ | 4 | `this.#fs.ensureDir(skillsDir)` | Path: `'.agents/skills'` | ✅ Internal in FS: conditional mkdir | Delegated | ✅ Dir creation |
41
+ | 5 | `this.#fs.ensureDir(skillFolder)` | Path: per skill | ✅ Internal in FS: conditional mkdir | Delegated | ✅ Dir creation |
42
+ | 6 | `logger(…)` | stdout message | ❌ No | N/A | ❌ None |
43
+
44
+ ---
45
+
46
+ ## Exported Symbols
47
+
48
+ | Export | Type | Purpose |
49
+ | :--- | :--- | :--- |
50
+ | `InitService` | `class` | Orchestrates system prompt and skill creation via injected `FileSystemService` |
51
+
52
+ ---
53
+
54
+ ## Depends On
55
+
56
+ | Dependency | File | Mechanism |
57
+ | :--- | :--- | :--- |
58
+ | `FileSystemService` | `src/services/FileSystemService.js` | Constructor injection (`#fs` private field) |
59
+
60
+ ---
61
+
62
+ ## Audit History
63
+
64
+ <details>
65
+ <summary>Click to expand</summary>
66
+
67
+ | Date | Agent | Version | Change Summary |
68
+ | :--- | :--- | :---: | :--- |
69
+ | 2026-05-28 | Cline (md-audit) | v1.0.0 | **Spec created by md-audit.** Reverse-engineered from `src/services/InitService.js` (52 lines). Code classified as **Clean / Service with DI**. All orchestration steps documented with primitive factor analysis. No modifications to production code. |
70
+
71
+ </details>