awc-zns-mtd 2.8.0 → 2.10.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.
Files changed (40) hide show
  1. package/.github/workflows/ci.yml +148 -0
  2. package/.husky/pre-commit +2 -0
  3. package/.prettierignore +31 -0
  4. package/.prettierrc +13 -0
  5. package/IMPLEMENTATION_SUMMARY.md +410 -0
  6. package/PHASE_2_SUMMARY.md +289 -0
  7. package/README.md +114 -47
  8. package/SECURITY.md +58 -0
  9. package/eslint.config.js +70 -0
  10. package/jest.config.js +49 -0
  11. package/package.json +40 -14
  12. package/src/modules/awc-zns-mtd/config.yaml +1 -1
  13. package/src/modules/custom-agents/cli/awc-agent.js +505 -372
  14. package/test/integration/cli/cli-commands.integration.test.js +101 -0
  15. package/test/setup.js +22 -0
  16. package/test/unit/commands/version.test.js +39 -0
  17. package/test/unit/config/config-manager.test.js +147 -0
  18. package/test/unit/utils/file-utils.test.js +177 -0
  19. package/test/unit/utils/validators.test.js +57 -0
  20. package/tools/cli/commands/init.js +556 -513
  21. package/tools/cli/commands/new-project.js +680 -659
  22. package/tools/cli/commands/status.js +3 -3
  23. package/tools/cli/commands/validate.js +14 -14
  24. package/tools/cli/commands/version.js +6 -4
  25. package/tools/cli/utils/console-logger.js +41 -17
  26. package/tools/cli/utils/logger.js +176 -0
  27. package/tools/cli/utils/project-analyzer.js +33 -16
  28. package/tools/cli/utils/validators.js +144 -0
  29. package/tools/cli/utils/version.js +6 -2
  30. package/tools/config/config-manager.js +243 -0
  31. package/tools/version/changelog-manager.js +301 -288
  32. package/tools/version/update-checker.js +32 -32
  33. package/tools/version/version-bump.js +89 -90
  34. package/tools/version/version-manager.js +17 -7
  35. package/tsconfig.json +47 -0
  36. package/types/index.d.ts +206 -0
  37. package/tools/cli/commands/init-old.js +0 -147
  38. package/tools/cli/commands/new-project-broken.js +0 -1302
  39. package/tools/cli/commands/new-project-old.js +0 -1302
  40. package/tools/cli/commands/new-project.js.backup +0 -1302
@@ -1,659 +1,680 @@
1
- /**
2
- * Comando: new
3
- * Crea un nuevo directorio de proyecto con configuración base AWC ZNS-MTD
4
- */
5
-
6
- const fs = require('fs-extra');
7
- const path = require('path');
8
- const chalk = require('chalk');
9
- const ora = require('ora');
10
- const inquirer = require('inquirer');
11
- const { displayLogo } = require('../utils/console-logger');
12
- const { getVersion } = require('../utils/version');
13
-
14
- /**
15
- * Comando principal para crear nuevo proyecto
16
- */
17
- async function newProjectCommand(projectName, options = {}) {
18
- displayLogo();
19
-
20
- console.log(chalk.cyan('\n🚀 Crear Nuevo Proyecto AWC ZNS-MTD\n'));
21
-
22
- // Preguntar nombre del proyecto si no se proporcionó
23
- if (!projectName) {
24
- const { name } = await inquirer.prompt([
25
- {
26
- type: 'input',
27
- name: 'name',
28
- message: '📦 Nombre del proyecto:',
29
- validate: (input) => {
30
- if (!input.trim()) return 'El nombre del proyecto es requerido';
31
- if (!/^[a-zA-Z0-9-_]+$/.test(input)) {
32
- return 'Solo se permiten letras, números, guiones y guiones bajos';
33
- }
34
- return true;
35
- }
36
- }
37
- ]);
38
- projectName = name;
39
- }
40
-
41
- // Verificar si el directorio ya existe
42
- const projectPath = path.join(process.cwd(), projectName);
43
- if (await fs.pathExists(projectPath)) {
44
- console.log(chalk.red(`\n❌ El directorio '${projectName}' ya existe.\n`));
45
- process.exit(1);
46
- }
47
-
48
- // Preguntar responsable del proyecto
49
- const { responsible, description, gitInit } = await inquirer.prompt([
50
- {
51
- type: 'input',
52
- name: 'responsible',
53
- message: '👤 Responsable del proyecto:',
54
- validate: (input) => {
55
- if (!input.trim()) return 'El responsable es requerido';
56
- return true;
57
- }
58
- },
59
- {
60
- type: 'input',
61
- name: 'description',
62
- message: '📝 Descripción breve (opcional):',
63
- default: `Proyecto ${projectName}`
64
- },
65
- {
66
- type: 'confirm',
67
- name: 'gitInit',
68
- message: '🔧 Inicializar repositorio Git?',
69
- default: true
70
- }
71
- ]);
72
-
73
- const spinner = ora('Creando estructura base del proyecto...').start();
74
-
75
- try {
76
- // 1. Crear directorio raíz del proyecto
77
- await fs.ensureDir(projectPath);
78
- spinner.text = `Directorio ${projectName} creado`;
79
-
80
- // 2. Crear estructura base mínima
81
- const baseDirectories = [
82
- '.awc/agents',
83
- '.awc/workflows',
84
- '.awc/templates',
85
- 'docs'
86
- ];
87
-
88
- for (const dir of baseDirectories) {
89
- await fs.ensureDir(path.join(projectPath, dir));
90
- }
91
- spinner.text = 'Estructura base creada';
92
-
93
- // 3. Copiar agentes base (4 agentes core)
94
- const srcAgentsPath = path.join(__dirname, '../../../src/modules/awc-zns-mtd/agents');
95
- const destAgentsPath = path.join(projectPath, '.awc/agents');
96
-
97
- if (await fs.pathExists(srcAgentsPath)) {
98
- await fs.copy(srcAgentsPath, destAgentsPath);
99
- spinner.text = 'Agentes base copiados';
100
- }
101
-
102
- // 4. Copiar agentes especializados (22 agentes)
103
- const srcCustomAgentsPath = path.join(__dirname, '../../../src/modules/custom-agents/cli/.awc-agents');
104
- const destCustomAgentsPath = path.join(projectPath, '.awc/agents/specialized');
105
-
106
- if (await fs.pathExists(srcCustomAgentsPath)) {
107
- await fs.copy(srcCustomAgentsPath, destCustomAgentsPath);
108
- spinner.text = 'Agentes especializados copiados';
109
- }
110
-
111
- // 5. Copiar workflows
112
- const srcWorkflowsPath = path.join(__dirname, '../../../src/modules/awc-zns-mtd/workflows');
113
- const destWorkflowsPath = path.join(projectPath, '.awc/workflows');
114
-
115
- if (await fs.pathExists(srcWorkflowsPath)) {
116
- await fs.copy(srcWorkflowsPath, destWorkflowsPath);
117
- spinner.text = 'Workflows copiados';
118
- }
119
-
120
- // 6. Copiar templates
121
- const srcTemplatesPath = path.join(__dirname, '../../../src/modules/awc-zns-mtd/templates');
122
- const destTemplatesPath = path.join(projectPath, '.awc/templates');
123
-
124
- if (await fs.pathExists(srcTemplatesPath)) {
125
- await fs.copy(srcTemplatesPath, destTemplatesPath);
126
- spinner.text = 'Templates copiados';
127
- }
128
-
129
- // 7. Crear archivo de configuración AWC
130
- const awcConfig = {
131
- version: getVersion(),
132
- createdAt: new Date().toISOString(),
133
- project: {
134
- name: projectName,
135
- description: description,
136
- responsible: responsible
137
- },
138
- projectType: null,
139
- initialized: false,
140
- preferences: {
141
- communication_language: 'Spanish',
142
- document_output_language: 'Spanish',
143
- code_language: 'English'
144
- },
145
- workflows: {
146
- current_phase: null,
147
- completed_phases: []
148
- }
149
- };
150
-
151
- await fs.writeJson(
152
- path.join(projectPath, '.awc/config.json'),
153
- awcConfig,
154
- { spaces: 2 }
155
- );
156
- spinner.text = 'Configuración AWC creada';
157
-
158
- // 8. Crear README.md del proyecto
159
- const readme = createReadmeContent(projectName, responsible, description);
160
- await fs.writeFile(path.join(projectPath, 'README.md'), readme);
161
- spinner.text = 'README.md creado';
162
-
163
- // 9. Crear .gitignore
164
- const gitignore = createGitignoreContent();
165
- await fs.writeFile(path.join(projectPath, '.gitignore'), gitignore);
166
- spinner.text = '.gitignore creado';
167
-
168
- // 10. Crear configuración de VS Code
169
- await createVSCodeConfig(projectPath, projectName);
170
- spinner.text = 'Configuración VS Code creada';
171
-
172
- // 11. Generar copilot-instructions.md con agentes embebidos
173
- const githubDir = path.join(projectPath, '.github');
174
- await fs.ensureDir(githubDir);
175
- const copilotInstructions = await generateCopilotInstructions(projectPath);
176
- await fs.writeFile(path.join(githubDir, 'copilot-instructions.md'), copilotInstructions);
177
- spinner.text = 'GitHub Copilot instructions creadas';
178
-
179
- // 12. Crear archivo NEXT_STEPS.md
180
- const nextSteps = createNextStepsContent(projectName);
181
- await fs.writeFile(path.join(projectPath, 'NEXT_STEPS.md'), nextSteps);
182
- spinner.text = 'Guía de próximos pasos creada';
183
-
184
- // 13. Inicializar Git si se solicitó
185
- if (gitInit) {
186
- const { execSync } = require('child_process');
187
- try {
188
- execSync('git init', { cwd: projectPath, stdio: 'ignore' });
189
- execSync('git add .', { cwd: projectPath, stdio: 'ignore' });
190
- execSync(`git commit -m "feat: Inicializar proyecto ${projectName} con AWC ZNS-MTD"`, {
191
- cwd: projectPath,
192
- stdio: 'ignore'
193
- });
194
- spinner.text = 'Repositorio Git inicializado';
195
- } catch (error) {
196
- // Git no está disponible o fallo, continuar sin git
197
- }
198
- }
199
-
200
- spinner.succeed(chalk.green('✅ Proyecto creado exitosamente'));
201
-
202
- // Mostrar resumen
203
- console.log(chalk.cyan('\n' + ''.repeat(60)));
204
- console.log(chalk.cyan('📦 Proyecto Creado'));
205
- console.log(chalk.cyan('═'.repeat(60) + '\n'));
206
-
207
- console.log(`${chalk.gray('Nombre:')} ${chalk.green(projectName)}`);
208
- console.log(`${chalk.gray('Responsable:')} ${chalk.yellow(responsible)}`);
209
- console.log(`${chalk.gray('Ubicación:')} ${chalk.blue(projectPath)}`);
210
- console.log(`${chalk.gray('AWC Versión:')} ${chalk.yellow(getVersion())}\n`);
211
-
212
- // Próximos pasos
213
- console.log(chalk.cyan('📚 Próximos Pasos:\n'));
214
- console.log(` ${chalk.green('1.')} cd ${projectName}`);
215
- console.log(` ${chalk.green('2.')} zns init ${chalk.gray('# Inicializar tipo de proyecto')}`);
216
- console.log(` ${chalk.green('3.')} Leer ${chalk.yellow('NEXT_STEPS.md')} para más detalles\n`);
217
-
218
- console.log(chalk.yellow('⚠️ La estructura de fases se creará al ejecutar') + chalk.green(' zns init\n'));
219
-
220
- } catch (error) {
221
- spinner.fail(chalk.red('❌ Error creando proyecto'));
222
- console.error(error);
223
- throw error;
224
- }
225
- }
226
-
227
- /**
228
- * Crea el contenido del README.md
229
- */
230
- function createReadmeContent(projectName, responsible, description) {
231
- return `# ${projectName}
232
-
233
- > ${description}
234
-
235
- ## 📋 Información del Proyecto
236
-
237
- - **Responsable**: ${responsible}
238
- - **Metodología**: AWC ZNS-MTD (Minimalismo Estratégico)
239
- - **Estado**: Pendiente de inicialización
240
-
241
- ## 🚀 Próximos Pasos
242
-
243
- Este proyecto ha sido creado con la estructura base de AWC ZNS-MTD.
244
-
245
- ### 1. Inicializar Tipo de Proyecto
246
-
247
- \`\`\`bash
248
- zns init
249
- \`\`\`
250
-
251
- El comando \`zns init\` te preguntará:
252
- - Tipo de proyecto (auditoría, desarrollo nuevo, migración, etc.)
253
- - Tecnologías a utilizar
254
- - Tipo de workflow (quick, standard, enterprise)
255
-
256
- Basado en tus respuestas, creará automáticamente:
257
- - ✅ Estructura de directorios por fase
258
- - ✅ Directorios client-docs específicos
259
- - ✅ Templates relevantes para tu proyecto
260
- - ✅ Workflows configurados
261
-
262
- ### 2. Comenzar a Trabajar
263
-
264
- Una vez inicializado, seguir las guías en cada fase del proyecto.
265
-
266
- ## 🔧 Configuración AWC
267
-
268
- El directorio \`.awc/\` contiene:
269
-
270
- - \`agents/\` - 4 agentes base + 22 agentes especializados
271
- - \`workflows/\` - 8 workflows completos
272
- - \`templates/\` - 7 templates profesionales
273
- - \`config.json\` - Configuración del proyecto
274
-
275
- ## 📝 Comandos Disponibles
276
-
277
- \`\`\`bash
278
- # Inicializar proyecto (siguiente paso)
279
- zns init
280
-
281
- # Ver estado del proyecto
282
- zns status
283
-
284
- # Validar estructura
285
- zns validate
286
-
287
- # Ver configuración
288
- zns config
289
- \`\`\`
290
-
291
- ---
292
-
293
- Generado con ❤️ usando AWC ZNS-MTD Method v${getVersion()}
294
- `;
295
- }
296
-
297
- /**
298
- * Crea el contenido del .gitignore
299
- */
300
- function createGitignoreContent() {
301
- return `# Dependencies
302
- node_modules/
303
- vendor/
304
- bower_components/
305
-
306
- # Build outputs
307
- dist/
308
- build/
309
- out/
310
- target/
311
- *.exe
312
- *.dll
313
- *.so
314
- *.dylib
315
-
316
- # IDE
317
- .vscode/
318
- .idea/
319
- *.swp
320
- *.swo
321
- *~
322
-
323
- # Logs
324
- logs/
325
- *.log
326
- npm-debug.log*
327
- yarn-debug.log*
328
- yarn-error.log*
329
-
330
- # Environment variables
331
- .env
332
- .env.local
333
- .env.*.local
334
-
335
- # OS
336
- Thumbs.db
337
- .DS_Store
338
-
339
- # Temporary files
340
- tmp/
341
- temp/
342
- *.tmp
343
-
344
- # Coverage
345
- coverage/
346
- *.lcov
347
- .nyc_output/
348
-
349
- # Confidential (keep locally, never commit)
350
- **/client-docs/contratos/
351
- **/client-docs/accesos/
352
- **/*-confidential.*
353
- `;
354
- }
355
-
356
- /**
357
- * Crea contenido de NEXT_STEPS.md
358
- */
359
- function createNextStepsContent(projectName) {
360
- return `# 🎯 Próximos Pasos - ${projectName}
361
-
362
- ## ¿Qué hacer ahora?
363
-
364
- Tu proyecto ha sido creado con la **estructura base** de AWC ZNS-MTD.
365
-
366
- ### 📌 Paso 1: Inicializar el Proyecto
367
-
368
- Ejecuta el comando de inicialización:
369
-
370
- \`\`\`bash
371
- zns init
372
- \`\`\`
373
-
374
- ### 🔍 ¿Qué hace \`zns init\`?
375
-
376
- El comando \`zns init\` te preguntará:
377
-
378
- #### 1️⃣ Tipo de Proyecto
379
- - **🔍 Auditoría de Código Existente**: Evaluar sistema legacy
380
- - **🆕 Desarrollo Desde Cero**: Nuevo proyecto desde cero
381
- - **🔄 Migración/Modernización**: Migrar sistema existente
382
- - **🛠️ Mantenimiento/Soporte**: Dar soporte a sistema existente
383
- - **📱 Aplicación Móvil**: App iOS/Android
384
- - **🌐 API/Microservicios**: Backend services
385
- - **🏢 Sistema Empresarial**: ERP, CRM, etc.
386
-
387
- #### 2️⃣ Workflow Recomendado
388
- - **⚡ Quick**: Proyectos pequeños (1-2 semanas)
389
- - **📊 Standard**: Proyectos medianos (1-3 meses)
390
- - **🏢 Enterprise**: Proyectos grandes (3+ meses)
391
-
392
- #### 3️⃣ Stack Tecnológico
393
- - Backend: Java, .NET, Python, PHP, Node.js
394
- - Frontend: React, Angular, Vue
395
- - Base de datos: SQL, NoSQL
396
-
397
- ### ✅ Resultado de \`zns init\`
398
-
399
- Basado en tus respuestas, creará automáticamente:
400
-
401
- - ✅ **Estructura de fases** (01-comercial, 02-inception, 03-analysis, etc.)
402
- - **Directorios client-docs/** específicos para tu tipo de proyecto
403
- - ✅ **Templates** relevantes copiados a cada fase
404
- - ✅ **Agentes especializados** cargados según tu stack
405
- - ✅ **Guías START_HERE.md** en cada fase
406
-
407
- ### 📂 Ejemplos de Estructura Según Tipo
408
-
409
- **Auditoría de Código**:
410
- \`\`\`
411
- proyecto/
412
- ├── 01-comercial/ # Discovery y contrato
413
- ├── 03-analysis/ # PRINCIPAL: Auditoría completa
414
- │ ├── docs/client-docs/ # Código existente del cliente
415
- │ └── reports/ # Reportes de auditoría
416
- ├── 04-planning/ # Plan de mejoras
417
- └── 08-support/ # Recomendaciones
418
- \`\`\`
419
-
420
- **Desarrollo Desde Cero**:
421
- \`\`\`
422
- proyecto/
423
- ├── 01-comercial/ # Discovery
424
- ├── 02-inception/ # PRINCIPAL: PRD y diseño
425
- ├── 04-planning/ # Sprints
426
- ├── 05-development/ # PRINCIPAL: Implementación
427
- │ ├── src/
428
- │ └── tests/
429
- ├── 06-qa/ # Testing
430
- └── 07-deployment/ # Despliegue
431
- \`\`\`
432
-
433
- **Migración/Modernización**:
434
- \`\`\`
435
- proyecto/
436
- ├── 01-comercial/ # Análisis de viabilidad
437
- ├── 03-analysis/ # PRINCIPAL: Análisis de sistema legacy
438
- │ ├── docs/client-docs/ # Documentación sistema actual
439
- │ └── migration-plan/
440
- ├── 05-development/ # Desarrollo nuevo sistema
441
- └── 07-deployment/ # Plan de migración
442
- \`\`\`
443
-
444
- ### 🎯 Comandos Útiles
445
-
446
- \`\`\`bash
447
- # Inicializar proyecto
448
- zns init
449
-
450
- # Ver estado actual
451
- zns status
452
-
453
- # Validar estructura
454
- zns validate
455
-
456
- # Ver configuración
457
- zns config
458
- \`\`\`
459
-
460
- ### 📚 Más Información
461
-
462
- - **Documentación**: [README.md](./README.md)
463
- - **Agentes**: Revisa \`.awc/agents/\` para ver los 26 agentes disponibles
464
- - **Workflows**: Consulta \`.awc/workflows/\` para ver los 8 workflows
465
- - **Templates**: Usa \`.awc/templates/\` para documentos profesionales
466
-
467
- ---
468
-
469
- 🚀 **¡Listo para empezar!** Ejecuta \`awc init\` ahora.
470
- `;
471
- }
472
-
473
- /**
474
- * Crea configuración de VS Code para cargar AWC automáticamente
475
- */
476
- async function createVSCodeConfig(projectPath, projectName) {
477
- const vscodeDir = path.join(projectPath, '.vscode');
478
- await fs.ensureDir(vscodeDir);
479
-
480
- // settings.json
481
- const settings = {
482
- "github.copilot.enable": {
483
- "*": true
484
- },
485
- "github.copilot.advanced": {},
486
- "files.associations": {
487
- "*.agent.yaml": "yaml",
488
- "copilot-instructions.md": "markdown"
489
- },
490
- "files.exclude": {
491
- "**/.git": true,
492
- "**/.DS_Store": true,
493
- "**/node_modules": true
494
- },
495
- "search.exclude": {
496
- "**/node_modules": true,
497
- "**/bower_components": true,
498
- "**/*.code-search": true
499
- },
500
- "awc-zns-mtd.enabled": true,
501
- "awc-zns-mtd.autoLoadInstructions": true
502
- };
503
-
504
- await fs.writeJson(
505
- path.join(vscodeDir, 'settings.json'),
506
- settings,
507
- { spaces: 2 }
508
- );
509
-
510
- // extensions.json
511
- const extensions = {
512
- "recommendations": [
513
- "github.copilot",
514
- "github.copilot-chat",
515
- "redhat.vscode-yaml",
516
- "yzhang.markdown-all-in-one"
517
- ]
518
- };
519
-
520
- await fs.writeJson(
521
- path.join(vscodeDir, 'extensions.json'),
522
- extensions,
523
- { spaces: 2 }
524
- );
525
-
526
- // workspace file
527
- const workspace = {
528
- "folders": [
529
- {
530
- "path": ".",
531
- "name": projectName
532
- }
533
- ],
534
- "settings": {
535
- "github.copilot.enable": {
536
- "*": true
537
- },
538
- "awc-zns-mtd.enabled": true
539
- },
540
- "extensions": {
541
- "recommendations": [
542
- "github.copilot",
543
- "github.copilot-chat"
544
- ]
545
- }
546
- };
547
-
548
- await fs.writeJson(
549
- path.join(projectPath, `${projectName}.code-workspace`),
550
- workspace,
551
- { spaces: 2 }
552
- );
553
- }
554
-
555
- /**
556
- * Genera copilot-instructions.md con agentes embebidos
557
- */
558
- async function generateCopilotInstructions(projectPath) {
559
- const yaml = require('js-yaml');
560
- const agentsPath = path.join(projectPath, '.awc/agents');
561
-
562
- let content = `# GitHub Copilot - AWC ZNS-MTD Method
563
-
564
- > **Instrucciones para GitHub Copilot**: Este proyecto utiliza el método AWC ZNS-MTD con agentes especializados.
565
-
566
- ## 🎯 Agentes Disponibles
567
-
568
- Los siguientes agentes están disponibles en este proyecto. Cada agente tiene un rol específico y expertise técnica.
569
-
570
- `;
571
-
572
- // Leer agentes base
573
- const baseAgents = await fs.readdir(agentsPath);
574
- for (const agentFile of baseAgents.filter(f => f.endsWith('.agent.yaml'))) {
575
- try {
576
- const agentPath = path.join(agentsPath, agentFile);
577
- const agentContent = await fs.readFile(agentPath, 'utf8');
578
- const agentData = yaml.load(agentContent);
579
-
580
- if (agentData && agentData.agent) {
581
- const meta = agentData.agent.metadata || {};
582
- const persona = agentData.agent.persona || {};
583
-
584
- content += `### ${meta.icon || '🤖'} ${meta.name || agentFile}
585
-
586
- **ID**: \`${meta.id || 'unknown'}\`
587
- **Cuándo usar**: ${meta.whenToUse || 'No especificado'}
588
-
589
- `;
590
-
591
- if (persona.role) {
592
- content += `**Rol**: ${persona.role}\n\n`;
593
- }
594
-
595
- if (persona.identity) {
596
- content += `**Identidad**: ${persona.identity}\n\n`;
597
- }
598
-
599
- content += `---\n\n`;
600
- }
601
- } catch (error) {
602
- console.error(`Error leyendo agente ${agentFile}:`, error.message);
603
- }
604
- }
605
-
606
- // Leer agentes especializados si existen
607
- const specializedPath = path.join(agentsPath, 'specialized');
608
- if (await fs.pathExists(specializedPath)) {
609
- content += `## 🔧 Agentes Especializados
610
-
611
- `;
612
- const specializedAgents = await fs.readdir(specializedPath);
613
- for (const agentFile of specializedAgents.filter(f => f.endsWith('.agent.yaml'))) {
614
- try {
615
- const agentPath = path.join(specializedPath, agentFile);
616
- const agentContent = await fs.readFile(agentPath, 'utf8');
617
- const agentData = yaml.load(agentContent);
618
-
619
- if (agentData && agentData.agent) {
620
- const meta = agentData.agent.metadata || {};
621
-
622
- content += `- **${meta.icon || '🔧'} ${meta.name || agentFile}** (\`${meta.id || 'unknown'}\`): ${meta.whenToUse || 'Agente especializado'}\n`;
623
- }
624
- } catch (error) {
625
- console.error(`Error leyendo agente especializado ${agentFile}:`, error.message);
626
- }
627
- }
628
- }
629
-
630
- content += `
631
-
632
- ## 📋 Instrucciones Generales
633
-
634
- Al trabajar en este proyecto:
635
-
636
- 1. **Consulta el agente apropiado** según la tarea (ver lista arriba)
637
- 2. **Sigue la metodología ZNS-MTD**: Minimalismo Estratégico (máximo impacto, mínima complejidad)
638
- 3. **Usa los templates** disponibles en \`.awc/templates/\`
639
- 4. **Documenta decisiones** arquitectónicas importantes
640
- 5. **Mantén trazabilidad** de cambios y motivaciones
641
-
642
- ## 🚀 Comandos Disponibles
643
-
644
- \`\`\`bash
645
- zns init # Inicializar tipo de proyecto
646
- zns status # Ver estado del proyecto
647
- zns validate # Validar estructura
648
- zns config # Configurar preferencias
649
- \`\`\`
650
-
651
- ---
652
-
653
- *Generado automáticamente por AWC ZNS-MTD*
654
- `;
655
-
656
- return content;
657
- }
658
-
659
- module.exports = { newProjectCommand };
1
+ /**
2
+ * Comando: new
3
+ * Crea un nuevo directorio de proyecto con configuración base ZΞNAPSΞS
4
+ */
5
+
6
+ const fs = require('fs-extra');
7
+ const path = require('path');
8
+ const chalk = require('chalk');
9
+ const ora = require('ora');
10
+ const inquirer = require('inquirer');
11
+ const { displayLogo } = require('../utils/console-logger');
12
+ const { getVersion } = require('../utils/version');
13
+ const { validateProjectName, validatePath } = require('../utils/validators');
14
+ const { CLILogger } = require('../utils/logger');
15
+ // const ConfigManager = require('../../config/config-manager');
16
+
17
+ /**
18
+ * Comando principal para crear nuevo proyecto
19
+ */
20
+ async function newProjectCommand(projectName, options = {}) {
21
+ const startTime = Date.now();
22
+ let spinner; // Definir spinner al inicio
23
+
24
+ try {
25
+ CLILogger.commandStart('new-project', { projectName, options });
26
+
27
+ displayLogo();
28
+
29
+ console.log(chalk.cyan('\n🚀 Crear Nuevo Proyecto ZΞNAPSΞS\n'));
30
+
31
+ // Preguntar nombre del proyecto si no se proporcionó
32
+ if (!projectName) {
33
+ const { name } = await inquirer.prompt([
34
+ {
35
+ type: 'input',
36
+ name: 'name',
37
+ message: '📦 Nombre del proyecto:',
38
+ validate: (input) => {
39
+ if (!validateProjectName(input)) {
40
+ return 'Nombre inválido. Solo letras, números, guiones y guiones bajos (3-50 caracteres)';
41
+ }
42
+ return true;
43
+ }
44
+ }
45
+ ]);
46
+ projectName = name;
47
+ } else {
48
+ // Validar nombre proporcionado por argumento
49
+ if (!validateProjectName(projectName)) {
50
+ console.log(chalk.red('\n❌ Nombre de proyecto inválido\n'));
51
+ console.log(chalk.yellow('Reglas:'));
52
+ console.log(' • Solo letras, números, guiones y guiones bajos');
53
+ console.log(' Entre 3 y 50 caracteres');
54
+ console.log(' • No puede ser un nombre reservado\n');
55
+ CLILogger.commandError('new-project', new Error('Invalid project name'));
56
+ process.exit(1);
57
+ }
58
+ }
59
+
60
+ // Verificar si el directorio ya existe
61
+ const projectPath = path.join(process.cwd(), projectName);
62
+ if (await fs.pathExists(projectPath)) {
63
+ console.log(chalk.red(`\n❌ El directorio '${projectName}' ya existe.\n`));
64
+ CLILogger.commandError('new-project', new Error('Directory already exists'));
65
+ process.exit(1);
66
+ }
67
+
68
+ // Validar path de seguridad
69
+ if (!validatePath(projectPath)) {
70
+ console.log(chalk.red('\n❌ Path no seguro detectado\n'));
71
+ CLILogger.commandError('new-project', new Error('Unsafe path'));
72
+ process.exit(1);
73
+ }
74
+
75
+ // Preguntar responsable del proyecto
76
+ const { responsible, description, gitInit } = await inquirer.prompt([
77
+ {
78
+ type: 'input',
79
+ name: 'responsible',
80
+ message: '👤 Responsable del proyecto:',
81
+ validate: (input) => {
82
+ if (!input.trim()) {
83
+ return 'El responsable es requerido';
84
+ }
85
+ return true;
86
+ }
87
+ },
88
+ {
89
+ type: 'input',
90
+ name: 'description',
91
+ message: '📝 Descripción breve (opcional):',
92
+ default: `Proyecto ${projectName}`
93
+ },
94
+ {
95
+ type: 'confirm',
96
+ name: 'gitInit',
97
+ message: '🔧 Inicializar repositorio Git?',
98
+ default: true
99
+ }
100
+ ]);
101
+
102
+ const spinner = ora('Creando estructura base del proyecto...').start();
103
+
104
+ // 1. Crear directorio raíz del proyecto
105
+ await fs.ensureDir(projectPath);
106
+ spinner.text = `Directorio ${projectName} creado`;
107
+
108
+ // 2. Crear estructura base mínima
109
+ const baseDirectories = ['.awc/agents', '.awc/workflows', '.awc/templates', 'docs'];
110
+
111
+ for (const dir of baseDirectories) {
112
+ await fs.ensureDir(path.join(projectPath, dir));
113
+ }
114
+ spinner.text = 'Estructura base creada';
115
+
116
+ // 3. Copiar agentes base (4 agentes core)
117
+ const srcAgentsPath = path.join(__dirname, '../../../src/modules/awc-zns-mtd/agents');
118
+ const destAgentsPath = path.join(projectPath, '.awc/agents');
119
+
120
+ if (await fs.pathExists(srcAgentsPath)) {
121
+ await fs.copy(srcAgentsPath, destAgentsPath);
122
+ spinner.text = 'Agentes base copiados';
123
+ }
124
+
125
+ // 4. Copiar agentes especializados (22 agentes)
126
+ const srcCustomAgentsPath = path.join(
127
+ __dirname,
128
+ '../../../src/modules/custom-agents/cli/.awc-agents'
129
+ );
130
+ const destCustomAgentsPath = path.join(projectPath, '.awc/agents/specialized');
131
+
132
+ if (await fs.pathExists(srcCustomAgentsPath)) {
133
+ await fs.copy(srcCustomAgentsPath, destCustomAgentsPath);
134
+ spinner.text = 'Agentes especializados copiados';
135
+ }
136
+
137
+ // 5. Copiar workflows
138
+ const srcWorkflowsPath = path.join(__dirname, '../../../src/modules/awc-zns-mtd/workflows');
139
+ const destWorkflowsPath = path.join(projectPath, '.awc/workflows');
140
+
141
+ if (await fs.pathExists(srcWorkflowsPath)) {
142
+ await fs.copy(srcWorkflowsPath, destWorkflowsPath);
143
+ spinner.text = 'Workflows copiados';
144
+ }
145
+
146
+ // 6. Copiar templates
147
+ const srcTemplatesPath = path.join(__dirname, '../../../src/modules/awc-zns-mtd/templates');
148
+ const destTemplatesPath = path.join(projectPath, '.awc/templates');
149
+
150
+ if (await fs.pathExists(srcTemplatesPath)) {
151
+ await fs.copy(srcTemplatesPath, destTemplatesPath);
152
+ spinner.text = 'Templates copiados';
153
+ }
154
+
155
+ // 7. Crear archivo de configuración AWC
156
+ const awcConfig = {
157
+ version: getVersion(),
158
+ createdAt: new Date().toISOString(),
159
+ project: {
160
+ name: projectName,
161
+ description,
162
+ responsible
163
+ },
164
+ projectType: null,
165
+ initialized: false,
166
+ preferences: {
167
+ communication_language: 'Spanish',
168
+ document_output_language: 'Spanish',
169
+ code_language: 'English'
170
+ },
171
+ workflows: {
172
+ current_phase: null,
173
+ completed_phases: []
174
+ }
175
+ };
176
+
177
+ await fs.writeJson(path.join(projectPath, '.awc/config.json'), awcConfig, { spaces: 2 });
178
+ spinner.text = 'Configuración AWC creada';
179
+
180
+ // 8. Crear README.md del proyecto
181
+ const readme = createReadmeContent(projectName, responsible, description);
182
+ await fs.writeFile(path.join(projectPath, 'README.md'), readme);
183
+ spinner.text = 'README.md creado';
184
+
185
+ // 9. Crear .gitignore
186
+ const gitignore = createGitignoreContent();
187
+ await fs.writeFile(path.join(projectPath, '.gitignore'), gitignore);
188
+ spinner.text = '.gitignore creado';
189
+
190
+ // 10. Crear configuración de VS Code
191
+ await createVSCodeConfig(projectPath, projectName);
192
+ spinner.text = 'Configuración VS Code creada';
193
+
194
+ // 11. Generar copilot-instructions.md con agentes embebidos
195
+ const githubDir = path.join(projectPath, '.github');
196
+ await fs.ensureDir(githubDir);
197
+ const copilotInstructions = await generateCopilotInstructions(projectPath);
198
+ await fs.writeFile(path.join(githubDir, 'copilot-instructions.md'), copilotInstructions);
199
+ spinner.text = 'GitHub Copilot instructions creadas';
200
+
201
+ // 12. Crear archivo NEXT_STEPS.md
202
+ const nextSteps = createNextStepsContent(projectName);
203
+ await fs.writeFile(path.join(projectPath, 'NEXT_STEPS.md'), nextSteps);
204
+ spinner.text = 'Guía de próximos pasos creada';
205
+
206
+ // 13. Inicializar Git si se solicitó
207
+ if (gitInit) {
208
+ const { execSync } = require('child_process');
209
+ try {
210
+ execSync('git init', { cwd: projectPath, stdio: 'ignore' });
211
+ execSync('git add .', { cwd: projectPath, stdio: 'ignore' });
212
+ execSync(`git commit -m "feat: Inicializar proyecto ${projectName} con ZΞNAPSΞS"`, {
213
+ cwd: projectPath,
214
+ stdio: 'ignore'
215
+ });
216
+ spinner.text = 'Repositorio Git inicializado';
217
+ } catch {
218
+ // Git no está disponible o fallo, continuar sin git
219
+ }
220
+ }
221
+
222
+ spinner.succeed(chalk.green('✅ Proyecto creado exitosamente'));
223
+
224
+ // Mostrar resumen
225
+ console.log(chalk.cyan(`\n${'═'.repeat(60)}`));
226
+ console.log(chalk.cyan('📦 Proyecto Creado'));
227
+ console.log(chalk.cyan(`${'═'.repeat(60)}\n`));
228
+
229
+ console.log(`${chalk.gray('Nombre:')} ${chalk.green(projectName)}`);
230
+ console.log(`${chalk.gray('Responsable:')} ${chalk.yellow(responsible)}`);
231
+ console.log(`${chalk.gray('Ubicación:')} ${chalk.blue(projectPath)}`);
232
+ console.log(`${chalk.gray('AWC Versión:')} ${chalk.yellow(getVersion())}\n`);
233
+
234
+ // Próximos pasos
235
+ console.log(chalk.cyan('📚 Próximos Pasos:\n'));
236
+ console.log(` ${chalk.green('1.')} cd ${projectName}`);
237
+ console.log(` ${chalk.green('2.')} zns init ${chalk.gray('# Inicializar tipo de proyecto')}`);
238
+ console.log(` ${chalk.green('3.')} Leer ${chalk.yellow('NEXT_STEPS.md')} para más detalles\n`);
239
+
240
+ console.log(
241
+ chalk.yellow('⚠️ La estructura de fases se creará al ejecutar') + chalk.green(' zns init\n')
242
+ );
243
+
244
+ const duration = Date.now() - startTime;
245
+ CLILogger.commandEnd('new-project', true, duration);
246
+ CLILogger.fileOperation('create-project', projectPath, true);
247
+ } catch (error) {
248
+ if (spinner) {
249
+ spinner.fail(chalk.red('❌ Error creando proyecto'));
250
+ }
251
+ console.error(chalk.red('\n❌ Error:'), error.message);
252
+
253
+ const duration = Date.now() - startTime;
254
+ CLILogger.commandError('new-project', error);
255
+ CLILogger.commandEnd('new-project', false, duration);
256
+
257
+ throw error;
258
+ }
259
+ }
260
+
261
+ /**
262
+ * Crea el contenido del README.md
263
+ */
264
+ function createReadmeContent(projectName, responsible, description) {
265
+ return `# ${projectName}
266
+
267
+ > ${description}
268
+
269
+ ## 📋 Información del Proyecto
270
+
271
+ - **Responsable**: ${responsible}
272
+ - **Metodología**: ZΞNAPSΞS by ΛNWICO (Minimalismo Estratégico)
273
+ - **Estado**: Pendiente de inicialización
274
+
275
+ ## 🚀 Próximos Pasos
276
+
277
+ Este proyecto ha sido creado con la estructura base de ZΞNAPSΞS.
278
+
279
+ ### 1. Inicializar Tipo de Proyecto
280
+
281
+ \`\`\`bash
282
+ zns init
283
+ \`\`\`
284
+
285
+ El comando \`zns init\` te preguntará:
286
+ - Tipo de proyecto (auditoría, desarrollo nuevo, migración, etc.)
287
+ - Tecnologías a utilizar
288
+ - Tipo de workflow (quick, standard, enterprise)
289
+
290
+ Basado en tus respuestas, creará automáticamente:
291
+ - ✅ Estructura de directorios por fase
292
+ - ✅ Directorios client-docs específicos
293
+ - Templates relevantes para tu proyecto
294
+ - ✅ Workflows configurados
295
+
296
+ ### 2. Comenzar a Trabajar
297
+
298
+ Una vez inicializado, seguir las guías en cada fase del proyecto.
299
+
300
+ ## 🔧 Configuración AWC
301
+
302
+ El directorio \`.awc/\` contiene:
303
+
304
+ - \`agents/\` - 4 agentes base + 22 agentes especializados
305
+ - \`workflows/\` - 8 workflows completos
306
+ - \`templates/\` - 7 templates profesionales
307
+ - \`config.json\` - Configuración del proyecto
308
+
309
+ ## 📝 Comandos Disponibles
310
+
311
+ \`\`\`bash
312
+ # Inicializar proyecto (siguiente paso)
313
+ zns init
314
+
315
+ # Ver estado del proyecto
316
+ zns status
317
+
318
+ # Validar estructura
319
+ zns validate
320
+
321
+ # Ver configuración
322
+ zns config
323
+ \`\`\`
324
+
325
+ ---
326
+
327
+ Generado con ❤️ usando ZΞNAPSΞS by ΛNWICO v${getVersion()}
328
+ `;
329
+ }
330
+
331
+ /**
332
+ * Crea el contenido del .gitignore
333
+ */
334
+ function createGitignoreContent() {
335
+ return `# Dependencies
336
+ node_modules/
337
+ vendor/
338
+ bower_components/
339
+
340
+ # Build outputs
341
+ dist/
342
+ build/
343
+ out/
344
+ target/
345
+ *.exe
346
+ *.dll
347
+ *.so
348
+ *.dylib
349
+
350
+ # IDE
351
+ .vscode/
352
+ .idea/
353
+ *.swp
354
+ *.swo
355
+ *~
356
+
357
+ # Logs
358
+ logs/
359
+ *.log
360
+ npm-debug.log*
361
+ yarn-debug.log*
362
+ yarn-error.log*
363
+
364
+ # Environment variables
365
+ .env
366
+ .env.local
367
+ .env.*.local
368
+
369
+ # OS
370
+ Thumbs.db
371
+ .DS_Store
372
+
373
+ # Temporary files
374
+ tmp/
375
+ temp/
376
+ *.tmp
377
+
378
+ # Coverage
379
+ coverage/
380
+ *.lcov
381
+ .nyc_output/
382
+
383
+ # Confidential (keep locally, never commit)
384
+ **/client-docs/contratos/
385
+ **/client-docs/accesos/
386
+ **/*-confidential.*
387
+ `;
388
+ }
389
+
390
+ /**
391
+ * Crea contenido de NEXT_STEPS.md
392
+ */
393
+ function createNextStepsContent(projectName) {
394
+ return `# 🎯 Próximos Pasos - ${projectName}
395
+
396
+ ## ¿Qué hacer ahora?
397
+
398
+ Tu proyecto ha sido creado con la **estructura base** de ZΞNAPSΞS.
399
+
400
+ ### 📌 Paso 1: Inicializar el Proyecto
401
+
402
+ Ejecuta el comando de inicialización:
403
+
404
+ \`\`\`bash
405
+ zns init
406
+ \`\`\`
407
+
408
+ ### 🔍 ¿Qué hace \`zns init\`?
409
+
410
+ El comando \`zns init\` te preguntará:
411
+
412
+ #### 1️⃣ Tipo de Proyecto
413
+ - **🔍 Auditoría de Código Existente**: Evaluar sistema legacy
414
+ - **🆕 Desarrollo Desde Cero**: Nuevo proyecto desde cero
415
+ - **🔄 Migración/Modernización**: Migrar sistema existente
416
+ - **🛠️ Mantenimiento/Soporte**: Dar soporte a sistema existente
417
+ - **📱 Aplicación Móvil**: App iOS/Android
418
+ - **🌐 API/Microservicios**: Backend services
419
+ - **🏢 Sistema Empresarial**: ERP, CRM, etc.
420
+
421
+ #### 2️⃣ Workflow Recomendado
422
+ - **⚡ Quick**: Proyectos pequeños (1-2 semanas)
423
+ - **📊 Standard**: Proyectos medianos (1-3 meses)
424
+ - **🏢 Enterprise**: Proyectos grandes (3+ meses)
425
+
426
+ #### 3️⃣ Stack Tecnológico
427
+ - Backend: Java, .NET, Python, PHP, Node.js
428
+ - Frontend: React, Angular, Vue
429
+ - Base de datos: SQL, NoSQL
430
+
431
+ ### ✅ Resultado de \`zns init\`
432
+
433
+ Basado en tus respuestas, creará automáticamente:
434
+
435
+ - ✅ **Estructura de fases** (01-comercial, 02-inception, 03-analysis, etc.)
436
+ - ✅ **Directorios client-docs/** específicos para tu tipo de proyecto
437
+ - **Templates** relevantes copiados a cada fase
438
+ - **Agentes especializados** cargados según tu stack
439
+ - ✅ **Guías START_HERE.md** en cada fase
440
+
441
+ ### 📂 Ejemplos de Estructura Según Tipo
442
+
443
+ **Auditoría de Código**:
444
+ \`\`\`
445
+ proyecto/
446
+ ├── 01-comercial/ # Discovery y contrato
447
+ ├── 03-analysis/ # PRINCIPAL: Auditoría completa
448
+ │ ├── docs/client-docs/ # Código existente del cliente
449
+ │ └── reports/ # Reportes de auditoría
450
+ ├── 04-planning/ # Plan de mejoras
451
+ └── 08-support/ # Recomendaciones
452
+ \`\`\`
453
+
454
+ **Desarrollo Desde Cero**:
455
+ \`\`\`
456
+ proyecto/
457
+ ├── 01-comercial/ # Discovery
458
+ ├── 02-inception/ # PRINCIPAL: PRD y diseño
459
+ ├── 04-planning/ # Sprints
460
+ ├── 05-development/ # PRINCIPAL: Implementación
461
+ │ ├── src/
462
+ │ └── tests/
463
+ ├── 06-qa/ # Testing
464
+ └── 07-deployment/ # Despliegue
465
+ \`\`\`
466
+
467
+ **Migración/Modernización**:
468
+ \`\`\`
469
+ proyecto/
470
+ ├── 01-comercial/ # Análisis de viabilidad
471
+ ├── 03-analysis/ # PRINCIPAL: Análisis de sistema legacy
472
+ │ ├── docs/client-docs/ # Documentación sistema actual
473
+ │ └── migration-plan/
474
+ ├── 05-development/ # Desarrollo nuevo sistema
475
+ └── 07-deployment/ # Plan de migración
476
+ \`\`\`
477
+
478
+ ### 🎯 Comandos Útiles
479
+
480
+ \`\`\`bash
481
+ # Inicializar proyecto
482
+ zns init
483
+
484
+ # Ver estado actual
485
+ zns status
486
+
487
+ # Validar estructura
488
+ zns validate
489
+
490
+ # Ver configuración
491
+ zns config
492
+ \`\`\`
493
+
494
+ ### 📚 Más Información
495
+
496
+ - **Documentación**: [README.md](./README.md)
497
+ - **Agentes**: Revisa \`.awc/agents/\` para ver los 26 agentes disponibles
498
+ - **Workflows**: Consulta \`.awc/workflows/\` para ver los 8 workflows
499
+ - **Templates**: Usa \`.awc/templates/\` para documentos profesionales
500
+
501
+ ---
502
+
503
+ 🚀 **¡Listo para empezar!** Ejecuta \`awc init\` ahora.
504
+ `;
505
+ }
506
+
507
+ /**
508
+ * Crea configuración de VS Code para cargar AWC automáticamente
509
+ */
510
+ async function createVSCodeConfig(projectPath, projectName) {
511
+ const vscodeDir = path.join(projectPath, '.vscode');
512
+ await fs.ensureDir(vscodeDir);
513
+
514
+ // settings.json
515
+ const settings = {
516
+ 'github.copilot.enable': {
517
+ '*': true
518
+ },
519
+ 'github.copilot.advanced': {},
520
+ 'files.associations': {
521
+ '*.agent.yaml': 'yaml',
522
+ 'copilot-instructions.md': 'markdown'
523
+ },
524
+ 'files.exclude': {
525
+ '**/.git': true,
526
+ '**/.DS_Store': true,
527
+ '**/node_modules': true
528
+ },
529
+ 'search.exclude': {
530
+ '**/node_modules': true,
531
+ '**/bower_components': true,
532
+ '**/*.code-search': true
533
+ },
534
+ 'awc-zns-mtd.enabled': true,
535
+ 'awc-zns-mtd.autoLoadInstructions': true
536
+ };
537
+
538
+ await fs.writeJson(path.join(vscodeDir, 'settings.json'), settings, { spaces: 2 });
539
+
540
+ // extensions.json
541
+ const extensions = {
542
+ recommendations: [
543
+ 'github.copilot',
544
+ 'github.copilot-chat',
545
+ 'redhat.vscode-yaml',
546
+ 'yzhang.markdown-all-in-one'
547
+ ]
548
+ };
549
+
550
+ await fs.writeJson(path.join(vscodeDir, 'extensions.json'), extensions, { spaces: 2 });
551
+
552
+ // workspace file
553
+ const workspace = {
554
+ folders: [
555
+ {
556
+ path: '.',
557
+ name: projectName
558
+ }
559
+ ],
560
+ settings: {
561
+ 'github.copilot.enable': {
562
+ '*': true
563
+ },
564
+ 'awc-zns-mtd.enabled': true
565
+ },
566
+ extensions: {
567
+ recommendations: ['github.copilot', 'github.copilot-chat']
568
+ }
569
+ };
570
+
571
+ await fs.writeJson(path.join(projectPath, `${projectName}.code-workspace`), workspace, {
572
+ spaces: 2
573
+ });
574
+ }
575
+
576
+ /**
577
+ * Genera copilot-instructions.md con agentes embebidos
578
+ */
579
+ async function generateCopilotInstructions(projectPath) {
580
+ const yaml = require('js-yaml');
581
+ const agentsPath = path.join(projectPath, '.awc/agents');
582
+
583
+ let content = `# GitHub Copilot - ZΞNAPSΞS by ΛNWICO
584
+
585
+ > **Instrucciones para GitHub Copilot**: Este proyecto utiliza el método ZΞNAPSΞS con agentes especializados.
586
+
587
+ ## 🎯 Agentes Disponibles
588
+
589
+ Los siguientes agentes están disponibles en este proyecto. Cada agente tiene un rol específico y expertise técnica.
590
+
591
+ `;
592
+
593
+ // Leer agentes base
594
+ const baseAgents = await fs.readdir(agentsPath);
595
+ for (const agentFile of baseAgents.filter((f) => f.endsWith('.agent.yaml'))) {
596
+ try {
597
+ const agentPath = path.join(agentsPath, agentFile);
598
+ const agentContent = await fs.readFile(agentPath, 'utf8');
599
+ const agentData = yaml.load(agentContent);
600
+
601
+ if (agentData && agentData.agent) {
602
+ const meta = agentData.agent.metadata || {};
603
+ const persona = agentData.agent.persona || {};
604
+
605
+ content += `### ${meta.icon || '🤖'} ${meta.name || agentFile}
606
+
607
+ **ID**: \`${meta.id || 'unknown'}\`
608
+ **Cuándo usar**: ${meta.whenToUse || 'No especificado'}
609
+
610
+ `;
611
+
612
+ if (persona.role) {
613
+ content += `**Rol**: ${persona.role}\n\n`;
614
+ }
615
+
616
+ if (persona.identity) {
617
+ content += `**Identidad**: ${persona.identity}\n\n`;
618
+ }
619
+
620
+ content += '---\n\n';
621
+ }
622
+ } catch (error) {
623
+ console.error(`Error leyendo agente ${agentFile}:`, error.message);
624
+ }
625
+ }
626
+
627
+ // Leer agentes especializados si existen
628
+ const specializedPath = path.join(agentsPath, 'specialized');
629
+ if (await fs.pathExists(specializedPath)) {
630
+ content += `## 🔧 Agentes Especializados
631
+
632
+ `;
633
+ const specializedAgents = await fs.readdir(specializedPath);
634
+ for (const agentFile of specializedAgents.filter((f) => f.endsWith('.agent.yaml'))) {
635
+ try {
636
+ const agentPath = path.join(specializedPath, agentFile);
637
+ const agentContent = await fs.readFile(agentPath, 'utf8');
638
+ const agentData = yaml.load(agentContent);
639
+
640
+ if (agentData && agentData.agent) {
641
+ const meta = agentData.agent.metadata || {};
642
+
643
+ content += `- **${meta.icon || '🔧'} ${meta.name || agentFile}** (\`${meta.id || 'unknown'}\`): ${meta.whenToUse || 'Agente especializado'}\n`;
644
+ }
645
+ } catch (error) {
646
+ console.error(`Error leyendo agente especializado ${agentFile}:`, error.message);
647
+ }
648
+ }
649
+ }
650
+
651
+ content += `
652
+
653
+ ## 📋 Instrucciones Generales
654
+
655
+ Al trabajar en este proyecto:
656
+
657
+ 1. **Consulta el agente apropiado** según la tarea (ver lista arriba)
658
+ 2. **Sigue la metodología ZNS-MTD**: Minimalismo Estratégico (máximo impacto, mínima complejidad)
659
+ 3. **Usa los templates** disponibles en \`.awc/templates/\`
660
+ 4. **Documenta decisiones** arquitectónicas importantes
661
+ 5. **Mantén trazabilidad** de cambios y motivaciones
662
+
663
+ ## 🚀 Comandos Disponibles
664
+
665
+ \`\`\`bash
666
+ zns init # Inicializar tipo de proyecto
667
+ zns status # Ver estado del proyecto
668
+ zns validate # Validar estructura
669
+ zns config # Configurar preferencias
670
+ \`\`\`
671
+
672
+ ---
673
+
674
+ *Generado automáticamente por ZΞNAPSΞS*
675
+ `;
676
+
677
+ return content;
678
+ }
679
+
680
+ module.exports = { newProjectCommand };