@saulwade/swl-ses 1.3.8 → 1.4.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 (128) hide show
  1. package/CLAUDE.md +12 -4
  2. package/README.md +1 -1
  3. package/bin/swl-mcp-server.js +187 -187
  4. package/bin/swl-webhook-server.js +198 -0
  5. package/comandos/swl/.evolved.json +22 -22
  6. package/comandos/swl/adoptar-proyecto.md +21 -1
  7. package/comandos/swl/claudemd.md +14 -1
  8. package/comandos/swl/contribuir.md +233 -233
  9. package/comandos/swl/exportar-vault.md +108 -0
  10. package/comandos/swl/nuevo-proyecto.md +24 -2
  11. package/gateway/adapters/base.js +109 -0
  12. package/gateway/adapters/discord.js +167 -0
  13. package/gateway/adapters/email.js +221 -0
  14. package/gateway/adapters/slack.js +192 -0
  15. package/gateway/adapters/telegram.js +183 -0
  16. package/gateway/adapters/webhook.js +113 -0
  17. package/gateway/adapters/whatsapp.js +214 -0
  18. package/gateway/agent-executor.js +322 -0
  19. package/gateway/command-relay.js +271 -0
  20. package/gateway/cron/jobs.js +263 -0
  21. package/gateway/cron/scheduler.js +322 -0
  22. package/gateway/cron/store.js +335 -0
  23. package/gateway/index.js +320 -0
  24. package/gateway/lib/event-channel.js +191 -0
  25. package/gateway/session.js +131 -0
  26. package/gateway/webhook-server.js +324 -0
  27. package/habilidades/backend-production-resilience/SKILL.md +288 -288
  28. package/habilidades/benchmark-memoria/SKILL.md +186 -186
  29. package/habilidades/build-errors-nextjs/SKILL.md +55 -1
  30. package/habilidades/diagrama-arquitectura/assets/template.html +276 -276
  31. package/habilidades/doubt-driven-review/SKILL.md +171 -171
  32. package/habilidades/doubt-driven-review/recursos/EXAMPLES.md +130 -130
  33. package/habilidades/eval-framework/SKILL.md +212 -212
  34. package/habilidades/extractor-de-aprendizajes/SKILL.md +20 -10
  35. package/habilidades/harness-claude-code/SKILL.md +299 -299
  36. package/habilidades/infra-github-actions/SKILL.md +166 -166
  37. package/habilidades/legacy-code-rescue/SKILL.md +267 -267
  38. package/habilidades/manejo-errores/.evolved.json +8 -8
  39. package/habilidades/meta-skills-estandar/recursos/convencion-examples.md +93 -93
  40. package/habilidades/meta-skills-estandar/recursos/skills-as-agents.md +163 -163
  41. package/habilidades/nextjs-testing/SKILL.md +89 -5
  42. package/habilidades/node-experto/SKILL.md +37 -1
  43. package/habilidades/patrones-python/SKILL.md +229 -229
  44. package/habilidades/patrones-python/recursos/patrones-avanzados.md +469 -469
  45. package/habilidades/planear-fase/SKILL.md +319 -319
  46. package/habilidades/react-experto/SKILL.md +45 -4
  47. package/habilidades/release-semver/.evolved.json +8 -8
  48. package/habilidades/tdd-workflow/SKILL.md +36 -4
  49. package/habilidades/testing-python/SKILL.md +340 -340
  50. package/hooks/claudemd-bloat-detector.js +161 -161
  51. package/hooks/inyeccion-contexto.js +8 -3
  52. package/hooks/lib/agent-routing.js +107 -107
  53. package/hooks/lib/auto-consolidator.js +335 -335
  54. package/hooks/lib/error-classifier.js +308 -308
  55. package/hooks/lib/merkle-audit.js +96 -96
  56. package/hooks/lib/provenance-tracker.js +191 -191
  57. package/hooks/lib/rate-limit-ip.js +177 -0
  58. package/hooks/lib/rate-limit-tracker.js +253 -253
  59. package/hooks/lib/resource-quota.js +122 -122
  60. package/hooks/lib/retry-jitter.js +165 -165
  61. package/hooks/lib/skill-auditor.js +588 -588
  62. package/hooks/lib/sync-status.js +228 -228
  63. package/hooks/lib/taint-tracker.js +107 -107
  64. package/hooks/lib/text-similarity.js +241 -241
  65. package/hooks/lib/toon-compressor.js +245 -245
  66. package/hooks/lib/webhook-dedup.js +184 -0
  67. package/hooks/lib/webhook-verify.js +123 -0
  68. package/hooks/proteccion-rutas.js +120 -15
  69. package/hooks/registro-turnos.js +209 -209
  70. package/hooks/sugerir-regenerar-inventario.js +170 -170
  71. package/hooks/validar-formato-post-subagente.js +140 -140
  72. package/hooks/validar-memoria-hook.js +218 -218
  73. package/instintos/prompt-appendices.yaml +57 -57
  74. package/manifiestos/agent-output-schemas.json +57 -57
  75. package/manifiestos/modulos.json +1 -0
  76. package/manifiestos/skills-lock.json +34 -34
  77. package/package.json +5 -3
  78. package/plantillas/auditor-veto-template.md +105 -105
  79. package/plantillas/github-workflows/README.md +47 -47
  80. package/plantillas/github-workflows/release-please.yml +44 -44
  81. package/plantillas/github-workflows/swl-ci.yml +107 -107
  82. package/plantillas/github-workflows/swl-security.yml +51 -51
  83. package/plugin.json +1 -1
  84. package/reglas/analisis-previo-tareas-grandes.md +172 -172
  85. package/reglas/arreglar-al-detectar.md +147 -147
  86. package/reglas/fragmentos-compartidos.md +152 -152
  87. package/reglas/harness-claude-code.md +213 -213
  88. package/reglas/usar-context7.md +226 -226
  89. package/reglas/usar-sistema-swl.md +251 -0
  90. package/schemas/diary-entry.schema.json +80 -80
  91. package/scripts/benchmark-memoria.js +167 -167
  92. package/scripts/comandos/skills.js +251 -2
  93. package/scripts/configurar-branch-protection.js +418 -418
  94. package/scripts/detectar-aprendizajes-duplicados.js +151 -151
  95. package/scripts/field-report.js +199 -199
  96. package/scripts/generar-checklists-consolidados.js +273 -273
  97. package/scripts/generar-inventario.js +420 -420
  98. package/scripts/generar-matriz-lenguajes.js +271 -271
  99. package/scripts/lib/artefactos-python.js +43 -43
  100. package/scripts/lib/benchmark-metrics.js +160 -160
  101. package/scripts/lib/budget-enforcer.js +252 -252
  102. package/scripts/lib/configurar-ci.js +380 -380
  103. package/scripts/lib/contadores-inventario.js +217 -217
  104. package/scripts/lib/detectar-stack-detallado.js +307 -307
  105. package/scripts/lib/diary-entry.js +234 -234
  106. package/scripts/lib/eval-metrics-store.js +218 -218
  107. package/scripts/lib/eval-quality.js +171 -171
  108. package/scripts/lib/eval-schemas.js +144 -144
  109. package/scripts/lib/eval-self-correct.js +106 -106
  110. package/scripts/lib/eval-validator.js +185 -185
  111. package/scripts/lib/jaccard-similarity.js +98 -98
  112. package/scripts/lib/longmemeval-runner.js +125 -125
  113. package/scripts/lib/npm-version.js +261 -261
  114. package/scripts/lib/paquetes-conocidos.js +50 -50
  115. package/scripts/lib/prompt-builder.js +264 -264
  116. package/scripts/lib/rrf-fusion.js +175 -175
  117. package/scripts/lib/scoring-instintos.js +277 -277
  118. package/scripts/lib/semantic-search.js +252 -252
  119. package/scripts/limpiar-artefactos-python.js +131 -131
  120. package/scripts/mcp-server/README.md +128 -128
  121. package/scripts/mcp-server/handlers.js +206 -206
  122. package/scripts/migrar-csv-a-array.js +168 -168
  123. package/scripts/migrar-fase-dominio.js +201 -201
  124. package/scripts/publicar.js +511 -511
  125. package/scripts/run-eval.js +141 -141
  126. package/scripts/validar-manifest.js +195 -195
  127. package/scripts/validar-userland-vacio.js +110 -110
  128. package/scripts/verificar-release.js +110 -0
@@ -1,245 +1,245 @@
1
- 'use strict';
2
-
3
- /**
4
- * TOON Compressor — Compresión de schemas y documentos estructurados.
5
- *
6
- * Patrón adoptado de CC Workflow Studio (generate-toon-schema.ts).
7
- * Reduce el tamaño de JSON schemas y documentos estructurados ~20-25%
8
- * eliminando redundancia sin perder información semántica.
9
- *
10
- * Técnicas aplicadas:
11
- * 1. Eliminar whitespace y formateo innecesario
12
- * 2. Abreviar claves repetitivas con diccionario
13
- * 3. Colapsar descripciones a una línea
14
- * 4. Eliminar campos opcionales con valor default
15
- * 5. Usar notación compacta para tipos simples
16
- *
17
- * Zero dependencias externas.
18
- *
19
- * Uso:
20
- * const { comprimirSchema, descomprimirSchema, comprimirTexto } = require('./lib/toon-compressor');
21
- * const compacto = comprimirSchema(schemaJSON);
22
- * console.log(`Reducción: ${compacto.reduccionPorcentaje}%`);
23
- *
24
- * @module hooks/lib/toon-compressor
25
- */
26
-
27
- // ---------------------------------------------------------------------------
28
- // Diccionario de abreviaciones para claves JSON Schema
29
- // ---------------------------------------------------------------------------
30
-
31
- /**
32
- * Mapeo de claves largas a abreviaciones cortas.
33
- * Solo para claves que aparecen ≥3 veces en un schema típico.
34
- */
35
- const ABREVIACIONES = {
36
- description: 'desc',
37
- properties: 'props',
38
- required: 'req',
39
- additionalProperties: 'addl',
40
- type: 't',
41
- items: 'it',
42
- default: 'def',
43
- enum: 'en',
44
- maxLength: 'maxL',
45
- minLength: 'minL',
46
- minimum: 'min',
47
- maximum: 'max',
48
- pattern: 'pat',
49
- oneOf: '1of',
50
- anyOf: 'aof',
51
- allOf: 'allof',
52
- };
53
-
54
- /** Mapeo inverso para descompresión. */
55
- const ABREVIACIONES_INV = Object.fromEntries(
56
- Object.entries(ABREVIACIONES).map(([k, v]) => [v, k])
57
- );
58
-
59
- // ---------------------------------------------------------------------------
60
- // Funciones core
61
- // ---------------------------------------------------------------------------
62
-
63
- /**
64
- * Comprime un objeto JSON Schema reemplazando claves por abreviaciones.
65
- *
66
- * @param {object} obj - Objeto a comprimir (se clona internamente)
67
- * @returns {object} Objeto con claves abreviadas
68
- */
69
- function _abreviarClaves(obj) {
70
- if (Array.isArray(obj)) {
71
- return obj.map(_abreviarClaves);
72
- }
73
- if (obj !== null && typeof obj === 'object') {
74
- const resultado = {};
75
- for (const [clave, valor] of Object.entries(obj)) {
76
- const claveCorta = ABREVIACIONES[clave] || clave;
77
- resultado[claveCorta] = _abreviarClaves(valor);
78
- }
79
- return resultado;
80
- }
81
- return obj;
82
- }
83
-
84
- /**
85
- * Descomprime un objeto con claves abreviadas a sus nombres originales.
86
- *
87
- * @param {object} obj - Objeto con claves abreviadas
88
- * @returns {object} Objeto con claves originales
89
- */
90
- function _expandirClaves(obj) {
91
- if (Array.isArray(obj)) {
92
- return obj.map(_expandirClaves);
93
- }
94
- if (obj !== null && typeof obj === 'object') {
95
- const resultado = {};
96
- for (const [clave, valor] of Object.entries(obj)) {
97
- const claveLarga = ABREVIACIONES_INV[clave] || clave;
98
- resultado[claveLarga] = _expandirClaves(valor);
99
- }
100
- return resultado;
101
- }
102
- return obj;
103
- }
104
-
105
- /**
106
- * Elimina campos opcionales con valor default conocido.
107
- *
108
- * @param {object} obj - Schema JSON
109
- * @returns {object} Schema sin defaults redundantes
110
- */
111
- function _eliminarDefaults(obj) {
112
- if (Array.isArray(obj)) {
113
- return obj.map(_eliminarDefaults);
114
- }
115
- if (obj !== null && typeof obj === 'object') {
116
- const resultado = {};
117
- for (const [clave, valor] of Object.entries(obj)) {
118
- // Eliminar additionalProperties: true (es el default)
119
- if (clave === 'additionalProperties' && valor === true) continue;
120
- // Eliminar required: [] (vacío = sin requeridos)
121
- if (clave === 'required' && Array.isArray(valor) && valor.length === 0) continue;
122
- // Eliminar description vacía
123
- if (clave === 'description' && valor === '') continue;
124
- resultado[clave] = _eliminarDefaults(valor);
125
- }
126
- return resultado;
127
- }
128
- return obj;
129
- }
130
-
131
- /**
132
- * Colapsa descripciones multi-línea a una sola línea.
133
- *
134
- * @param {object} obj
135
- * @returns {object}
136
- */
137
- function _colapsarDescripciones(obj) {
138
- if (Array.isArray(obj)) {
139
- return obj.map(_colapsarDescripciones);
140
- }
141
- if (obj !== null && typeof obj === 'object') {
142
- const resultado = {};
143
- for (const [clave, valor] of Object.entries(obj)) {
144
- if (clave === 'description' && typeof valor === 'string') {
145
- resultado[clave] = valor.replace(/\s+/g, ' ').trim();
146
- } else {
147
- resultado[clave] = _colapsarDescripciones(valor);
148
- }
149
- }
150
- return resultado;
151
- }
152
- return obj;
153
- }
154
-
155
- // ---------------------------------------------------------------------------
156
- // API pública
157
- // ---------------------------------------------------------------------------
158
-
159
- /**
160
- * Comprime un JSON Schema aplicando todas las técnicas de reducción.
161
- *
162
- * @param {object|string} schema - JSON Schema (objeto o string JSON)
163
- * @returns {{ comprimido: string, original: number, reducido: number, reduccionPorcentaje: number }}
164
- */
165
- function comprimirSchema(schema) {
166
- const obj = typeof schema === 'string' ? JSON.parse(schema) : schema;
167
- const original = JSON.stringify(obj);
168
-
169
- let procesado = _eliminarDefaults(obj);
170
- procesado = _colapsarDescripciones(procesado);
171
- procesado = _abreviarClaves(procesado);
172
-
173
- const comprimido = JSON.stringify(procesado);
174
-
175
- const tamOriginal = original.length;
176
- const tamReducido = comprimido.length;
177
- const reduccion = ((tamOriginal - tamReducido) / tamOriginal) * 100;
178
-
179
- return {
180
- comprimido,
181
- original: tamOriginal,
182
- reducido: tamReducido,
183
- reduccionPorcentaje: Math.round(reduccion * 10) / 10,
184
- };
185
- }
186
-
187
- /**
188
- * Descomprime un JSON Schema con claves abreviadas.
189
- *
190
- * @param {string|object} comprimido - Schema comprimido
191
- * @returns {object} Schema original con claves expandidas
192
- */
193
- function descomprimirSchema(comprimido) {
194
- const obj = typeof comprimido === 'string' ? JSON.parse(comprimido) : comprimido;
195
- return _expandirClaves(obj);
196
- }
197
-
198
- /**
199
- * Comprime texto Markdown eliminando redundancia para reducir tokens.
200
- *
201
- * Técnicas:
202
- * - Colapsar múltiples líneas vacías a una
203
- * - Eliminar trailing whitespace
204
- * - Comprimir tablas (eliminar padding)
205
- * - Eliminar comentarios HTML
206
- *
207
- * @param {string} texto - Texto Markdown
208
- * @returns {{ comprimido: string, original: number, reducido: number, reduccionPorcentaje: number }}
209
- */
210
- function comprimirTexto(texto) {
211
- const original = texto.length;
212
-
213
- let resultado = texto;
214
- // Colapsar 3+ líneas vacías a 2
215
- resultado = resultado.replace(/\n{3,}/g, '\n\n');
216
- // Eliminar trailing whitespace
217
- resultado = resultado.replace(/[ \t]+$/gm, '');
218
- // Eliminar comentarios HTML
219
- resultado = resultado.replace(/<!--[\s\S]*?-->/g, '');
220
- // Comprimir padding en tablas (múltiples espacios → uno)
221
- resultado = resultado.replace(/\|[ \t]{2,}/g, '| ');
222
- resultado = resultado.replace(/[ \t]{2,}\|/g, ' |');
223
-
224
- const reducido = resultado.length;
225
- const reduccion = ((original - reducido) / original) * 100;
226
-
227
- return {
228
- comprimido: resultado,
229
- original,
230
- reducido,
231
- reduccionPorcentaje: Math.round(reduccion * 10) / 10,
232
- };
233
- }
234
-
235
- // ---------------------------------------------------------------------------
236
- // Exports
237
- // ---------------------------------------------------------------------------
238
-
239
- module.exports = {
240
- comprimirSchema,
241
- descomprimirSchema,
242
- comprimirTexto,
243
- // Exponer diccionario para tests
244
- ABREVIACIONES,
245
- };
1
+ 'use strict';
2
+
3
+ /**
4
+ * TOON Compressor — Compresión de schemas y documentos estructurados.
5
+ *
6
+ * Patrón adoptado de CC Workflow Studio (generate-toon-schema.ts).
7
+ * Reduce el tamaño de JSON schemas y documentos estructurados ~20-25%
8
+ * eliminando redundancia sin perder información semántica.
9
+ *
10
+ * Técnicas aplicadas:
11
+ * 1. Eliminar whitespace y formateo innecesario
12
+ * 2. Abreviar claves repetitivas con diccionario
13
+ * 3. Colapsar descripciones a una línea
14
+ * 4. Eliminar campos opcionales con valor default
15
+ * 5. Usar notación compacta para tipos simples
16
+ *
17
+ * Zero dependencias externas.
18
+ *
19
+ * Uso:
20
+ * const { comprimirSchema, descomprimirSchema, comprimirTexto } = require('./lib/toon-compressor');
21
+ * const compacto = comprimirSchema(schemaJSON);
22
+ * console.log(`Reducción: ${compacto.reduccionPorcentaje}%`);
23
+ *
24
+ * @module hooks/lib/toon-compressor
25
+ */
26
+
27
+ // ---------------------------------------------------------------------------
28
+ // Diccionario de abreviaciones para claves JSON Schema
29
+ // ---------------------------------------------------------------------------
30
+
31
+ /**
32
+ * Mapeo de claves largas a abreviaciones cortas.
33
+ * Solo para claves que aparecen ≥3 veces en un schema típico.
34
+ */
35
+ const ABREVIACIONES = {
36
+ description: 'desc',
37
+ properties: 'props',
38
+ required: 'req',
39
+ additionalProperties: 'addl',
40
+ type: 't',
41
+ items: 'it',
42
+ default: 'def',
43
+ enum: 'en',
44
+ maxLength: 'maxL',
45
+ minLength: 'minL',
46
+ minimum: 'min',
47
+ maximum: 'max',
48
+ pattern: 'pat',
49
+ oneOf: '1of',
50
+ anyOf: 'aof',
51
+ allOf: 'allof',
52
+ };
53
+
54
+ /** Mapeo inverso para descompresión. */
55
+ const ABREVIACIONES_INV = Object.fromEntries(
56
+ Object.entries(ABREVIACIONES).map(([k, v]) => [v, k])
57
+ );
58
+
59
+ // ---------------------------------------------------------------------------
60
+ // Funciones core
61
+ // ---------------------------------------------------------------------------
62
+
63
+ /**
64
+ * Comprime un objeto JSON Schema reemplazando claves por abreviaciones.
65
+ *
66
+ * @param {object} obj - Objeto a comprimir (se clona internamente)
67
+ * @returns {object} Objeto con claves abreviadas
68
+ */
69
+ function _abreviarClaves(obj) {
70
+ if (Array.isArray(obj)) {
71
+ return obj.map(_abreviarClaves);
72
+ }
73
+ if (obj !== null && typeof obj === 'object') {
74
+ const resultado = {};
75
+ for (const [clave, valor] of Object.entries(obj)) {
76
+ const claveCorta = ABREVIACIONES[clave] || clave;
77
+ resultado[claveCorta] = _abreviarClaves(valor);
78
+ }
79
+ return resultado;
80
+ }
81
+ return obj;
82
+ }
83
+
84
+ /**
85
+ * Descomprime un objeto con claves abreviadas a sus nombres originales.
86
+ *
87
+ * @param {object} obj - Objeto con claves abreviadas
88
+ * @returns {object} Objeto con claves originales
89
+ */
90
+ function _expandirClaves(obj) {
91
+ if (Array.isArray(obj)) {
92
+ return obj.map(_expandirClaves);
93
+ }
94
+ if (obj !== null && typeof obj === 'object') {
95
+ const resultado = {};
96
+ for (const [clave, valor] of Object.entries(obj)) {
97
+ const claveLarga = ABREVIACIONES_INV[clave] || clave;
98
+ resultado[claveLarga] = _expandirClaves(valor);
99
+ }
100
+ return resultado;
101
+ }
102
+ return obj;
103
+ }
104
+
105
+ /**
106
+ * Elimina campos opcionales con valor default conocido.
107
+ *
108
+ * @param {object} obj - Schema JSON
109
+ * @returns {object} Schema sin defaults redundantes
110
+ */
111
+ function _eliminarDefaults(obj) {
112
+ if (Array.isArray(obj)) {
113
+ return obj.map(_eliminarDefaults);
114
+ }
115
+ if (obj !== null && typeof obj === 'object') {
116
+ const resultado = {};
117
+ for (const [clave, valor] of Object.entries(obj)) {
118
+ // Eliminar additionalProperties: true (es el default)
119
+ if (clave === 'additionalProperties' && valor === true) continue;
120
+ // Eliminar required: [] (vacío = sin requeridos)
121
+ if (clave === 'required' && Array.isArray(valor) && valor.length === 0) continue;
122
+ // Eliminar description vacía
123
+ if (clave === 'description' && valor === '') continue;
124
+ resultado[clave] = _eliminarDefaults(valor);
125
+ }
126
+ return resultado;
127
+ }
128
+ return obj;
129
+ }
130
+
131
+ /**
132
+ * Colapsa descripciones multi-línea a una sola línea.
133
+ *
134
+ * @param {object} obj
135
+ * @returns {object}
136
+ */
137
+ function _colapsarDescripciones(obj) {
138
+ if (Array.isArray(obj)) {
139
+ return obj.map(_colapsarDescripciones);
140
+ }
141
+ if (obj !== null && typeof obj === 'object') {
142
+ const resultado = {};
143
+ for (const [clave, valor] of Object.entries(obj)) {
144
+ if (clave === 'description' && typeof valor === 'string') {
145
+ resultado[clave] = valor.replace(/\s+/g, ' ').trim();
146
+ } else {
147
+ resultado[clave] = _colapsarDescripciones(valor);
148
+ }
149
+ }
150
+ return resultado;
151
+ }
152
+ return obj;
153
+ }
154
+
155
+ // ---------------------------------------------------------------------------
156
+ // API pública
157
+ // ---------------------------------------------------------------------------
158
+
159
+ /**
160
+ * Comprime un JSON Schema aplicando todas las técnicas de reducción.
161
+ *
162
+ * @param {object|string} schema - JSON Schema (objeto o string JSON)
163
+ * @returns {{ comprimido: string, original: number, reducido: number, reduccionPorcentaje: number }}
164
+ */
165
+ function comprimirSchema(schema) {
166
+ const obj = typeof schema === 'string' ? JSON.parse(schema) : schema;
167
+ const original = JSON.stringify(obj);
168
+
169
+ let procesado = _eliminarDefaults(obj);
170
+ procesado = _colapsarDescripciones(procesado);
171
+ procesado = _abreviarClaves(procesado);
172
+
173
+ const comprimido = JSON.stringify(procesado);
174
+
175
+ const tamOriginal = original.length;
176
+ const tamReducido = comprimido.length;
177
+ const reduccion = ((tamOriginal - tamReducido) / tamOriginal) * 100;
178
+
179
+ return {
180
+ comprimido,
181
+ original: tamOriginal,
182
+ reducido: tamReducido,
183
+ reduccionPorcentaje: Math.round(reduccion * 10) / 10,
184
+ };
185
+ }
186
+
187
+ /**
188
+ * Descomprime un JSON Schema con claves abreviadas.
189
+ *
190
+ * @param {string|object} comprimido - Schema comprimido
191
+ * @returns {object} Schema original con claves expandidas
192
+ */
193
+ function descomprimirSchema(comprimido) {
194
+ const obj = typeof comprimido === 'string' ? JSON.parse(comprimido) : comprimido;
195
+ return _expandirClaves(obj);
196
+ }
197
+
198
+ /**
199
+ * Comprime texto Markdown eliminando redundancia para reducir tokens.
200
+ *
201
+ * Técnicas:
202
+ * - Colapsar múltiples líneas vacías a una
203
+ * - Eliminar trailing whitespace
204
+ * - Comprimir tablas (eliminar padding)
205
+ * - Eliminar comentarios HTML
206
+ *
207
+ * @param {string} texto - Texto Markdown
208
+ * @returns {{ comprimido: string, original: number, reducido: number, reduccionPorcentaje: number }}
209
+ */
210
+ function comprimirTexto(texto) {
211
+ const original = texto.length;
212
+
213
+ let resultado = texto;
214
+ // Colapsar 3+ líneas vacías a 2
215
+ resultado = resultado.replace(/\n{3,}/g, '\n\n');
216
+ // Eliminar trailing whitespace
217
+ resultado = resultado.replace(/[ \t]+$/gm, '');
218
+ // Eliminar comentarios HTML
219
+ resultado = resultado.replace(/<!--[\s\S]*?-->/g, '');
220
+ // Comprimir padding en tablas (múltiples espacios → uno)
221
+ resultado = resultado.replace(/\|[ \t]{2,}/g, '| ');
222
+ resultado = resultado.replace(/[ \t]{2,}\|/g, ' |');
223
+
224
+ const reducido = resultado.length;
225
+ const reduccion = ((original - reducido) / original) * 100;
226
+
227
+ return {
228
+ comprimido: resultado,
229
+ original,
230
+ reducido,
231
+ reduccionPorcentaje: Math.round(reduccion * 10) / 10,
232
+ };
233
+ }
234
+
235
+ // ---------------------------------------------------------------------------
236
+ // Exports
237
+ // ---------------------------------------------------------------------------
238
+
239
+ module.exports = {
240
+ comprimirSchema,
241
+ descomprimirSchema,
242
+ comprimirTexto,
243
+ // Exponer diccionario para tests
244
+ ABREVIACIONES,
245
+ };
@@ -0,0 +1,184 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * webhook-dedup.js — Ledger JSONL append-only para idempotencia de webhooks.
5
+ *
6
+ * GitHub y otros proveedores reentregan el mismo webhook si el receptor no
7
+ * responde 2xx rápido. Para evitar reprocesar el mismo evento varias veces,
8
+ * mantenemos un ledger de `event-id` aceptados con timestamp.
9
+ *
10
+ * Estrategia:
11
+ * - Ledger en JSONL append-only (zero-deps; sin SQLite).
12
+ * - Cache en memoria (Set) construido al primer acceso desde el archivo.
13
+ * - Ventana de retención configurable (default 7 días) — entradas más
14
+ * viejas se ignoran al construir cache y se mueven a archive con
15
+ * `rotar()`.
16
+ * - Líneas corruptas (JSON inválido) se descartan silenciosamente al
17
+ * leer; no rompen el sistema.
18
+ *
19
+ * Origen: patrón derivado de `webhook_events` table de
20
+ * `temp/claude-code-telegram-main/` (SQLite) adaptado a JSONL siguiendo la
21
+ * convención SWL (CLAUDE.md: "JSONL para alta frecuencia").
22
+ *
23
+ * Zero-deps.
24
+ *
25
+ * @module hooks/lib/webhook-dedup
26
+ */
27
+
28
+ const fs = require('fs');
29
+ const path = require('path');
30
+
31
+ const VENTANA_DEDUP_MS_DEFAULT = 7 * 24 * 60 * 60 * 1000; // 7 días
32
+
33
+ class WebhookDedup {
34
+ /**
35
+ * @param {object} opciones
36
+ * @param {string} opciones.rutaLedger Ruta absoluta o relativa al CWD del ledger JSONL.
37
+ * @param {number} [opciones.ventanaMs=7d] Ventana de retención en ms.
38
+ */
39
+ constructor({ rutaLedger, ventanaMs = VENTANA_DEDUP_MS_DEFAULT } = {}) {
40
+ if (!rutaLedger || typeof rutaLedger !== 'string') {
41
+ throw new Error('webhook-dedup: rutaLedger es requerida');
42
+ }
43
+ if (!Number.isFinite(ventanaMs) || ventanaMs <= 0) {
44
+ throw new Error('webhook-dedup: ventanaMs debe ser número positivo');
45
+ }
46
+ this.rutaLedger = rutaLedger;
47
+ this.ventanaMs = ventanaMs;
48
+ this._cache = null; // Set<eventId>, lazy load
49
+ }
50
+
51
+ /**
52
+ * ¿El eventId ya fue procesado dentro de la ventana?
53
+ * @param {string} eventId
54
+ * @param {number} [ahora=Date.now()]
55
+ * @returns {boolean}
56
+ */
57
+ yaVisto(eventId, ahora) {
58
+ if (typeof ahora !== 'number') ahora = Date.now();
59
+ if (!eventId || typeof eventId !== 'string') return false;
60
+ this._asegurarCache(ahora);
61
+ return this._cache.has(eventId);
62
+ }
63
+
64
+ /**
65
+ * Registra un nuevo evento. Si ya estaba, retorna false sin escribir.
66
+ * @param {string} eventId
67
+ * @param {string} provider Nombre del proveedor (github, generic, etc.).
68
+ * @param {number} [ahora=Date.now()]
69
+ * @returns {boolean} true si se registró; false si ya estaba.
70
+ */
71
+ registrar(eventId, provider, ahora) {
72
+ if (typeof ahora !== 'number') ahora = Date.now();
73
+ if (!eventId || typeof eventId !== 'string') return false;
74
+ if (!provider || typeof provider !== 'string') return false;
75
+ if (this.yaVisto(eventId, ahora)) return false;
76
+
77
+ const entrada = {
78
+ event_id: eventId,
79
+ provider,
80
+ ts: new Date(ahora).toISOString(),
81
+ };
82
+ fs.mkdirSync(path.dirname(this.rutaLedger), { recursive: true });
83
+ fs.appendFileSync(this.rutaLedger, JSON.stringify(entrada) + '\n', 'utf8');
84
+ this._cache.add(eventId);
85
+ return true;
86
+ }
87
+
88
+ /**
89
+ * Mueve entradas más viejas que la ventana al directorio archive.
90
+ * Reescribe el ledger sólo con entradas dentro de ventana.
91
+ *
92
+ * Idempotente: llamar dos veces seguidas no duplica el archivo de archive
93
+ * (la segunda llamada no encuentra entradas viejas).
94
+ *
95
+ * @param {number} [ahora=Date.now()]
96
+ * @returns {{rotadas: number, conservadas: number}}
97
+ */
98
+ rotar(ahora) {
99
+ if (typeof ahora !== 'number') ahora = Date.now();
100
+ if (!fs.existsSync(this.rutaLedger)) {
101
+ return { rotadas: 0, conservadas: 0 };
102
+ }
103
+
104
+ const contenido = fs.readFileSync(this.rutaLedger, 'utf8');
105
+ const lineas = contenido.split('\n');
106
+ const limite = ahora - this.ventanaMs;
107
+
108
+ const archivar = [];
109
+ const conservar = [];
110
+
111
+ for (const linea of lineas) {
112
+ const trimmed = linea.trim();
113
+ if (!trimmed) continue;
114
+ try {
115
+ const entrada = JSON.parse(trimmed);
116
+ const ts = Date.parse(entrada.ts);
117
+ if (!Number.isFinite(ts)) continue; // ts inválido, descartar
118
+ if (ts < limite) {
119
+ archivar.push(trimmed);
120
+ } else {
121
+ conservar.push(trimmed);
122
+ }
123
+ } catch (_) {
124
+ // línea corrupta, descartar
125
+ }
126
+ }
127
+
128
+ if (archivar.length > 0) {
129
+ const fechaArchivo = new Date(ahora).toISOString().slice(0, 10);
130
+ const dirArchive = path.join(path.dirname(this.rutaLedger), 'webhook-events-archive');
131
+ const archivoArchive = path.join(dirArchive, `events-${fechaArchivo}.jsonl`);
132
+ fs.mkdirSync(dirArchive, { recursive: true });
133
+ fs.appendFileSync(archivoArchive, archivar.join('\n') + '\n', 'utf8');
134
+ }
135
+
136
+ const nuevoContenido = conservar.length > 0 ? conservar.join('\n') + '\n' : '';
137
+ fs.writeFileSync(this.rutaLedger, nuevoContenido, 'utf8');
138
+ this._cache = null; // invalidar cache
139
+
140
+ return { rotadas: archivar.length, conservadas: conservar.length };
141
+ }
142
+
143
+ /**
144
+ * Tamaño actual del cache (para tests).
145
+ * @returns {number}
146
+ */
147
+ tamanoCache() {
148
+ return this._cache ? this._cache.size : 0;
149
+ }
150
+
151
+ /**
152
+ * Carga el cache desde el archivo si aún no está cargado.
153
+ * Entradas fuera de ventana se ignoran.
154
+ * @param {number} ahora
155
+ */
156
+ _asegurarCache(ahora) {
157
+ if (this._cache !== null) return;
158
+ this._cache = new Set();
159
+ if (!fs.existsSync(this.rutaLedger)) return;
160
+
161
+ const contenido = fs.readFileSync(this.rutaLedger, 'utf8');
162
+ const limite = ahora - this.ventanaMs;
163
+
164
+ for (const linea of contenido.split('\n')) {
165
+ const trimmed = linea.trim();
166
+ if (!trimmed) continue;
167
+ try {
168
+ const entrada = JSON.parse(trimmed);
169
+ const ts = Date.parse(entrada.ts);
170
+ if (!Number.isFinite(ts)) continue;
171
+ if (ts >= limite) {
172
+ this._cache.add(entrada.event_id);
173
+ }
174
+ } catch (_) {
175
+ // línea corrupta, ignorar
176
+ }
177
+ }
178
+ }
179
+ }
180
+
181
+ module.exports = {
182
+ WebhookDedup,
183
+ VENTANA_DEDUP_MS_DEFAULT,
184
+ };