@saulwade/swl-ses 1.5.1 → 1.6.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 (155) hide show
  1. package/CLAUDE.md +225 -209
  2. package/README.md +578 -561
  3. package/agentes/arquitecto-swl.md +33 -1
  4. package/agentes/nemesis-auditor-swl.md +59 -19
  5. package/bin/swl-mcp-server.js +214 -214
  6. package/bin/swl-ses.js +49 -7
  7. package/comandos/swl/.evolved.json +22 -22
  8. package/comandos/swl/contribuir.md +233 -233
  9. package/comandos/swl/nemesis.md +230 -56
  10. package/gateway/lib/event-channel.js +191 -191
  11. package/habilidades/backend-production-resilience/SKILL.md +288 -288
  12. package/habilidades/benchmark-memoria/SKILL.md +186 -186
  13. package/habilidades/diagrama-arquitectura/assets/template.html +276 -276
  14. package/habilidades/doubt-driven-review/SKILL.md +171 -171
  15. package/habilidades/doubt-driven-review/recursos/EXAMPLES.md +130 -130
  16. package/habilidades/ejecutar-task-iterativo/SKILL.md +278 -278
  17. package/habilidades/eval-framework/SKILL.md +212 -212
  18. package/habilidades/feynman-auditor-swl/SKILL.md +123 -123
  19. package/habilidades/feynman-auditor-swl/recursos/preguntas-language-agnostic.md +108 -108
  20. package/habilidades/harness-claude-code/SKILL.md +299 -299
  21. package/habilidades/infra-github-actions/SKILL.md +166 -166
  22. package/habilidades/legacy-code-rescue/SKILL.md +267 -267
  23. package/habilidades/manejo-errores/.evolved.json +8 -8
  24. package/habilidades/meta-skills-estandar/SKILL.md +207 -4
  25. package/habilidades/meta-skills-estandar/recursos/convencion-examples.md +93 -93
  26. package/habilidades/meta-skills-estandar/recursos/skills-as-agents.md +163 -163
  27. package/habilidades/nemesis-evaluacion-json/SKILL.md +266 -0
  28. package/habilidades/nemesis-redistribuir/SKILL.md +341 -0
  29. package/habilidades/node-experto/SKILL.md +94 -4
  30. package/habilidades/patrones-python/SKILL.md +229 -229
  31. package/habilidades/patrones-python/recursos/patrones-avanzados.md +469 -469
  32. package/habilidades/planear-fase/SKILL.md +319 -319
  33. package/habilidades/protocolo-revision-swl/SKILL.md +350 -276
  34. package/habilidades/release-semver/.evolved.json +8 -8
  35. package/habilidades/state-inconsistency-auditor-swl/SKILL.md +166 -166
  36. package/habilidades/state-inconsistency-auditor-swl/recursos/coupled-state-patterns.md +147 -147
  37. package/habilidades/tdd-workflow/SKILL.md +121 -4
  38. package/habilidades/testing-python/SKILL.md +340 -340
  39. package/habilidades/web-fetcher-routing/SKILL.md +75 -75
  40. package/hooks/check-update.js +31 -3
  41. package/hooks/claudemd-bloat-detector.js +161 -161
  42. package/hooks/extraccion-aprendizajes.js +11 -0
  43. package/hooks/lib/agent-routing.js +107 -107
  44. package/hooks/lib/auto-consolidator.js +335 -335
  45. package/hooks/lib/error-classifier.js +308 -308
  46. package/hooks/lib/merkle-audit.js +96 -96
  47. package/hooks/lib/provenance-tracker.js +191 -191
  48. package/hooks/lib/rate-limit-tracker.js +253 -253
  49. package/hooks/lib/resource-quota.js +122 -122
  50. package/hooks/lib/retry-jitter.js +165 -165
  51. package/hooks/lib/security-net.js +201 -201
  52. package/hooks/lib/skill-auditor.js +588 -588
  53. package/hooks/lib/sync-status.js +228 -228
  54. package/hooks/lib/taint-tracker.js +107 -107
  55. package/hooks/lib/text-similarity.js +241 -241
  56. package/hooks/lib/toon-compressor.js +245 -245
  57. package/hooks/registro-turnos.js +209 -209
  58. package/hooks/sugerir-regenerar-inventario.js +170 -170
  59. package/hooks/validar-formato-post-subagente.js +140 -140
  60. package/hooks/validar-memoria-hook.js +218 -218
  61. package/instintos/prompt-appendices.yaml +57 -57
  62. package/manifiestos/agent-output-schemas.json +57 -57
  63. package/manifiestos/modulos.json +1324 -1321
  64. package/manifiestos/skills-lock.json +1142 -1114
  65. package/package.json +5 -4
  66. package/plantillas/auditor-veto-template.md +105 -105
  67. package/plantillas/github-workflows/README.md +47 -47
  68. package/plantillas/github-workflows/release-please.yml +44 -44
  69. package/plantillas/github-workflows/swl-ci.yml +107 -107
  70. package/plantillas/github-workflows/swl-security.yml +51 -51
  71. package/plugin.json +355 -351
  72. package/reglas/analisis-previo-tareas-grandes.md +172 -172
  73. package/reglas/arreglar-al-detectar.md +147 -147
  74. package/reglas/fragmentos-compartidos.md +152 -152
  75. package/reglas/harness-claude-code.md +213 -213
  76. package/reglas/registro-componentes-nuevos.md +192 -0
  77. package/reglas/usar-context7.md +226 -226
  78. package/schemas/diary-entry.schema.json +80 -80
  79. package/scripts/actualizar.js +110 -1
  80. package/scripts/audit-tools/audit-history.js +330 -330
  81. package/scripts/audit-tools/bundle-tracker.js +290 -290
  82. package/scripts/audit-tools/canary-monitor.js +352 -352
  83. package/scripts/audit-tools/code-profiler.js +605 -605
  84. package/scripts/audit-tools/dep-doctor.js +320 -320
  85. package/scripts/audit-tools/env-validator.js +206 -206
  86. package/scripts/audit-tools/lib/fs-walk.js +48 -48
  87. package/scripts/audit-tools/lib/output.js +23 -23
  88. package/scripts/audit-tools/migration-checker.js +392 -392
  89. package/scripts/audit-tools/pentest-scanner.js +1436 -1436
  90. package/scripts/benchmark-memoria.js +167 -167
  91. package/scripts/configurar-branch-protection.js +418 -418
  92. package/scripts/derivar-feature-list.js +489 -489
  93. package/scripts/desinstalar.js +105 -24
  94. package/scripts/detectar-aprendizajes-duplicados.js +151 -151
  95. package/scripts/doctor.js +27 -0
  96. package/scripts/field-report.js +199 -199
  97. package/scripts/generar-checklists-consolidados.js +273 -273
  98. package/scripts/generar-inventario.js +420 -420
  99. package/scripts/generar-matriz-lenguajes.js +271 -271
  100. package/scripts/instalador.js +55 -4
  101. package/scripts/lib/artefactos-python.js +43 -43
  102. package/scripts/lib/benchmark-metrics.js +160 -160
  103. package/scripts/lib/budget-enforcer.js +252 -252
  104. package/scripts/lib/configurar-ci.js +380 -380
  105. package/scripts/lib/contadores-inventario.js +217 -217
  106. package/scripts/lib/detectar-stack-detallado.js +307 -307
  107. package/scripts/lib/diary-entry.js +234 -234
  108. package/scripts/lib/eval-metrics-store.js +218 -218
  109. package/scripts/lib/eval-quality.js +171 -171
  110. package/scripts/lib/eval-schemas.js +144 -144
  111. package/scripts/lib/eval-self-correct.js +106 -106
  112. package/scripts/lib/eval-validator.js +185 -185
  113. package/scripts/lib/expandir-targets.js +71 -71
  114. package/scripts/lib/jaccard-similarity.js +98 -98
  115. package/scripts/lib/longmemeval-runner.js +125 -125
  116. package/scripts/lib/mcp_config.py +127 -0
  117. package/scripts/lib/npm-version.js +261 -261
  118. package/scripts/lib/paquetes-conocidos.js +50 -50
  119. package/scripts/lib/parsear-opciones.js +3 -0
  120. package/scripts/lib/prompt-builder.js +264 -264
  121. package/scripts/lib/rrf-fusion.js +175 -175
  122. package/scripts/lib/scoring-instintos.js +277 -277
  123. package/scripts/lib/semantic-search.js +252 -252
  124. package/scripts/lib/toml-merge.js +204 -204
  125. package/scripts/lib/transformadores/codex.js +375 -375
  126. package/scripts/lib/transformadores/cursor.js +359 -359
  127. package/scripts/lib/ui.js +148 -22
  128. package/scripts/limpiar-artefactos-python.js +131 -131
  129. package/scripts/mcp-orchestrator.py +8 -18
  130. package/scripts/mcp-pool-manager.py +12 -23
  131. package/scripts/mcp-server/README.md +170 -170
  132. package/scripts/mcp-server/auth.js +105 -105
  133. package/scripts/mcp-server/cache.js +106 -106
  134. package/scripts/mcp-server/telemetry.js +78 -78
  135. package/scripts/migrar-csv-a-array.js +168 -168
  136. package/scripts/migrar-fase-dominio.js +201 -201
  137. package/scripts/publicar.js +511 -511
  138. package/scripts/run-eval.js +141 -141
  139. package/scripts/tui/componentes/selector-multi.js +189 -0
  140. package/scripts/tui/componentes/selector-unico.js +158 -0
  141. package/scripts/tui/ejecutores.js +375 -0
  142. package/scripts/tui/index.js +162 -0
  143. package/scripts/tui/lib/colores.js +129 -0
  144. package/scripts/tui/lib/render.js +264 -0
  145. package/scripts/tui/lib/teclas.js +113 -0
  146. package/scripts/tui/pantallas/inspect.js +173 -0
  147. package/scripts/tui/pantallas/install-wizard.js +334 -0
  148. package/scripts/tui/pantallas/menu-principal.js +52 -0
  149. package/scripts/tui/pantallas/progreso.js +274 -0
  150. package/scripts/tui/pantallas/resumen.js +132 -0
  151. package/scripts/tui/pantallas/uninstall-wizard.js +208 -0
  152. package/scripts/tui/pantallas/update-wizard.js +232 -0
  153. package/scripts/tui/pantallas/welcome.js +187 -0
  154. package/scripts/validar-userland-vacio.js +110 -110
  155. package/scripts/verificar-docs-vs-codigo.js +425 -0
@@ -1,359 +1,359 @@
1
- 'use strict';
2
-
3
- /**
4
- * Transformador para Cursor.
5
- *
6
- * Cursor consume (formato confirmado vía docs oficiales el 2026-05-15):
7
- * - `.cursor/agents/<name>.md` con frontmatter YAML compatible con Claude:
8
- * name, description, model (default "inherit"), readonly, is_background
9
- * Cursor también acepta `.claude/agents/` y `.codex/agents/` como legacy.
10
- * Origen: https://cursor.com/es/docs/subagents
11
- *
12
- * - `.cursor/skills/<name>/SKILL.md` (mismo formato que Claude Code skills):
13
- * directorio con SKILL.md + scripts/ + references/ + assets/ opcionales.
14
- * Frontmatter: name, description, paths (opcional), disable-model-invocation.
15
- * Cursor también acepta `.agents/skills/`, `.claude/skills/` y `.codex/skills/`.
16
- * Origen: https://cursor.com/es/docs/skills
17
- *
18
- * - `.cursor/rules/*.mdc` con frontmatter YAML:
19
- * description, alwaysApply, globs (opcional).
20
- *
21
- * - `.cursor/mcp.json` o `~/.cursor/mcp.json` con:
22
- * { "mcpServers": { "<nombre>": { "command": "...", "args": [...], "env": {...} } } }
23
- *
24
- * Cursor NO soporta nativamente desde filesystem:
25
- * - Comandos slash custom (descartados — fuera de scope).
26
- * - Hooks (PreToolUse, PostToolUse, etc.).
27
- *
28
- * Side effect: si `contexto.withMcp`, escribe `.cursor/mcp.json` con `swl-memory`.
29
- */
30
-
31
- const fs = require('fs');
32
- const path = require('path');
33
- const TransformadorBase = require('./base');
34
- const { atomicWriteSync } = require('../../../hooks/lib/atomic-write');
35
-
36
- const MAX_DESCRIPTION_LEN = 200;
37
-
38
- class TransformadorCursor extends TransformadorBase {
39
- transformarAgente(contenidoMd, metadatos) {
40
- // Cursor lee agentes desde .cursor/agents/<name>.md (Sub-fase 7 v1.5.0).
41
- // El frontmatter Claude es subset del soportado por Cursor — pasamos el
42
- // archivo tal cual normalizando solo los campos que Cursor reconoce.
43
- const { frontmatter, cuerpo } = this.parsearFrontmatter(contenidoMd);
44
-
45
- const fmCursor = {};
46
- if (frontmatter.name) fmCursor.name = frontmatter.name;
47
- if (frontmatter.description) fmCursor.description = frontmatter.description;
48
- // Cursor admite `model: inherit` para heredar del padre. Si el agente SWL
49
- // declara modelo, lo mantenemos; si no, default a inherit.
50
- fmCursor.model = frontmatter.model || 'inherit';
51
- // Mapeo conservador: si el agente declara `permisosEscritura: false` en SWL,
52
- // se propaga como `readonly: true` en Cursor.
53
- if (frontmatter.permisosEscritura === false || frontmatter.readonly === true) {
54
- fmCursor.readonly = true;
55
- }
56
- if (frontmatter.is_background === true) {
57
- fmCursor.is_background = true;
58
- }
59
-
60
- return {
61
- contenido: this.construirMarkdown(fmCursor, cuerpo),
62
- rutaRelativa: `agents/${metadatos.nombreArchivo}`,
63
- };
64
- }
65
-
66
- transformarSkill(dirSkill, metadatos) {
67
- // Cursor carga skills desde .cursor/skills/<name>/SKILL.md (Sub-fase 7 v1.5.0).
68
- // Mismo formato que Claude Code skills — pasar el directorio completo.
69
- return {
70
- tipo: 'directorio',
71
- rutaRelativa: `skills/${metadatos.nombreDirectorio}`,
72
- };
73
- }
74
-
75
- transformarRegla(contenidoMd, metadatos) {
76
- const { frontmatter, cuerpo } = this.parsearFrontmatter(contenidoMd);
77
-
78
- // Derivar descripción para el .mdc (Cursor la lee del frontmatter)
79
- // Priorizar el `description:` si existe, si no, usar el name, si no, el nombre del archivo.
80
- let descripcion = frontmatter.description || frontmatter.name || metadatos.nombreArchivo || 'Regla SWL';
81
- descripcion = String(descripcion).replace(/\s+/g, ' ').trim();
82
- if (descripcion.length > MAX_DESCRIPTION_LEN) {
83
- descripcion = descripcion.slice(0, MAX_DESCRIPTION_LEN - 3) + '...';
84
- }
85
-
86
- // alwaysApply: las reglas SWL son políticas obligatorias → true por default.
87
- // Si el frontmatter declara `globs`, los propagamos.
88
- const globs = Array.isArray(frontmatter.globs) ? frontmatter.globs : null;
89
- const alwaysApply = globs ? false : true;
90
-
91
- const fm = { description: descripcion, alwaysApply };
92
- if (globs) fm.globs = globs;
93
-
94
- // .mdc usa el MISMO formato Markdown que .md, solo cambia el reconocimiento
95
- // por parte de Cursor. Pasamos el cuerpo tal cual (regla SWL completa).
96
- const contenido = this.construirMdc(fm, cuerpo);
97
-
98
- // Cambiar extensión .md → .mdc
99
- const baseNombre = (metadatos.nombreArchivo || 'regla.md').replace(/\.md$/i, '');
100
- return {
101
- contenido,
102
- rutaRelativa: `rules/${baseNombre}.mdc`,
103
- };
104
- }
105
-
106
- transformarComando(contenidoMd, metadatos) {
107
- // Cursor no soporta comandos slash custom — descartar
108
- return null;
109
- }
110
-
111
- /**
112
- * Genera un archivo principal consolidado de agentes en .cursor/rules/swl-agentes.mdc.
113
- * Es el equivalente a generarArchivoInstrucciones de otros targets, pero se enmascara
114
- * como una "regla SWL" para que Cursor lo cargue siempre.
115
- *
116
- * @param {object} contexto
117
- * @param {string} contexto.version
118
- * @param {string} contexto.perfil
119
- * @param {Array} contexto.agentes
120
- * @param {Array} contexto.skills (solo para tabla referencial)
121
- * @param {boolean} [contexto.esGlobal]
122
- * @param {string} [contexto.dirRuntimeGlobal]
123
- * @param {boolean} [contexto.withMcp]
124
- * @param {string} [contexto.swlBinPath]
125
- * @returns {object} Metadata de escritura
126
- */
127
- generarArchivoInstrucciones(contexto) {
128
- const lineas = [];
129
- const fecha = new Date().toISOString().split('T')[0];
130
-
131
- lineas.push('# Sistema SWL — agentes y referencia operativa (Cursor)');
132
- lineas.push('');
133
- lineas.push(`> Generado por swl-ses v${contexto.version} — ${fecha}`);
134
- lineas.push(`> Perfil: \`${contexto.perfil || 'default'}\`. Scope: \`${contexto.esGlobal ? 'global (~/.cursor/)' : 'proyecto'}\`.`);
135
- lineas.push(`> Regenerar con: \`npx @saulwade/swl-ses@latest install --target cursor${contexto.esGlobal ? ' --global' : ''} --force\`.`);
136
- lineas.push('');
137
-
138
- lineas.push('## Reglas de máxima prioridad');
139
- lineas.push('');
140
- lineas.push('1. **Idioma: español de México** — respuestas, comentarios, commits, docs.');
141
- lineas.push('2. **Investigar antes de editar** — leer el archivo completo antes de modificar.');
142
- lineas.push('3. **Memoria SWL accesible vía MCP** — usar `swl-memory` (server MCP) si está configurado para consultar aprendizajes, sesiones e instintos del proyecto.');
143
- lineas.push('');
144
-
145
- if (contexto.agentes && contexto.agentes.length > 0) {
146
- lineas.push('## Agentes disponibles (referencia conceptual)');
147
- lineas.push('');
148
- lineas.push(`> Total: ${contexto.agentes.length} agentes. Cursor no carga agentes desde filesystem; esta tabla documenta qué rol invocar conceptualmente al pedir tareas.`);
149
- lineas.push('');
150
- lineas.push('| Agente | Descripción |');
151
- lineas.push('|--------|-------------|');
152
- for (const ag of contexto.agentes) {
153
- const { frontmatter } = this.parsearFrontmatter(ag.contenido || '');
154
- const nombre = frontmatter.name || ag.nombre || 'sin-nombre';
155
- const desc = String(frontmatter.description || '').replace(/\|/g, '\\|');
156
- const descCorta = desc.length > 100 ? desc.slice(0, 97) + '...' : desc;
157
- lineas.push(`| \`${nombre}\` | ${descCorta} |`);
158
- }
159
- lineas.push('');
160
- }
161
-
162
- if (contexto.skills && contexto.skills.length > 0) {
163
- lineas.push('## Skills (acceso vía MCP swl-memory)');
164
- lineas.push('');
165
- lineas.push(`> Total: ${contexto.skills.length} skills. Cursor no carga skills desde filesystem. Si \`swl-memory\` está activo, usa las tools del MCP para invocar conocimiento operacional.`);
166
- lineas.push('');
167
- }
168
-
169
- lineas.push('## Memoria SWL (MCP)');
170
- lineas.push('');
171
- if (contexto.withMcp) {
172
- lineas.push('El servidor `swl-memory` está configurado en `.cursor/mcp.json`. Cursor lo expone con las tools:');
173
- lineas.push('');
174
- lineas.push('- `swl_memory_search` — búsqueda híbrida en memoria SWL.');
175
- lineas.push('- `swl_aprendizajes_recientes` — últimos aprendizajes del proyecto.');
176
- lineas.push('- `swl_instintos_activos` — patrones validados.');
177
- lineas.push('');
178
- lineas.push('Verificar en Cursor: Settings → Features → MCP debería listar `swl-memory` conectado.');
179
- } else {
180
- lineas.push('Para habilitar la memoria SWL en Cursor:');
181
- lineas.push('');
182
- lineas.push('```bash');
183
- lineas.push(`npx @saulwade/swl-ses@latest install --target cursor${contexto.esGlobal ? ' --global' : ''} --with-mcp --force`);
184
- lineas.push('```');
185
- }
186
- lineas.push('');
187
-
188
- // Side effect: si withMcp, escribir mcp.json
189
- if (contexto.withMcp) {
190
- this._escribirMcpJson(contexto);
191
- }
192
-
193
- const cuerpo = lineas.join('\n');
194
- const fm = {
195
- description: 'Sistema SWL — agentes, reglas obligatorias y memoria MCP para Cursor',
196
- alwaysApply: true,
197
- };
198
- const contenido = this.construirMdc(fm, cuerpo);
199
-
200
- const dirBase = contexto.esGlobal && contexto.dirRuntimeGlobal
201
- ? contexto.dirRuntimeGlobal
202
- : '.cursor';
203
-
204
- return {
205
- contenido,
206
- rutaRelativa: 'rules/swl-agentes.mdc',
207
- dirBase,
208
- };
209
- }
210
-
211
- /**
212
- * Sub-fase 10 v1.5.0: Cursor SÍ soporta hooks via .cursor/hooks.json
213
- * (cursor.com/es/docs/hooks). Schema:
214
- * { "version": 1, "hooks": { "preToolUse": [{ "command": "...", "type": "command", ... }] } }
215
- *
216
- * Mapeo Claude → Cursor:
217
- * PreToolUse → preToolUse, PostToolUse → postToolUse, Stop → stop,
218
- * SessionStart → sessionStart, UserPromptSubmit → beforeSubmitPrompt,
219
- * SubagentStop → subagentStop.
220
- * Notification → sin equivalente, descartar.
221
- */
222
- transformarHooks(hooksConfig, opciones) {
223
- if (!hooksConfig || typeof hooksConfig !== 'object') return null;
224
- const opts = opciones || {};
225
- const hookFilesFiltro = Array.isArray(opts.hookFiles) ? new Set(opts.hookFiles) : null;
226
- const rutaHooksDir = opts.rutaHooksDir || 'hooks';
227
-
228
- const MAPEO = {
229
- PreToolUse: 'preToolUse',
230
- PostToolUse: 'postToolUse',
231
- Stop: 'stop',
232
- SessionStart: 'sessionStart',
233
- UserPromptSubmit: 'beforeSubmitPrompt',
234
- SubagentStop: 'subagentStop',
235
- };
236
-
237
- const grupos = {};
238
- const descartados = [];
239
-
240
- for (const [hookFile, def] of Object.entries(hooksConfig)) {
241
- if (hookFilesFiltro && !hookFilesFiltro.has(hookFile)) continue;
242
- if (!def || !Array.isArray(def.events)) continue;
243
-
244
- for (const event of def.events) {
245
- const cursorEvent = MAPEO[event];
246
- if (!cursorEvent) {
247
- descartados.push({ hookFile, event, motivo: 'sin equivalente Cursor' });
248
- continue;
249
- }
250
- if (!grupos[cursorEvent]) grupos[cursorEvent] = [];
251
- // Cursor: entrada plana, sin grupo intermedio.
252
- const entry = {
253
- command: `node ${rutaHooksDir}/${hookFile}`,
254
- type: 'command',
255
- ...(def.timeout ? { timeout: def.timeout } : {}),
256
- ...(def.matcher ? { matcher: def.matcher } : {}),
257
- ...(def.failClosed === true ? { failClosed: true } : {}),
258
- };
259
- grupos[cursorEvent].push(entry);
260
- }
261
- }
262
-
263
- return {
264
- formato: 'cursor-hooks-json',
265
- destino: 'hooks.json',
266
- config: { version: 1, hooks: grupos },
267
- descartados,
268
- };
269
- }
270
-
271
- soportaTipo(tipo) {
272
- // Sub-fase 7 + 10 v1.5.0: Cursor soporta agentes, habilidades, reglas Y hooks.
273
- // Comandos slash custom: NO existen como filesystem (equivalente = skills).
274
- return ['agentes', 'habilidades', 'reglas', 'hooks'].includes(tipo);
275
- }
276
-
277
- // ---------------------------------------------------------------------------
278
- // Helpers
279
- // ---------------------------------------------------------------------------
280
-
281
- /**
282
- * Construye un archivo .mdc (formato Cursor) con frontmatter YAML mínimo.
283
- * Solo serializa los campos que Cursor entiende: description, alwaysApply, globs.
284
- */
285
- construirMdc(frontmatter, cuerpo) {
286
- const lineas = ['---'];
287
- if (frontmatter.description !== undefined) {
288
- lineas.push(`description: ${this._yamlString(frontmatter.description)}`);
289
- }
290
- if (frontmatter.alwaysApply !== undefined) {
291
- lineas.push(`alwaysApply: ${Boolean(frontmatter.alwaysApply)}`);
292
- }
293
- if (Array.isArray(frontmatter.globs) && frontmatter.globs.length > 0) {
294
- const items = frontmatter.globs.map(g => this._yamlString(g)).join(', ');
295
- lineas.push(`globs: [${items}]`);
296
- }
297
- lineas.push('---');
298
- lineas.push('');
299
- lineas.push(cuerpo);
300
- return lineas.join('\n');
301
- }
302
-
303
- _yamlString(s) {
304
- // Escapado simple para YAML inline — doblequotes con escape de backslash y doblequote.
305
- const escapado = String(s)
306
- .replace(/\\/g, '\\\\')
307
- .replace(/"/g, '\\"')
308
- .replace(/\n/g, ' ');
309
- return `"${escapado}"`;
310
- }
311
-
312
- /**
313
- * Escribe (o actualiza idempotentemente) `.cursor/mcp.json` con el server `swl-memory`.
314
- * Preserva otros mcpServers ya configurados por el usuario.
315
- *
316
- * Cursor lee `.cursor/mcp.json` per-proyecto y `~/.cursor/mcp.json` global. La función
317
- * decide según `contexto.esGlobal`.
318
- */
319
- _escribirMcpJson(contexto) {
320
- if (!contexto.swlBinPath) {
321
- console.warn('[cursor] withMcp=true pero no se proporcionó swlBinPath; .cursor/mcp.json no actualizado.');
322
- return;
323
- }
324
- const dirBase = contexto.esGlobal && contexto.dirRuntimeGlobal
325
- ? contexto.dirRuntimeGlobal
326
- : path.resolve('.cursor');
327
- fs.mkdirSync(dirBase, { recursive: true });
328
-
329
- const rutaMcp = path.join(dirBase, 'mcp.json');
330
- let existente = { mcpServers: {} };
331
- if (fs.existsSync(rutaMcp)) {
332
- try {
333
- const raw = fs.readFileSync(rutaMcp, 'utf-8');
334
- if (raw.trim().length > 0) {
335
- const parsed = JSON.parse(raw);
336
- existente = parsed && typeof parsed === 'object' ? parsed : { mcpServers: {} };
337
- if (!existente.mcpServers || typeof existente.mcpServers !== 'object') {
338
- existente.mcpServers = {};
339
- }
340
- }
341
- } catch (err) {
342
- console.warn(`[cursor] .cursor/mcp.json existente no es JSON válido (${err.message}). Se reemplazará preservando solo la entrada swl-memory.`);
343
- existente = { mcpServers: {} };
344
- }
345
- }
346
-
347
- existente.mcpServers['swl-memory'] = {
348
- command: 'node',
349
- args: [contexto.swlBinPath],
350
- env: {
351
- SWL_MCP_BASE_DIR: process.cwd(),
352
- },
353
- };
354
-
355
- atomicWriteSync(rutaMcp, JSON.stringify(existente, null, 2) + '\n', 'utf8', { mode: 0o600 });
356
- }
357
- }
358
-
359
- module.exports = TransformadorCursor;
1
+ 'use strict';
2
+
3
+ /**
4
+ * Transformador para Cursor.
5
+ *
6
+ * Cursor consume (formato confirmado vía docs oficiales el 2026-05-15):
7
+ * - `.cursor/agents/<name>.md` con frontmatter YAML compatible con Claude:
8
+ * name, description, model (default "inherit"), readonly, is_background
9
+ * Cursor también acepta `.claude/agents/` y `.codex/agents/` como legacy.
10
+ * Origen: https://cursor.com/es/docs/subagents
11
+ *
12
+ * - `.cursor/skills/<name>/SKILL.md` (mismo formato que Claude Code skills):
13
+ * directorio con SKILL.md + scripts/ + references/ + assets/ opcionales.
14
+ * Frontmatter: name, description, paths (opcional), disable-model-invocation.
15
+ * Cursor también acepta `.agents/skills/`, `.claude/skills/` y `.codex/skills/`.
16
+ * Origen: https://cursor.com/es/docs/skills
17
+ *
18
+ * - `.cursor/rules/*.mdc` con frontmatter YAML:
19
+ * description, alwaysApply, globs (opcional).
20
+ *
21
+ * - `.cursor/mcp.json` o `~/.cursor/mcp.json` con:
22
+ * { "mcpServers": { "<nombre>": { "command": "...", "args": [...], "env": {...} } } }
23
+ *
24
+ * Cursor NO soporta nativamente desde filesystem:
25
+ * - Comandos slash custom (descartados — fuera de scope).
26
+ * - Hooks (PreToolUse, PostToolUse, etc.).
27
+ *
28
+ * Side effect: si `contexto.withMcp`, escribe `.cursor/mcp.json` con `swl-memory`.
29
+ */
30
+
31
+ const fs = require('fs');
32
+ const path = require('path');
33
+ const TransformadorBase = require('./base');
34
+ const { atomicWriteSync } = require('../../../hooks/lib/atomic-write');
35
+
36
+ const MAX_DESCRIPTION_LEN = 200;
37
+
38
+ class TransformadorCursor extends TransformadorBase {
39
+ transformarAgente(contenidoMd, metadatos) {
40
+ // Cursor lee agentes desde .cursor/agents/<name>.md (Sub-fase 7 v1.5.0).
41
+ // El frontmatter Claude es subset del soportado por Cursor — pasamos el
42
+ // archivo tal cual normalizando solo los campos que Cursor reconoce.
43
+ const { frontmatter, cuerpo } = this.parsearFrontmatter(contenidoMd);
44
+
45
+ const fmCursor = {};
46
+ if (frontmatter.name) fmCursor.name = frontmatter.name;
47
+ if (frontmatter.description) fmCursor.description = frontmatter.description;
48
+ // Cursor admite `model: inherit` para heredar del padre. Si el agente SWL
49
+ // declara modelo, lo mantenemos; si no, default a inherit.
50
+ fmCursor.model = frontmatter.model || 'inherit';
51
+ // Mapeo conservador: si el agente declara `permisosEscritura: false` en SWL,
52
+ // se propaga como `readonly: true` en Cursor.
53
+ if (frontmatter.permisosEscritura === false || frontmatter.readonly === true) {
54
+ fmCursor.readonly = true;
55
+ }
56
+ if (frontmatter.is_background === true) {
57
+ fmCursor.is_background = true;
58
+ }
59
+
60
+ return {
61
+ contenido: this.construirMarkdown(fmCursor, cuerpo),
62
+ rutaRelativa: `agents/${metadatos.nombreArchivo}`,
63
+ };
64
+ }
65
+
66
+ transformarSkill(dirSkill, metadatos) {
67
+ // Cursor carga skills desde .cursor/skills/<name>/SKILL.md (Sub-fase 7 v1.5.0).
68
+ // Mismo formato que Claude Code skills — pasar el directorio completo.
69
+ return {
70
+ tipo: 'directorio',
71
+ rutaRelativa: `skills/${metadatos.nombreDirectorio}`,
72
+ };
73
+ }
74
+
75
+ transformarRegla(contenidoMd, metadatos) {
76
+ const { frontmatter, cuerpo } = this.parsearFrontmatter(contenidoMd);
77
+
78
+ // Derivar descripción para el .mdc (Cursor la lee del frontmatter)
79
+ // Priorizar el `description:` si existe, si no, usar el name, si no, el nombre del archivo.
80
+ let descripcion = frontmatter.description || frontmatter.name || metadatos.nombreArchivo || 'Regla SWL';
81
+ descripcion = String(descripcion).replace(/\s+/g, ' ').trim();
82
+ if (descripcion.length > MAX_DESCRIPTION_LEN) {
83
+ descripcion = descripcion.slice(0, MAX_DESCRIPTION_LEN - 3) + '...';
84
+ }
85
+
86
+ // alwaysApply: las reglas SWL son políticas obligatorias → true por default.
87
+ // Si el frontmatter declara `globs`, los propagamos.
88
+ const globs = Array.isArray(frontmatter.globs) ? frontmatter.globs : null;
89
+ const alwaysApply = globs ? false : true;
90
+
91
+ const fm = { description: descripcion, alwaysApply };
92
+ if (globs) fm.globs = globs;
93
+
94
+ // .mdc usa el MISMO formato Markdown que .md, solo cambia el reconocimiento
95
+ // por parte de Cursor. Pasamos el cuerpo tal cual (regla SWL completa).
96
+ const contenido = this.construirMdc(fm, cuerpo);
97
+
98
+ // Cambiar extensión .md → .mdc
99
+ const baseNombre = (metadatos.nombreArchivo || 'regla.md').replace(/\.md$/i, '');
100
+ return {
101
+ contenido,
102
+ rutaRelativa: `rules/${baseNombre}.mdc`,
103
+ };
104
+ }
105
+
106
+ transformarComando(contenidoMd, metadatos) {
107
+ // Cursor no soporta comandos slash custom — descartar
108
+ return null;
109
+ }
110
+
111
+ /**
112
+ * Genera un archivo principal consolidado de agentes en .cursor/rules/swl-agentes.mdc.
113
+ * Es el equivalente a generarArchivoInstrucciones de otros targets, pero se enmascara
114
+ * como una "regla SWL" para que Cursor lo cargue siempre.
115
+ *
116
+ * @param {object} contexto
117
+ * @param {string} contexto.version
118
+ * @param {string} contexto.perfil
119
+ * @param {Array} contexto.agentes
120
+ * @param {Array} contexto.skills (solo para tabla referencial)
121
+ * @param {boolean} [contexto.esGlobal]
122
+ * @param {string} [contexto.dirRuntimeGlobal]
123
+ * @param {boolean} [contexto.withMcp]
124
+ * @param {string} [contexto.swlBinPath]
125
+ * @returns {object} Metadata de escritura
126
+ */
127
+ generarArchivoInstrucciones(contexto) {
128
+ const lineas = [];
129
+ const fecha = new Date().toISOString().split('T')[0];
130
+
131
+ lineas.push('# Sistema SWL — agentes y referencia operativa (Cursor)');
132
+ lineas.push('');
133
+ lineas.push(`> Generado por swl-ses v${contexto.version} — ${fecha}`);
134
+ lineas.push(`> Perfil: \`${contexto.perfil || 'default'}\`. Scope: \`${contexto.esGlobal ? 'global (~/.cursor/)' : 'proyecto'}\`.`);
135
+ lineas.push(`> Regenerar con: \`npx @saulwade/swl-ses@latest install --target cursor${contexto.esGlobal ? ' --global' : ''} --force\`.`);
136
+ lineas.push('');
137
+
138
+ lineas.push('## Reglas de máxima prioridad');
139
+ lineas.push('');
140
+ lineas.push('1. **Idioma: español de México** — respuestas, comentarios, commits, docs.');
141
+ lineas.push('2. **Investigar antes de editar** — leer el archivo completo antes de modificar.');
142
+ lineas.push('3. **Memoria SWL accesible vía MCP** — usar `swl-memory` (server MCP) si está configurado para consultar aprendizajes, sesiones e instintos del proyecto.');
143
+ lineas.push('');
144
+
145
+ if (contexto.agentes && contexto.agentes.length > 0) {
146
+ lineas.push('## Agentes disponibles (referencia conceptual)');
147
+ lineas.push('');
148
+ lineas.push(`> Total: ${contexto.agentes.length} agentes. Cursor no carga agentes desde filesystem; esta tabla documenta qué rol invocar conceptualmente al pedir tareas.`);
149
+ lineas.push('');
150
+ lineas.push('| Agente | Descripción |');
151
+ lineas.push('|--------|-------------|');
152
+ for (const ag of contexto.agentes) {
153
+ const { frontmatter } = this.parsearFrontmatter(ag.contenido || '');
154
+ const nombre = frontmatter.name || ag.nombre || 'sin-nombre';
155
+ const desc = String(frontmatter.description || '').replace(/\|/g, '\\|');
156
+ const descCorta = desc.length > 100 ? desc.slice(0, 97) + '...' : desc;
157
+ lineas.push(`| \`${nombre}\` | ${descCorta} |`);
158
+ }
159
+ lineas.push('');
160
+ }
161
+
162
+ if (contexto.skills && contexto.skills.length > 0) {
163
+ lineas.push('## Skills (acceso vía MCP swl-memory)');
164
+ lineas.push('');
165
+ lineas.push(`> Total: ${contexto.skills.length} skills. Cursor no carga skills desde filesystem. Si \`swl-memory\` está activo, usa las tools del MCP para invocar conocimiento operacional.`);
166
+ lineas.push('');
167
+ }
168
+
169
+ lineas.push('## Memoria SWL (MCP)');
170
+ lineas.push('');
171
+ if (contexto.withMcp) {
172
+ lineas.push('El servidor `swl-memory` está configurado en `.cursor/mcp.json`. Cursor lo expone con las tools:');
173
+ lineas.push('');
174
+ lineas.push('- `swl_memory_search` — búsqueda híbrida en memoria SWL.');
175
+ lineas.push('- `swl_aprendizajes_recientes` — últimos aprendizajes del proyecto.');
176
+ lineas.push('- `swl_instintos_activos` — patrones validados.');
177
+ lineas.push('');
178
+ lineas.push('Verificar en Cursor: Settings → Features → MCP debería listar `swl-memory` conectado.');
179
+ } else {
180
+ lineas.push('Para habilitar la memoria SWL en Cursor:');
181
+ lineas.push('');
182
+ lineas.push('```bash');
183
+ lineas.push(`npx @saulwade/swl-ses@latest install --target cursor${contexto.esGlobal ? ' --global' : ''} --with-mcp --force`);
184
+ lineas.push('```');
185
+ }
186
+ lineas.push('');
187
+
188
+ // Side effect: si withMcp, escribir mcp.json
189
+ if (contexto.withMcp) {
190
+ this._escribirMcpJson(contexto);
191
+ }
192
+
193
+ const cuerpo = lineas.join('\n');
194
+ const fm = {
195
+ description: 'Sistema SWL — agentes, reglas obligatorias y memoria MCP para Cursor',
196
+ alwaysApply: true,
197
+ };
198
+ const contenido = this.construirMdc(fm, cuerpo);
199
+
200
+ const dirBase = contexto.esGlobal && contexto.dirRuntimeGlobal
201
+ ? contexto.dirRuntimeGlobal
202
+ : '.cursor';
203
+
204
+ return {
205
+ contenido,
206
+ rutaRelativa: 'rules/swl-agentes.mdc',
207
+ dirBase,
208
+ };
209
+ }
210
+
211
+ /**
212
+ * Sub-fase 10 v1.5.0: Cursor SÍ soporta hooks via .cursor/hooks.json
213
+ * (cursor.com/es/docs/hooks). Schema:
214
+ * { "version": 1, "hooks": { "preToolUse": [{ "command": "...", "type": "command", ... }] } }
215
+ *
216
+ * Mapeo Claude → Cursor:
217
+ * PreToolUse → preToolUse, PostToolUse → postToolUse, Stop → stop,
218
+ * SessionStart → sessionStart, UserPromptSubmit → beforeSubmitPrompt,
219
+ * SubagentStop → subagentStop.
220
+ * Notification → sin equivalente, descartar.
221
+ */
222
+ transformarHooks(hooksConfig, opciones) {
223
+ if (!hooksConfig || typeof hooksConfig !== 'object') return null;
224
+ const opts = opciones || {};
225
+ const hookFilesFiltro = Array.isArray(opts.hookFiles) ? new Set(opts.hookFiles) : null;
226
+ const rutaHooksDir = opts.rutaHooksDir || 'hooks';
227
+
228
+ const MAPEO = {
229
+ PreToolUse: 'preToolUse',
230
+ PostToolUse: 'postToolUse',
231
+ Stop: 'stop',
232
+ SessionStart: 'sessionStart',
233
+ UserPromptSubmit: 'beforeSubmitPrompt',
234
+ SubagentStop: 'subagentStop',
235
+ };
236
+
237
+ const grupos = {};
238
+ const descartados = [];
239
+
240
+ for (const [hookFile, def] of Object.entries(hooksConfig)) {
241
+ if (hookFilesFiltro && !hookFilesFiltro.has(hookFile)) continue;
242
+ if (!def || !Array.isArray(def.events)) continue;
243
+
244
+ for (const event of def.events) {
245
+ const cursorEvent = MAPEO[event];
246
+ if (!cursorEvent) {
247
+ descartados.push({ hookFile, event, motivo: 'sin equivalente Cursor' });
248
+ continue;
249
+ }
250
+ if (!grupos[cursorEvent]) grupos[cursorEvent] = [];
251
+ // Cursor: entrada plana, sin grupo intermedio.
252
+ const entry = {
253
+ command: `node ${rutaHooksDir}/${hookFile}`,
254
+ type: 'command',
255
+ ...(def.timeout ? { timeout: def.timeout } : {}),
256
+ ...(def.matcher ? { matcher: def.matcher } : {}),
257
+ ...(def.failClosed === true ? { failClosed: true } : {}),
258
+ };
259
+ grupos[cursorEvent].push(entry);
260
+ }
261
+ }
262
+
263
+ return {
264
+ formato: 'cursor-hooks-json',
265
+ destino: 'hooks.json',
266
+ config: { version: 1, hooks: grupos },
267
+ descartados,
268
+ };
269
+ }
270
+
271
+ soportaTipo(tipo) {
272
+ // Sub-fase 7 + 10 v1.5.0: Cursor soporta agentes, habilidades, reglas Y hooks.
273
+ // Comandos slash custom: NO existen como filesystem (equivalente = skills).
274
+ return ['agentes', 'habilidades', 'reglas', 'hooks'].includes(tipo);
275
+ }
276
+
277
+ // ---------------------------------------------------------------------------
278
+ // Helpers
279
+ // ---------------------------------------------------------------------------
280
+
281
+ /**
282
+ * Construye un archivo .mdc (formato Cursor) con frontmatter YAML mínimo.
283
+ * Solo serializa los campos que Cursor entiende: description, alwaysApply, globs.
284
+ */
285
+ construirMdc(frontmatter, cuerpo) {
286
+ const lineas = ['---'];
287
+ if (frontmatter.description !== undefined) {
288
+ lineas.push(`description: ${this._yamlString(frontmatter.description)}`);
289
+ }
290
+ if (frontmatter.alwaysApply !== undefined) {
291
+ lineas.push(`alwaysApply: ${Boolean(frontmatter.alwaysApply)}`);
292
+ }
293
+ if (Array.isArray(frontmatter.globs) && frontmatter.globs.length > 0) {
294
+ const items = frontmatter.globs.map(g => this._yamlString(g)).join(', ');
295
+ lineas.push(`globs: [${items}]`);
296
+ }
297
+ lineas.push('---');
298
+ lineas.push('');
299
+ lineas.push(cuerpo);
300
+ return lineas.join('\n');
301
+ }
302
+
303
+ _yamlString(s) {
304
+ // Escapado simple para YAML inline — doblequotes con escape de backslash y doblequote.
305
+ const escapado = String(s)
306
+ .replace(/\\/g, '\\\\')
307
+ .replace(/"/g, '\\"')
308
+ .replace(/\n/g, ' ');
309
+ return `"${escapado}"`;
310
+ }
311
+
312
+ /**
313
+ * Escribe (o actualiza idempotentemente) `.cursor/mcp.json` con el server `swl-memory`.
314
+ * Preserva otros mcpServers ya configurados por el usuario.
315
+ *
316
+ * Cursor lee `.cursor/mcp.json` per-proyecto y `~/.cursor/mcp.json` global. La función
317
+ * decide según `contexto.esGlobal`.
318
+ */
319
+ _escribirMcpJson(contexto) {
320
+ if (!contexto.swlBinPath) {
321
+ console.warn('[cursor] withMcp=true pero no se proporcionó swlBinPath; .cursor/mcp.json no actualizado.');
322
+ return;
323
+ }
324
+ const dirBase = contexto.esGlobal && contexto.dirRuntimeGlobal
325
+ ? contexto.dirRuntimeGlobal
326
+ : path.resolve('.cursor');
327
+ fs.mkdirSync(dirBase, { recursive: true });
328
+
329
+ const rutaMcp = path.join(dirBase, 'mcp.json');
330
+ let existente = { mcpServers: {} };
331
+ if (fs.existsSync(rutaMcp)) {
332
+ try {
333
+ const raw = fs.readFileSync(rutaMcp, 'utf-8');
334
+ if (raw.trim().length > 0) {
335
+ const parsed = JSON.parse(raw);
336
+ existente = parsed && typeof parsed === 'object' ? parsed : { mcpServers: {} };
337
+ if (!existente.mcpServers || typeof existente.mcpServers !== 'object') {
338
+ existente.mcpServers = {};
339
+ }
340
+ }
341
+ } catch (err) {
342
+ console.warn(`[cursor] .cursor/mcp.json existente no es JSON válido (${err.message}). Se reemplazará preservando solo la entrada swl-memory.`);
343
+ existente = { mcpServers: {} };
344
+ }
345
+ }
346
+
347
+ existente.mcpServers['swl-memory'] = {
348
+ command: 'node',
349
+ args: [contexto.swlBinPath],
350
+ env: {
351
+ SWL_MCP_BASE_DIR: process.cwd(),
352
+ },
353
+ };
354
+
355
+ atomicWriteSync(rutaMcp, JSON.stringify(existente, null, 2) + '\n', 'utf8', { mode: 0o600 });
356
+ }
357
+ }
358
+
359
+ module.exports = TransformadorCursor;