@saulwade/swl-ses 2.2.4 → 2.3.1

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 (325) hide show
  1. package/CLAUDE.md +48 -7
  2. package/README.md +3 -3
  3. package/agentes/accesibilidad-wcag-swl.md +690 -690
  4. package/agentes/arquitecto-swl.md +267 -267
  5. package/agentes/auto-evolucion-swl.md +908 -908
  6. package/agentes/backend-api-swl.md +472 -472
  7. package/agentes/backend-csharp-swl.md +420 -420
  8. package/agentes/backend-go-swl.md +390 -390
  9. package/agentes/backend-java-swl.md +281 -281
  10. package/agentes/backend-node-swl.md +479 -479
  11. package/agentes/backend-python-swl.md +605 -605
  12. package/agentes/backend-rust-swl.md +364 -364
  13. package/agentes/backend-workers-swl.md +482 -482
  14. package/agentes/cloud-infra-swl.md +509 -509
  15. package/agentes/consolidador-swl.md +541 -541
  16. package/agentes/datos-swl.md +605 -605
  17. package/agentes/depurador-swl.md +352 -352
  18. package/agentes/devops-ci-swl.md +400 -400
  19. package/agentes/disenador-ui-swl.md +569 -569
  20. package/agentes/documentador-swl.md +345 -345
  21. package/agentes/frontend-angular-swl.md +621 -621
  22. package/agentes/frontend-css-swl.md +716 -716
  23. package/agentes/frontend-react-swl.md +692 -692
  24. package/agentes/frontend-swl.md +496 -496
  25. package/agentes/frontend-tailwind-swl.md +826 -826
  26. package/agentes/gh-fix-ci-swl.md +2 -2
  27. package/agentes/implementador-swl.md +328 -328
  28. package/agentes/investigador-swl.md +432 -432
  29. package/agentes/investigador-ux-swl.md +505 -505
  30. package/agentes/llm-apps-swl.md +278 -278
  31. package/agentes/migrador-swl.md +442 -442
  32. package/agentes/mobile-android-swl.md +511 -511
  33. package/agentes/mobile-cross-swl.md +541 -541
  34. package/agentes/mobile-ios-swl.md +502 -502
  35. package/agentes/mobile-testing-swl.md +302 -302
  36. package/agentes/nemesis-auditor-swl.md +285 -285
  37. package/agentes/notificador-swl.md +918 -918
  38. package/agentes/observabilidad-swl.md +438 -438
  39. package/agentes/orquestador-swl.md +1026 -1026
  40. package/agentes/pagos-swl.md +310 -310
  41. package/agentes/perfilador-usuario-swl.md +321 -321
  42. package/agentes/planificador-swl.md +399 -399
  43. package/agentes/producto-prd-swl.md +589 -589
  44. package/agentes/red-team-swl.md +1 -1
  45. package/agentes/release-manager-swl.md +590 -590
  46. package/agentes/rendimiento-swl.md +713 -713
  47. package/agentes/resolutor-build-swl.md +245 -245
  48. package/agentes/revisor-angular-swl.md +278 -278
  49. package/agentes/revisor-codigo-swl.md +505 -505
  50. package/agentes/revisor-csharp-swl.md +264 -264
  51. package/agentes/revisor-go-swl.md +259 -259
  52. package/agentes/revisor-java-swl.md +257 -257
  53. package/agentes/revisor-kotlin-swl.md +273 -273
  54. package/agentes/revisor-nextjs-swl.md +281 -281
  55. package/agentes/revisor-php-swl.md +271 -271
  56. package/agentes/revisor-react-swl.md +278 -278
  57. package/agentes/revisor-rust-swl.md +346 -346
  58. package/agentes/revisor-seguridad-swl.md +399 -399
  59. package/agentes/revisor-swift-swl.md +268 -268
  60. package/agentes/revisor-typescript-swl.md +346 -346
  61. package/agentes/sre-swl.md +291 -291
  62. package/agentes/tdd-qa-swl.md +393 -393
  63. package/comandos/swl/aprobar-plan.md +146 -141
  64. package/comandos/swl/briefing.md +119 -119
  65. package/comandos/swl/contribuir.md +233 -233
  66. package/comandos/swl/predecir.md +139 -139
  67. package/comandos/swl/release.md +30 -8
  68. package/comandos/swl/sesiones.md +1 -1
  69. package/comandos/swl/status.md +343 -333
  70. package/gateway/agent-executor.js +1 -1
  71. package/gateway/lib/event-channel.js +191 -191
  72. package/habilidades/agent-deep-links/SKILL.md +148 -148
  73. package/habilidades/agentes-como-servicio/SKILL.md +2 -2
  74. package/habilidades/angular-moderno/SKILL.md +20 -1
  75. package/habilidades/auto-evolucion-protocolo/SKILL.md +276 -276
  76. package/habilidades/backend-async-postgres-testing/SKILL.md +215 -215
  77. package/habilidades/backend-error-design/SKILL.md +221 -221
  78. package/habilidades/backend-production-resilience/SKILL.md +288 -288
  79. package/habilidades/benchmark-memoria/SKILL.md +186 -186
  80. package/habilidades/calidad-anti-patrones-universales/SKILL.md +368 -368
  81. package/habilidades/calidad-contract-testing/SKILL.md +165 -165
  82. package/habilidades/calidad-mutation-testing/SKILL.md +170 -170
  83. package/habilidades/changelog-generator/scripts/parse-commits.js +367 -367
  84. package/habilidades/checklist-seguridad/recursos/stride-cobertura.md +60 -60
  85. package/habilidades/contenedores-docker/SKILL.md +3 -1
  86. package/habilidades/diagrama-arquitectura/assets/template.html +276 -276
  87. package/habilidades/doubt-driven-review/recursos/EXAMPLES.md +130 -130
  88. package/habilidades/drift-detection/SKILL.md +179 -179
  89. package/habilidades/ejecutar-fase/SKILL.md +564 -541
  90. package/habilidades/ejecutar-task-iterativo/SKILL.md +278 -278
  91. package/habilidades/estructura-proyecto-claude/recursos/frontmatter-y-hooks-referencia.md +1 -1
  92. package/habilidades/estructura-proyecto-claude/recursos/mcp-json-template.json +57 -57
  93. package/habilidades/eval-framework/SKILL.md +212 -212
  94. package/habilidades/extractor-de-aprendizajes/SKILL.md +3 -3
  95. package/habilidades/feynman-auditor-swl/recursos/preguntas-language-agnostic.md +108 -108
  96. package/habilidades/harness-claude-code/recursos/disciplina-harness-regla.md +252 -252
  97. package/habilidades/legacy-code-rescue/SKILL.md +267 -267
  98. package/habilidades/meta-skills-estandar/recursos/convencion-examples.md +93 -93
  99. package/habilidades/patrones-python/recursos/patrones-avanzados.md +469 -469
  100. package/habilidades/perfil-usuario/SKILL.md +200 -200
  101. package/habilidades/planear-fase/SKILL.md +15 -1
  102. package/habilidades/prevencion-sobreingenieria/recursos/EXAMPLES.md +580 -580
  103. package/habilidades/proceso-ddia-fundamentos/SKILL.md +255 -255
  104. package/habilidades/proceso-ddia-streaming/SKILL.md +231 -231
  105. package/habilidades/proceso-debate-adversarial/SKILL.md +191 -164
  106. package/habilidades/proceso-debate-adversarial/recursos/personas.md +105 -105
  107. package/habilidades/proceso-discovery-machote/SKILL.md +157 -157
  108. package/habilidades/proceso-dynamic-workflows/SKILL.md +138 -138
  109. package/habilidades/proceso-dynamic-workflows/recursos/template-adversarial-verify.js +65 -65
  110. package/habilidades/proceso-dynamic-workflows/recursos/template-triage.js +65 -65
  111. package/habilidades/proceso-intent-engineering/SKILL.md +269 -269
  112. package/habilidades/proceso-modular-split/SKILL.md +256 -256
  113. package/habilidades/prompt-engineering/recursos/patrones-avanzados.md +2 -2
  114. package/habilidades/state-inconsistency-auditor-swl/recursos/coupled-state-patterns.md +147 -147
  115. package/habilidades/structured-outputs/SKILL.md +2 -2
  116. package/habilidades/swl-claudemd/recursos/contrato-aprender.md +83 -83
  117. package/habilidades/swl-claudemd/recursos/duplicacion-reglas-globales.md +85 -85
  118. package/habilidades/swl-claudemd/recursos/plantillas-init.md +94 -94
  119. package/habilidades/swl-dashboard/SKILL.md +2 -2
  120. package/habilidades/tdd-workflow/SKILL.md +33 -1
  121. package/habilidades/tdd-workflow/recursos/gherkin-bdd.md +111 -111
  122. package/habilidades/validacion-ci-sistema/recursos/validadores-completos.md +1 -1
  123. package/habilidades/validacion-ci-sistema/scripts/validar-sistema.sh +1 -1
  124. package/hooks/captura-acciones-post.js +151 -0
  125. package/hooks/captura-acciones-session.js +155 -0
  126. package/hooks/ciclo-evolucion-subagente.js +26 -26
  127. package/hooks/ciclo-evolucion.js +26 -26
  128. package/hooks/claudemd-bloat-detector.js +161 -161
  129. package/hooks/claudemd-duplicacion-detector.js +170 -170
  130. package/hooks/contexto-iteracion.js +144 -144
  131. package/hooks/guardrail-modelo.js +1 -1
  132. package/hooks/lib/agent-routing.js +107 -107
  133. package/hooks/lib/auto-consolidator.js +335 -335
  134. package/hooks/lib/autonomia.js +208 -208
  135. package/hooks/lib/briefing.js +512 -474
  136. package/hooks/lib/captura-acciones.js +392 -0
  137. package/hooks/lib/ciclo-evolucion.js +47 -47
  138. package/hooks/lib/deep-links.js +185 -185
  139. package/hooks/lib/error-classifier.js +308 -308
  140. package/hooks/lib/etapa-auto-evolucion.js +701 -701
  141. package/hooks/lib/etapa-metricas.js +388 -388
  142. package/hooks/lib/etapa-perfil-usuario.js +376 -376
  143. package/hooks/lib/loop-telemetry.js +321 -321
  144. package/hooks/lib/merkle-audit.js +96 -96
  145. package/hooks/lib/model-router.js +2 -2
  146. package/hooks/lib/propose-step.js +358 -358
  147. package/hooks/lib/provenance-tracker.js +191 -191
  148. package/hooks/lib/rate-limit-tracker.js +253 -253
  149. package/hooks/lib/resource-quota.js +122 -122
  150. package/hooks/lib/retry-jitter.js +165 -165
  151. package/hooks/lib/security-net.js +201 -201
  152. package/hooks/lib/skill-auditor.js +588 -588
  153. package/hooks/lib/sync-status.js +228 -228
  154. package/hooks/lib/taint-tracker.js +107 -107
  155. package/hooks/lib/text-similarity.js +241 -241
  156. package/hooks/lib/token-estimator.js +1 -0
  157. package/hooks/lib/toon-compressor.js +245 -245
  158. package/hooks/lib/usage-model.js +1 -1
  159. package/hooks/linea-estado.js +2 -0
  160. package/hooks/registro-turnos.js +209 -209
  161. package/hooks/session-briefing.js +98 -98
  162. package/hooks/spec-gate.js +211 -211
  163. package/hooks/sugerir-regenerar-inventario.js +170 -170
  164. package/hooks/tdd-gate.js +241 -241
  165. package/hooks/telemetria-skill-routing.js +100 -100
  166. package/hooks/validar-formato-post-subagente.js +140 -140
  167. package/hooks/validar-intent-spec.js +242 -242
  168. package/hooks/validar-memoria-hook.js +218 -218
  169. package/hooks/validar-planning-paths.js +134 -134
  170. package/instintos/autonomia.yaml +27 -27
  171. package/instintos/prompt-appendices.yaml +57 -57
  172. package/llms.txt +2 -2
  173. package/manifiestos/agent-output-schemas.json +57 -57
  174. package/manifiestos/canonical-hashes.json +2291 -1637
  175. package/manifiestos/hooks-config.json +18 -0
  176. package/manifiestos/modulos.json +4 -0
  177. package/manifiestos/planning-paths.json +44 -44
  178. package/manifiestos/skills-lock.json +1282 -1282
  179. package/package.json +2 -2
  180. package/plantillas/auditor-veto-template.md +105 -105
  181. package/plantillas/github-workflows/README.md +47 -47
  182. package/plantillas/github-workflows/release-please.yml +44 -44
  183. package/plantillas/github-workflows/swl-ci.yml +107 -107
  184. package/plantillas/github-workflows/swl-security.yml +51 -51
  185. package/plugin.json +2 -2
  186. package/reglas/accesibilidad.md +10 -10
  187. package/reglas/analisis-previo-tareas-grandes.md +172 -172
  188. package/reglas/api-diseno.md +9 -9
  189. package/reglas/arreglar-al-detectar.md +240 -240
  190. package/reglas/auditorias-documentales-estructurales.md +7 -7
  191. package/reglas/cloud-infra.md +8 -8
  192. package/reglas/consultar-vault-primero.md +195 -195
  193. package/reglas/debatir-antes-de-aceptar.md +158 -158
  194. package/reglas/fragmentos-compartidos.md +183 -183
  195. package/reglas/hooks.md +6 -6
  196. package/reglas/intent-engineering.md +218 -218
  197. package/reglas/markitdown.md +8 -8
  198. package/reglas/memoria-consolidada.md +41 -0
  199. package/reglas/monitor-ci.md +309 -309
  200. package/reglas/patrones.md +6 -6
  201. package/reglas/seguridad-agentes.md +66 -0
  202. package/reglas/sesiones-paralelas.md +180 -180
  203. package/reglas/sin-duplicacion-reglas-globales.md +182 -182
  204. package/reglas/skills-estandar.md +6 -6
  205. package/reglas/testing.md +7 -7
  206. package/reglas/tests-cleanup.md +224 -224
  207. package/reglas/usar-code-review-graph.md +155 -155
  208. package/reglas/usar-context7.md +226 -226
  209. package/reglas/verificar-citas-normativas.md +548 -548
  210. package/schemas/agent-frontmatter.schema.json +3 -3
  211. package/schemas/agent-message.schema.json +73 -73
  212. package/schemas/agent-output-implementacion.schema.json +114 -114
  213. package/schemas/agent-output-planificacion.schema.json +150 -150
  214. package/schemas/agent-output-review.schema.json +98 -98
  215. package/schemas/diary-entry.schema.json +112 -112
  216. package/schemas/hook-profiles.schema.json +54 -54
  217. package/schemas/hooks-config.schema.json +89 -89
  218. package/schemas/instinct.schema.json +161 -152
  219. package/schemas/modulos.schema.json +38 -38
  220. package/schemas/perfiles.schema.json +36 -36
  221. package/schemas/plugin.schema.json +77 -77
  222. package/schemas/skill-evals.schema.json +119 -119
  223. package/schemas/skill-frontmatter.schema.json +245 -245
  224. package/scripts/audit-tools/audit-history.js +330 -330
  225. package/scripts/audit-tools/bundle-tracker.js +290 -290
  226. package/scripts/audit-tools/canary-monitor.js +352 -352
  227. package/scripts/audit-tools/code-profiler.js +605 -605
  228. package/scripts/audit-tools/dep-doctor.js +320 -320
  229. package/scripts/audit-tools/env-validator.js +206 -206
  230. package/scripts/audit-tools/lib/fs-walk.js +48 -48
  231. package/scripts/audit-tools/lib/output.js +23 -23
  232. package/scripts/audit-tools/migration-checker.js +392 -392
  233. package/scripts/audit-tools/pentest-scanner.js +1436 -1436
  234. package/scripts/benchmark-memoria.js +167 -167
  235. package/scripts/bootstrap-instintos.js +25 -7
  236. package/scripts/cli/aprobar-plan.js +73 -73
  237. package/scripts/cli/briefing.js +23 -23
  238. package/scripts/cli/ciclo-evolucion.js +26 -26
  239. package/scripts/cli/configurar-ci.js +40 -40
  240. package/scripts/cli/derivar-feature-list.js +25 -25
  241. package/scripts/cli/detectar-host.js +27 -27
  242. package/scripts/cli/diary-entry.js +69 -69
  243. package/scripts/cli/execution-state.js +18 -18
  244. package/scripts/cli/gateway-notify.js +41 -41
  245. package/scripts/cli/liberar-fase.js +42 -42
  246. package/scripts/cli/loop-telemetry.js +125 -125
  247. package/scripts/cli/mark-evolved.js +56 -56
  248. package/scripts/cli/metricas-dora.js +26 -26
  249. package/scripts/cli/near-duplicate.js +55 -55
  250. package/scripts/cli/notificaciones.js +123 -123
  251. package/scripts/cli/propose-step.js +29 -29
  252. package/scripts/cli/schedule-parse.js +19 -19
  253. package/scripts/cli/sugerir-modelo.js +20 -20
  254. package/scripts/cli/verificar-plan.js +36 -36
  255. package/scripts/cli/verificar-trazabilidad.js +35 -35
  256. package/scripts/configurar-branch-protection.js +418 -418
  257. package/scripts/detectar-aprendizajes-duplicados.js +151 -151
  258. package/scripts/field-report.js +199 -199
  259. package/scripts/generar-checklists-consolidados.js +273 -273
  260. package/scripts/generar-matriz-lenguajes.js +271 -271
  261. package/scripts/lib/artefactos-python.js +43 -43
  262. package/scripts/lib/auditar-invocaciones-comandos.js +104 -104
  263. package/scripts/lib/benchmark-metrics.js +160 -160
  264. package/scripts/lib/budget-enforcer.js +252 -252
  265. package/scripts/lib/ci-reader.js +193 -193
  266. package/scripts/lib/claude-sessions.js +1 -0
  267. package/scripts/lib/configurar-ci.js +380 -380
  268. package/scripts/lib/contadores-inventario.js +217 -217
  269. package/scripts/lib/detectar-host-swl.js +175 -175
  270. package/scripts/lib/detectar-stack-detallado.js +307 -307
  271. package/scripts/lib/detector-autoduplicacion-intra-archivo.js +234 -234
  272. package/scripts/lib/detector-reglas-duplicadas.js +220 -220
  273. package/scripts/lib/diary-entry.js +234 -234
  274. package/scripts/lib/eval-metrics-store.js +218 -218
  275. package/scripts/lib/eval-quality.js +171 -171
  276. package/scripts/lib/eval-schemas.js +144 -144
  277. package/scripts/lib/eval-self-correct.js +106 -106
  278. package/scripts/lib/eval-validator.js +185 -185
  279. package/scripts/lib/evidencia-release.js +322 -322
  280. package/scripts/lib/expandir-targets.js +71 -71
  281. package/scripts/lib/gate-hooks-requires.js +249 -249
  282. package/scripts/lib/gate-licencias.js +212 -212
  283. package/scripts/lib/git-metricas.js +257 -257
  284. package/scripts/lib/gitignore-manifest.js +44 -11
  285. package/scripts/lib/jaccard-similarity.js +98 -98
  286. package/scripts/lib/longmemeval-runner.js +125 -125
  287. package/scripts/lib/metricas-dora.js +204 -204
  288. package/scripts/lib/npm-version.js +261 -261
  289. package/scripts/lib/paquetes-conocidos.js +50 -50
  290. package/scripts/lib/plan-lock.js +275 -275
  291. package/scripts/lib/pr-analyzer.js +399 -399
  292. package/scripts/lib/prompt-builder.js +264 -264
  293. package/scripts/lib/reglas-globales-conocidas.json +180 -180
  294. package/scripts/lib/resolver-plan-fase.js +37 -37
  295. package/scripts/lib/rrf-fusion.js +175 -175
  296. package/scripts/lib/schema-version.js +164 -164
  297. package/scripts/lib/scoring-instintos.js +277 -277
  298. package/scripts/lib/semantic-search.js +252 -252
  299. package/scripts/lib/skill-metrics.js +41 -1
  300. package/scripts/lib/toml-merge.js +204 -204
  301. package/scripts/lib/tool-cost-analyzer.js +1 -0
  302. package/scripts/limpiar-artefactos-python.js +131 -131
  303. package/scripts/mcp-server/auth.js +105 -105
  304. package/scripts/mcp-server/cache.js +106 -106
  305. package/scripts/migrar-csv-a-array.js +168 -168
  306. package/scripts/migrar-fase-dominio.js +200 -200
  307. package/scripts/publicar.js +497 -497
  308. package/scripts/run-eval.js +141 -141
  309. package/scripts/tui/componentes/selector-multi.js +189 -189
  310. package/scripts/tui/componentes/selector-unico.js +158 -158
  311. package/scripts/tui/ejecutores.js +375 -375
  312. package/scripts/tui/index.js +162 -162
  313. package/scripts/tui/lib/colores.js +129 -129
  314. package/scripts/tui/lib/render.js +264 -264
  315. package/scripts/tui/lib/teclas.js +113 -113
  316. package/scripts/tui/pantallas/inspect.js +173 -173
  317. package/scripts/tui/pantallas/install-wizard.js +334 -334
  318. package/scripts/tui/pantallas/menu-principal.js +52 -52
  319. package/scripts/tui/pantallas/progreso.js +274 -274
  320. package/scripts/tui/pantallas/resumen.js +132 -132
  321. package/scripts/tui/pantallas/uninstall-wizard.js +208 -208
  322. package/scripts/tui/pantallas/update-wizard.js +232 -232
  323. package/scripts/tui/pantallas/welcome.js +187 -187
  324. package/scripts/validar-userland-vacio.js +110 -110
  325. package/scripts/verificar-trazabilidad.js +329 -298
@@ -1,474 +1,512 @@
1
- 'use strict';
2
-
3
- /**
4
- * briefing.js — Recolectores de señales para el briefing proactivo de sesión.
5
- *
6
- * Fase 12 (ADR-0036). Cada recolector es una función PURA que recibe `baseDir`
7
- * (raíz del proyecto destino) y `hoy` (Date inyectable para testabilidad) y
8
- * devuelve un array de ítems `{ categoria, titulo, accion, hash }`:
9
- * - categoria: clave estable de la señal (para telemetría y dedupe por grupo).
10
- * - titulo: texto corto de qué pasa.
11
- * - accion: comando ejecutable concreto (REQ-12-03: nunca consejo vago).
12
- * - hash: sha1 corto de categoria+titulo, para dedupe entre digests (D-18).
13
- *
14
- * Solo lecturas de filesystem ya computado: cero LLM, cero red, presupuesto
15
- * <200ms (REQ-12-02). Las señales caras (CVEs, cobertura, hubs del grafo) viven
16
- * en el comando `/swl:briefing`, no aquí (D-12).
17
- *
18
- * Zero-deps. El hook session-briefing.js consume esta lib con require de
19
- * fallback dual (repo madre `./lib/briefing` vs destino aplanado `./briefing`).
20
- *
21
- * @module hooks/lib/briefing
22
- */
23
-
24
- const fs = require('fs');
25
- const path = require('path');
26
- const crypto = require('crypto');
27
-
28
- // Métricas DORA (Fase 15, ADR-0039): require tolerante. En modo de instalación
29
- // `flat` el require cross-dir hooks/lib → scripts/lib no resuelve y el recolector
30
- // degrada a silencio; en modo `copy` (default) resuelve y el aviso proactivo
31
- // funciona. El recolector usa SOLO git (rápido); NUNCA invoca gh.
32
- let detectarDegradacionEntrega = null;
33
- try {
34
- ({ detectarDegradacionEntrega } = require('../../scripts/lib/git-metricas'));
35
- } catch {
36
- try {
37
- ({ detectarDegradacionEntrega } = require('./git-metricas'));
38
- } catch {
39
- detectarDegradacionEntrega = null;
40
- }
41
- }
42
-
43
- const VENTANA_CALIBRACION_MS = 14 * 24 * 3600 * 1000; // 14 días (ADR-0034/0035)
44
-
45
- // Gates en calibración → kind de su nudge (conocimiento de dominio, Fase 10).
46
- const GATES_CALIBRABLES = {
47
- 'spec-gate.js': 'spec-gate',
48
- 'tdd-gate.js': 'tdd-red-evidence',
49
- };
50
-
51
- // ─── utilidades ──────────────────────────────────────────────────────────────
52
-
53
- function leerTexto(p) {
54
- try {
55
- return fs.readFileSync(p, 'utf8');
56
- } catch {
57
- return null;
58
- }
59
- }
60
-
61
- function hashItem(categoria, titulo) {
62
- return crypto.createHash('sha1').update(`${categoria}\u0000${titulo}`).digest('hex').slice(0, 10);
63
- }
64
-
65
- function item(categoria, titulo, accion) {
66
- return { categoria, titulo, accion, hash: hashItem(categoria, titulo) };
67
- }
68
-
69
- /** Primera fecha ISO `YYYY-MM-DD` de un texto, como Date (UTC) o null. */
70
- function primeraFechaISO(texto) {
71
- const m = (texto || '').match(/(\d{4})-(\d{2})-(\d{2})/);
72
- if (!m) return null;
73
- const d = new Date(`${m[1]}-${m[2]}-${m[3]}T00:00:00Z`);
74
- return Number.isNaN(d.getTime()) ? null : d;
75
- }
76
-
77
- /** Lee `.planning/evolution/nudges.jsonl` como array de objetos (tolera líneas corruptas). */
78
- function leerNudges(baseDir) {
79
- const txt = leerTexto(path.join(baseDir, '.planning', 'evolution', 'nudges.jsonl'));
80
- if (!txt) return [];
81
- const out = [];
82
- for (const linea of txt.split('\n')) {
83
- const t = linea.trim();
84
- if (!t) continue;
85
- try {
86
- out.push(JSON.parse(t));
87
- } catch {
88
- /* línea corrupta: ignorar */
89
- }
90
- }
91
- return out;
92
- }
93
-
94
- // ─── recolectores ──────────────────────────────────────────────────────────
95
-
96
- /**
97
- * ADRs en estado Propuesto cuya fecha de reevaluación ya pasó.
98
- * Fuente: `.planning/adrs/README.md` (tabla `| # | Título | Estado | Fecha | Reevaluar |`).
99
- */
100
- function adrsVencidos(baseDir, hoy = new Date()) {
101
- const txt = leerTexto(path.join(baseDir, '.planning', 'adrs', 'README.md'));
102
- if (!txt) return [];
103
- const out = [];
104
- for (const linea of txt.split('\n')) {
105
- if (!linea.includes('|')) continue;
106
- const celdas = linea.split('|').map((c) => c.trim());
107
- // celdas: ['', '#', 'Título', 'Estado', 'Fecha', 'Reevaluar', '']
108
- if (celdas.length < 6) continue;
109
- const num = celdas[1];
110
- const titulo = celdas[2];
111
- const estado = celdas[3];
112
- const reevaluar = celdas[5];
113
- if (!/^\d{3,4}$/.test(num)) continue; // fila de datos (no encabezado/separador)
114
- if (!/Propuesto/i.test(estado)) continue;
115
- const fecha = primeraFechaISO(reevaluar);
116
- if (!fecha || fecha.getTime() > hoy.getTime()) continue;
117
- out.push(
118
- item(
119
- 'adr-vencido',
120
- `ADR-${num} Propuesto con reevaluación vencida (${reevaluar.replace(/\*/g, '')})`,
121
- `Revisar .planning/adrs/${num}-*.md y resolver (aceptar / descartar / extender)`
122
- )
123
- );
124
- }
125
- return out;
126
- }
127
-
128
- /**
129
- * Deuda técnica Abierta cuyo trigger verificable contiene una fecha ISO ya pasada.
130
- * Solo fechas (D-16): los triggers en prosa libre quedan para `/swl:briefing`.
131
- * Fuente: `.planning/DEUDA-TECNICA.md` (entradas `## DT-X —`, `**Estado**: Abierta`).
132
- */
133
- function deudaTriggerCumplido(baseDir, hoy = new Date()) {
134
- const txt = leerTexto(path.join(baseDir, '.planning', 'DEUDA-TECNICA.md'));
135
- if (!txt) return [];
136
- const out = [];
137
- // Partir por encabezados `## DT-...` / `## DA-...` / `## OP-...`
138
- const bloques = txt.split(/\n(?=## (?:DT|DA|OP)-)/);
139
- for (const bloque of bloques) {
140
- const cab = bloque.match(/^##\s+((?:DT|DA|OP)-[A-Z0-9-]+)\s*(?:—\s*(.*))?/m);
141
- if (!cab) continue;
142
- const id = cab[1];
143
- if (!/\*\*Estado\*\*\s*:\s*Abierta/i.test(bloque)) continue;
144
- // Buscar fecha ISO en la sección de trigger (o en todo el bloque como fallback)
145
- const triggerSec = bloque.split(/###\s*Trigger/i)[1] || bloque;
146
- const fecha = primeraFechaISO(triggerSec);
147
- if (!fecha || fecha.getTime() > hoy.getTime()) continue;
148
- out.push(
149
- item(
150
- 'deuda-trigger',
151
- `${id}: trigger con fecha cumplida (${fecha.toISOString().slice(0, 10)})`,
152
- `Revisar .planning/DEUDA-TECNICA.md § ${id} y cerrar o re-planear`
153
- )
154
- );
155
- }
156
- return out;
157
- }
158
-
159
- /**
160
- * Nudges sin accionar acumulados (formato nudge-tracker: { kind, accionado }).
161
- * Las líneas legacy sin `kind` se ignoran.
162
- */
163
- function nudgesPendientes(baseDir /*, hoy */) {
164
- const nudges = leerNudges(baseDir).filter((n) => n && n.kind && n.accionado === false);
165
- if (nudges.length === 0) return [];
166
- const porKind = {};
167
- for (const n of nudges) porKind[n.kind] = (porKind[n.kind] || 0) + 1;
168
- const detalle = Object.entries(porKind)
169
- .map(([k, c]) => `${k}×${c}`)
170
- .join(', ');
171
- return [
172
- item(
173
- 'nudges-pendientes',
174
- `${nudges.length} nudge(s) sin accionar (${detalle})`,
175
- 'Ejecutar /swl:evolucion-estado para revisarlos y accionar'
176
- ),
177
- ];
178
- }
179
-
180
- /**
181
- * Gates en calibración (warn-only) cuya ventana de ~14 días ya se cumplió:
182
- * blocking:false en hooks-config Y el nudge más antiguo de su kind ≥14 días.
183
- * Señal de que toca decidir la promoción a blocking (ADR-0034/0035).
184
- */
185
- function gatesEnCalibracion(baseDir, hoy = new Date(), opts = {}) {
186
- const hooksConfigPath =
187
- opts.hooksConfigPath || path.join(baseDir, 'manifiestos', 'hooks-config.json');
188
- const txt = leerTexto(hooksConfigPath);
189
- if (!txt) return [];
190
- let config;
191
- try {
192
- config = JSON.parse(txt);
193
- } catch {
194
- return [];
195
- }
196
- const hooks = (config && config.hooks) || {};
197
- const nudges = leerNudges(baseDir).filter((n) => n && n.kind && n.ts);
198
- const out = [];
199
- for (const [archivo, kind] of Object.entries(GATES_CALIBRABLES)) {
200
- const entry = hooks[archivo];
201
- if (!entry || entry.blocking !== false) continue; // ya promovido o ausente
202
- const delKind = nudges
203
- .map((n) => (n.kind === kind ? Date.parse(n.ts) : NaN))
204
- .filter((t) => Number.isFinite(t));
205
- if (delKind.length === 0) continue; // sin evidencia todavía
206
- const masAntiguo = Math.min(...delKind);
207
- if (hoy.getTime() - masAntiguo < VENTANA_CALIBRACION_MS) continue; // ventana no cumplida
208
- out.push(
209
- item(
210
- 'gate-calibracion',
211
- `Gate ${archivo} en calibración con ventana cumplida (${delKind.length} nudge[s] kind:${kind})`,
212
- `Revisar promoción a blocking (ADR-0034/0035) y flip en manifiestos/hooks-config.json`
213
- )
214
- );
215
- }
216
- return out;
217
- }
218
-
219
- /**
220
- * Trabajo pendiente de retoma: existe `.planning/continue-here.md`.
221
- */
222
- function continuePendiente(baseDir /*, hoy */) {
223
- const p = path.join(baseDir, '.planning', 'continue-here.md');
224
- const txt = leerTexto(p);
225
- if (txt === null) return [];
226
- const m = txt.match(/\*\*Checkpoint creado\*\*\s*:\s*(.+)/);
227
- const cuando = m ? m[1].trim() : 'desconocido';
228
- return [
229
- item(
230
- 'continue-here',
231
- `Checkpoint de retoma pendiente (${cuando})`,
232
- 'Leer .planning/continue-here.md y .planning/ESTADO.md para retomar'
233
- ),
234
- ];
235
- }
236
-
237
- /**
238
- * Recolector DORA (Fase 15, REQ-15-07): avisa SOLO cuando la velocidad de entrega
239
- * se degrada (deploy freq cae >50% o lead time mediano sube >50% vs la ventana
240
- * previa). Git-only y rápido — NUNCA invoca `gh` (la latencia de gh queda para el
241
- * subcomando bajo demanda). Opt-out: `SWL_DORA=0`. Silencio si la entrega es
242
- * estable, si no hay repo git, o si la lib no resuelve (modo `flat`).
243
- */
244
- function doraDegradado(baseDir, hoy = new Date()) {
245
- if (process.env.SWL_DORA === '0') return [];
246
- if (typeof detectarDegradacionEntrega !== 'function') return [];
247
- let r;
248
- try {
249
- r = detectarDegradacionEntrega(baseDir, { hoy });
250
- } catch {
251
- return [];
252
- }
253
- if (!r || !r.disponible || !r.degradado) return [];
254
- return [
255
- item(
256
- 'dora-degradado',
257
- `Velocidad de entrega degradada: ${r.motivo}`,
258
- 'Revisar con /swl:status dora'
259
- ),
260
- ];
261
- }
262
-
263
- /** Orden de prioridad de categorías para el digest (mayor primero). */
264
- const PRIORIDAD = [
265
- 'continue-here',
266
- 'gate-calibracion',
267
- 'deuda-trigger',
268
- 'dora-degradado',
269
- 'adr-vencido',
270
- 'nudges-pendientes',
271
- ];
272
-
273
- /** Ejecuta todos los recolectores y devuelve el array plano de ítems. */
274
- function recolectarTodo(baseDir, hoy = new Date(), opts = {}) {
275
- return [
276
- ...continuePendiente(baseDir, hoy),
277
- ...gatesEnCalibracion(baseDir, hoy, opts),
278
- ...deudaTriggerCumplido(baseDir, hoy),
279
- ...doraDegradado(baseDir, hoy),
280
- ...adrsVencidos(baseDir, hoy),
281
- ...nudgesPendientes(baseDir, hoy),
282
- ];
283
- }
284
-
285
- const TOPE_DIGEST = 5; // D-13: máximo de ítems por digest
286
-
287
- /** Índice de prioridad de una categoría (menor = mayor prioridad). */
288
- function indicePrioridad(categoria) {
289
- const i = PRIORIDAD.indexOf(categoria);
290
- return i === -1 ? PRIORIDAD.length : i;
291
- }
292
-
293
- /**
294
- * Arma el digest del briefing aplicando dedupe diario (D-15), tope de 5 con
295
- * overflow (D-13), y sugerencia de `/swl:briefing` solo con volumen (D-14).
296
- *
297
- * @param {Array} items ítems recolectados (recolectarTodo)
298
- * @param {object} estadoPrevio { hashesPrevios: string[], dia: 'YYYY-MM-DD' }
299
- * @param {string} dia día actual 'YYYY-MM-DD' (inyectable)
300
- * @returns {{ texto: string, estado: object, mostrados: string[] } | null}
301
- * null = silencio total (sin señales nuevas).
302
- */
303
- function armarDigest(items, estadoPrevio = {}, dia, opts = {}) {
304
- const hoyStr = dia || new Date().toISOString().slice(0, 10);
305
- const mismoDia = estadoPrevio && estadoPrevio.dia === hoyStr;
306
- const yaMostrados = mismoDia && Array.isArray(estadoPrevio.hashesPrevios)
307
- ? new Set(estadoPrevio.hashesPrevios)
308
- : new Set();
309
-
310
- // Dedupe: en el mismo día, omitir ítems ya mostrados. Día nuevo → set vacío.
311
- const frescos = (items || []).filter((it) => it && !yaMostrados.has(it.hash));
312
- if (frescos.length === 0) return null; // silencio total (REQ-12-01)
313
-
314
- // Categorías silenciadas (telemetría D-18): sus ítems no entran al top 5,
315
- // van al final (overflow) para no copar el digest con señales que el usuario ignora.
316
- const silenciadas = opts.categoriasSilenciadas instanceof Set ? opts.categoriasSilenciadas : new Set();
317
-
318
- // Orden: prioridad de categoría, pero las silenciadas siempre al final.
319
- frescos.sort((a, b) => {
320
- const sa = silenciadas.has(a.categoria) ? 1 : 0;
321
- const sb = silenciadas.has(b.categoria) ? 1 : 0;
322
- if (sa !== sb) return sa - sb;
323
- return indicePrioridad(a.categoria) - indicePrioridad(b.categoria);
324
- });
325
-
326
- const visibles = frescos.slice(0, TOPE_DIGEST);
327
- const overflow = frescos.length - visibles.length;
328
-
329
- const lineas = ['Briefing de sesión — señales pendientes:'];
330
- for (const it of visibles) {
331
- lineas.push(`— [${it.categoria}] ${it.titulo} ${it.accion}`);
332
- }
333
- // Sugerencia de /swl:briefing SOLO con overflow (D-14).
334
- if (overflow > 0) {
335
- lineas.push(`+${overflow} señales más ejecuta /swl:briefing para el análisis completo`);
336
- }
337
-
338
- // Estado nuevo: acumula los hashes mostrados HOY (frescos completos, no solo visibles —
339
- // los de overflow también se consideran "vistos" para no re-listarlos mañana mismo).
340
- const hashesMostrados = mismoDia
341
- ? [...yaMostrados, ...frescos.map((it) => it.hash)]
342
- : frescos.map((it) => it.hash);
343
-
344
- return {
345
- texto: lineas.join('\n'),
346
- estado: { dia: hoyStr, hashesPrevios: [...new Set(hashesMostrados)] },
347
- mostrados: visibles.map((it) => it.hash),
348
- };
349
- }
350
-
351
- /** Lee el estado de dedupe persistido en `.planning/user-profile/briefing-estado.json`. */
352
- function leerEstadoBriefing(baseDir) {
353
- const txt = leerTexto(path.join(baseDir, '.planning', 'user-profile', 'briefing-estado.json'));
354
- if (!txt) return { dia: null, hashesPrevios: [] };
355
- try {
356
- const o = JSON.parse(txt);
357
- return { dia: o.dia || null, hashesPrevios: Array.isArray(o.hashesPrevios) ? o.hashesPrevios : [] };
358
- } catch {
359
- return { dia: null, hashesPrevios: [] };
360
- }
361
- }
362
-
363
- // ─── telemetría de aceptación (D-18, REQ-12-05) ──────────────────────────────
364
-
365
- const UMBRAL_IGNORADO = 3; // apariciones sin resolver para contar "ignorado"
366
- const RATIO_SILENCIO = 0.8; // ignorado/mostrado para silenciar la categoría
367
- const MIN_MUESTRAS_SILENCIO = 5; // mínimo de mostrados antes de silenciar
368
-
369
- function catVacia() {
370
- return { mostrado: 0, actuado: 0, ignorado: 0, silenciada: false, ultima_ts: null };
371
- }
372
-
373
- /**
374
- * Actualiza la telemetría de aceptación comparando lo visto antes con lo que
375
- * sigue presente ahora (D-18: detección por resolución de señal, zero-LLM):
376
- * - señal que desaparece de los ítems actuales "actuado" en su categoría.
377
- * - señal nueva → "mostrado" y entra a `vistos`.
378
- * - señal que persiste ≥UMBRAL_IGNORADO corridas → "ignorado" (una sola vez).
379
- * - categoría con ignorado/mostrado ≥RATIO_SILENCIO y ≥MIN_MUESTRAS → silenciada.
380
- *
381
- * @param {object} prev { vistos:{hash:{categoria,veces,contadoIgnorado?}}, categorias:{} }
382
- * @param {Array} itemsActuales ítems recolectados ahora
383
- * @param {string} hoyISO timestamp ISO de esta corrida
384
- * @returns {object} telemetría nueva (consumible por perfilador-usuario-swl)
385
- */
386
- function actualizarTelemetria(prev, itemsActuales, hoyISO) {
387
- const vistos = { ...(prev && prev.vistos) };
388
- const categorias = {};
389
- for (const [k, v] of Object.entries((prev && prev.categorias) || {})) {
390
- categorias[k] = { ...catVacia(), ...v };
391
- }
392
- const ensure = (cat) => {
393
- if (!categorias[cat]) categorias[cat] = catVacia();
394
- return categorias[cat];
395
- };
396
-
397
- const hashesActuales = new Set((itemsActuales || []).map((it) => it.hash));
398
-
399
- // 1. Resueltos: lo que estaba visto y ya no aparece → actuado.
400
- for (const [hash, info] of Object.entries(vistos)) {
401
- if (!hashesActuales.has(hash)) {
402
- ensure(info.categoria).actuado += 1;
403
- ensure(info.categoria).ultima_ts = hoyISO;
404
- delete vistos[hash];
405
- }
406
- }
407
-
408
- // 2. Presentes ahora: nuevos (mostrado++) o persistentes (veces++ → ignorado).
409
- for (const it of itemsActuales || []) {
410
- const c = ensure(it.categoria);
411
- c.ultima_ts = hoyISO;
412
- if (!vistos[it.hash]) {
413
- vistos[it.hash] = { categoria: it.categoria, veces: 1, contadoIgnorado: false };
414
- c.mostrado += 1;
415
- } else {
416
- vistos[it.hash].veces += 1;
417
- if (vistos[it.hash].veces >= UMBRAL_IGNORADO && !vistos[it.hash].contadoIgnorado) {
418
- c.ignorado += 1;
419
- vistos[it.hash].contadoIgnorado = true;
420
- }
421
- }
422
- }
423
-
424
- // 3. Silenciar categorías con ratio de ignorado alto.
425
- for (const c of Object.values(categorias)) {
426
- c.silenciada =
427
- c.mostrado >= MIN_MUESTRAS_SILENCIO && c.ignorado / c.mostrado >= RATIO_SILENCIO;
428
- }
429
-
430
- return { vistos, categorias };
431
- }
432
-
433
- /** Lee la telemetría persistida en `.planning/user-profile/briefing-telemetria.json`. */
434
- function leerTelemetria(baseDir) {
435
- const txt = leerTexto(path.join(baseDir, '.planning', 'user-profile', 'briefing-telemetria.json'));
436
- if (!txt) return { vistos: {}, categorias: {} };
437
- try {
438
- const o = JSON.parse(txt);
439
- return { vistos: o.vistos || {}, categorias: o.categorias || {} };
440
- } catch {
441
- return { vistos: {}, categorias: {} };
442
- }
443
- }
444
-
445
- /** Conjunto de categorías actualmente silenciadas (para que armarDigest las degrade). */
446
- function categoriasSilenciadas(telemetria) {
447
- const set = new Set();
448
- for (const [cat, v] of Object.entries((telemetria && telemetria.categorias) || {})) {
449
- if (v && v.silenciada) set.add(cat);
450
- }
451
- return set;
452
- }
453
-
454
- module.exports = {
455
- adrsVencidos,
456
- deudaTriggerCumplido,
457
- nudgesPendientes,
458
- gatesEnCalibracion,
459
- continuePendiente,
460
- doraDegradado,
461
- recolectarTodo,
462
- armarDigest,
463
- leerEstadoBriefing,
464
- actualizarTelemetria,
465
- leerTelemetria,
466
- categoriasSilenciadas,
467
- PRIORIDAD,
468
- TOPE_DIGEST,
469
- VENTANA_CALIBRACION_MS,
470
- UMBRAL_IGNORADO,
471
- RATIO_SILENCIO,
472
- MIN_MUESTRAS_SILENCIO,
473
- _hashItem: hashItem,
474
- };
1
+ 'use strict';
2
+
3
+ /**
4
+ * briefing.js — Recolectores de señales para el briefing proactivo de sesión.
5
+ *
6
+ * Fase 12 (ADR-0036). Cada recolector es una función PURA que recibe `baseDir`
7
+ * (raíz del proyecto destino) y `hoy` (Date inyectable para testabilidad) y
8
+ * devuelve un array de ítems `{ categoria, titulo, accion, hash }`:
9
+ * - categoria: clave estable de la señal (para telemetría y dedupe por grupo).
10
+ * - titulo: texto corto de qué pasa.
11
+ * - accion: comando ejecutable concreto (REQ-12-03: nunca consejo vago).
12
+ * - hash: sha1 corto de categoria+titulo, para dedupe entre digests (D-18).
13
+ *
14
+ * Solo lecturas de filesystem ya computado: cero LLM, cero red, presupuesto
15
+ * <200ms (REQ-12-02). Las señales caras (CVEs, cobertura, hubs del grafo) viven
16
+ * en el comando `/swl:briefing`, no aquí (D-12).
17
+ *
18
+ * Zero-deps. El hook session-briefing.js consume esta lib con require de
19
+ * fallback dual (repo madre `./lib/briefing` vs destino aplanado `./briefing`).
20
+ *
21
+ * @module hooks/lib/briefing
22
+ */
23
+
24
+ const fs = require('fs');
25
+ const path = require('path');
26
+ const crypto = require('crypto');
27
+
28
+ // Métricas DORA (Fase 15, ADR-0039): require tolerante. En modo de instalación
29
+ // `flat` el require cross-dir hooks/lib → scripts/lib no resuelve y el recolector
30
+ // degrada a silencio; en modo `copy` (default) resuelve y el aviso proactivo
31
+ // funciona. El recolector usa SOLO git (rápido); NUNCA invoca gh.
32
+ let detectarDegradacionEntrega = null;
33
+ try {
34
+ ({ detectarDegradacionEntrega } = require('../../scripts/lib/git-metricas'));
35
+ } catch {
36
+ try {
37
+ ({ detectarDegradacionEntrega } = require('./git-metricas'));
38
+ } catch {
39
+ detectarDegradacionEntrega = null;
40
+ }
41
+ }
42
+
43
+ // Staleness de skills (Fase 20): require tolerante cross-dir. En modo `flat` no
44
+ // resuelve y el recolector degrada a silencio (patrón de doraDegradado).
45
+ let skillsStaleLib = null;
46
+ try {
47
+ ({ skillsStale: skillsStaleLib } = require('../../scripts/lib/skill-metrics'));
48
+ } catch {
49
+ try {
50
+ ({ skillsStale: skillsStaleLib } = require('./skill-metrics'));
51
+ } catch {
52
+ skillsStaleLib = null;
53
+ }
54
+ }
55
+
56
+ const VENTANA_CALIBRACION_MS = 14 * 24 * 3600 * 1000; // 14 días (ADR-0034/0035)
57
+
58
+ // Gates en calibración → kind de su nudge (conocimiento de dominio, Fase 10).
59
+ const GATES_CALIBRABLES = {
60
+ 'spec-gate.js': 'spec-gate',
61
+ 'tdd-gate.js': 'tdd-red-evidence',
62
+ };
63
+
64
+ // ─── utilidades ──────────────────────────────────────────────────────────────
65
+
66
+ function leerTexto(p) {
67
+ try {
68
+ return fs.readFileSync(p, 'utf8');
69
+ } catch {
70
+ return null;
71
+ }
72
+ }
73
+
74
+ function hashItem(categoria, titulo) {
75
+ return crypto.createHash('sha1').update(`${categoria}\u0000${titulo}`).digest('hex').slice(0, 10);
76
+ }
77
+
78
+ function item(categoria, titulo, accion) {
79
+ return { categoria, titulo, accion, hash: hashItem(categoria, titulo) };
80
+ }
81
+
82
+ /** Primera fecha ISO `YYYY-MM-DD` de un texto, como Date (UTC) o null. */
83
+ function primeraFechaISO(texto) {
84
+ const m = (texto || '').match(/(\d{4})-(\d{2})-(\d{2})/);
85
+ if (!m) return null;
86
+ const d = new Date(`${m[1]}-${m[2]}-${m[3]}T00:00:00Z`);
87
+ return Number.isNaN(d.getTime()) ? null : d;
88
+ }
89
+
90
+ /** Lee `.planning/evolution/nudges.jsonl` como array de objetos (tolera líneas corruptas). */
91
+ function leerNudges(baseDir) {
92
+ const txt = leerTexto(path.join(baseDir, '.planning', 'evolution', 'nudges.jsonl'));
93
+ if (!txt) return [];
94
+ const out = [];
95
+ for (const linea of txt.split('\n')) {
96
+ const t = linea.trim();
97
+ if (!t) continue;
98
+ try {
99
+ out.push(JSON.parse(t));
100
+ } catch {
101
+ /* línea corrupta: ignorar */
102
+ }
103
+ }
104
+ return out;
105
+ }
106
+
107
+ // ─── recolectores ──────────────────────────────────────────────────────────
108
+
109
+ /**
110
+ * ADRs en estado Propuesto cuya fecha de reevaluación ya pasó.
111
+ * Fuente: `.planning/adrs/README.md` (tabla `| # | Título | Estado | Fecha | Reevaluar |`).
112
+ */
113
+ function adrsVencidos(baseDir, hoy = new Date()) {
114
+ const txt = leerTexto(path.join(baseDir, '.planning', 'adrs', 'README.md'));
115
+ if (!txt) return [];
116
+ const out = [];
117
+ for (const linea of txt.split('\n')) {
118
+ if (!linea.includes('|')) continue;
119
+ const celdas = linea.split('|').map((c) => c.trim());
120
+ // celdas: ['', '#', 'Título', 'Estado', 'Fecha', 'Reevaluar', '']
121
+ if (celdas.length < 6) continue;
122
+ const num = celdas[1];
123
+ const titulo = celdas[2];
124
+ const estado = celdas[3];
125
+ const reevaluar = celdas[5];
126
+ if (!/^\d{3,4}$/.test(num)) continue; // fila de datos (no encabezado/separador)
127
+ if (!/Propuesto/i.test(estado)) continue;
128
+ const fecha = primeraFechaISO(reevaluar);
129
+ if (!fecha || fecha.getTime() > hoy.getTime()) continue;
130
+ out.push(
131
+ item(
132
+ 'adr-vencido',
133
+ `ADR-${num} Propuesto con reevaluación vencida (${reevaluar.replace(/\*/g, '')})`,
134
+ `Revisar .planning/adrs/${num}-*.md y resolver (aceptar / descartar / extender)`
135
+ )
136
+ );
137
+ }
138
+ return out;
139
+ }
140
+
141
+ /**
142
+ * Deuda técnica Abierta cuyo trigger verificable contiene una fecha ISO ya pasada.
143
+ * Solo fechas (D-16): los triggers en prosa libre quedan para `/swl:briefing`.
144
+ * Fuente: `.planning/DEUDA-TECNICA.md` (entradas `## DT-X —`, `**Estado**: Abierta`).
145
+ */
146
+ function deudaTriggerCumplido(baseDir, hoy = new Date()) {
147
+ const txt = leerTexto(path.join(baseDir, '.planning', 'DEUDA-TECNICA.md'));
148
+ if (!txt) return [];
149
+ const out = [];
150
+ // Partir por encabezados `## DT-...` / `## DA-...` / `## OP-...`
151
+ const bloques = txt.split(/\n(?=## (?:DT|DA|OP)-)/);
152
+ for (const bloque of bloques) {
153
+ const cab = bloque.match(/^##\s+((?:DT|DA|OP)-[A-Z0-9-]+)\s*(?:—\s*(.*))?/m);
154
+ if (!cab) continue;
155
+ const id = cab[1];
156
+ if (!/\*\*Estado\*\*\s*:\s*Abierta/i.test(bloque)) continue;
157
+ // Buscar fecha ISO en la sección de trigger (o en todo el bloque como fallback)
158
+ const triggerSec = bloque.split(/###\s*Trigger/i)[1] || bloque;
159
+ const fecha = primeraFechaISO(triggerSec);
160
+ if (!fecha || fecha.getTime() > hoy.getTime()) continue;
161
+ out.push(
162
+ item(
163
+ 'deuda-trigger',
164
+ `${id}: trigger con fecha cumplida (${fecha.toISOString().slice(0, 10)})`,
165
+ `Revisar .planning/DEUDA-TECNICA.md § ${id} y cerrar o re-planear`
166
+ )
167
+ );
168
+ }
169
+ return out;
170
+ }
171
+
172
+ /**
173
+ * Nudges sin accionar acumulados (formato nudge-tracker: { kind, accionado }).
174
+ * Las líneas legacy sin `kind` se ignoran.
175
+ */
176
+ function nudgesPendientes(baseDir /*, hoy */) {
177
+ const nudges = leerNudges(baseDir).filter((n) => n && n.kind && n.accionado === false);
178
+ if (nudges.length === 0) return [];
179
+ const porKind = {};
180
+ for (const n of nudges) porKind[n.kind] = (porKind[n.kind] || 0) + 1;
181
+ const detalle = Object.entries(porKind)
182
+ .map(([k, c]) => `${k}×${c}`)
183
+ .join(', ');
184
+ return [
185
+ item(
186
+ 'nudges-pendientes',
187
+ `${nudges.length} nudge(s) sin accionar (${detalle})`,
188
+ 'Ejecutar /swl:evolucion-estado para revisarlos y accionar'
189
+ ),
190
+ ];
191
+ }
192
+
193
+ /**
194
+ * Gates en calibración (warn-only) cuya ventana de ~14 días ya se cumplió:
195
+ * blocking:false en hooks-config Y el nudge más antiguo de su kind ≥14 días.
196
+ * Señal de que toca decidir la promoción a blocking (ADR-0034/0035).
197
+ */
198
+ function gatesEnCalibracion(baseDir, hoy = new Date(), opts = {}) {
199
+ const hooksConfigPath =
200
+ opts.hooksConfigPath || path.join(baseDir, 'manifiestos', 'hooks-config.json');
201
+ const txt = leerTexto(hooksConfigPath);
202
+ if (!txt) return [];
203
+ let config;
204
+ try {
205
+ config = JSON.parse(txt);
206
+ } catch {
207
+ return [];
208
+ }
209
+ const hooks = (config && config.hooks) || {};
210
+ const nudges = leerNudges(baseDir).filter((n) => n && n.kind && n.ts);
211
+ const out = [];
212
+ for (const [archivo, kind] of Object.entries(GATES_CALIBRABLES)) {
213
+ const entry = hooks[archivo];
214
+ if (!entry || entry.blocking !== false) continue; // ya promovido o ausente
215
+ const delKind = nudges
216
+ .map((n) => (n.kind === kind ? Date.parse(n.ts) : NaN))
217
+ .filter((t) => Number.isFinite(t));
218
+ if (delKind.length === 0) continue; // sin evidencia todavía
219
+ const masAntiguo = Math.min(...delKind);
220
+ if (hoy.getTime() - masAntiguo < VENTANA_CALIBRACION_MS) continue; // ventana no cumplida
221
+ out.push(
222
+ item(
223
+ 'gate-calibracion',
224
+ `Gate ${archivo} en calibración con ventana cumplida (${delKind.length} nudge[s] kind:${kind})`,
225
+ `Revisar promoción a blocking (ADR-0034/0035) y flip en manifiestos/hooks-config.json`
226
+ )
227
+ );
228
+ }
229
+ return out;
230
+ }
231
+
232
+ /**
233
+ * Trabajo pendiente de retoma: existe `.planning/continue-here.md`.
234
+ */
235
+ function continuePendiente(baseDir /*, hoy */) {
236
+ const p = path.join(baseDir, '.planning', 'continue-here.md');
237
+ const txt = leerTexto(p);
238
+ if (txt === null) return [];
239
+ const m = txt.match(/\*\*Checkpoint creado\*\*\s*:\s*(.+)/);
240
+ const cuando = m ? m[1].trim() : 'desconocido';
241
+ return [
242
+ item(
243
+ 'continue-here',
244
+ `Checkpoint de retoma pendiente (${cuando})`,
245
+ 'Leer .planning/continue-here.md y .planning/ESTADO.md para retomar'
246
+ ),
247
+ ];
248
+ }
249
+
250
+ /**
251
+ * Recolector DORA (Fase 15, REQ-15-07): avisa SOLO cuando la velocidad de entrega
252
+ * se degrada (deploy freq cae >50% o lead time mediano sube >50% vs la ventana
253
+ * previa). Git-only y rápido — NUNCA invoca `gh` (la latencia de gh queda para el
254
+ * subcomando bajo demanda). Opt-out: `SWL_DORA=0`. Silencio si la entrega es
255
+ * estable, si no hay repo git, o si la lib no resuelve (modo `flat`).
256
+ */
257
+ function doraDegradado(baseDir, hoy = new Date()) {
258
+ if (process.env.SWL_DORA === '0') return [];
259
+ if (typeof detectarDegradacionEntrega !== 'function') return [];
260
+ let r;
261
+ try {
262
+ r = detectarDegradacionEntrega(baseDir, { hoy });
263
+ } catch {
264
+ return [];
265
+ }
266
+ if (!r || !r.disponible || !r.degradado) return [];
267
+ return [
268
+ item(
269
+ 'dora-degradado',
270
+ `Velocidad de entrega degradada: ${r.motivo}`,
271
+ 'Revisar con /swl:status dora'
272
+ ),
273
+ ];
274
+ }
275
+
276
+ const TOPE_SKILLS_STALE = 3; // no saturar el digest con skills fríos
277
+
278
+ /**
279
+ * Skills que tuvieron uso y se enfriaron (>N días sin invocarse) — superficie
280
+ * temporal que los skills no tenían (Fase 20, análisis self-learning). Acción:
281
+ * re-validar con /swl:evaluar-skill. Opt-out: SWL_SKILL_STALE=0. Degrada a
282
+ * silencio si la lib no resuelve (modo `flat`) o no hay métricas.
283
+ */
284
+ function skillsStale(baseDir, hoy = new Date()) {
285
+ if (process.env.SWL_SKILL_STALE === '0') return [];
286
+ if (typeof skillsStaleLib !== 'function') return [];
287
+ let frios;
288
+ try {
289
+ frios = skillsStaleLib(baseDir, hoy);
290
+ } catch {
291
+ return [];
292
+ }
293
+ return (frios || []).slice(0, TOPE_SKILLS_STALE).map((s) =>
294
+ item('skill-stale', `Skill frío: ${s.skill} (${s.diasInactivo}d sin uso)`, `/swl:evaluar-skill ${s.skill}`)
295
+ );
296
+ }
297
+
298
+ /** Orden de prioridad de categorías para el digest (mayor primero). */
299
+ const PRIORIDAD = [
300
+ 'continue-here',
301
+ 'gate-calibracion',
302
+ 'deuda-trigger',
303
+ 'dora-degradado',
304
+ 'adr-vencido',
305
+ 'nudges-pendientes',
306
+ 'skill-stale',
307
+ ];
308
+
309
+ /** Ejecuta todos los recolectores y devuelve el array plano de ítems. */
310
+ function recolectarTodo(baseDir, hoy = new Date(), opts = {}) {
311
+ return [
312
+ ...continuePendiente(baseDir, hoy),
313
+ ...gatesEnCalibracion(baseDir, hoy, opts),
314
+ ...deudaTriggerCumplido(baseDir, hoy),
315
+ ...doraDegradado(baseDir, hoy),
316
+ ...adrsVencidos(baseDir, hoy),
317
+ ...nudgesPendientes(baseDir, hoy),
318
+ ...skillsStale(baseDir, hoy),
319
+ ];
320
+ }
321
+
322
+ const TOPE_DIGEST = 5; // D-13: máximo de ítems por digest
323
+
324
+ /** Índice de prioridad de una categoría (menor = mayor prioridad). */
325
+ function indicePrioridad(categoria) {
326
+ const i = PRIORIDAD.indexOf(categoria);
327
+ return i === -1 ? PRIORIDAD.length : i;
328
+ }
329
+
330
+ /**
331
+ * Arma el digest del briefing aplicando dedupe diario (D-15), tope de 5 con
332
+ * overflow (D-13), y sugerencia de `/swl:briefing` solo con volumen (D-14).
333
+ *
334
+ * @param {Array} items ítems recolectados (recolectarTodo)
335
+ * @param {object} estadoPrevio { hashesPrevios: string[], dia: 'YYYY-MM-DD' }
336
+ * @param {string} dia día actual 'YYYY-MM-DD' (inyectable)
337
+ * @returns {{ texto: string, estado: object, mostrados: string[] } | null}
338
+ * null = silencio total (sin señales nuevas).
339
+ */
340
+ function armarDigest(items, estadoPrevio = {}, dia, opts = {}) {
341
+ const hoyStr = dia || new Date().toISOString().slice(0, 10);
342
+ const mismoDia = estadoPrevio && estadoPrevio.dia === hoyStr;
343
+ const yaMostrados = mismoDia && Array.isArray(estadoPrevio.hashesPrevios)
344
+ ? new Set(estadoPrevio.hashesPrevios)
345
+ : new Set();
346
+
347
+ // Dedupe: en el mismo día, omitir ítems ya mostrados. Día nuevo → set vacío.
348
+ const frescos = (items || []).filter((it) => it && !yaMostrados.has(it.hash));
349
+ if (frescos.length === 0) return null; // silencio total (REQ-12-01)
350
+
351
+ // Categorías silenciadas (telemetría D-18): sus ítems no entran al top 5,
352
+ // van al final (overflow) para no copar el digest con señales que el usuario ignora.
353
+ const silenciadas = opts.categoriasSilenciadas instanceof Set ? opts.categoriasSilenciadas : new Set();
354
+
355
+ // Orden: prioridad de categoría, pero las silenciadas siempre al final.
356
+ frescos.sort((a, b) => {
357
+ const sa = silenciadas.has(a.categoria) ? 1 : 0;
358
+ const sb = silenciadas.has(b.categoria) ? 1 : 0;
359
+ if (sa !== sb) return sa - sb;
360
+ return indicePrioridad(a.categoria) - indicePrioridad(b.categoria);
361
+ });
362
+
363
+ const visibles = frescos.slice(0, TOPE_DIGEST);
364
+ const overflow = frescos.length - visibles.length;
365
+
366
+ const lineas = ['Briefing de sesión señales pendientes:'];
367
+ for (const it of visibles) {
368
+ lineas.push(`— [${it.categoria}] ${it.titulo} → ${it.accion}`);
369
+ }
370
+ // Sugerencia de /swl:briefing SOLO con overflow (D-14).
371
+ if (overflow > 0) {
372
+ lineas.push(`+${overflow} señales más → ejecuta /swl:briefing para el análisis completo`);
373
+ }
374
+
375
+ // Estado nuevo: acumula los hashes mostrados HOY (frescos completos, no solo visibles
376
+ // los de overflow también se consideran "vistos" para no re-listarlos mañana mismo).
377
+ const hashesMostrados = mismoDia
378
+ ? [...yaMostrados, ...frescos.map((it) => it.hash)]
379
+ : frescos.map((it) => it.hash);
380
+
381
+ return {
382
+ texto: lineas.join('\n'),
383
+ estado: { dia: hoyStr, hashesPrevios: [...new Set(hashesMostrados)] },
384
+ mostrados: visibles.map((it) => it.hash),
385
+ };
386
+ }
387
+
388
+ /** Lee el estado de dedupe persistido en `.planning/user-profile/briefing-estado.json`. */
389
+ function leerEstadoBriefing(baseDir) {
390
+ const txt = leerTexto(path.join(baseDir, '.planning', 'user-profile', 'briefing-estado.json'));
391
+ if (!txt) return { dia: null, hashesPrevios: [] };
392
+ try {
393
+ const o = JSON.parse(txt);
394
+ return { dia: o.dia || null, hashesPrevios: Array.isArray(o.hashesPrevios) ? o.hashesPrevios : [] };
395
+ } catch {
396
+ return { dia: null, hashesPrevios: [] };
397
+ }
398
+ }
399
+
400
+ // ─── telemetría de aceptación (D-18, REQ-12-05) ──────────────────────────────
401
+
402
+ const UMBRAL_IGNORADO = 3; // apariciones sin resolver para contar "ignorado"
403
+ const RATIO_SILENCIO = 0.8; // ignorado/mostrado para silenciar la categoría
404
+ const MIN_MUESTRAS_SILENCIO = 5; // mínimo de mostrados antes de silenciar
405
+
406
+ function catVacia() {
407
+ return { mostrado: 0, actuado: 0, ignorado: 0, silenciada: false, ultima_ts: null };
408
+ }
409
+
410
+ /**
411
+ * Actualiza la telemetría de aceptación comparando lo visto antes con lo que
412
+ * sigue presente ahora (D-18: detección por resolución de señal, zero-LLM):
413
+ * - señal que desaparece de los ítems actuales → "actuado" en su categoría.
414
+ * - señal nueva → "mostrado" y entra a `vistos`.
415
+ * - señal que persiste ≥UMBRAL_IGNORADO corridas → "ignorado" (una sola vez).
416
+ * - categoría con ignorado/mostrado ≥RATIO_SILENCIO y ≥MIN_MUESTRAS → silenciada.
417
+ *
418
+ * @param {object} prev { vistos:{hash:{categoria,veces,contadoIgnorado?}}, categorias:{} }
419
+ * @param {Array} itemsActuales ítems recolectados ahora
420
+ * @param {string} hoyISO timestamp ISO de esta corrida
421
+ * @returns {object} telemetría nueva (consumible por perfilador-usuario-swl)
422
+ */
423
+ function actualizarTelemetria(prev, itemsActuales, hoyISO) {
424
+ const vistos = { ...(prev && prev.vistos) };
425
+ const categorias = {};
426
+ for (const [k, v] of Object.entries((prev && prev.categorias) || {})) {
427
+ categorias[k] = { ...catVacia(), ...v };
428
+ }
429
+ const ensure = (cat) => {
430
+ if (!categorias[cat]) categorias[cat] = catVacia();
431
+ return categorias[cat];
432
+ };
433
+
434
+ const hashesActuales = new Set((itemsActuales || []).map((it) => it.hash));
435
+
436
+ // 1. Resueltos: lo que estaba visto y ya no aparece → actuado.
437
+ for (const [hash, info] of Object.entries(vistos)) {
438
+ if (!hashesActuales.has(hash)) {
439
+ ensure(info.categoria).actuado += 1;
440
+ ensure(info.categoria).ultima_ts = hoyISO;
441
+ delete vistos[hash];
442
+ }
443
+ }
444
+
445
+ // 2. Presentes ahora: nuevos (mostrado++) o persistentes (veces++ → ignorado).
446
+ for (const it of itemsActuales || []) {
447
+ const c = ensure(it.categoria);
448
+ c.ultima_ts = hoyISO;
449
+ if (!vistos[it.hash]) {
450
+ vistos[it.hash] = { categoria: it.categoria, veces: 1, contadoIgnorado: false };
451
+ c.mostrado += 1;
452
+ } else {
453
+ vistos[it.hash].veces += 1;
454
+ if (vistos[it.hash].veces >= UMBRAL_IGNORADO && !vistos[it.hash].contadoIgnorado) {
455
+ c.ignorado += 1;
456
+ vistos[it.hash].contadoIgnorado = true;
457
+ }
458
+ }
459
+ }
460
+
461
+ // 3. Silenciar categorías con ratio de ignorado alto.
462
+ for (const c of Object.values(categorias)) {
463
+ c.silenciada =
464
+ c.mostrado >= MIN_MUESTRAS_SILENCIO && c.ignorado / c.mostrado >= RATIO_SILENCIO;
465
+ }
466
+
467
+ return { vistos, categorias };
468
+ }
469
+
470
+ /** Lee la telemetría persistida en `.planning/user-profile/briefing-telemetria.json`. */
471
+ function leerTelemetria(baseDir) {
472
+ const txt = leerTexto(path.join(baseDir, '.planning', 'user-profile', 'briefing-telemetria.json'));
473
+ if (!txt) return { vistos: {}, categorias: {} };
474
+ try {
475
+ const o = JSON.parse(txt);
476
+ return { vistos: o.vistos || {}, categorias: o.categorias || {} };
477
+ } catch {
478
+ return { vistos: {}, categorias: {} };
479
+ }
480
+ }
481
+
482
+ /** Conjunto de categorías actualmente silenciadas (para que armarDigest las degrade). */
483
+ function categoriasSilenciadas(telemetria) {
484
+ const set = new Set();
485
+ for (const [cat, v] of Object.entries((telemetria && telemetria.categorias) || {})) {
486
+ if (v && v.silenciada) set.add(cat);
487
+ }
488
+ return set;
489
+ }
490
+
491
+ module.exports = {
492
+ adrsVencidos,
493
+ deudaTriggerCumplido,
494
+ nudgesPendientes,
495
+ gatesEnCalibracion,
496
+ continuePendiente,
497
+ doraDegradado,
498
+ skillsStale,
499
+ recolectarTodo,
500
+ armarDigest,
501
+ leerEstadoBriefing,
502
+ actualizarTelemetria,
503
+ leerTelemetria,
504
+ categoriasSilenciadas,
505
+ PRIORIDAD,
506
+ TOPE_DIGEST,
507
+ VENTANA_CALIBRACION_MS,
508
+ UMBRAL_IGNORADO,
509
+ RATIO_SILENCIO,
510
+ MIN_MUESTRAS_SILENCIO,
511
+ _hashItem: hashItem,
512
+ };