@saulwade/swl-ses 2.6.0 → 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 (435) hide show
  1. package/CLAUDE.md +209 -197
  2. package/README.md +647 -600
  3. package/agentes/accesibilidad-wcag-swl.md +690 -690
  4. package/agentes/arquitecto-swl.md +267 -267
  5. package/agentes/auto-evolucion-swl.md +932 -932
  6. package/agentes/backend-csharp-swl.md +420 -420
  7. package/agentes/backend-go-swl.md +390 -390
  8. package/agentes/backend-java-swl.md +281 -281
  9. package/agentes/backend-rust-swl.md +364 -364
  10. package/agentes/backend-workers-swl.md +482 -482
  11. package/agentes/cloud-infra-swl.md +509 -509
  12. package/agentes/consolidador-swl.md +541 -541
  13. package/agentes/depurador-swl.md +352 -352
  14. package/agentes/devops-ci-swl.md +400 -400
  15. package/agentes/disenador-ui-swl.md +569 -569
  16. package/agentes/documentador-swl.md +345 -345
  17. package/agentes/frontend-angular-swl.md +621 -621
  18. package/agentes/frontend-css-swl.md +716 -716
  19. package/agentes/frontend-react-swl.md +692 -692
  20. package/agentes/frontend-swl.md +496 -496
  21. package/agentes/frontend-tailwind-swl.md +826 -826
  22. package/agentes/investigador-swl.md +432 -432
  23. package/agentes/investigador-ux-swl.md +505 -505
  24. package/agentes/migrador-swl.md +442 -442
  25. package/agentes/mobile-android-swl.md +511 -511
  26. package/agentes/mobile-cross-swl.md +541 -541
  27. package/agentes/mobile-ios-swl.md +502 -502
  28. package/agentes/mobile-testing-swl.md +302 -302
  29. package/agentes/nemesis-auditor-swl.md +285 -285
  30. package/agentes/observabilidad-swl.md +438 -438
  31. package/agentes/pagos-swl.md +310 -310
  32. package/agentes/perfilador-usuario-swl.md +321 -321
  33. package/agentes/planificador-swl.md +399 -399
  34. package/agentes/producto-prd-swl.md +589 -589
  35. package/agentes/red-team-swl.md +218 -218
  36. package/agentes/release-manager-swl.md +590 -590
  37. package/agentes/rendimiento-swl.md +713 -713
  38. package/agentes/revisor-angular-swl.md +278 -278
  39. package/agentes/revisor-csharp-swl.md +264 -264
  40. package/agentes/revisor-go-swl.md +259 -259
  41. package/agentes/revisor-java-swl.md +257 -257
  42. package/agentes/revisor-kotlin-swl.md +273 -273
  43. package/agentes/revisor-nextjs-swl.md +281 -281
  44. package/agentes/revisor-php-swl.md +271 -271
  45. package/agentes/revisor-react-swl.md +278 -278
  46. package/agentes/revisor-rust-swl.md +346 -346
  47. package/agentes/revisor-seguridad-swl.md +399 -399
  48. package/agentes/revisor-swift-swl.md +268 -268
  49. package/agentes/revisor-typescript-swl.md +346 -346
  50. package/agentes/tdd-qa-swl.md +393 -393
  51. package/bin/swl-ses.js +10 -0
  52. package/comandos/swl/actualizar.md +174 -174
  53. package/comandos/swl/adoptar-proyecto.md +265 -265
  54. package/comandos/swl/aprender.md +836 -836
  55. package/comandos/swl/aprobar-plan.md +146 -146
  56. package/comandos/swl/auditar-deps.md +134 -134
  57. package/comandos/swl/autoresearch.md +264 -264
  58. package/comandos/swl/ayuda.md +224 -224
  59. package/comandos/swl/brainstorm.md +52 -51
  60. package/comandos/swl/checkpoint.md +325 -325
  61. package/comandos/swl/claudemd.md +234 -234
  62. package/comandos/swl/compactar.md +310 -310
  63. package/comandos/swl/configurar-ci.md +235 -235
  64. package/comandos/swl/contexto.md +110 -110
  65. package/comandos/swl/crear-skill.md +292 -292
  66. package/comandos/swl/cron.md +194 -194
  67. package/comandos/swl/deuda-codigo.md +97 -97
  68. package/comandos/swl/discutir-fase.md +169 -169
  69. package/comandos/swl/ejecutar-fase.md +233 -233
  70. package/comandos/swl/evaluar-skill.md +520 -520
  71. package/comandos/swl/evolucion-continua.md +73 -73
  72. package/comandos/swl/evolucionar.md +267 -267
  73. package/comandos/swl/exportar-vault.md +583 -583
  74. package/comandos/swl/fix.md +118 -118
  75. package/comandos/swl/gateway.md +158 -158
  76. package/comandos/swl/inbox.md +116 -116
  77. package/comandos/swl/instalar.md +220 -220
  78. package/comandos/swl/instintos.md +86 -86
  79. package/comandos/swl/mapear-codebase.md +312 -312
  80. package/comandos/swl/mcp-status.md +176 -175
  81. package/comandos/swl/modelo.md +100 -100
  82. package/comandos/swl/nemesis.md +433 -433
  83. package/comandos/swl/notificaciones.md +299 -299
  84. package/comandos/swl/nuevo-proyecto.md +251 -251
  85. package/comandos/swl/planear-fase.md +263 -263
  86. package/comandos/swl/plugins.md +256 -256
  87. package/comandos/swl/predecir.md +169 -169
  88. package/comandos/swl/reflect-skills.md +125 -125
  89. package/comandos/swl/release.md +450 -450
  90. package/comandos/swl/revisar-impacto.md +201 -201
  91. package/comandos/swl/revisar.md +330 -330
  92. package/comandos/swl/seguridad.md +189 -189
  93. package/comandos/swl/sesiones.md +200 -200
  94. package/comandos/swl/skill-search.md +113 -113
  95. package/comandos/swl/status.md +345 -345
  96. package/comandos/swl/verificar.md +817 -817
  97. package/comandos/swl/wiki.md +620 -620
  98. package/gateway/cron/jobs.example.json +12 -12
  99. package/gateway/lib/event-channel.js +191 -191
  100. package/habilidades/agent-deep-links/SKILL.md +148 -148
  101. package/habilidades/auto-evolucion-protocolo/SKILL.md +294 -294
  102. package/habilidades/backend-async-postgres-testing/SKILL.md +216 -215
  103. package/habilidades/backend-error-design/SKILL.md +221 -221
  104. package/habilidades/backend-production-resilience/SKILL.md +288 -288
  105. package/habilidades/calidad-anti-patrones-universales/SKILL.md +105 -1
  106. package/habilidades/calidad-contract-testing/SKILL.md +165 -165
  107. package/habilidades/calidad-mutation-testing/SKILL.md +25 -1
  108. package/habilidades/changelog-generator/SKILL.md +174 -174
  109. package/habilidades/checklist-seguridad/recursos/stride-cobertura.md +60 -60
  110. package/habilidades/ci-cd-pipelines/SKILL.md +5 -1
  111. package/habilidades/compactacion-contexto/SKILL.md +2 -1
  112. package/habilidades/contenedores-docker/SKILL.md +4 -2
  113. package/habilidades/css-moderno/SKILL.md +7 -1
  114. package/habilidades/diagrama-arquitectura/assets/template.html +276 -276
  115. package/habilidades/doubt-driven-review/SKILL.md +207 -207
  116. package/habilidades/doubt-driven-review/recursos/EXAMPLES.md +130 -130
  117. package/habilidades/drift-detection/SKILL.md +1 -1
  118. package/habilidades/ejecutar-task-iterativo/SKILL.md +278 -278
  119. package/habilidades/estructura-proyecto-claude/recursos/mcp-json-template.json +57 -57
  120. package/habilidades/extractor-de-aprendizajes/SKILL.md +12 -2
  121. package/habilidades/feynman-auditor-swl/recursos/preguntas-language-agnostic.md +108 -108
  122. package/habilidades/git-worktrees-paralelo/SKILL.md +19 -1
  123. package/habilidades/harness-claude-code/SKILL.md +315 -314
  124. package/habilidades/instalar-sistema/SKILL.md +227 -227
  125. package/habilidades/meta-skills-estandar/recursos/convencion-examples.md +93 -93
  126. package/habilidades/patrones-python/recursos/patrones-avanzados.md +469 -469
  127. package/habilidades/perfil-usuario/SKILL.md +200 -200
  128. package/habilidades/planear-fase/SKILL.md +358 -358
  129. package/habilidades/prevencion-sobreingenieria/recursos/EXAMPLES.md +580 -580
  130. package/habilidades/proceso-ddia-streaming/SKILL.md +231 -231
  131. package/habilidades/proceso-discovery-machote/SKILL.md +157 -157
  132. package/habilidades/proceso-dynamic-workflows/SKILL.md +60 -0
  133. package/habilidades/proceso-dynamic-workflows/recursos/template-adversarial-verify.js +65 -65
  134. package/habilidades/proceso-dynamic-workflows/recursos/template-triage.js +65 -65
  135. package/habilidades/proceso-ingenieria-requerimientos/SKILL.md +147 -147
  136. package/habilidades/proceso-intent-engineering/SKILL.md +269 -269
  137. package/habilidades/proceso-modular-split/SKILL.md +256 -256
  138. package/habilidades/release-semver/SKILL.md +2 -2
  139. package/habilidades/state-inconsistency-auditor-swl/recursos/coupled-state-patterns.md +147 -147
  140. package/habilidades/swl-claudemd/recursos/contrato-aprender.md +83 -83
  141. package/habilidades/swl-claudemd/recursos/duplicacion-reglas-globales.md +85 -85
  142. package/habilidades/swl-claudemd/recursos/plantillas-init.md +94 -94
  143. package/habilidades/tdd-workflow/SKILL.md +749 -749
  144. package/habilidades/tdd-workflow/recursos/gherkin-bdd.md +111 -111
  145. package/hooks/agente-lifecycle.js +1 -1
  146. package/hooks/audit-trail.js +1 -1
  147. package/hooks/auto-consolidacion.js +1 -1
  148. package/hooks/calidad-pre-commit.js +159 -10
  149. package/hooks/captura-acciones-post.js +1 -1
  150. package/hooks/captura-acciones-session.js +1 -1
  151. package/hooks/captura-feedback-usuario.js +1 -1
  152. package/hooks/ciclo-evolucion-subagente.js +26 -26
  153. package/hooks/ciclo-evolucion.js +26 -26
  154. package/hooks/contexto-iteracion.js +1 -1
  155. package/hooks/degradacion-instintos.js +1 -1
  156. package/hooks/grafo-contexto.js +1 -1
  157. package/hooks/guardrail-modelo.js +1 -1
  158. package/hooks/inbox-aviso.js +1 -1
  159. package/hooks/inyeccion-contexto.js +1 -1
  160. package/hooks/lib/agent-matcher.js +1 -1
  161. package/hooks/lib/agent-routing.js +1 -1
  162. package/hooks/lib/auto-consolidator.js +335 -335
  163. package/hooks/lib/captura-acciones.js +1 -1
  164. package/hooks/lib/ciclo-evolucion.js +47 -47
  165. package/hooks/lib/deep-links.js +185 -185
  166. package/hooks/lib/error-classifier.js +308 -308
  167. package/hooks/lib/etapa-metricas.js +1 -1
  168. package/hooks/lib/evolution-tracker.js +1 -1
  169. package/hooks/lib/gateway-notify.js +193 -193
  170. package/hooks/lib/mcp-health.js +1 -1
  171. package/hooks/lib/notificacion-formato.js +92 -0
  172. package/hooks/lib/nudge-tracker.js +1 -1
  173. package/hooks/lib/otlp-exporter.js +1 -1
  174. package/hooks/lib/propose-step.js +1 -1
  175. package/hooks/lib/provenance-tracker.js +191 -191
  176. package/hooks/lib/raiz-proyecto.js +158 -102
  177. package/hooks/lib/resource-quota.js +122 -122
  178. package/hooks/lib/retry-jitter.js +165 -165
  179. package/hooks/lib/run-log.js +1 -1
  180. package/hooks/lib/security-net.js +201 -201
  181. package/hooks/lib/singleton-guard.js +20 -13
  182. package/hooks/lib/skill-auditor.js +588 -588
  183. package/hooks/lib/sync-status.js +228 -228
  184. package/hooks/lib/taint-tracker.js +107 -107
  185. package/hooks/lib/telegram-cliente.js +11 -3
  186. package/hooks/lib/text-similarity.js +241 -241
  187. package/hooks/lib/toon-compressor.js +245 -245
  188. package/hooks/notificacion-telegram.js +17 -13
  189. package/hooks/preservar-estado-pre-compact.js +1 -1
  190. package/hooks/registro-turnos.js +1 -1
  191. package/hooks/resumen-sesion.js +1 -1
  192. package/hooks/risk-scoring.js +1 -1
  193. package/hooks/session-briefing.js +13 -5
  194. package/hooks/spec-gate.js +1 -1
  195. package/hooks/sugerir-regenerar-inventario.js +1 -1
  196. package/hooks/tdd-gate.js +1 -1
  197. package/hooks/telemetria-agentes.js +1 -1
  198. package/hooks/telemetria-skill-routing.js +1 -1
  199. package/hooks/tracking-costos.js +1 -1
  200. package/hooks/validar-formato-post-subagente.js +1 -1
  201. package/hooks/validar-intent-spec.js +1 -1
  202. package/hooks/validar-planning-paths.js +1 -1
  203. package/instintos/autonomia.yaml +27 -27
  204. package/instintos/prompt-appendices.yaml +57 -57
  205. package/llms.txt +29 -29
  206. package/manifiestos/agent-output-schemas.json +57 -57
  207. package/manifiestos/canonical-hashes.json +6250 -5257
  208. package/manifiestos/harness-ir.json +47536 -0
  209. package/manifiestos/modulos.json +1429 -1428
  210. package/manifiestos/policy-bundle.json +2065 -0
  211. package/manifiestos/policy-corpus-w2.json +3926 -0
  212. package/manifiestos/runtime-adapters-core3.json +208 -0
  213. package/manifiestos/runtime-conformance.json +139 -0
  214. package/manifiestos/skills-lock.json +1275 -1275
  215. package/package.json +94 -94
  216. package/plantillas/auditor-veto-template.md +105 -105
  217. package/plantillas/github-workflows/release-please.yml +44 -44
  218. package/plantillas/github-workflows/swl-ci.yml +107 -107
  219. package/plantillas/github-workflows/swl-security.yml +51 -51
  220. package/plugin.json +369 -369
  221. package/reglas/accesibilidad.md +10 -10
  222. package/reglas/auditorias-documentales-estructurales.md +7 -7
  223. package/reglas/cloud-infra.md +8 -8
  224. package/reglas/consultar-vault-primero.md +195 -195
  225. package/reglas/git-workflow.md +1 -0
  226. package/reglas/hooks.md +6 -6
  227. package/reglas/intent-engineering.md +218 -218
  228. package/reglas/markitdown.md +8 -8
  229. package/reglas/monitor-ci.md +12 -0
  230. package/reglas/patrones.md +6 -6
  231. package/reglas/testing.md +7 -7
  232. package/reglas/tests-cleanup.md +224 -224
  233. package/schemas/agent-message.schema.json +73 -73
  234. package/schemas/agent-output-implementacion.schema.json +114 -114
  235. package/schemas/agent-output-planificacion.schema.json +150 -150
  236. package/schemas/agent-output-review.schema.json +98 -98
  237. package/schemas/diary-entry.schema.json +112 -112
  238. package/schemas/gate-state.schema.json +76 -0
  239. package/schemas/harness-ir.schema.json +369 -0
  240. package/schemas/hook-profiles.schema.json +54 -54
  241. package/schemas/hooks-config.schema.json +89 -89
  242. package/schemas/legacy-gates.schema.json +45 -0
  243. package/schemas/modulos.schema.json +38 -38
  244. package/schemas/perfiles.schema.json +36 -36
  245. package/schemas/plugin.schema.json +77 -77
  246. package/schemas/policy-bundle.schema.json +140 -0
  247. package/schemas/policy-enforcement.schema.json +117 -0
  248. package/schemas/policy-operation.schema.json +261 -0
  249. package/schemas/runtime-adapter.schema.json +176 -0
  250. package/schemas/runtime-build-attestation.schema.json +100 -0
  251. package/schemas/runtime-conformance.schema.json +239 -0
  252. package/schemas/runtime-diagnostic.schema.json +395 -0
  253. package/schemas/skill-evals.schema.json +119 -119
  254. package/schemas/skill-frontmatter.schema.json +245 -245
  255. package/schemas/w4-certification-request.schema.json +72 -0
  256. package/schemas/w4-certification-verdict.schema.json +224 -0
  257. package/schemas/w4-corpus.schema.json +172 -0
  258. package/schemas/w4-mutation-report.schema.json +116 -0
  259. package/schemas/w4-replay-result.schema.json +164 -0
  260. package/schemas/w4-scoring-report.schema.json +89 -0
  261. package/scripts/audit-tools/audit-history.js +330 -330
  262. package/scripts/audit-tools/bundle-tracker.js +290 -290
  263. package/scripts/audit-tools/canary-monitor.js +352 -352
  264. package/scripts/audit-tools/code-profiler.js +605 -605
  265. package/scripts/audit-tools/dep-doctor.js +320 -320
  266. package/scripts/audit-tools/env-validator.js +206 -206
  267. package/scripts/audit-tools/lib/fs-walk.js +48 -48
  268. package/scripts/audit-tools/lib/output.js +23 -23
  269. package/scripts/audit-tools/migration-checker.js +392 -392
  270. package/scripts/audit-tools/pentest-scanner.js +1436 -1436
  271. package/scripts/auditar-clases-conocidas.js +134 -134
  272. package/scripts/bootstrap-instintos.js +88 -14
  273. package/scripts/canario-hooks.js +166 -166
  274. package/scripts/cli/aprobar-plan.js +73 -73
  275. package/scripts/cli/autonomia.js +23 -23
  276. package/scripts/cli/benchmark-memoria.js +37 -37
  277. package/scripts/cli/briefing.js +23 -23
  278. package/scripts/cli/ciclo-autonomo.js +73 -73
  279. package/scripts/cli/ciclo-evolucion.js +26 -26
  280. package/scripts/cli/ciclo-fase-b.js +102 -102
  281. package/scripts/cli/derivar-feature-list.js +25 -25
  282. package/scripts/cli/detectar-host.js +27 -27
  283. package/scripts/cli/diary-entry.js +69 -69
  284. package/scripts/cli/execution-state.js +18 -18
  285. package/scripts/cli/gateway-notify.js +41 -41
  286. package/scripts/cli/guardrail-metrics.js +39 -39
  287. package/scripts/cli/liberar-fase.js +42 -42
  288. package/scripts/cli/mark-evolved.js +56 -56
  289. package/scripts/cli/memoria-search.js +69 -69
  290. package/scripts/cli/metricas-dora.js +26 -26
  291. package/scripts/cli/near-duplicate.js +55 -55
  292. package/scripts/cli/notificaciones.js +123 -123
  293. package/scripts/cli/nudge-accionar.js +39 -39
  294. package/scripts/cli/propose-step.js +29 -29
  295. package/scripts/cli/run-eval.js +38 -38
  296. package/scripts/cli/schedule-parse.js +19 -19
  297. package/scripts/cli/sugerir-modelo.js +20 -20
  298. package/scripts/cli/verificar-plan.js +36 -36
  299. package/scripts/cli/verificar-trazabilidad.js +35 -35
  300. package/scripts/comandos/install-asistido.js +8 -7
  301. package/scripts/configurar-branch-protection.js +418 -418
  302. package/scripts/detectar-aprendizajes-duplicados.js +151 -151
  303. package/scripts/doctor.js +61 -13
  304. package/scripts/evidencia-valor.js +101 -101
  305. package/scripts/field-report.js +16 -16
  306. package/scripts/generar-checklists-consolidados.js +273 -273
  307. package/scripts/generar-claims-runtime.js +1342 -0
  308. package/scripts/generar-harness-ir.js +257 -0
  309. package/scripts/generar-inventario.js +52 -54
  310. package/scripts/generar-policy-bundle.js +202 -0
  311. package/scripts/instalador.js +39 -7
  312. package/scripts/lib/activar-hooks-proyecto.js +116 -116
  313. package/scripts/lib/approval-receipts.js +190 -0
  314. package/scripts/lib/artefactos-python.js +43 -43
  315. package/scripts/lib/benchmark-metrics.js +160 -160
  316. package/scripts/lib/budget-enforcer.js +252 -252
  317. package/scripts/lib/certificacion-loop-state.js +421 -0
  318. package/scripts/lib/ci-reader.js +193 -193
  319. package/scripts/lib/ciclo-autonomo/candidatos.js +174 -174
  320. package/scripts/lib/ciclo-autonomo/config.js +165 -165
  321. package/scripts/lib/ciclo-autonomo/drenador-feedback.js +174 -174
  322. package/scripts/lib/ciclo-autonomo/fallback.js +77 -77
  323. package/scripts/lib/ciclo-autonomo/guard-convivencia.js +139 -139
  324. package/scripts/lib/ciclo-autonomo/higiene-nudges.js +112 -112
  325. package/scripts/lib/ciclo-autonomo/index.js +301 -301
  326. package/scripts/lib/ciclo-autonomo/lock.js +124 -124
  327. package/scripts/lib/ciclo-autonomo/presupuesto.js +122 -122
  328. package/scripts/lib/ciclo-autonomo/puente-degradacion.js +240 -240
  329. package/scripts/lib/ciclo-autonomo/runner-fase-b.js +248 -248
  330. package/scripts/lib/ciclo-autonomo/writer-instintos.js +190 -190
  331. package/scripts/lib/ciclo-autonomo/yaml-instintos.js +591 -535
  332. package/scripts/lib/clasificar-directorio.js +92 -0
  333. package/scripts/lib/contadores-inventario.js +217 -217
  334. package/scripts/lib/detectar-host-swl.js +175 -175
  335. package/scripts/lib/detectar-runtime.js +29 -20
  336. package/scripts/lib/detectar-stack-detallado.js +307 -307
  337. package/scripts/lib/detector-autoduplicacion-intra-archivo.js +234 -234
  338. package/scripts/lib/detector-reglas-duplicadas.js +220 -220
  339. package/scripts/lib/eval-metrics-store.js +218 -218
  340. package/scripts/lib/eval-quality.js +171 -171
  341. package/scripts/lib/eval-schemas.js +144 -144
  342. package/scripts/lib/eval-self-correct.js +106 -106
  343. package/scripts/lib/eval-validator.js +185 -185
  344. package/scripts/lib/evidence-verifier.js +192 -0
  345. package/scripts/lib/evidencia-release.js +322 -322
  346. package/scripts/lib/evidencia-valor.js +228 -228
  347. package/scripts/lib/expandir-targets.js +71 -71
  348. package/scripts/lib/frontmatter-canonico.js +509 -0
  349. package/scripts/lib/gate-engine.js +871 -0
  350. package/scripts/lib/gate-hooks-requires.js +249 -249
  351. package/scripts/lib/gate-licencias.js +212 -212
  352. package/scripts/lib/git-config-preflight.js +48 -0
  353. package/scripts/lib/git-metricas.js +257 -257
  354. package/scripts/lib/harness-ir.js +778 -0
  355. package/scripts/lib/harness-source-snapshot.js +309 -0
  356. package/scripts/lib/integrity-ledger.js +1147 -0
  357. package/scripts/lib/jaccard-similarity.js +98 -98
  358. package/scripts/lib/legacy-gate-migration.js +324 -0
  359. package/scripts/lib/limpiar-basura-global.js +204 -0
  360. package/scripts/lib/longmemeval-runner.js +125 -125
  361. package/scripts/lib/metricas-dora.js +204 -204
  362. package/scripts/lib/notificaciones-telegram.js +1 -0
  363. package/scripts/lib/npm-version.js +1 -0
  364. package/scripts/lib/paquetes-conocidos.js +50 -50
  365. package/scripts/lib/plan-lock.js +61 -13
  366. package/scripts/lib/policy-broker.js +338 -0
  367. package/scripts/lib/policy-bundle.js +342 -0
  368. package/scripts/lib/policy-context-provider.js +310 -0
  369. package/scripts/lib/policy-contract.js +479 -0
  370. package/scripts/lib/policy-verifier-utils.js +65 -0
  371. package/scripts/lib/pr-analyzer.js +399 -399
  372. package/scripts/lib/principal-verifier.js +178 -0
  373. package/scripts/lib/prompt-builder.js +264 -264
  374. package/scripts/lib/resolver-plan-fase.js +37 -37
  375. package/scripts/lib/rrf-fusion.js +175 -175
  376. package/scripts/lib/runtime-adapter-contract.js +267 -0
  377. package/scripts/lib/runtime-artifact-verifier.js +426 -0
  378. package/scripts/lib/runtime-build-attestation.js +127 -0
  379. package/scripts/lib/runtime-bundle-installer.js +586 -0
  380. package/scripts/lib/runtime-compiler.js +327 -0
  381. package/scripts/lib/runtime-conformance.js +202 -0
  382. package/scripts/lib/runtime-doctor-core3.js +567 -0
  383. package/scripts/lib/runtime-doctor-input.js +59 -0
  384. package/scripts/lib/runtime-operation-adapter.js +267 -0
  385. package/scripts/lib/schema-version.js +164 -164
  386. package/scripts/lib/semantic-search.js +252 -252
  387. package/scripts/lib/signed-envelope.js +545 -0
  388. package/scripts/lib/single-use-store.js +359 -0
  389. package/scripts/lib/skills-externas.js +31 -0
  390. package/scripts/lib/toml-merge.js +204 -204
  391. package/scripts/lib/transformadores/codex.js +15 -8
  392. package/scripts/lib/transformadores/gemini.js +79 -5
  393. package/scripts/lib/w4-attestation-adapter.js +158 -0
  394. package/scripts/lib/w4-canario.js +337 -0
  395. package/scripts/lib/w4-claims.js +182 -0
  396. package/scripts/lib/w4-corpus-generador.js +542 -0
  397. package/scripts/lib/w4-gate-c5.js +115 -0
  398. package/scripts/lib/w4-harness-bajo-prueba.js +155 -0
  399. package/scripts/lib/w4-matriz-combos.js +55 -0
  400. package/scripts/lib/w4-motor-mutacion.js +1348 -0
  401. package/scripts/lib/w4-motor-replay.js +735 -0
  402. package/scripts/lib/w4-pin-origen.js +54 -0
  403. package/scripts/lib/w4-publicar-request.js +132 -0
  404. package/scripts/lib/w4-revocacion.js +62 -0
  405. package/scripts/lib/w4-runtimes-core3.js +38 -0
  406. package/scripts/lib/w4-scorer-certificacion.js +692 -0
  407. package/scripts/lib/w4-superficie-candidato.js +49 -0
  408. package/scripts/lib/w4-veredicto.js +452 -0
  409. package/scripts/lib/w4-verificar-veredicto.js +302 -0
  410. package/scripts/limpiar-artefactos-python.js +131 -131
  411. package/scripts/mcp-server/auth.js +105 -105
  412. package/scripts/mcp-server/cache.js +106 -106
  413. package/scripts/migrar-csv-a-array.js +168 -168
  414. package/scripts/migrar-fase-dominio.js +200 -200
  415. package/scripts/migrar-gates-legacy.js +108 -0
  416. package/scripts/publicar-certification-request.js +115 -0
  417. package/scripts/runtime-doctor.js +107 -0
  418. package/scripts/tui/componentes/selector-multi.js +189 -189
  419. package/scripts/tui/componentes/selector-unico.js +158 -158
  420. package/scripts/tui/ejecutores.js +375 -375
  421. package/scripts/tui/lib/colores.js +129 -129
  422. package/scripts/tui/lib/render.js +264 -264
  423. package/scripts/tui/lib/teclas.js +113 -113
  424. package/scripts/tui/pantallas/install-wizard.js +408 -403
  425. package/scripts/tui/pantallas/menu-principal.js +52 -52
  426. package/scripts/tui/pantallas/progreso.js +274 -274
  427. package/scripts/tui/pantallas/resumen.js +132 -132
  428. package/scripts/validar-userland-vacio.js +110 -110
  429. package/scripts/verificar-aislamiento-swl-eval.js +87 -0
  430. package/scripts/verificar-empaquetado-downstream.js +375 -0
  431. package/scripts/verificar-loop-constructor.js +215 -0
  432. package/scripts/verificar-trazabilidad.js +13 -6
  433. package/scripts/verificar-veredicto-real.js +84 -0
  434. package/instintos/.backups/perfil-usuario.yaml.2026-07-10-165128.bak +0 -53
  435. package/instintos/.backups/proyecto.yaml.2026-07-10-165128.bak +0 -372
@@ -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();