@saulwade/swl-ses 2.6.1 → 2.8.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 (268) hide show
  1. package/CLAUDE.md +14 -2
  2. package/README.md +65 -18
  3. package/agentes/_intent-spec.md +73 -73
  4. package/agentes/_propose-step.md +90 -90
  5. package/bin/swl-ses.js +10 -0
  6. package/comandos/swl/brainstorm.md +1 -0
  7. package/comandos/swl/briefing.md +119 -119
  8. package/comandos/swl/contribuir.md +233 -233
  9. package/comandos/swl/deuda-codigo.md +97 -97
  10. package/comandos/swl/mcp-status.md +1 -0
  11. package/gateway/lib/event-channel.js +191 -191
  12. package/habilidades/agent-deep-links/SKILL.md +148 -148
  13. package/habilidades/backend-async-postgres-testing/SKILL.md +216 -216
  14. package/habilidades/backend-error-design/SKILL.md +221 -221
  15. package/habilidades/backend-production-resilience/SKILL.md +288 -288
  16. package/habilidades/calidad-anti-patrones-universales/SKILL.md +105 -1
  17. package/habilidades/calidad-contract-testing/SKILL.md +165 -165
  18. package/habilidades/calidad-mutation-testing/SKILL.md +25 -1
  19. package/habilidades/checklist-seguridad/recursos/stride-cobertura.md +60 -60
  20. package/habilidades/ci-cd-pipelines/SKILL.md +5 -1
  21. package/habilidades/css-moderno/SKILL.md +7 -1
  22. package/habilidades/diagrama-arquitectura/assets/template.html +276 -276
  23. package/habilidades/doubt-driven-review/recursos/EXAMPLES.md +130 -130
  24. package/habilidades/estructura-proyecto-claude/recursos/mcp-json-template.json +57 -57
  25. package/habilidades/extractor-de-aprendizajes/SKILL.md +5 -1
  26. package/habilidades/feynman-auditor-swl/recursos/preguntas-language-agnostic.md +108 -108
  27. package/habilidades/harness-claude-code/SKILL.md +3 -2
  28. package/habilidades/meta-skills-estandar/recursos/convencion-examples.md +93 -93
  29. package/habilidades/patrones-python/recursos/patrones-avanzados.md +469 -469
  30. package/habilidades/perfil-usuario/SKILL.md +200 -200
  31. package/habilidades/prevencion-sobreingenieria/recursos/EXAMPLES.md +580 -580
  32. package/habilidades/prevencion-sobreingenieria/recursos/soluciones-nativas.md +166 -166
  33. package/habilidades/prevencion-sobreingenieria/recursos/variables-residuales-post-refactor.md +85 -85
  34. package/habilidades/proceso-ddia-streaming/SKILL.md +231 -231
  35. package/habilidades/proceso-discovery-machote/SKILL.md +157 -157
  36. package/habilidades/proceso-dynamic-workflows/SKILL.md +60 -0
  37. package/habilidades/proceso-dynamic-workflows/recursos/template-adversarial-verify.js +65 -65
  38. package/habilidades/proceso-dynamic-workflows/recursos/template-triage.js +65 -65
  39. package/habilidades/proceso-intent-engineering/SKILL.md +269 -269
  40. package/habilidades/proceso-modular-split/SKILL.md +256 -256
  41. package/habilidades/state-inconsistency-auditor-swl/recursos/coupled-state-patterns.md +147 -147
  42. package/habilidades/swl-claudemd/recursos/contrato-aprender.md +83 -83
  43. package/habilidades/swl-claudemd/recursos/duplicacion-reglas-globales.md +85 -85
  44. package/habilidades/swl-claudemd/recursos/plantillas-init.md +94 -94
  45. package/habilidades/tdd-workflow/recursos/gherkin-bdd.md +111 -111
  46. package/hooks/calidad-pre-commit.js +159 -10
  47. package/hooks/ciclo-evolucion-subagente.js +26 -26
  48. package/hooks/ciclo-evolucion.js +26 -26
  49. package/hooks/contexto-subagente.js +68 -68
  50. package/hooks/lib/auto-consolidator.js +335 -335
  51. package/hooks/lib/ciclo-evolucion.js +47 -47
  52. package/hooks/lib/deep-links.js +185 -185
  53. package/hooks/lib/error-classifier.js +308 -308
  54. package/hooks/lib/notificacion-formato.js +45 -11
  55. package/hooks/lib/provenance-tracker.js +191 -191
  56. package/hooks/lib/raiz-proyecto.js +35 -4
  57. package/hooks/lib/resource-quota.js +122 -122
  58. package/hooks/lib/retry-jitter.js +165 -165
  59. package/hooks/lib/security-net.js +201 -201
  60. package/hooks/lib/skill-auditor.js +588 -588
  61. package/hooks/lib/sync-status.js +228 -228
  62. package/hooks/lib/taint-tracker.js +107 -107
  63. package/hooks/lib/text-similarity.js +241 -241
  64. package/hooks/lib/toon-compressor.js +245 -245
  65. package/hooks/notificacion-telegram.js +5 -11
  66. package/hooks/session-briefing.js +12 -4
  67. package/instintos/autonomia.yaml +27 -27
  68. package/instintos/prompt-appendices.yaml +57 -57
  69. package/llms.txt +1 -1
  70. package/manifiestos/agent-output-schemas.json +57 -57
  71. package/manifiestos/canonical-hashes.json +662 -0
  72. package/manifiestos/harness-ir.json +47536 -0
  73. package/manifiestos/hooks-config.json +469 -469
  74. package/manifiestos/invariantes-criticos.json +30 -30
  75. package/manifiestos/policy-bundle.json +2065 -0
  76. package/manifiestos/policy-corpus-w2.json +3926 -0
  77. package/manifiestos/runtime-adapters-core3.json +208 -0
  78. package/manifiestos/runtime-conformance.json +139 -0
  79. package/manifiestos/skills-lock.json +43 -43
  80. package/package.json +2 -2
  81. package/plantillas/auditor-veto-template.md +105 -105
  82. package/plantillas/github-workflows/release-please.yml +44 -44
  83. package/plantillas/github-workflows/swl-ci.yml +107 -107
  84. package/plantillas/github-workflows/swl-security.yml +51 -51
  85. package/plugin.json +2 -2
  86. package/reglas/accesibilidad.md +10 -10
  87. package/reglas/auditorias-documentales-estructurales.md +7 -7
  88. package/reglas/cloud-infra.md +8 -8
  89. package/reglas/consultar-vault-primero.md +195 -195
  90. package/reglas/git-workflow.md +1 -0
  91. package/reglas/hooks.md +6 -6
  92. package/reglas/intent-engineering.md +218 -218
  93. package/reglas/markitdown.md +8 -8
  94. package/reglas/monitor-ci.md +12 -0
  95. package/reglas/patrones.md +6 -6
  96. package/reglas/testing.md +7 -7
  97. package/reglas/tests-cleanup.md +224 -224
  98. package/schemas/agent-message.schema.json +73 -73
  99. package/schemas/agent-output-implementacion.schema.json +114 -114
  100. package/schemas/agent-output-planificacion.schema.json +150 -150
  101. package/schemas/agent-output-review.schema.json +98 -98
  102. package/schemas/diary-entry.schema.json +112 -112
  103. package/schemas/gate-state.schema.json +76 -0
  104. package/schemas/harness-ir.schema.json +369 -0
  105. package/schemas/hook-profiles.schema.json +54 -54
  106. package/schemas/hooks-config.schema.json +89 -89
  107. package/schemas/legacy-gates.schema.json +45 -0
  108. package/schemas/modulos.schema.json +38 -38
  109. package/schemas/perfiles.schema.json +36 -36
  110. package/schemas/plugin.schema.json +77 -77
  111. package/schemas/policy-bundle.schema.json +140 -0
  112. package/schemas/policy-enforcement.schema.json +117 -0
  113. package/schemas/policy-operation.schema.json +261 -0
  114. package/schemas/runtime-adapter.schema.json +176 -0
  115. package/schemas/runtime-build-attestation.schema.json +100 -0
  116. package/schemas/runtime-conformance.schema.json +239 -0
  117. package/schemas/runtime-diagnostic.schema.json +395 -0
  118. package/schemas/skill-evals.schema.json +119 -119
  119. package/schemas/skill-frontmatter.schema.json +245 -245
  120. package/schemas/w4-certification-request.schema.json +72 -0
  121. package/schemas/w4-certification-verdict.schema.json +224 -0
  122. package/schemas/w4-corpus.schema.json +172 -0
  123. package/schemas/w4-mutation-report.schema.json +116 -0
  124. package/schemas/w4-replay-result.schema.json +164 -0
  125. package/schemas/w4-scoring-report.schema.json +89 -0
  126. package/scripts/audit-tools/audit-history.js +330 -330
  127. package/scripts/audit-tools/bundle-tracker.js +290 -290
  128. package/scripts/audit-tools/canary-monitor.js +352 -352
  129. package/scripts/audit-tools/code-profiler.js +605 -605
  130. package/scripts/audit-tools/dep-doctor.js +320 -320
  131. package/scripts/audit-tools/env-validator.js +206 -206
  132. package/scripts/audit-tools/lib/fs-walk.js +48 -48
  133. package/scripts/audit-tools/lib/output.js +23 -23
  134. package/scripts/audit-tools/migration-checker.js +392 -392
  135. package/scripts/audit-tools/pentest-scanner.js +1436 -1436
  136. package/scripts/bootstrap-instintos.js +3 -0
  137. package/scripts/cli/aprobar-plan.js +73 -73
  138. package/scripts/cli/briefing.js +23 -23
  139. package/scripts/cli/ciclo-evolucion.js +26 -26
  140. package/scripts/cli/derivar-feature-list.js +25 -25
  141. package/scripts/cli/detectar-host.js +27 -27
  142. package/scripts/cli/diary-entry.js +69 -69
  143. package/scripts/cli/execution-state.js +18 -18
  144. package/scripts/cli/gateway-notify.js +41 -41
  145. package/scripts/cli/liberar-fase.js +42 -42
  146. package/scripts/cli/mark-evolved.js +56 -56
  147. package/scripts/cli/metricas-dora.js +26 -26
  148. package/scripts/cli/near-duplicate.js +55 -55
  149. package/scripts/cli/notificaciones.js +123 -123
  150. package/scripts/cli/propose-step.js +29 -29
  151. package/scripts/cli/schedule-parse.js +19 -19
  152. package/scripts/cli/sugerir-modelo.js +20 -20
  153. package/scripts/cli/verificar-plan.js +36 -36
  154. package/scripts/cli/verificar-trazabilidad.js +35 -35
  155. package/scripts/comandos/install-asistido.js +8 -7
  156. package/scripts/configurar-branch-protection.js +418 -418
  157. package/scripts/detectar-aprendizajes-duplicados.js +151 -151
  158. package/scripts/doctor.js +61 -36
  159. package/scripts/generar-checklists-consolidados.js +273 -273
  160. package/scripts/generar-claims-runtime.js +1342 -0
  161. package/scripts/generar-harness-ir.js +257 -0
  162. package/scripts/generar-inventario.js +52 -54
  163. package/scripts/generar-policy-bundle.js +202 -0
  164. package/scripts/instalador.js +26 -7
  165. package/scripts/lib/approval-receipts.js +190 -0
  166. package/scripts/lib/artefactos-python.js +43 -43
  167. package/scripts/lib/benchmark-metrics.js +160 -160
  168. package/scripts/lib/budget-enforcer.js +252 -252
  169. package/scripts/lib/certificacion-loop-state.js +421 -0
  170. package/scripts/lib/ci-reader.js +193 -193
  171. package/scripts/lib/ciclo-autonomo/yaml-instintos.js +56 -0
  172. package/scripts/lib/clasificar-directorio.js +92 -0
  173. package/scripts/lib/contadores-inventario.js +217 -217
  174. package/scripts/lib/detectar-host-swl.js +175 -175
  175. package/scripts/lib/detectar-runtime.js +29 -20
  176. package/scripts/lib/detectar-stack-detallado.js +307 -307
  177. package/scripts/lib/detector-autoduplicacion-intra-archivo.js +234 -234
  178. package/scripts/lib/detector-reglas-duplicadas.js +220 -220
  179. package/scripts/lib/eval-metrics-store.js +218 -218
  180. package/scripts/lib/eval-quality.js +171 -171
  181. package/scripts/lib/eval-schemas.js +144 -144
  182. package/scripts/lib/eval-self-correct.js +106 -106
  183. package/scripts/lib/eval-validator.js +185 -185
  184. package/scripts/lib/evidence-verifier.js +192 -0
  185. package/scripts/lib/evidencia-release.js +322 -322
  186. package/scripts/lib/frontmatter-canonico.js +509 -0
  187. package/scripts/lib/gate-engine.js +871 -0
  188. package/scripts/lib/gate-hooks-requires.js +249 -249
  189. package/scripts/lib/gate-licencias.js +212 -212
  190. package/scripts/lib/git-config-preflight.js +48 -0
  191. package/scripts/lib/git-metricas.js +257 -257
  192. package/scripts/lib/harness-ir.js +778 -0
  193. package/scripts/lib/harness-source-snapshot.js +309 -0
  194. package/scripts/lib/integrity-ledger.js +1147 -0
  195. package/scripts/lib/jaccard-similarity.js +98 -98
  196. package/scripts/lib/legacy-gate-migration.js +324 -0
  197. package/scripts/lib/limpiar-basura-global.js +45 -2
  198. package/scripts/lib/longmemeval-runner.js +125 -125
  199. package/scripts/lib/metricas-dora.js +204 -204
  200. package/scripts/lib/notificaciones-telegram.js +1 -0
  201. package/scripts/lib/npm-version.js +1 -0
  202. package/scripts/lib/paquetes-conocidos.js +50 -50
  203. package/scripts/lib/plan-lock.js +61 -13
  204. package/scripts/lib/policy-broker.js +338 -0
  205. package/scripts/lib/policy-bundle.js +342 -0
  206. package/scripts/lib/policy-context-provider.js +310 -0
  207. package/scripts/lib/policy-contract.js +479 -0
  208. package/scripts/lib/policy-verifier-utils.js +65 -0
  209. package/scripts/lib/pr-analyzer.js +399 -399
  210. package/scripts/lib/principal-verifier.js +178 -0
  211. package/scripts/lib/prompt-builder.js +264 -264
  212. package/scripts/lib/resolver-plan-fase.js +37 -37
  213. package/scripts/lib/rrf-fusion.js +175 -175
  214. package/scripts/lib/runtime-adapter-contract.js +267 -0
  215. package/scripts/lib/runtime-artifact-verifier.js +426 -0
  216. package/scripts/lib/runtime-build-attestation.js +127 -0
  217. package/scripts/lib/runtime-bundle-installer.js +586 -0
  218. package/scripts/lib/runtime-compiler.js +327 -0
  219. package/scripts/lib/runtime-conformance.js +202 -0
  220. package/scripts/lib/runtime-doctor-core3.js +567 -0
  221. package/scripts/lib/runtime-doctor-input.js +59 -0
  222. package/scripts/lib/runtime-operation-adapter.js +267 -0
  223. package/scripts/lib/schema-version.js +164 -164
  224. package/scripts/lib/semantic-search.js +252 -252
  225. package/scripts/lib/signed-envelope.js +545 -0
  226. package/scripts/lib/single-use-store.js +359 -0
  227. package/scripts/lib/skills-externas.js +31 -0
  228. package/scripts/lib/transformadores/codex.js +15 -8
  229. package/scripts/lib/transformadores/gemini.js +79 -5
  230. package/scripts/lib/w4-attestation-adapter.js +158 -0
  231. package/scripts/lib/w4-canario.js +337 -0
  232. package/scripts/lib/w4-claims.js +182 -0
  233. package/scripts/lib/w4-corpus-generador.js +542 -0
  234. package/scripts/lib/w4-gate-c5.js +115 -0
  235. package/scripts/lib/w4-harness-bajo-prueba.js +155 -0
  236. package/scripts/lib/w4-matriz-combos.js +55 -0
  237. package/scripts/lib/w4-motor-mutacion.js +1348 -0
  238. package/scripts/lib/w4-motor-replay.js +735 -0
  239. package/scripts/lib/w4-pin-origen.js +54 -0
  240. package/scripts/lib/w4-publicar-request.js +132 -0
  241. package/scripts/lib/w4-revocacion.js +62 -0
  242. package/scripts/lib/w4-runtimes-core3.js +38 -0
  243. package/scripts/lib/w4-scorer-certificacion.js +692 -0
  244. package/scripts/lib/w4-superficie-candidato.js +49 -0
  245. package/scripts/lib/w4-veredicto.js +452 -0
  246. package/scripts/lib/w4-verificar-veredicto.js +302 -0
  247. package/scripts/limpiar-artefactos-python.js +131 -131
  248. package/scripts/migrar-csv-a-array.js +168 -168
  249. package/scripts/migrar-fase-dominio.js +200 -200
  250. package/scripts/migrar-gates-legacy.js +108 -0
  251. package/scripts/publicar-certification-request.js +115 -0
  252. package/scripts/runtime-doctor.js +107 -0
  253. package/scripts/tui/componentes/selector-multi.js +189 -189
  254. package/scripts/tui/componentes/selector-unico.js +158 -158
  255. package/scripts/tui/ejecutores.js +375 -375
  256. package/scripts/tui/lib/colores.js +129 -129
  257. package/scripts/tui/lib/render.js +264 -264
  258. package/scripts/tui/lib/teclas.js +113 -113
  259. package/scripts/tui/pantallas/install-wizard.js +12 -7
  260. package/scripts/tui/pantallas/menu-principal.js +52 -52
  261. package/scripts/tui/pantallas/progreso.js +274 -274
  262. package/scripts/tui/pantallas/resumen.js +132 -132
  263. package/scripts/validar-userland-vacio.js +110 -110
  264. package/scripts/verificar-aislamiento-swl-eval.js +87 -0
  265. package/scripts/verificar-empaquetado-downstream.js +375 -0
  266. package/scripts/verificar-loop-constructor.js +215 -0
  267. package/scripts/verificar-trazabilidad.js +13 -6
  268. package/scripts/verificar-veredicto-real.js +84 -0
@@ -0,0 +1,1342 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * Proyecta el bootstrap canónico de claims runtime sobre superficies públicas.
6
+ * La migración legacy es explícita y transaccional; el modo estable nunca
7
+ * inserta marcadores faltantes ni busca secciones por aproximación.
8
+ */
9
+
10
+ const crypto = require('node:crypto');
11
+ const childProcess = require('node:child_process');
12
+ const fs = require('node:fs');
13
+ const path = require('node:path');
14
+
15
+ const { atomicWriteSync } = require('../hooks/lib/atomic-write');
16
+ const {
17
+ cargarConformance,
18
+ derivarSupportLabel,
19
+ validarConformance,
20
+ } = require('./lib/runtime-conformance');
21
+
22
+ const RAIZ = path.resolve(__dirname, '..');
23
+ const MARCA_INICIO = '<!-- BEGIN:RUNTIME-CONFORMANCE (generado por scripts/generar-claims-runtime.js; no editar) -->';
24
+ const MARCA_FIN = '<!-- END:RUNTIME-CONFORMANCE -->';
25
+ const EXTENSIONES_ESCANEADAS = new Set(['.md', '.json', '.js']);
26
+ const PATRON_RUNTIME = new RegExp([
27
+ String.raw`(?<![.\p{L}\p{N}_-])`,
28
+ String.raw`(?:claude(?:[- ]code)?|openclaude|open[- ]?code|gemini(?:[- ]cli)?|`,
29
+ String.raw`cursor|codex(?:[- ]cli)?|github[- ]copilot|copilot)`,
30
+ String.raw`(?![.\p{L}\p{N}_-])`,
31
+ ].join(''), 'iu');
32
+ const PATRON_ESTADO = new RegExp([
33
+ String.raw`(?<![\p{L}\p{N}_])`,
34
+ String.raw`(?:soporte\s+(?:completo|parcial)|completo|parcial|experimental|`,
35
+ String.raw`no[_ -]?soportado)(?![\p{L}\p{N}_])`,
36
+ ].join(''), 'iu');
37
+ const PATRON_CONTEXTO_CLAIM = new RegExp([
38
+ String.raw`(?:soporte|compatibilidad|conformidad|certificaci[oó]n|`,
39
+ String.raw`support(?:label)?|certificationstatus|(?:estado|status)\s*[:=])`,
40
+ ].join(''), 'iu');
41
+ const PREFIJOS_EXCLUIDOS = Object.freeze([
42
+ '.planning/adrs/',
43
+ '.planning/audit/',
44
+ '.planning/archive/',
45
+ 'releases/',
46
+ 'temp/',
47
+ 'respositorios-git/',
48
+ ]);
49
+ const DESCRIPCION = [
50
+ 'Sistema de ingeniería de software auto-evolutivo para proyectos downstream, políglota en',
51
+ '11 lenguajes, con 61 agentes, 181 habilidades, 48 comandos, 77 reglas, 49 hooks, instalación',
52
+ 'multi-target, MCP, gateway y auditoría Nemesis. Siete targets runtime con compatibilidad',
53
+ 'experimental y certificación pendiente de evidencia externa.',
54
+ ].join(' ');
55
+ const CLAIM_README_LEGACY = [
56
+ 'Soporta 7 runtimes de IA: Claude Code, OpenClaude, OpenCode y Gemini CLI (soporte completo);',
57
+ 'Cursor, Codex CLI y GitHub Copilot (soporte parcial — reglas + MCP server o consolidación en',
58
+ 'archivo de instrucciones según el runtime). Incluye sistema de transformadores que adapta el',
59
+ 'formato canónico SWL al formato nativo de cada runtime, **multi-target install**',
60
+ '(`--target=claude,cursor,codex` en una sola invocación), y **`swl-mcp-server` v1.0.0** con auth',
61
+ 'opt-in para que Cursor, Codex y otros clientes MCP consulten la memoria SWL (aprendizajes,',
62
+ 'instintos, sesiones).',
63
+ ].join(' ');
64
+ const CLAIM_README_DOWNSTREAM = [
65
+ 'SWL reconoce siete targets de instalación de IA. La disponibilidad de un transformador no',
66
+ 'certifica conformidad con el harness; los estados públicos se derivan del manifiesto canónico.',
67
+ 'Incluye instalación multi-target y `swl-mcp-server` con autenticación opt-in para clientes MCP.',
68
+ ].join(' ');
69
+ const INTRO_AGENTS_DOWNSTREAM = [
70
+ 'Sistema de ingeniería de software auto-evolutivo para proyectos downstream que cubre el SDLC',
71
+ 'completo.',
72
+ ].join(' ');
73
+ const REGISTRO_SUPERFICIES = Object.freeze({
74
+ markdown: [
75
+ {
76
+ path: 'README.md',
77
+ strategy: 'markdown-block',
78
+ migration: {
79
+ startAnchor: '### Targets soportados',
80
+ endAnchor: '### Ejemplos',
81
+ sha256: '3e15271b46c9b82d72a1555526a3d0935ff39264c05b5bafcfb2d2e9aede946b',
82
+ neutralizations: [{
83
+ text: CLAIM_README_LEGACY,
84
+ sha256: 'd6829938f987fdc340a2ca86074e1cdbae1dcc822e2fef9c9003591204a8e8f5',
85
+ replacement: CLAIM_README_DOWNSTREAM,
86
+ }],
87
+ },
88
+ },
89
+ {
90
+ path: 'COMANDOS.md',
91
+ strategy: 'markdown-block',
92
+ migration: {
93
+ startAnchor: '## Sistema de transformadores (multi-runtime)',
94
+ endAnchor: '## Comandos desde Claude Code (`/swl:*`)',
95
+ sha256: '41f95080021404ff7954a7f6a768dd1c0f720019f76f8d728dd38fa0b9b156d5',
96
+ neutralizations: [],
97
+ },
98
+ },
99
+ {
100
+ path: 'MANUAL_USO.md',
101
+ strategy: 'markdown-block',
102
+ migration: {
103
+ startAnchor: '### Runtimes soportados (`--target`)',
104
+ endAnchor: '#### Multi-target install (v1.5.0+) — un solo comando para varios editores',
105
+ sha256: '45cde0f47be17cd24df4265c1ae30eaecd150f2dd2b68d483e582ac3547b98c7',
106
+ neutralizations: [],
107
+ },
108
+ },
109
+ {
110
+ path: 'INSTALACION.md',
111
+ strategy: 'markdown-block',
112
+ migration: {
113
+ startAnchor: '### 3.5 Targets soportados y transformaciones',
114
+ endAnchor: '#### Codex CLI — detalle de instalación',
115
+ sha256: 'fa8ea3ce43d1037d4e8110b9b2c671d9892ee411c17c701b478e55a62839aac0',
116
+ neutralizations: [],
117
+ },
118
+ },
119
+ {
120
+ path: 'AGENTS.md',
121
+ strategy: 'markdown-block',
122
+ migration: {
123
+ startAnchor: '7 runtimes:',
124
+ endAnchor: '**Idioma**',
125
+ sha256: 'a6f55cb3b999f163cf366933520018855e4e0b4c44b8d5ca391146c584f0c1ee',
126
+ neutralizations: [{
127
+ text: 'Sistema de ingeniería de software auto-evolutivo multi-runtime polyglot que cubre el SDLC completo.',
128
+ sha256: 'b942a36a79101a5a10928d5398155217357eca33f7bfd9fd5ae1c43c039326f9',
129
+ replacement: INTRO_AGENTS_DOWNSTREAM,
130
+ }],
131
+ },
132
+ },
133
+ ],
134
+ json: [
135
+ { path: 'package.json', strategy: 'json-description', jsonPath: ['description'] },
136
+ { path: 'plugin.json', strategy: 'json-description', jsonPath: ['description'] },
137
+ ],
138
+ managed: [
139
+ { path: 'INVENTARIO.md', strategy: 'generar-inventario' },
140
+ ],
141
+ operational: [
142
+ { path: 'scripts/lib/detectar-runtime.js', strategy: 'derived-label' },
143
+ { path: 'scripts/comandos/install-asistido.js', strategy: 'derived-label' },
144
+ { path: 'scripts/tui/pantallas/install-wizard.js', strategy: 'derived-label' },
145
+ { path: 'scripts/instalador.js', strategy: 'derived-label' },
146
+ ],
147
+ });
148
+
149
+ class ErrorDrift extends Error {}
150
+
151
+ function sha256(contenido) {
152
+ return crypto.createHash('sha256').update(contenido).digest('hex');
153
+ }
154
+
155
+ function contar(contenido, texto) {
156
+ return contenido.split(texto).length - 1;
157
+ }
158
+
159
+ function detectarEol(contenido) {
160
+ return contenido.includes('\r\n') ? '\r\n' : '\n';
161
+ }
162
+
163
+ function usarEol(contenido, eol) {
164
+ return contenido.replace(/\r?\n/g, eol);
165
+ }
166
+
167
+ function cargarContrato(opciones) {
168
+ if (opciones.conformance) return validarConformance(opciones.conformance);
169
+ return cargarConformance({ manifestPath: opciones.manifestPath });
170
+ }
171
+
172
+ function renderBloque(opciones = {}) {
173
+ const conformance = cargarContrato(opciones);
174
+ const lineas = [
175
+ MARCA_INICIO,
176
+ '',
177
+ '### Conformidad de runtimes',
178
+ '',
179
+ '> Estado bootstrap: disponibilidad de instalación no equivale a certificación del harness.',
180
+ '',
181
+ '| Runtime | Target | Soporte público | Certificación |',
182
+ '|---|---|---|---|',
183
+ ];
184
+ for (const runtime of conformance.runtimes) {
185
+ lineas.push(`| ${runtime.id} | ${runtime.installerTarget} | ${derivarSupportLabel(runtime)} | ${runtime.certificationStatus} |`);
186
+ }
187
+ lineas.push('', MARCA_FIN);
188
+ return lineas.join('\n');
189
+ }
190
+
191
+ function resolverRuta(root, rutaRelativa) {
192
+ const rootReal = fs.realpathSync(root);
193
+ const absoluta = path.resolve(root, rutaRelativa);
194
+ const relativa = path.relative(root, absoluta);
195
+ if (relativa.startsWith('..') || path.isAbsolute(relativa)) {
196
+ throw new TypeError(`superficie fuera de root: ${rutaRelativa}`);
197
+ }
198
+ const padreReal = fs.realpathSync(path.dirname(absoluta));
199
+ validarConfinamiento(rootReal, padreReal, rutaRelativa);
200
+ if (fs.existsSync(absoluta)) {
201
+ validarConfinamiento(rootReal, fs.realpathSync(absoluta), rutaRelativa);
202
+ }
203
+ return absoluta;
204
+ }
205
+
206
+ function crearResolvedorConfinado(root) {
207
+ const rootReal = fs.realpathSync(root);
208
+ const padresReales = new Map();
209
+ return (rutaRelativa) => {
210
+ const absoluta = path.resolve(root, rutaRelativa);
211
+ const relativa = path.relative(root, absoluta);
212
+ if (relativa.startsWith('..') || path.isAbsolute(relativa)) {
213
+ throw new TypeError(`superficie fuera de root: ${rutaRelativa}`);
214
+ }
215
+ const padre = path.dirname(absoluta);
216
+ const padreReal = padresReales.get(padre) || fs.realpathSync(padre);
217
+ padresReales.set(padre, padreReal);
218
+ validarConfinamiento(rootReal, padreReal, rutaRelativa);
219
+ if (fs.lstatSync(absoluta).isSymbolicLink()) {
220
+ validarConfinamiento(rootReal, fs.realpathSync(absoluta), rutaRelativa);
221
+ }
222
+ return absoluta;
223
+ };
224
+ }
225
+
226
+ function validarConfinamiento(rootReal, rutaReal, rutaRelativa) {
227
+ const relativa = path.relative(rootReal, rutaReal);
228
+ if (relativa.startsWith('..') || path.isAbsolute(relativa)) {
229
+ throw new TypeError(`superficie resuelve fuera de root: ${rutaRelativa}`);
230
+ }
231
+ }
232
+
233
+ function reemplazarBloque(contenido, bloque) {
234
+ if (contar(contenido, MARCA_INICIO) !== 1 || contar(contenido, MARCA_FIN) !== 1) {
235
+ throw new ErrorDrift('se requiere exactamente un par de marcadores runtime');
236
+ }
237
+ const inicio = contenido.indexOf(MARCA_INICIO);
238
+ const fin = contenido.indexOf(MARCA_FIN, inicio);
239
+ if (fin < inicio) throw new ErrorDrift('orden de marcadores runtime inválido');
240
+ const eol = detectarEol(contenido);
241
+ const despues = fin + MARCA_FIN.length;
242
+ return contenido.slice(0, inicio) + usarEol(bloque, eol) + contenido.slice(despues);
243
+ }
244
+
245
+ function validarAnclas(contenido, migracion) {
246
+ const inicios = contar(contenido, migracion.startAnchor);
247
+ const finales = contar(contenido, migracion.endAnchor);
248
+ if (inicios !== 1 || finales !== 1) throw new TypeError('anclas legacy ausentes o ambiguas');
249
+ const inicio = contenido.indexOf(migracion.startAnchor);
250
+ const fin = contenido.indexOf(migracion.endAnchor, inicio + migracion.startAnchor.length);
251
+ if (fin < inicio) throw new TypeError('orden de anclas legacy inválido');
252
+ return { inicio, fin };
253
+ }
254
+
255
+ function neutralizarClaims(contenido, neutralizaciones) {
256
+ let salida = contenido;
257
+ for (const regla of neutralizaciones || []) {
258
+ if (sha256(regla.text) !== regla.sha256 || contar(salida, regla.text) !== 1) {
259
+ throw new TypeError('claim introductorio no coincide con su hash exacto');
260
+ }
261
+ salida = salida.replace(regla.text, regla.replacement);
262
+ }
263
+ return salida;
264
+ }
265
+
266
+ function validarNeutralizacionesMigradas(contenido, neutralizaciones) {
267
+ for (const regla of neutralizaciones || []) {
268
+ const configValida = sha256(regla.text) === regla.sha256;
269
+ const estadoValido = contar(contenido, regla.text) === 0
270
+ && contar(contenido, regla.replacement) === 1;
271
+ if (!configValida || !estadoValido) {
272
+ throw new TypeError('claim introductorio pre-marcado no está neutralizado');
273
+ }
274
+ }
275
+ }
276
+
277
+ function validarEstadoMigrado(contenido, superficie, bloque) {
278
+ const inicio = contenido.indexOf(MARCA_INICIO);
279
+ const fin = contenido.indexOf(MARCA_FIN, inicio) + MARCA_FIN.length;
280
+ const bloqueActual = contenido.slice(inicio, fin).replace(/\r\n/g, '\n');
281
+ if (bloqueActual !== bloque) {
282
+ throw new TypeError(`bloque pre-marcado no es canónico: ${superficie.path}`);
283
+ }
284
+ const migracion = superficie.migration;
285
+ if (contar(contenido, migracion.startAnchor) !== 0
286
+ || contar(contenido, migracion.endAnchor) !== 1) {
287
+ throw new TypeError(`estado posmigración inválido: ${superficie.path}`);
288
+ }
289
+ validarNeutralizacionesMigradas(contenido, migracion.neutralizations);
290
+ return contenido;
291
+ }
292
+
293
+ function migrarMarkdown(contenido, superficie, bloque) {
294
+ const tieneInicio = contar(contenido, MARCA_INICIO);
295
+ const tieneFin = contar(contenido, MARCA_FIN);
296
+ if (tieneInicio === 1 && tieneFin === 1) {
297
+ if (!superficie.migration) throw new TypeError(`migración no registrada: ${superficie.path}`);
298
+ return validarEstadoMigrado(contenido, superficie, bloque);
299
+ }
300
+ if (tieneInicio !== 0 || tieneFin !== 0) throw new TypeError('migración encontró marcadores parciales');
301
+ if (!superficie.migration) throw new TypeError(`migración no registrada: ${superficie.path}`);
302
+ const { inicio, fin } = validarAnclas(contenido, superficie.migration);
303
+ const region = contenido.slice(inicio, fin);
304
+ if (sha256(region) !== superficie.migration.sha256) {
305
+ throw new TypeError(`hash legacy distinto: ${superficie.path}`);
306
+ }
307
+ const eol = detectarEol(contenido);
308
+ const reemplazado = contenido.slice(0, inicio) + usarEol(`${bloque}\n\n`, eol) + contenido.slice(fin);
309
+ return neutralizarClaims(reemplazado, superficie.migration.neutralizations);
310
+ }
311
+
312
+ function actualizarJson(contenido, superficie) {
313
+ const documento = JSON.parse(contenido);
314
+ if (JSON.stringify(superficie.jsonPath) !== JSON.stringify(['description'])) {
315
+ throw new TypeError(`ruta JSON no permitida: ${superficie.path}`);
316
+ }
317
+ if (!Object.hasOwn(documento, 'description')) {
318
+ throw new ErrorDrift(`description ausente: ${superficie.path}`);
319
+ }
320
+ documento.description = DESCRIPCION;
321
+ const eol = detectarEol(contenido);
322
+ return usarEol(`${JSON.stringify(documento, null, 2)}\n`, eol);
323
+ }
324
+
325
+ function prepararCambios(opciones, modo) {
326
+ const root = path.resolve(opciones.root || RAIZ);
327
+ const registry = opciones.registry || REGISTRO_SUPERFICIES;
328
+ const bloque = renderBloque(opciones);
329
+ const cambios = [];
330
+ for (const superficie of registry.markdown || []) {
331
+ const ruta = resolverRuta(root, superficie.path);
332
+ const original = fs.readFileSync(ruta, 'utf8');
333
+ const salida = modo === 'migrate'
334
+ ? migrarMarkdown(original, superficie, bloque)
335
+ : reemplazarBloque(original, bloque);
336
+ cambios.push({ ruta, original, salida });
337
+ }
338
+ for (const superficie of registry.managed || []) {
339
+ const ruta = resolverRuta(root, superficie.path);
340
+ const original = fs.readFileSync(ruta, 'utf8');
341
+ cambios.push({ ruta, original, salida: reemplazarBloque(original, bloque) });
342
+ }
343
+ for (const superficie of registry.json || []) {
344
+ const ruta = resolverRuta(root, superficie.path);
345
+ const original = fs.readFileSync(ruta, 'utf8');
346
+ cambios.push({ ruta, original, salida: actualizarJson(original, superficie) });
347
+ }
348
+ return cambios;
349
+ }
350
+
351
+ function intentarPreparar(opciones, modo) {
352
+ try {
353
+ return { ok: true, cambios: prepararCambios(opciones, modo), errors: [] };
354
+ } catch (error) {
355
+ const code = error instanceof ErrorDrift ? 2 : 1;
356
+ return { ok: false, cambios: [], errors: [error.message], code };
357
+ }
358
+ }
359
+
360
+ function revertirCambios(aplicados) {
361
+ const errores = [];
362
+ for (const cambio of [...aplicados].reverse()) {
363
+ try {
364
+ const actual = fs.readFileSync(cambio.ruta, 'utf8');
365
+ if (actual === cambio.salida) atomicWriteSync(cambio.ruta, cambio.original, 'utf8');
366
+ else errores.push(`rollback CAS rechazado: ${cambio.ruta}`);
367
+ } catch (error) {
368
+ errores.push(`rollback falló: ${cambio.ruta}: ${error.message}`);
369
+ }
370
+ }
371
+ return errores;
372
+ }
373
+
374
+ function adquirirLock(root) {
375
+ const ruta = path.join(fs.realpathSync(root), '.swl-runtime-claims.lock');
376
+ let descriptor;
377
+ try {
378
+ descriptor = fs.openSync(ruta, 'wx', 0o600);
379
+ fs.writeFileSync(descriptor, `${JSON.stringify({ pid: process.pid })}\n`, 'utf8');
380
+ } catch (error) {
381
+ if (descriptor !== undefined) {
382
+ try { fs.closeSync(descriptor); } catch {}
383
+ try { fs.unlinkSync(ruta); } catch {}
384
+ }
385
+ throw new TypeError(`no se pudo adquirir lock transaccional: ${error.message}`);
386
+ }
387
+ return () => {
388
+ fs.closeSync(descriptor);
389
+ fs.unlinkSync(ruta);
390
+ };
391
+ }
392
+
393
+ function aplicarCambios(preparacion, opciones = {}) {
394
+ if (!preparacion.ok) return { ok: false, changed: 0, errors: preparacion.errors };
395
+ const distintos = preparacion.cambios.filter(({ original, salida }) => original !== salida);
396
+ if (distintos.length === 0) return { ok: true, changed: 0, errors: [] };
397
+ const writeFile = opciones.writeFile || atomicWriteSync;
398
+ const aplicados = [];
399
+ let liberarLock;
400
+ let resultado;
401
+ try {
402
+ liberarLock = adquirirLock(path.resolve(opciones.root || RAIZ));
403
+ for (const cambio of distintos) {
404
+ if (fs.readFileSync(cambio.ruta, 'utf8') !== cambio.original) {
405
+ throw new TypeError(`CAS rechazado por edición concurrente: ${cambio.ruta}`);
406
+ }
407
+ writeFile(cambio.ruta, cambio.salida, 'utf8');
408
+ aplicados.push(cambio);
409
+ }
410
+ resultado = { ok: true, changed: distintos.length, errors: [] };
411
+ } catch (error) {
412
+ const erroresRollback = revertirCambios(aplicados);
413
+ resultado = { ok: false, changed: 0, errors: [error.message, ...erroresRollback] };
414
+ }
415
+ try {
416
+ if (liberarLock) liberarLock();
417
+ } catch (error) {
418
+ resultado = { ok: false, changed: 0, errors: [...resultado.errors, error.message] };
419
+ }
420
+ return resultado;
421
+ }
422
+
423
+ function migrarBootstrap(opciones = {}) {
424
+ return aplicarCambios(intentarPreparar(opciones, 'migrate'), opciones);
425
+ }
426
+
427
+ function escribirClaims(opciones = {}) {
428
+ return aplicarCambios(intentarPreparar(opciones, 'stable'), opciones);
429
+ }
430
+
431
+ function normalizarRuta(rutaRelativa) {
432
+ return rutaRelativa.replace(/\\/g, '/').replace(/^\.\//, '');
433
+ }
434
+
435
+ function esRutaExcluida(rutaRelativa) {
436
+ const normalizada = normalizarRuta(rutaRelativa).toLowerCase();
437
+ if (normalizada === 'changelog.md') return true;
438
+ if (PREFIJOS_EXCLUIDOS.some((prefijo) => normalizada.startsWith(prefijo))) return true;
439
+ return /(^|\/)(?:tests?|node_modules|fixtures?|__fixtures__)(?:\/|$)/u.test(normalizada);
440
+ }
441
+
442
+ function ejecutarArchivoSinShell(...args) {
443
+ return childProcess.execFileSync(...args);
444
+ }
445
+
446
+ function listarCandidatos(root, opciones = {}) {
447
+ if (Array.isArray(opciones.trackedFiles)) return [...opciones.trackedFiles];
448
+ const ejecutar = opciones.execFile || ejecutarArchivoSinShell;
449
+ const salida = ejecutar('git', ['ls-files', '-z'], {
450
+ cwd: root,
451
+ encoding: 'utf8',
452
+ windowsHide: true,
453
+ stdio: ['ignore', 'pipe', 'pipe'],
454
+ });
455
+ return salida.split('\0').filter(Boolean);
456
+ }
457
+
458
+ function preservarSaltos(contenido) {
459
+ return contenido.replace(/[^\r\n]/gu, ' ');
460
+ }
461
+
462
+ function esComentarioHistorico(comentario) {
463
+ if (/\b(?:ahora|actualmente|hoy|ya|en la actualidad)\b/iu.test(comentario)) return false;
464
+ if (/(?:hist[oó]ric[oa]|legacy)/iu.test(comentario)) return true;
465
+ const runtime = comentario.match(PATRON_RUNTIME);
466
+ const estado = comentario.match(PATRON_ESTADO);
467
+ if (!runtime || !estado || runtime.index >= estado.index) return false;
468
+ const relacion = comentario.slice(runtime.index + runtime[0].length, estado.index);
469
+ return /\b(?:era|fue|ten[ií]a|contaba con)\b/iu.test(relacion);
470
+ }
471
+
472
+ function avanzarDelimitado(contenido, inicio, delimitador) {
473
+ let indice = inicio + 1;
474
+ while (indice < contenido.length) {
475
+ if (contenido[indice] === '\\') indice += 2;
476
+ else if (contenido[indice] === delimitador) return indice + 1;
477
+ else indice += 1;
478
+ }
479
+ return contenido.length;
480
+ }
481
+
482
+ function avanzarRegexJs(contenido, inicio) {
483
+ let indice = inicio + 1;
484
+ let enClase = false;
485
+ while (indice < contenido.length) {
486
+ if (contenido[indice] === '\\') indice += 2;
487
+ else if (contenido[indice] === '[') { enClase = true; indice += 1; }
488
+ else if (contenido[indice] === ']') { enClase = false; indice += 1; }
489
+ else if (contenido[indice] === '/' && !enClase) {
490
+ indice += 1;
491
+ while (/\p{L}/u.test(contenido[indice] || '')) indice += 1;
492
+ return indice;
493
+ } else indice += 1;
494
+ }
495
+ return contenido.length;
496
+ }
497
+
498
+ function obtenerPalabraSignificativa(contenido, ultimoSignificativo) {
499
+ if (ultimoSignificativo < 0) return '';
500
+ let inicio = ultimoSignificativo;
501
+ while (inicio >= 0 && /[\p{L}\p{N}_$]/u.test(contenido[inicio])) inicio -= 1;
502
+ if (contenido[inicio] === '.') return '';
503
+ return contenido.slice(inicio + 1, ultimoSignificativo + 1);
504
+ }
505
+
506
+ function esAperturaControl(contenido, ultimoSignificativo) {
507
+ const palabra = obtenerPalabraSignificativa(contenido, ultimoSignificativo);
508
+ return /^(?:if|while|for|with|switch|catch)$/u.test(palabra);
509
+ }
510
+
511
+ function puedeIniciarRegex(contenido, indice, ultimoSignificativo, cierresControl) {
512
+ if (ultimoSignificativo < 0) return true;
513
+ if ('=(:,![{;?&|+-*%~<>^'.includes(contenido[ultimoSignificativo])) return true;
514
+ if (cierresControl.has(ultimoSignificativo)) return true;
515
+ const palabra = obtenerPalabraSignificativa(contenido, ultimoSignificativo);
516
+ if (/^(?:return|case|throw|delete|typeof|void|new|await|yield|else|do)$/u.test(palabra)) {
517
+ return true;
518
+ }
519
+ if (contenido.slice(Math.max(0, ultimoSignificativo - 1), ultimoSignificativo + 1)
520
+ === '=>') return true;
521
+ return false;
522
+ }
523
+
524
+ function crearToken(contenido, tipo, inicio, fin) {
525
+ return { tipo, inicio, fin, texto: contenido.slice(inicio, fin) };
526
+ }
527
+
528
+ function reconocerDelimitadoJs(contenido, indice) {
529
+ const delimitador = contenido[indice];
530
+ if (!'"\'`'.includes(delimitador)) return null;
531
+ const fin = avanzarDelimitado(contenido, indice, delimitador);
532
+ const tipo = delimitador === '`' ? 'template' : 'string';
533
+ return crearToken(contenido, tipo, indice, fin);
534
+ }
535
+
536
+ function reconocerComentarioLineaJs(contenido, indice) {
537
+ if (contenido.slice(indice, indice + 2) !== '//') return null;
538
+ const salto = contenido.indexOf('\n', indice + 2);
539
+ const fin = salto < 0 ? contenido.length : salto;
540
+ return crearToken(contenido, 'comment', indice, fin);
541
+ }
542
+
543
+ function reconocerComentarioBloqueJs(contenido, indice) {
544
+ if (contenido.slice(indice, indice + 2) !== '/*') return null;
545
+ const cierre = contenido.indexOf('*/', indice + 2);
546
+ const fin = cierre < 0 ? contenido.length : cierre + 2;
547
+ return crearToken(contenido, 'comment', indice, fin);
548
+ }
549
+
550
+ function reconocerComentarioJs(contenido, indice) {
551
+ return reconocerComentarioLineaJs(contenido, indice)
552
+ || reconocerComentarioBloqueJs(contenido, indice);
553
+ }
554
+
555
+ function reconocerRegexJs(contenido, estado) {
556
+ if (contenido[estado.indice] !== '/') return null;
557
+ const esRegex = puedeIniciarRegex(
558
+ contenido,
559
+ estado.indice,
560
+ estado.ultimoSignificativo,
561
+ estado.cierresControl
562
+ );
563
+ if (!esRegex) return null;
564
+ const fin = avanzarRegexJs(contenido, estado.indice);
565
+ return crearToken(contenido, 'regex', estado.indice, fin);
566
+ }
567
+
568
+ function reconocerTokenJs(contenido, estado) {
569
+ return reconocerDelimitadoJs(contenido, estado.indice)
570
+ || reconocerComentarioJs(contenido, estado.indice)
571
+ || reconocerRegexJs(contenido, estado);
572
+ }
573
+
574
+ function consumirTokenJs(estado, token) {
575
+ estado.tokens.push(token);
576
+ if (token.tipo !== 'comment') estado.ultimoSignificativo = token.fin - 1;
577
+ estado.indice = token.fin;
578
+ }
579
+
580
+ function avanzarEstructuraJs(contenido, estado) {
581
+ const actual = contenido[estado.indice];
582
+ if (actual === '(') {
583
+ estado.parentesis.push(esAperturaControl(contenido, estado.ultimoSignificativo));
584
+ }
585
+ if (actual === ')' && estado.parentesis.pop()) estado.cierresControl.add(estado.indice);
586
+ if (!/\s/u.test(actual)) estado.ultimoSignificativo = estado.indice;
587
+ estado.indice += 1;
588
+ }
589
+
590
+ function tokenizarJs(contenido) {
591
+ const estado = {
592
+ tokens: [],
593
+ indice: 0,
594
+ ultimoSignificativo: -1,
595
+ parentesis: [],
596
+ cierresControl: new Set(),
597
+ };
598
+ while (estado.indice < contenido.length) {
599
+ const token = reconocerTokenJs(contenido, estado);
600
+ if (token) consumirTokenJs(estado, token);
601
+ else avanzarEstructuraJs(contenido, estado);
602
+ }
603
+ return estado.tokens;
604
+ }
605
+
606
+ function enmascararTokens(contenido, tokens) {
607
+ const fragmentos = [];
608
+ let cursor = 0;
609
+ for (const token of tokens) {
610
+ fragmentos.push(contenido.slice(cursor, token.inicio));
611
+ fragmentos.push(preservarSaltos(contenido.slice(token.inicio, token.fin)));
612
+ cursor = token.fin;
613
+ }
614
+ fragmentos.push(contenido.slice(cursor));
615
+ return fragmentos.join('');
616
+ }
617
+
618
+ function ocultarComentariosHistoricosJs(contenido) {
619
+ const historicos = tokenizarJs(contenido)
620
+ .filter(({ tipo }) => tipo === 'comment')
621
+ .flatMap(expandirLiteralJs)
622
+ .filter(({ texto }) => esComentarioHistorico(texto));
623
+ return enmascararTokens(contenido, historicos);
624
+ }
625
+
626
+ function ocultarComentariosHistoricosMarkdown(contenido) {
627
+ const comentarios = [...contenido.matchAll(/<!--[\s\S]*?-->/gu)]
628
+ .map((coincidencia) => ({
629
+ tipo: 'comment',
630
+ inicio: coincidencia.index,
631
+ fin: coincidencia.index + coincidencia[0].length,
632
+ texto: coincidencia[0],
633
+ }))
634
+ .flatMap(expandirLiteralJs)
635
+ .filter(({ texto }) => esComentarioHistorico(texto));
636
+ return enmascararTokens(contenido, comentarios);
637
+ }
638
+
639
+ function ocultarHistoria(contenido, extension) {
640
+ let salida = contenido;
641
+ if (extension === '.js') salida = ocultarComentariosHistoricosJs(salida);
642
+ if (extension === '.md') salida = ocultarComentariosHistoricosMarkdown(salida);
643
+ return salida.replace(
644
+ /const\s+CLAIM_README_LEGACY\s*=\s*\[[\s\S]*?\]\.join\([^;]+;/gu,
645
+ preservarSaltos
646
+ );
647
+ }
648
+
649
+ function neutralizarNombresTecnicos(unidad) {
650
+ return unidad.replace(
651
+ /(?:--)?(?:perfil|profile)[`"']?(?:\s+|\s*[:=]\s*)[`"']?completo[`"']?/giu,
652
+ 'perfil'
653
+ );
654
+ }
655
+
656
+ function tieneRelacionDeClaim(evaluable, runtime, estado) {
657
+ if (PATRON_CONTEXTO_CLAIM.test(evaluable)) return true;
658
+ const runtimeFin = runtime.index + runtime[0].length;
659
+ const estadoFin = estado.index + estado[0].length;
660
+ if (runtime.index < estado.index) {
661
+ if (/^[\s"'`]*:\s*\[?\s*["'`]*$/u.test(evaluable.slice(runtimeFin, estado.index))) {
662
+ return true;
663
+ }
664
+ return /^(?:[\s"'`]*)(?:(?:es|est[aá]|figura como|queda(?: como)?|se considera)|[:=—-])(?:[\s"'`]*)$/iu
665
+ .test(evaluable.slice(runtimeFin, estado.index));
666
+ }
667
+ return /^(?:[\s"'`]*)(?:para(?: el runtime)?|[:=—-])(?:[\s"'`]*)$/iu
668
+ .test(evaluable.slice(estadoFin, runtime.index));
669
+ }
670
+
671
+ function obtenerCoincidencias(texto, patron) {
672
+ const flags = patron.flags.includes('g') ? patron.flags : `${patron.flags}g`;
673
+ return [...texto.matchAll(new RegExp(patron.source, flags))];
674
+ }
675
+
676
+ function detectarClaim(unidad, forzarContexto = false) {
677
+ const evaluable = neutralizarNombresTecnicos(unidad);
678
+ const runtimes = obtenerCoincidencias(evaluable, PATRON_RUNTIME);
679
+ const estados = obtenerCoincidencias(evaluable, PATRON_ESTADO);
680
+ const pares = runtimes.flatMap((runtime) => estados.map((estado) => ({ runtime, estado })))
681
+ .sort((a, b) => Math.abs(a.runtime.index - a.estado.index)
682
+ - Math.abs(b.runtime.index - b.estado.index));
683
+ const par = pares.find(({ runtime, estado }) => (
684
+ forzarContexto || tieneRelacionDeClaim(evaluable, runtime, estado)
685
+ ));
686
+ if (!par) return null;
687
+ const runtimeOrdinal = runtimes.filter((runtime) => (
688
+ runtime.index <= par.runtime.index
689
+ && runtime[0].toLowerCase() === par.runtime[0].toLowerCase()
690
+ )).length - 1;
691
+ return {
692
+ runtime: par.runtime[0],
693
+ estado: par.estado[0],
694
+ runtimeOrdinal,
695
+ };
696
+ }
697
+
698
+ function obtenerIndiceOcurrencia(contenido, texto, ordinal = 0, desde = 0) {
699
+ let indice = desde - 1;
700
+ for (let actual = 0; actual <= ordinal; actual += 1) {
701
+ indice = contenido.toLowerCase().indexOf(texto.toLowerCase(), indice + 1);
702
+ if (indice < 0) return -1;
703
+ }
704
+ return indice;
705
+ }
706
+
707
+ function obtenerLineaEnIndice(contenido, indice) {
708
+ if (indice < 0) return 1;
709
+ return contenido.slice(0, indice).split(/\r?\n/u).length;
710
+ }
711
+
712
+ function obtenerLinea(contenido, texto, desde = 0) {
713
+ return obtenerLineaEnIndice(contenido, obtenerIndiceOcurrencia(contenido, texto, 0, desde));
714
+ }
715
+
716
+ function crearHallazgo(rutaRelativa, line, claim) {
717
+ return {
718
+ path: rutaRelativa,
719
+ line,
720
+ runtime: claim.runtime,
721
+ estado: claim.estado,
722
+ };
723
+ }
724
+
725
+ function segmentarOracionesConOffset(texto) {
726
+ const oraciones = [];
727
+ let inicio = 0;
728
+ let indice = 0;
729
+ while (indice < texto.length) {
730
+ if (!'.!?'.includes(texto[indice])) {
731
+ indice += 1;
732
+ continue;
733
+ }
734
+ while (indice < texto.length && '.!?'.includes(texto[indice])) indice += 1;
735
+ oraciones.push({ inicio, texto: texto.slice(inicio, indice) });
736
+ inicio = indice;
737
+ }
738
+ if (inicio < texto.length) oraciones.push({ inicio, texto: texto.slice(inicio) });
739
+ return oraciones;
740
+ }
741
+
742
+ function segmentarLinea(linea) {
743
+ return segmentarOracionesConOffset(linea).map(({ texto }) => texto).filter(Boolean);
744
+ }
745
+
746
+ function esFilaTabla(linea) {
747
+ return linea.includes('|');
748
+ }
749
+
750
+ function esSeparadorTabla(linea) {
751
+ const celdas = obtenerCeldasTabla(linea);
752
+ return celdas.length > 0 && celdas.every((celda) => /^:?-+:?$/u.test(celda));
753
+ }
754
+
755
+ function normalizarCelda(celda) {
756
+ const sinMarkdown = normalizarMarkdown(celda).trim();
757
+ return sinMarkdown.replace(/^(["'])(.*)\1$/u, '$2').trim();
758
+ }
759
+
760
+ function normalizarMarkdown(texto) {
761
+ return texto
762
+ .replace(/!?\[([^\]]+)\]\([^)]+\)/gu, '$1')
763
+ .replace(/<\/?[\p{L}][^>]*>/gu, '')
764
+ .replace(/(?<![\p{L}\p{N}])_+(?=[\p{L}\p{N}])/gu, '')
765
+ .replace(/(?<=[\p{L}\p{N}])_+(?![\p{L}\p{N}])/gu, '')
766
+ .replace(/[*`~]/gu, '');
767
+ }
768
+
769
+ function coincideCompleto(valor, patron) {
770
+ const coincidencia = valor.match(patron);
771
+ return coincidencia?.index === 0 && coincidencia[0].length === valor.length;
772
+ }
773
+
774
+ function obtenerCeldasTabla(linea) {
775
+ const celdas = linea.split('|');
776
+ if (celdas[0].trim() === '') celdas.shift();
777
+ if (celdas.at(-1)?.trim() === '') celdas.pop();
778
+ return celdas.map(normalizarCelda);
779
+ }
780
+
781
+ function obtenerIndiceTarea(celdas) {
782
+ const normalizadas = celdas.map((celda) => celda.toLowerCase());
783
+ if (!normalizadas.includes('id')) return -1;
784
+ return normalizadas.indexOf('tarea');
785
+ }
786
+
787
+ function esFilaTareaDeFase(celdas, rutaRelativa, indiceTarea) {
788
+ return rutaRelativa.startsWith('.planning/fases/')
789
+ && indiceTarea >= 0
790
+ && /^\d+(?:\.\d+)*$/u.test(celdas[0] || '');
791
+ }
792
+
793
+ function detectarClaimEnFila(linea, rutaRelativa, indiceTarea) {
794
+ const celdas = obtenerCeldasTabla(linea);
795
+ const esTarea = esFilaTareaDeFase(celdas, rutaRelativa, indiceTarea);
796
+ const evaluables = esTarea
797
+ ? celdas.filter((_, indice) => indice !== indiceTarea)
798
+ : celdas;
799
+ for (const celda of evaluables) {
800
+ const claim = detectarClaim(celda);
801
+ if (claim) return claim;
802
+ }
803
+ const runtime = evaluables.find((celda) => coincideCompleto(celda, PATRON_RUNTIME));
804
+ const estado = evaluables.find((celda) => coincideCompleto(celda, PATRON_ESTADO));
805
+ return runtime && estado ? { runtime, estado } : null;
806
+ }
807
+
808
+ function rangoCanonico(contenido) {
809
+ const inicio = contenido.indexOf(MARCA_INICIO);
810
+ const fin = contenido.indexOf(MARCA_FIN, inicio);
811
+ if (inicio < 0 || fin < inicio) return null;
812
+ return {
813
+ inicio: obtenerLinea(contenido, MARCA_INICIO),
814
+ fin: obtenerLinea(contenido, MARCA_FIN, inicio),
815
+ };
816
+ }
817
+
818
+ function escanearTextoPorLinea(contenido, rutaRelativa, rango, esMarkdown) {
819
+ const hallazgos = [];
820
+ const lineas = contenido.split(/\r?\n/u);
821
+ let indiceTarea = -1;
822
+ for (let indice = 0; indice < lineas.length; indice += 1) {
823
+ const linea = lineas[indice];
824
+ const numero = indice + 1;
825
+ if (rango && numero >= rango.inicio && numero <= rango.fin) {
826
+ indiceTarea = -1;
827
+ continue;
828
+ }
829
+ if (esMarkdown && esSeparadorTabla(linea)) continue;
830
+ if (esMarkdown && esFilaTabla(linea)) {
831
+ const celdas = obtenerCeldasTabla(linea);
832
+ if (esSeparadorTabla(lineas[indice + 1] || '')) {
833
+ indiceTarea = obtenerIndiceTarea(celdas);
834
+ continue;
835
+ }
836
+ const claim = detectarClaimEnFila(linea, rutaRelativa, indiceTarea);
837
+ if (claim) hallazgos.push(crearHallazgo(rutaRelativa, numero, claim));
838
+ continue;
839
+ }
840
+ indiceTarea = -1;
841
+ for (const unidad of segmentarLinea(normalizarMarkdown(linea))) {
842
+ const claim = detectarClaim(unidad);
843
+ if (!claim) continue;
844
+ hallazgos.push(crearHallazgo(rutaRelativa, numero, claim));
845
+ }
846
+ }
847
+ return hallazgos;
848
+ }
849
+
850
+ function escanearParrafo(lineas, inicio, rutaRelativa) {
851
+ const texto = normalizarMarkdown(lineas.join('\n'));
852
+ const hallazgos = [];
853
+ for (const oracion of segmentarOracionesConOffset(texto)) {
854
+ const claim = detectarClaim(oracion.texto);
855
+ if (!claim) continue;
856
+ const indiceRuntime = obtenerIndiceOcurrencia(
857
+ oracion.texto,
858
+ claim.runtime,
859
+ claim.runtimeOrdinal
860
+ );
861
+ const offset = oracion.inicio + indiceRuntime;
862
+ const line = inicio + texto.slice(0, offset).split('\n').length - 1;
863
+ hallazgos.push(crearHallazgo(rutaRelativa, line, claim));
864
+ }
865
+ return hallazgos;
866
+ }
867
+
868
+ function escanearParrafosMarkdown(contenido, rutaRelativa, rango) {
869
+ const hallazgos = [];
870
+ let lineas = [];
871
+ let inicio = 1;
872
+ const vaciar = () => {
873
+ hallazgos.push(...escanearParrafo(lineas, inicio, rutaRelativa));
874
+ lineas = [];
875
+ };
876
+ contenido.split(/\r?\n/u).forEach((linea, indice) => {
877
+ const numero = indice + 1;
878
+ const seOmite = !linea.trim() || esFilaTabla(linea) || /^[\p{L}\p{N}_-]+:\s/iu.test(linea)
879
+ || (rango && numero >= rango.inicio && numero <= rango.fin);
880
+ if (seOmite) return vaciar();
881
+ if (lineas.length === 0) inicio = numero;
882
+ lineas.push(linea);
883
+ });
884
+ vaciar();
885
+ return hallazgos;
886
+ }
887
+
888
+ function escanearBloquesClaveValorMarkdown(contenido, rutaRelativa, rango) {
889
+ const hallazgos = [];
890
+ let entradas = [];
891
+ const vaciar = () => {
892
+ const relevantes = entradas.filter(({ clave }) => (
893
+ /^(?:runtime|target|soporte|support|estado|status|compatibilidad|conformidad|certificaci[oó]n)$/iu
894
+ .test(clave)
895
+ ));
896
+ const unidad = relevantes.map(({ clave, valor }) => `${clave}:${valor}`).join('\n');
897
+ const claim = detectarClaim(unidad, true);
898
+ const entradaRuntime = relevantes.find(({ valor }) => PATRON_RUNTIME.test(valor));
899
+ if (claim && entradaRuntime) {
900
+ hallazgos.push(crearHallazgo(rutaRelativa, entradaRuntime.linea, claim));
901
+ }
902
+ entradas = [];
903
+ };
904
+ contenido.split(/\r?\n/u).forEach((linea, indice) => {
905
+ const numero = indice + 1;
906
+ const coincidencia = linea.match(/^\s*([\p{L}\p{N}_-]+):\s*(.*?)\s*$/u);
907
+ if (!coincidencia || (rango && numero >= rango.inicio && numero <= rango.fin)) {
908
+ vaciar();
909
+ return;
910
+ }
911
+ entradas.push({ clave: coincidencia[1], valor: coincidencia[2], linea: numero });
912
+ });
913
+ vaciar();
914
+ return hallazgos;
915
+ }
916
+
917
+ function crearMascaraEstructuralJs(contenido, tokens) {
918
+ return enmascararTokens(contenido, tokens);
919
+ }
920
+
921
+ function esInicioObjetoJs(mascara, indice) {
922
+ let cursor = indice - 1;
923
+ while (cursor >= 0 && /\s/u.test(mascara[cursor])) cursor -= 1;
924
+ const anterior = mascara[cursor] || '';
925
+ const prefijo = mascara.slice(Math.max(0, cursor - 80), cursor + 1);
926
+ if (/tiposSoportados\s*=\s*$/u.test(prefijo)) return false;
927
+ return '=([,:'.includes(anterior) || /\b(?:return|default)$/u.test(prefijo);
928
+ }
929
+
930
+ function extraerObjetosJs(contenido, tokens) {
931
+ const mascara = crearMascaraEstructuralJs(contenido, tokens);
932
+ const pila = [];
933
+ const objetos = [];
934
+ for (let indice = 0; indice < mascara.length; indice += 1) {
935
+ if (mascara[indice] === '{') {
936
+ pila.push({ inicio: indice, esObjeto: esInicioObjetoJs(mascara, indice) });
937
+ }
938
+ if (mascara[indice] !== '}' || pila.length === 0) continue;
939
+ const actual = pila.pop();
940
+ if (actual.esObjeto) {
941
+ objetos.push({
942
+ tipo: 'object',
943
+ inicio: actual.inicio,
944
+ texto: contenido.slice(actual.inicio, indice + 1),
945
+ });
946
+ }
947
+ }
948
+ return objetos;
949
+ }
950
+
951
+ function encontrarFinValorJs(texto, inicio, tokens) {
952
+ let profundidad = 0;
953
+ let indiceToken = 0;
954
+ for (let indice = inicio; indice < texto.length; indice += 1) {
955
+ while (tokens[indiceToken]?.fin <= indice) indiceToken += 1;
956
+ const token = tokens[indiceToken];
957
+ if (token && token.inicio === indice) {
958
+ indice = token.fin - 1;
959
+ continue;
960
+ }
961
+ const caracter = texto[indice];
962
+ if ('[{('.includes(caracter)) profundidad += 1;
963
+ else if (']})'.includes(caracter)) {
964
+ if (profundidad === 0) return indice;
965
+ profundidad -= 1;
966
+ } else if (',;'.includes(caracter) && profundidad === 0) return indice;
967
+ }
968
+ return texto.length;
969
+ }
970
+
971
+ function esNombreTecnico(nombre) {
972
+ return /^(?:tiposSoportados|profiles?|perfiles?)$/iu.test(nombre);
973
+ }
974
+
975
+ function quitarRangosSolapados(rangos) {
976
+ const noSolapados = [];
977
+ for (const rango of rangos) {
978
+ if (rango.inicio >= (noSolapados.at(-1)?.fin || 0)) noSolapados.push(rango);
979
+ }
980
+ return noSolapados;
981
+ }
982
+
983
+ function ocultarSubarbolesTecnicosJs(texto) {
984
+ const tokens = tokenizarJs(texto);
985
+ const rangos = [];
986
+ const patronTecnico = new RegExp(
987
+ String.raw`(?<![\p{L}\p{N}_$])(?:tiposSoportados|profiles?|perfiles?)`,
988
+ 'giu'
989
+ );
990
+ for (const coincidencia of texto.matchAll(patronTecnico)) {
991
+ const resto = texto.slice(coincidencia.index + coincidencia[0].length);
992
+ const separador = resto.match(/^["'`]?\s*\]?\s*[:=]/u);
993
+ if (!separador) continue;
994
+ const inicioValor = coincidencia.index + coincidencia[0].length + separador[0].length;
995
+ rangos.push({
996
+ inicio: coincidencia.index,
997
+ fin: encontrarFinValorJs(texto, inicioValor, tokens),
998
+ });
999
+ }
1000
+ return enmascararTokens(texto, quitarRangosSolapados(rangos));
1001
+ }
1002
+
1003
+ function ocultarSubarbolesTecnicosJsonFuente(texto) {
1004
+ const tokens = tokenizarJs(texto);
1005
+ const rangos = [];
1006
+ for (const token of tokens.filter(({ tipo }) => tipo === 'string')) {
1007
+ let clave;
1008
+ try { clave = JSON.parse(token.texto); } catch { continue; }
1009
+ if (!esNombreTecnico(clave)) continue;
1010
+ const resto = texto.slice(token.fin);
1011
+ const separador = resto.match(/^\s*:/u);
1012
+ if (!separador) continue;
1013
+ const inicioValor = token.fin + separador[0].length;
1014
+ rangos.push({
1015
+ inicio: token.inicio,
1016
+ fin: encontrarFinValorJs(texto, inicioValor, tokens),
1017
+ });
1018
+ }
1019
+ return enmascararTokens(texto, quitarRangosSolapados(rangos));
1020
+ }
1021
+
1022
+ function esInicioClaveRuntimeJs(texto, runtime) {
1023
+ let indice = runtime.index - 1;
1024
+ while (indice >= 0 && /\s/u.test(texto[indice])) indice -= 1;
1025
+ return indice < 0 || '{,\'"`'.includes(texto[indice]);
1026
+ }
1027
+
1028
+ function detectarMapeoRuntimeJs(texto) {
1029
+ if (!neutralizarNombresTecnicos(texto)) return null;
1030
+ const tokens = tokenizarJs(texto);
1031
+ for (const runtime of obtenerCoincidencias(texto, PATRON_RUNTIME)) {
1032
+ if (!esInicioClaveRuntimeJs(texto, runtime)) continue;
1033
+ const resto = texto.slice(runtime.index + runtime[0].length);
1034
+ const separador = resto.match(/^["'`]?\s*\]?\s*:/u);
1035
+ if (!separador) continue;
1036
+ const inicioValor = runtime.index + runtime[0].length + separador[0].length;
1037
+ const finValor = encontrarFinValorJs(texto, inicioValor, tokens);
1038
+ const valor = neutralizarNombresTecnicos(texto.slice(inicioValor, finValor));
1039
+ const estado = valor.match(PATRON_ESTADO);
1040
+ if (estado) {
1041
+ return {
1042
+ runtime: runtime[0],
1043
+ estado: estado[0],
1044
+ runtimeIndex: runtime.index,
1045
+ };
1046
+ }
1047
+ }
1048
+ return null;
1049
+ }
1050
+
1051
+ function escanearUnidadesJs(contenido, rutaRelativa, unidades) {
1052
+ const hallazgos = [];
1053
+ for (const { tipo, inicio, texto } of unidades) {
1054
+ const claim = tipo === 'object'
1055
+ ? detectarMapeoRuntimeJs(texto) || detectarClaim(texto)
1056
+ : detectarClaim(texto);
1057
+ if (!claim) continue;
1058
+ const indiceLocal = claim.runtimeIndex ?? obtenerIndiceOcurrencia(
1059
+ texto,
1060
+ claim.runtime,
1061
+ claim.runtimeOrdinal
1062
+ );
1063
+ hallazgos.push(crearHallazgo(
1064
+ rutaRelativa,
1065
+ obtenerLineaEnIndice(contenido, inicio + indiceLocal),
1066
+ claim
1067
+ ));
1068
+ }
1069
+ return hallazgos;
1070
+ }
1071
+
1072
+ function expandirLiteralJs(token) {
1073
+ return segmentarOracionesConOffset(token.texto)
1074
+ .map((oracion) => ({
1075
+ tipo: token.tipo,
1076
+ inicio: token.inicio + oracion.inicio,
1077
+ fin: token.inicio + oracion.inicio + oracion.texto.length,
1078
+ texto: oracion.texto,
1079
+ }));
1080
+ }
1081
+
1082
+ function escanearJs(contenido, rutaRelativa, tokens) {
1083
+ const literales = tokens
1084
+ .filter(({ tipo }) => ['string', 'template', 'comment'].includes(tipo))
1085
+ .flatMap(expandirLiteralJs);
1086
+ const objetos = extraerObjetosJs(contenido, tokens);
1087
+ return escanearUnidadesJs(
1088
+ contenido,
1089
+ rutaRelativa,
1090
+ [...literales, ...objetos]
1091
+ );
1092
+ }
1093
+
1094
+ function colectarUnidadesJson(valor, unidades = []) {
1095
+ if (!valor || typeof valor !== 'object') return unidades;
1096
+ if (Array.isArray(valor)) {
1097
+ valor.forEach((elemento) => colectarUnidadesJson(elemento, unidades));
1098
+ return unidades;
1099
+ }
1100
+ unidades.push(valor);
1101
+ Object.entries(valor).forEach(([clave, elemento]) => {
1102
+ if (!esNombreTecnico(clave)) {
1103
+ colectarUnidadesJson(elemento, unidades);
1104
+ }
1105
+ });
1106
+ return unidades;
1107
+ }
1108
+
1109
+ function detectarMapeoRuntimeJson(valor, ordinales = new Map()) {
1110
+ if (!valor || typeof valor !== 'object') return null;
1111
+ if (Array.isArray(valor)) {
1112
+ for (const elemento of valor) {
1113
+ const claim = detectarMapeoRuntimeJson(elemento, ordinales);
1114
+ if (claim) return claim;
1115
+ }
1116
+ return null;
1117
+ }
1118
+ for (const [clave, descendiente] of Object.entries(valor)) {
1119
+ const esRuntime = coincideCompleto(clave, PATRON_RUNTIME);
1120
+ if (esRuntime) {
1121
+ const identificador = clave.toLowerCase();
1122
+ const runtimeKeyOrdinal = ordinales.get(identificador) || 0;
1123
+ ordinales.set(identificador, runtimeKeyOrdinal + 1);
1124
+ const serializado = neutralizarNombresTecnicos(JSON.stringify(descendiente));
1125
+ const estado = serializado.match(PATRON_ESTADO);
1126
+ if (estado) return { runtime: clave, estado: estado[0], runtimeKeyOrdinal };
1127
+ }
1128
+ const claimAnidado = detectarMapeoRuntimeJson(descendiente, ordinales);
1129
+ if (claimAnidado) return claimAnidado;
1130
+ }
1131
+ return null;
1132
+ }
1133
+
1134
+ function analizarClavesJson(contenido) {
1135
+ const tokens = tokenizarJs(contenido);
1136
+ const scopes = [];
1137
+ const claves = [];
1138
+ let indiceToken = 0;
1139
+ for (let indice = 0; indice < contenido.length; indice += 1) {
1140
+ const token = tokens[indiceToken];
1141
+ if (token && token.inicio === indice) {
1142
+ if (token.tipo === 'string') {
1143
+ let cursor = token.fin;
1144
+ while (/\s/u.test(contenido[cursor] || '')) cursor += 1;
1145
+ if (contenido[cursor] === ':') {
1146
+ const clave = JSON.parse(token.texto);
1147
+ const scope = scopes.at(-1);
1148
+ if (scope?.has(clave)) throw new Error(`clave JSON duplicada: ${clave}`);
1149
+ scope?.add(clave);
1150
+ claves.push({ clave, index: token.inicio });
1151
+ }
1152
+ }
1153
+ indice = token.fin - 1;
1154
+ indiceToken += 1;
1155
+ continue;
1156
+ }
1157
+ if (contenido[indice] === '{') scopes.push(new Set());
1158
+ else if (contenido[indice] === '}') scopes.pop();
1159
+ }
1160
+ return claves;
1161
+ }
1162
+
1163
+ function obtenerLineaClaveJson(contenido, runtime, ordinal) {
1164
+ const claves = analizarClavesJson(contenido)
1165
+ .filter(({ clave }) => clave.toLowerCase() === runtime.toLowerCase());
1166
+ return obtenerLineaEnIndice(contenido, claves[ordinal]?.index ?? -1);
1167
+ }
1168
+
1169
+ function eliminarSubarbolesTecnicosJson(valor) {
1170
+ if (!valor || typeof valor !== 'object') return;
1171
+ if (Array.isArray(valor)) {
1172
+ valor.forEach(eliminarSubarbolesTecnicosJson);
1173
+ return;
1174
+ }
1175
+ for (const [clave, descendiente] of Object.entries(valor)) {
1176
+ if (esNombreTecnico(clave)) delete valor[clave];
1177
+ else eliminarSubarbolesTecnicosJson(descendiente);
1178
+ }
1179
+ }
1180
+
1181
+ function escanearJson(contenido, rutaRelativa, esJsonRegistrado) {
1182
+ analizarClavesJson(contenido);
1183
+ const fuenteEscaneable = ocultarSubarbolesTecnicosJsonFuente(contenido);
1184
+ const documento = JSON.parse(contenido);
1185
+ eliminarSubarbolesTecnicosJson(documento);
1186
+ if (esJsonRegistrado) delete documento.description;
1187
+ const serializada = JSON.stringify(documento);
1188
+ const mapeo = detectarMapeoRuntimeJson(documento);
1189
+ const claim = mapeo || detectarClaim(serializada);
1190
+ if (!claim) return [];
1191
+ const line = mapeo
1192
+ ? obtenerLineaClaveJson(fuenteEscaneable, claim.runtime, claim.runtimeKeyOrdinal)
1193
+ : obtenerLineaEnIndice(
1194
+ fuenteEscaneable,
1195
+ obtenerIndiceOcurrencia(fuenteEscaneable, claim.runtime, claim.runtimeOrdinal)
1196
+ );
1197
+ return [crearHallazgo(rutaRelativa, line, claim)];
1198
+ }
1199
+
1200
+ function deduplicarHallazgos(hallazgos) {
1201
+ const unicos = new Map();
1202
+ for (const hallazgo of hallazgos) {
1203
+ const clave = `${hallazgo.path}:${hallazgo.line}`;
1204
+ if (!unicos.has(clave)) unicos.set(clave, hallazgo);
1205
+ }
1206
+ return [...unicos.values()];
1207
+ }
1208
+
1209
+ function estaRegistrada(rutaRelativa, superficies) {
1210
+ return (superficies || []).some(({ path: ruta }) => ruta === rutaRelativa);
1211
+ }
1212
+
1213
+ function escanearArchivoMarkdown(contenido, rutaRelativa, registry) {
1214
+ const superficies = [...(registry.markdown || []), ...(registry.managed || [])];
1215
+ const rango = estaRegistrada(rutaRelativa, superficies) ? rangoCanonico(contenido) : null;
1216
+ return [
1217
+ ...escanearTextoPorLinea(contenido, rutaRelativa, rango, true),
1218
+ ...escanearParrafosMarkdown(contenido, rutaRelativa, rango),
1219
+ ...escanearBloquesClaveValorMarkdown(contenido, rutaRelativa, rango),
1220
+ ];
1221
+ }
1222
+
1223
+ function escanearArchivoJavaScript(contenido, rutaRelativa) {
1224
+ const escaneable = ocultarSubarbolesTecnicosJs(contenido);
1225
+ const tokens = tokenizarJs(escaneable);
1226
+ const sinRegex = enmascararTokens(
1227
+ escaneable,
1228
+ tokens.filter(({ tipo }) => tipo === 'regex')
1229
+ );
1230
+ return [
1231
+ ...escanearTextoPorLinea(sinRegex, rutaRelativa, null, false),
1232
+ ...escanearJs(escaneable, rutaRelativa, tokens),
1233
+ ];
1234
+ }
1235
+
1236
+ function escanearArchivo(
1237
+ root,
1238
+ rutaRelativa,
1239
+ registry,
1240
+ resolver = (ruta) => resolverRuta(root, ruta)
1241
+ ) {
1242
+ const extension = path.extname(rutaRelativa).toLowerCase();
1243
+ const contenido = ocultarHistoria(
1244
+ fs.readFileSync(resolver(rutaRelativa), 'utf8'),
1245
+ extension
1246
+ );
1247
+ if (extension === '.json') {
1248
+ return escanearJson(contenido, rutaRelativa, estaRegistrada(rutaRelativa, registry.json));
1249
+ }
1250
+ if (extension === '.md') return escanearArchivoMarkdown(contenido, rutaRelativa, registry);
1251
+ if (extension === '.js') return escanearArchivoJavaScript(contenido, rutaRelativa);
1252
+ return [];
1253
+ }
1254
+
1255
+ function escanearClaimsLegacy(opciones = {}) {
1256
+ const root = path.resolve(opciones.root || RAIZ);
1257
+ if (!Array.isArray(opciones.trackedFiles)) {
1258
+ const trackedFiles = listarCandidatos(root, opciones);
1259
+ return escanearClaimsLegacy({ ...opciones, root, trackedFiles });
1260
+ }
1261
+ const registry = opciones.registry || REGISTRO_SUPERFICIES;
1262
+ const candidatos = listarCandidatos(root, opciones)
1263
+ .map(normalizarRuta)
1264
+ .filter((ruta) => EXTENSIONES_ESCANEADAS.has(path.extname(ruta).toLowerCase()))
1265
+ .filter((ruta) => !esRutaExcluida(ruta));
1266
+ const hallazgos = [];
1267
+ const resolver = crearResolvedorConfinado(root);
1268
+ candidatos.forEach((ruta) => {
1269
+ hallazgos.push(...escanearArchivo(root, ruta, registry, resolver));
1270
+ });
1271
+ return deduplicarHallazgos(hallazgos);
1272
+ }
1273
+
1274
+ function verificarClaims(opciones = {}) {
1275
+ const preparacion = intentarPreparar(opciones, 'stable');
1276
+ if (!preparacion.ok) return {
1277
+ ok: false,
1278
+ code: preparacion.code,
1279
+ errors: preparacion.errors,
1280
+ };
1281
+ const drift = preparacion.cambios.filter(({ original, salida }) => original !== salida);
1282
+ try {
1283
+ const claimsLegacy = escanearClaimsLegacy(opciones);
1284
+ const ok = drift.length === 0 && claimsLegacy.length === 0;
1285
+ const errors = claimsLegacy.map(({ path: ruta, line }) => `claim legacy: ${ruta}:${line}`);
1286
+ return { ok, code: ok ? 0 : 2, drift, claimsLegacy, errors };
1287
+ } catch (error) {
1288
+ return { ok: false, code: 1, drift, claimsLegacy: [], errors: [error.message] };
1289
+ }
1290
+ }
1291
+
1292
+ function parsearArgs(argv) {
1293
+ const opciones = {};
1294
+ const modos = new Set(['--migrate-bootstrap', '--write', '--check']);
1295
+ const prefijos = ['--root=', '--manifest='];
1296
+ const desconocido = argv.find((argumento) => (
1297
+ !modos.has(argumento) && !prefijos.some((prefijo) => argumento.startsWith(prefijo))
1298
+ ));
1299
+ if (desconocido) throw new TypeError(`argumento desconocido: ${desconocido}`);
1300
+ const presentes = argv.filter((argumento) => modos.has(argumento));
1301
+ if (presentes.length !== 1) throw new TypeError('indica exactamente un modo: --migrate-bootstrap, --write o --check');
1302
+ opciones.mode = presentes[0];
1303
+ for (const argumento of argv) {
1304
+ if (argumento.startsWith('--root=')) opciones.root = argumento.slice(7);
1305
+ if (argumento.startsWith('--manifest=')) opciones.manifestPath = argumento.slice(11);
1306
+ }
1307
+ return opciones;
1308
+ }
1309
+
1310
+ function main(argv = process.argv.slice(2), dependencias = {}) {
1311
+ try {
1312
+ const opciones = parsearArgs(argv);
1313
+ if (dependencias.registry) opciones.registry = dependencias.registry;
1314
+ if (dependencias.trackedFiles) opciones.trackedFiles = dependencias.trackedFiles;
1315
+ const resultado = opciones.mode === '--migrate-bootstrap'
1316
+ ? migrarBootstrap(opciones)
1317
+ : opciones.mode === '--write' ? escribirClaims(opciones) : verificarClaims(opciones);
1318
+ if (!resultado.ok) console.error(`[generar-claims-runtime] ${resultado.errors?.join('; ') || 'drift detectado'}`);
1319
+ process.exitCode = opciones.mode === '--check' ? resultado.code : (resultado.ok ? 0 : 1);
1320
+ return resultado;
1321
+ } catch (error) {
1322
+ console.error(`[generar-claims-runtime] ${error.message}`);
1323
+ process.exitCode = 1;
1324
+ return { ok: false, errors: [error.message] };
1325
+ }
1326
+ }
1327
+
1328
+ module.exports = {
1329
+ DESCRIPCION,
1330
+ MARCA_FIN,
1331
+ MARCA_INICIO,
1332
+ REGISTRO_SUPERFICIES,
1333
+ escanearClaimsLegacy,
1334
+ escribirClaims,
1335
+ main,
1336
+ migrarBootstrap,
1337
+ parsearArgs,
1338
+ renderBloque,
1339
+ verificarClaims,
1340
+ };
1341
+
1342
+ if (require.main === module) main();