@saulwade/swl-ses 1.4.1 → 1.5.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 (136) hide show
  1. package/CLAUDE.md +3 -3
  2. package/README.md +561 -560
  3. package/agentes/nemesis-auditor-swl.md +161 -161
  4. package/bin/swl-mcp-server.js +49 -22
  5. package/bin/swl-ses.js +74 -0
  6. package/comandos/swl/.evolved.json +22 -22
  7. package/comandos/swl/contribuir.md +233 -233
  8. package/comandos/swl/ejecutar-fase.md +33 -4
  9. package/comandos/swl/metricas.md +72 -0
  10. package/comandos/swl/nemesis.md +122 -122
  11. package/gateway/lib/event-channel.js +191 -191
  12. package/habilidades/backend-production-resilience/SKILL.md +288 -288
  13. package/habilidades/benchmark-memoria/SKILL.md +186 -186
  14. package/habilidades/diagrama-arquitectura/assets/template.html +276 -276
  15. package/habilidades/discutir-fase/SKILL.md +50 -2
  16. package/habilidades/doubt-driven-review/SKILL.md +171 -171
  17. package/habilidades/doubt-driven-review/recursos/EXAMPLES.md +130 -130
  18. package/habilidades/ejecutar-task-iterativo/SKILL.md +278 -0
  19. package/habilidades/eval-framework/SKILL.md +212 -212
  20. package/habilidades/feynman-auditor-swl/SKILL.md +123 -123
  21. package/habilidades/feynman-auditor-swl/recursos/preguntas-language-agnostic.md +108 -108
  22. package/habilidades/harness-claude-code/SKILL.md +299 -299
  23. package/habilidades/infra-github-actions/SKILL.md +166 -166
  24. package/habilidades/legacy-code-rescue/SKILL.md +267 -267
  25. package/habilidades/manejo-errores/.evolved.json +8 -8
  26. package/habilidades/meta-skills-estandar/recursos/convencion-examples.md +93 -93
  27. package/habilidades/meta-skills-estandar/recursos/skills-as-agents.md +163 -163
  28. package/habilidades/patrones-python/SKILL.md +229 -229
  29. package/habilidades/patrones-python/recursos/patrones-avanzados.md +469 -469
  30. package/habilidades/planear-fase/SKILL.md +319 -319
  31. package/habilidades/protocolo-revision-swl/SKILL.md +276 -0
  32. package/habilidades/release-semver/.evolved.json +8 -8
  33. package/habilidades/state-inconsistency-auditor-swl/SKILL.md +166 -166
  34. package/habilidades/state-inconsistency-auditor-swl/recursos/coupled-state-patterns.md +147 -147
  35. package/habilidades/testing-python/SKILL.md +340 -340
  36. package/habilidades/verificar-trabajo/SKILL.md +49 -5
  37. package/habilidades/web-fetcher-routing/SKILL.md +75 -75
  38. package/hooks/claudemd-bloat-detector.js +161 -161
  39. package/hooks/lib/agent-routing.js +107 -107
  40. package/hooks/lib/auto-consolidator.js +335 -335
  41. package/hooks/lib/error-classifier.js +308 -308
  42. package/hooks/lib/merkle-audit.js +96 -96
  43. package/hooks/lib/provenance-tracker.js +191 -191
  44. package/hooks/lib/rate-limit-tracker.js +253 -253
  45. package/hooks/lib/resource-quota.js +122 -122
  46. package/hooks/lib/retry-jitter.js +165 -165
  47. package/hooks/lib/security-net.js +201 -201
  48. package/hooks/lib/skill-auditor.js +588 -588
  49. package/hooks/lib/sync-status.js +228 -228
  50. package/hooks/lib/taint-tracker.js +107 -107
  51. package/hooks/lib/text-similarity.js +241 -241
  52. package/hooks/lib/toon-compressor.js +245 -245
  53. package/hooks/registro-turnos.js +209 -209
  54. package/hooks/sugerir-regenerar-inventario.js +170 -170
  55. package/hooks/validar-formato-post-subagente.js +140 -140
  56. package/hooks/validar-memoria-hook.js +218 -218
  57. package/instintos/prompt-appendices.yaml +57 -57
  58. package/manifiestos/agent-output-schemas.json +57 -57
  59. package/manifiestos/modulos.json +1321 -1262
  60. package/manifiestos/perfiles.json +2 -1
  61. package/manifiestos/skills-lock.json +1114 -1114
  62. package/package.json +3 -3
  63. package/plantillas/auditor-veto-template.md +105 -105
  64. package/plantillas/github-workflows/README.md +47 -47
  65. package/plantillas/github-workflows/release-please.yml +44 -44
  66. package/plantillas/github-workflows/swl-ci.yml +107 -107
  67. package/plantillas/github-workflows/swl-security.yml +51 -51
  68. package/plugin.json +351 -343
  69. package/reglas/analisis-previo-tareas-grandes.md +172 -172
  70. package/reglas/arreglar-al-detectar.md +147 -147
  71. package/reglas/fragmentos-compartidos.md +152 -152
  72. package/reglas/harness-claude-code.md +213 -213
  73. package/reglas/usar-context7.md +226 -226
  74. package/schemas/diary-entry.schema.json +80 -80
  75. package/scripts/audit-tools/audit-history.js +330 -330
  76. package/scripts/audit-tools/bundle-tracker.js +290 -290
  77. package/scripts/audit-tools/canary-monitor.js +352 -352
  78. package/scripts/audit-tools/code-profiler.js +605 -605
  79. package/scripts/audit-tools/dep-doctor.js +320 -320
  80. package/scripts/audit-tools/env-validator.js +206 -206
  81. package/scripts/audit-tools/lib/fs-walk.js +48 -48
  82. package/scripts/audit-tools/lib/output.js +23 -23
  83. package/scripts/audit-tools/migration-checker.js +392 -392
  84. package/scripts/audit-tools/pentest-scanner.js +1436 -1436
  85. package/scripts/benchmark-memoria.js +167 -167
  86. package/scripts/configurar-branch-protection.js +418 -418
  87. package/scripts/derivar-feature-list.js +489 -0
  88. package/scripts/detectar-aprendizajes-duplicados.js +151 -151
  89. package/scripts/doctor.js +31 -4
  90. package/scripts/field-report.js +199 -199
  91. package/scripts/generar-checklists-consolidados.js +273 -273
  92. package/scripts/generar-inventario.js +420 -420
  93. package/scripts/generar-matriz-lenguajes.js +271 -271
  94. package/scripts/instalador.js +56 -5
  95. package/scripts/lib/artefactos-python.js +43 -43
  96. package/scripts/lib/benchmark-metrics.js +160 -160
  97. package/scripts/lib/budget-enforcer.js +252 -252
  98. package/scripts/lib/configurar-ci.js +380 -380
  99. package/scripts/lib/contadores-inventario.js +217 -217
  100. package/scripts/lib/detectar-runtime.js +75 -9
  101. package/scripts/lib/detectar-stack-detallado.js +307 -307
  102. package/scripts/lib/diary-entry.js +234 -234
  103. package/scripts/lib/estado.js +13 -1
  104. package/scripts/lib/eval-metrics-store.js +218 -218
  105. package/scripts/lib/eval-quality.js +171 -171
  106. package/scripts/lib/eval-schemas.js +144 -144
  107. package/scripts/lib/eval-self-correct.js +106 -106
  108. package/scripts/lib/eval-validator.js +185 -185
  109. package/scripts/lib/expandir-targets.js +71 -0
  110. package/scripts/lib/jaccard-similarity.js +98 -98
  111. package/scripts/lib/longmemeval-runner.js +125 -125
  112. package/scripts/lib/manifiestos.js +42 -1
  113. package/scripts/lib/npm-version.js +261 -261
  114. package/scripts/lib/paquetes-conocidos.js +50 -50
  115. package/scripts/lib/parsear-opciones.js +3 -0
  116. package/scripts/lib/prompt-builder.js +264 -264
  117. package/scripts/lib/rrf-fusion.js +175 -175
  118. package/scripts/lib/scoring-instintos.js +277 -277
  119. package/scripts/lib/semantic-search.js +252 -252
  120. package/scripts/lib/toml-merge.js +204 -0
  121. package/scripts/lib/transformadores/base.js +43 -9
  122. package/scripts/lib/transformadores/codex.js +375 -115
  123. package/scripts/lib/transformadores/cursor.js +359 -0
  124. package/scripts/lib/transformadores/index.js +2 -0
  125. package/scripts/limpiar-artefactos-python.js +131 -131
  126. package/scripts/mcp-server/README.md +122 -80
  127. package/scripts/mcp-server/auth.js +105 -0
  128. package/scripts/mcp-server/cache.js +106 -0
  129. package/scripts/mcp-server/handlers.js +386 -206
  130. package/scripts/mcp-server/telemetry.js +78 -0
  131. package/scripts/migrar-csv-a-array.js +168 -168
  132. package/scripts/migrar-fase-dominio.js +201 -201
  133. package/scripts/publicar.js +511 -511
  134. package/scripts/run-eval.js +141 -141
  135. package/scripts/validar-manifest.js +231 -195
  136. package/scripts/validar-userland-vacio.js +110 -110
@@ -0,0 +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;
@@ -5,6 +5,7 @@ const TransformadorCopilot = require('./copilot');
5
5
  const TransformadorOpenCode = require('./opencode');
6
6
  const TransformadorCodex = require('./codex');
7
7
  const TransformadorGemini = require('./gemini');
8
+ const TransformadorCursor = require('./cursor');
8
9
 
9
10
  const TRANSFORMADORES = {
10
11
  claude: TransformadorClaude,
@@ -13,6 +14,7 @@ const TRANSFORMADORES = {
13
14
  opencode: TransformadorOpenCode,
14
15
  codex: TransformadorCodex,
15
16
  gemini: TransformadorGemini,
17
+ cursor: TransformadorCursor, // ADR-0019 Sub-fase 2
16
18
  };
17
19
 
18
20
  function obtenerTransformador(targetId, runtimeConfig) {
@@ -1,131 +1,131 @@
1
- #!/usr/bin/env node
2
- 'use strict';
3
-
4
- /**
5
- * limpiar-artefactos-python.js — limpia caché Python antes de empaquetar.
6
- *
7
- * Se ejecuta como `prepack` antes de `npm pack` y `npm publish` para evitar
8
- * que artefactos locales (.pyc, __pycache__/) contaminen el tarball publicado.
9
- *
10
- * Reglas de seguridad (defensa en profundidad):
11
- * 1. Aborta si cwd no coincide con la raíz del package.json del repo.
12
- * 2. Profundidad máxima de recursión: 3 niveles desde la raíz.
13
- * 3. Allowlist explícita de directorios a EXCLUIR de la búsqueda
14
- * (node_modules, .git, temp, .planning, respositorios-git, _userland).
15
- * 4. Solo elimina directorios cuyo nombre coincide exactamente con el
16
- * conjunto cerrado: __pycache__, .pytest_cache, .mypy_cache, .ruff_cache.
17
- * 5. Solo elimina archivos sueltos con extensiones .pyc, .pyo.
18
- * 6. En CI no-interactivo respeta el flag SWL_PREPACK_DRY=1 (no borra,
19
- * solo lista).
20
- *
21
- * Exit codes:
22
- * 0 — OK (limpieza ejecutada o nada que limpiar)
23
- * 1 — error de invariante (cwd incorrecto, package.json no encontrado)
24
- */
25
-
26
- const fs = require('fs');
27
- const path = require('path');
28
-
29
- const { NOMBRES_VALIDOS } = require('./lib/paquetes-conocidos');
30
- const {
31
- DIRS_ARTEFACTOS_PYTHON: DIRS_A_LIMPIAR,
32
- EXTS_ARTEFACTOS_PYTHON: EXTS_A_LIMPIAR,
33
- } = require('./lib/artefactos-python');
34
-
35
- const PROFUNDIDAD_MAX = 3;
36
- const DIRS_EXCLUIDOS = new Set([
37
- 'node_modules', '.git', 'temp', '.planning', 'respositorios-git',
38
- '_userland', 'tests', '.github',
39
- ]);
40
-
41
- const dryRun = process.env.SWL_PREPACK_DRY === '1';
42
-
43
- function log(msg) { process.stdout.write(`[prepack] ${msg}\n`); }
44
- function err(msg) { process.stderr.write(`[prepack] ERROR: ${msg}\n`); }
45
-
46
- /**
47
- * Verifica que el cwd actual contiene el package.json del repo swl-ses.
48
- * Esto evita que el script borre directorios en la máquina del usuario si
49
- * algún día se invocara desde un cwd incorrecto (ej. dentro de un tarball
50
- * extraído por npm en .npm/_cacache).
51
- */
52
- function verificarRaiz() {
53
- const cwd = process.cwd();
54
- const pkgPath = path.join(cwd, 'package.json');
55
- if (!fs.existsSync(pkgPath)) {
56
- err(`no existe package.json en cwd: ${cwd}`);
57
- process.exit(1);
58
- }
59
- const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
60
- if (!NOMBRES_VALIDOS.includes(pkg.name)) {
61
- err(`package.json en ${cwd} no corresponde a swl-ses (name: ${pkg.name}). Abortando por seguridad.`);
62
- process.exit(1);
63
- }
64
- return cwd;
65
- }
66
-
67
- /**
68
- * Recorre el árbol desde root con profundidad limitada y elimina los
69
- * artefactos Python detectados. No sigue symlinks.
70
- */
71
- function limpiar(root, profundidad = 0) {
72
- if (profundidad > PROFUNDIDAD_MAX) return { dirs: 0, files: 0 };
73
-
74
- let dirsEliminados = 0;
75
- let filesEliminados = 0;
76
-
77
- let entries;
78
- try {
79
- entries = fs.readdirSync(root, { withFileTypes: true });
80
- } catch (e) {
81
- err(`no se pudo leer ${root}: ${e.message}`);
82
- return { dirs: 0, files: 0 };
83
- }
84
-
85
- for (const entry of entries) {
86
- if (entry.isSymbolicLink()) continue;
87
- const fullPath = path.join(root, entry.name);
88
-
89
- if (entry.isDirectory()) {
90
- if (DIRS_A_LIMPIAR.has(entry.name)) {
91
- if (dryRun) {
92
- log(`[dry-run] borraría dir: ${path.relative(process.cwd(), fullPath)}`);
93
- } else {
94
- fs.rmSync(fullPath, { recursive: true, force: true });
95
- log(`borrado dir: ${path.relative(process.cwd(), fullPath)}`);
96
- }
97
- dirsEliminados++;
98
- } else if (!DIRS_EXCLUIDOS.has(entry.name) && !entry.name.startsWith('.')) {
99
- const sub = limpiar(fullPath, profundidad + 1);
100
- dirsEliminados += sub.dirs;
101
- filesEliminados += sub.files;
102
- }
103
- } else if (entry.isFile()) {
104
- const ext = path.extname(entry.name).toLowerCase();
105
- if (EXTS_A_LIMPIAR.has(ext)) {
106
- if (dryRun) {
107
- log(`[dry-run] borraría archivo: ${path.relative(process.cwd(), fullPath)}`);
108
- } else {
109
- fs.rmSync(fullPath, { force: true });
110
- }
111
- filesEliminados++;
112
- }
113
- }
114
- }
115
-
116
- return { dirs: dirsEliminados, files: filesEliminados };
117
- }
118
-
119
- function main() {
120
- const root = verificarRaiz();
121
- const result = limpiar(root);
122
-
123
- if (result.dirs === 0 && result.files === 0) {
124
- log('sin artefactos Python que limpiar.');
125
- } else {
126
- const accion = dryRun ? 'detectados' : 'eliminados';
127
- log(`${accion}: ${result.dirs} directorios + ${result.files} archivos.`);
128
- }
129
- }
130
-
131
- main();
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * limpiar-artefactos-python.js — limpia caché Python antes de empaquetar.
6
+ *
7
+ * Se ejecuta como `prepack` antes de `npm pack` y `npm publish` para evitar
8
+ * que artefactos locales (.pyc, __pycache__/) contaminen el tarball publicado.
9
+ *
10
+ * Reglas de seguridad (defensa en profundidad):
11
+ * 1. Aborta si cwd no coincide con la raíz del package.json del repo.
12
+ * 2. Profundidad máxima de recursión: 3 niveles desde la raíz.
13
+ * 3. Allowlist explícita de directorios a EXCLUIR de la búsqueda
14
+ * (node_modules, .git, temp, .planning, respositorios-git, _userland).
15
+ * 4. Solo elimina directorios cuyo nombre coincide exactamente con el
16
+ * conjunto cerrado: __pycache__, .pytest_cache, .mypy_cache, .ruff_cache.
17
+ * 5. Solo elimina archivos sueltos con extensiones .pyc, .pyo.
18
+ * 6. En CI no-interactivo respeta el flag SWL_PREPACK_DRY=1 (no borra,
19
+ * solo lista).
20
+ *
21
+ * Exit codes:
22
+ * 0 — OK (limpieza ejecutada o nada que limpiar)
23
+ * 1 — error de invariante (cwd incorrecto, package.json no encontrado)
24
+ */
25
+
26
+ const fs = require('fs');
27
+ const path = require('path');
28
+
29
+ const { NOMBRES_VALIDOS } = require('./lib/paquetes-conocidos');
30
+ const {
31
+ DIRS_ARTEFACTOS_PYTHON: DIRS_A_LIMPIAR,
32
+ EXTS_ARTEFACTOS_PYTHON: EXTS_A_LIMPIAR,
33
+ } = require('./lib/artefactos-python');
34
+
35
+ const PROFUNDIDAD_MAX = 3;
36
+ const DIRS_EXCLUIDOS = new Set([
37
+ 'node_modules', '.git', 'temp', '.planning', 'respositorios-git',
38
+ '_userland', 'tests', '.github',
39
+ ]);
40
+
41
+ const dryRun = process.env.SWL_PREPACK_DRY === '1';
42
+
43
+ function log(msg) { process.stdout.write(`[prepack] ${msg}\n`); }
44
+ function err(msg) { process.stderr.write(`[prepack] ERROR: ${msg}\n`); }
45
+
46
+ /**
47
+ * Verifica que el cwd actual contiene el package.json del repo swl-ses.
48
+ * Esto evita que el script borre directorios en la máquina del usuario si
49
+ * algún día se invocara desde un cwd incorrecto (ej. dentro de un tarball
50
+ * extraído por npm en .npm/_cacache).
51
+ */
52
+ function verificarRaiz() {
53
+ const cwd = process.cwd();
54
+ const pkgPath = path.join(cwd, 'package.json');
55
+ if (!fs.existsSync(pkgPath)) {
56
+ err(`no existe package.json en cwd: ${cwd}`);
57
+ process.exit(1);
58
+ }
59
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
60
+ if (!NOMBRES_VALIDOS.includes(pkg.name)) {
61
+ err(`package.json en ${cwd} no corresponde a swl-ses (name: ${pkg.name}). Abortando por seguridad.`);
62
+ process.exit(1);
63
+ }
64
+ return cwd;
65
+ }
66
+
67
+ /**
68
+ * Recorre el árbol desde root con profundidad limitada y elimina los
69
+ * artefactos Python detectados. No sigue symlinks.
70
+ */
71
+ function limpiar(root, profundidad = 0) {
72
+ if (profundidad > PROFUNDIDAD_MAX) return { dirs: 0, files: 0 };
73
+
74
+ let dirsEliminados = 0;
75
+ let filesEliminados = 0;
76
+
77
+ let entries;
78
+ try {
79
+ entries = fs.readdirSync(root, { withFileTypes: true });
80
+ } catch (e) {
81
+ err(`no se pudo leer ${root}: ${e.message}`);
82
+ return { dirs: 0, files: 0 };
83
+ }
84
+
85
+ for (const entry of entries) {
86
+ if (entry.isSymbolicLink()) continue;
87
+ const fullPath = path.join(root, entry.name);
88
+
89
+ if (entry.isDirectory()) {
90
+ if (DIRS_A_LIMPIAR.has(entry.name)) {
91
+ if (dryRun) {
92
+ log(`[dry-run] borraría dir: ${path.relative(process.cwd(), fullPath)}`);
93
+ } else {
94
+ fs.rmSync(fullPath, { recursive: true, force: true });
95
+ log(`borrado dir: ${path.relative(process.cwd(), fullPath)}`);
96
+ }
97
+ dirsEliminados++;
98
+ } else if (!DIRS_EXCLUIDOS.has(entry.name) && !entry.name.startsWith('.')) {
99
+ const sub = limpiar(fullPath, profundidad + 1);
100
+ dirsEliminados += sub.dirs;
101
+ filesEliminados += sub.files;
102
+ }
103
+ } else if (entry.isFile()) {
104
+ const ext = path.extname(entry.name).toLowerCase();
105
+ if (EXTS_A_LIMPIAR.has(ext)) {
106
+ if (dryRun) {
107
+ log(`[dry-run] borraría archivo: ${path.relative(process.cwd(), fullPath)}`);
108
+ } else {
109
+ fs.rmSync(fullPath, { force: true });
110
+ }
111
+ filesEliminados++;
112
+ }
113
+ }
114
+ }
115
+
116
+ return { dirs: dirsEliminados, files: filesEliminados };
117
+ }
118
+
119
+ function main() {
120
+ const root = verificarRaiz();
121
+ const result = limpiar(root);
122
+
123
+ if (result.dirs === 0 && result.files === 0) {
124
+ log('sin artefactos Python que limpiar.');
125
+ } else {
126
+ const accion = dryRun ? 'detectados' : 'eliminados';
127
+ log(`${accion}: ${result.dirs} directorios + ${result.files} archivos.`);
128
+ }
129
+ }
130
+
131
+ main();