@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,778 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Compilador diagnóstico del Harness IR sobre fuentes tracked y confinadas.
5
+ * La normalización semántica se incorpora en la siguiente oleada de la Fase 29.
6
+ */
7
+
8
+ const SCHEMA = require('../../schemas/harness-ir.schema.json');
9
+ const crypto = require('node:crypto');
10
+
11
+ const { capturarHarnessSourceSnapshot } = require('./harness-source-snapshot');
12
+ const { CENTINELA_TODOS, SKILLS_EXTERNAS_SET } = require('./skills-externas');
13
+
14
+ const HOOKS_CONFIG = 'manifiestos/hooks-config.json';
15
+ const TIPOS = Object.freeze(['agent', 'command', 'skill', 'rule']);
16
+ const CAPABILITIES = Object.freeze([
17
+ 'delegate',
18
+ 'filesystem.mutate',
19
+ 'filesystem.read',
20
+ 'memory.read',
21
+ 'memory.write',
22
+ 'network.access',
23
+ 'shell.exec',
24
+ 'skill.invoke',
25
+ ]);
26
+ const TOOL_MAP = Object.freeze({
27
+ Agent: 'delegate',
28
+ Bash: 'shell.exec',
29
+ Edit: 'filesystem.mutate',
30
+ Glob: 'filesystem.read',
31
+ Grep: 'filesystem.read',
32
+ MultiEdit: 'filesystem.mutate',
33
+ Read: 'filesystem.read',
34
+ Skill: 'skill.invoke',
35
+ Task: 'delegate',
36
+ WebFetch: 'network.access',
37
+ WebSearch: 'network.access',
38
+ Write: 'filesystem.mutate',
39
+ });
40
+ const EVENT_MAP = Object.freeze({
41
+ PostToolUse: 'after_tool',
42
+ PreToolUse: 'before_tool',
43
+ SessionStart: 'session_start',
44
+ Stop: 'stop',
45
+ SubagentStart: 'before_agent',
46
+ SubagentStop: 'after_agent',
47
+ });
48
+ const EVENTOS_FUERA_V1 = new Set(['Notification', 'PreCompact', 'UserPromptSubmit']);
49
+ const RISK_MAP = Object.freeze({ ALTO: 'high', BAJO: 'low', MEDIO: 'medium' });
50
+ const TIER_MAP = Object.freeze({
51
+ fable: 'frontier',
52
+ haiku: 'light',
53
+ opus: 'critical',
54
+ sonnet: 'standard',
55
+ });
56
+ const TIER_DEFINITIONS = Object.freeze([
57
+ {
58
+ id: 'critical',
59
+ requirements: [
60
+ { key: 'reasoning', value: 'strong' },
61
+ { key: 'structuredOutput', value: 'required' },
62
+ { key: 'errorTolerance', value: 'low' },
63
+ ],
64
+ unresolvedDisposition: 'stop',
65
+ },
66
+ {
67
+ id: 'frontier',
68
+ requirements: [
69
+ { key: 'reasoning', value: 'maximum_available' },
70
+ { key: 'toolUse', value: 'required' },
71
+ { key: 'context', value: 'wide' },
72
+ ],
73
+ unresolvedDisposition: 'stop',
74
+ },
75
+ {
76
+ id: 'light',
77
+ requirements: [
78
+ { key: 'latency', value: 'low' },
79
+ { key: 'cost', value: 'low' },
80
+ { key: 'outputSchema', value: 'simple' },
81
+ ],
82
+ unresolvedDisposition: 'unresolved_in_w1',
83
+ },
84
+ {
85
+ id: 'standard',
86
+ requirements: [
87
+ { key: 'toolUse', value: 'reliable' },
88
+ { key: 'costLatency', value: 'balanced' },
89
+ ],
90
+ unresolvedDisposition: 'unresolved_in_w1',
91
+ },
92
+ ]);
93
+ const ALLOWLISTS = Object.freeze({
94
+ agent: new Set([
95
+ 'color', 'description', 'dominio', 'evolvable', 'evolvable_scope', 'exclusiones',
96
+ 'fase', 'fragmentos', 'hardGuardrails', 'healthMetrics', 'invariantes', 'maxTurnos',
97
+ 'model', 'modeloAlterno', 'name', 'nivelRiesgo', 'permisosComandos',
98
+ 'permisosEscritura', 'permisosRed', 'permissionMode', 'skillsInvocables',
99
+ 'skillsRestringidos', 'steering', 'strategy', 'toolBudget', 'tools',
100
+ 'ventanaContexto', 'version',
101
+ ]),
102
+ command: new Set([
103
+ 'allowed-tools', 'allowed_tools', 'argument-hint', 'description', 'name', 'tipo',
104
+ 'user-invocable', 'version',
105
+ ]),
106
+ rule: new Set(['paths']),
107
+ skill: new Set([
108
+ 'atlas_techniques', 'attack_techniques', 'author', 'd3fend_techniques',
109
+ 'dependencias', 'deprecated', 'deprecated-reason', 'deprecated-replacement',
110
+ 'deprecated-since', 'description', 'domain', 'evolvable', 'evolvable_scope',
111
+ 'evolved', 'exclusiones', 'fuente', 'herramientasPermitidas', 'license', 'name',
112
+ 'nist_ai_rmf', 'nist_csf', 'nivelRiesgo', 'provenance', 'skillsInvocables',
113
+ 'tags', 'toolsRequeridos', 'user-invocable', 'version', 'when_to_use',
114
+ ]),
115
+ });
116
+ const LOCATOR_ONLY = Object.freeze({
117
+ agent: new Set([...ALLOWLISTS.agent].filter((clave) => ![
118
+ 'description', 'model', 'name', 'nivelRiesgo', 'skillsInvocables', 'tools',
119
+ ].includes(clave))),
120
+ command: new Set(['tipo', 'user-invocable', 'version']),
121
+ rule: new Set([]),
122
+ skill: new Set([...ALLOWLISTS.skill].filter((clave) => !['description', 'name'].includes(clave))),
123
+ });
124
+ const TAINT_TERMS_V1 = Object.freeze([
125
+ 'anthropic', 'claude', 'claude-code', 'claude-api', 'openai', 'codex', 'gemini',
126
+ 'google', 'cursor', 'copilot', 'github-copilot', 'opencode', 'openclaude',
127
+ 'fable', 'opus', 'sonnet', 'haiku', 'read', 'write', 'edit', 'multiedit', 'bash',
128
+ 'grep', 'glob', 'agent', 'task', 'skill', 'websearch', 'webfetch', 'sessionstart',
129
+ 'pretooluse', 'posttooluse', 'subagentstart', 'subagentstop', 'stop',
130
+ 'userpromptsubmit', 'precompact', 'notification',
131
+ ]);
132
+ const CONFUSABLES_V1 = Object.freeze({
133
+ 'Α': 'a', 'Β': 'b', 'Ε': 'e', 'Η': 'h', 'Ι': 'i', 'Κ': 'k', 'Μ': 'm', 'Ν': 'n',
134
+ 'Ο': 'o', 'Ρ': 'p', 'Τ': 't', 'Χ': 'x', 'а': 'a', 'с': 'c', 'е': 'e', 'і': 'i',
135
+ 'ι': 'i', 'о': 'o', 'ο': 'o', 'р': 'p', 'ρ': 'p', 'ѕ': 's', 'х': 'x', 'χ': 'x',
136
+ 'у': 'y', 'υ': 'y',
137
+ });
138
+
139
+ function resolverRef(referencia) {
140
+ return referencia.slice(2).split('/').reduce((actual, token) => {
141
+ const clave = token.replaceAll('~1', '/').replaceAll('~0', '~');
142
+ return actual[clave];
143
+ }, SCHEMA);
144
+ }
145
+
146
+ function coincideTipo(tipo, valor) {
147
+ if (tipo === 'null') return valor === null;
148
+ if (tipo === 'array') return Array.isArray(valor);
149
+ if (tipo === 'object') {
150
+ return valor !== null && typeof valor === 'object' && !Array.isArray(valor);
151
+ }
152
+ if (tipo === 'integer') return Number.isInteger(valor);
153
+ return typeof valor === tipo;
154
+ }
155
+
156
+ function error(errores, ruta, codigo) {
157
+ errores.push({ path: ruta, code: codigo });
158
+ }
159
+
160
+ function validarObjeto(definicion, valor, ruta, errores) {
161
+ const propiedades = definicion.properties;
162
+ for (const requerida of definicion.required) {
163
+ if (!Object.hasOwn(valor, requerida)) error(errores, `${ruta}/${requerida}`, 'required');
164
+ }
165
+ for (const clave of Object.keys(valor)) {
166
+ if (!Object.hasOwn(propiedades, clave)) error(errores, `${ruta}/${clave}`, 'additional');
167
+ }
168
+ for (const [clave, hija] of Object.entries(propiedades)) {
169
+ if (Object.hasOwn(valor, clave)) validar(hija, valor[clave], `${ruta}/${clave}`, errores);
170
+ }
171
+ }
172
+
173
+ function validarLimites(definicion, valor, ruta, errores) {
174
+ if (definicion.minimum !== undefined && valor < definicion.minimum) {
175
+ error(errores, ruta, 'minimum');
176
+ }
177
+ if (definicion.maximum !== undefined && valor > definicion.maximum) {
178
+ error(errores, ruta, 'maximum');
179
+ }
180
+ if (definicion.maxItems !== undefined && valor.length > definicion.maxItems) {
181
+ error(errores, ruta, 'maxItems');
182
+ }
183
+ if (definicion.minItems !== undefined && valor.length < definicion.minItems) {
184
+ error(errores, ruta, 'minItems');
185
+ }
186
+ }
187
+
188
+ function validarRestricciones(definicion, valor, ruta, errores) {
189
+ if (definicion.const !== undefined && valor !== definicion.const) error(errores, ruta, 'const');
190
+ if (definicion.enum && !definicion.enum.includes(valor)) error(errores, ruta, 'enum');
191
+ if (definicion.pattern) {
192
+ if (!new RegExp(definicion.pattern, 'u').test(valor)) error(errores, ruta, 'pattern');
193
+ }
194
+ validarLimites(definicion, valor, ruta, errores);
195
+ }
196
+
197
+ function validarOneOf(opciones, valor, ruta, errores) {
198
+ const coincidencias = opciones.filter((opcion) => {
199
+ const locales = [];
200
+ validar(opcion, valor, ruta, locales);
201
+ return locales.length === 0;
202
+ });
203
+ if (coincidencias.length !== 1) error(errores, ruta, 'oneOf');
204
+ }
205
+
206
+ function validar(definicion, valor, ruta, errores) {
207
+ if (definicion.$ref) return validar(resolverRef(definicion.$ref), valor, ruta, errores);
208
+ if (definicion.oneOf) {
209
+ validarOneOf(definicion.oneOf, valor, ruta, errores);
210
+ return;
211
+ }
212
+ if (definicion.type && !coincideTipo(definicion.type, valor)) {
213
+ error(errores, ruta, 'type');
214
+ return;
215
+ }
216
+ validarRestricciones(definicion, valor, ruta, errores);
217
+ if (definicion.type === 'object') validarObjeto(definicion, valor, ruta, errores);
218
+ if (definicion.type === 'array') {
219
+ valor.forEach((item, indice) => validar(definicion.items, item, `${ruta}/${indice}`, errores));
220
+ }
221
+ }
222
+
223
+ function validarContrato(valor) {
224
+ const errors = [];
225
+ validar(SCHEMA, valor, '$', errors);
226
+ return { ok: errors.length === 0, errors };
227
+ }
228
+
229
+ function crearErrorHarness(codigo, mensaje, extras = {}) {
230
+ const excepcion = new Error(mensaje);
231
+ Object.assign(excepcion, { codigo, ...extras });
232
+ return excepcion;
233
+ }
234
+
235
+ function sha256(valor) {
236
+ return crypto.createHash('sha256').update(valor).digest('hex');
237
+ }
238
+
239
+ function clavesExactas(valor, requeridas, opcionales = []) {
240
+ if (!valor || typeof valor !== 'object' || Array.isArray(valor)) return false;
241
+ const permitidas = new Set([...requeridas, ...opcionales]);
242
+ return requeridas.every((clave) => Object.hasOwn(valor, clave))
243
+ && Object.keys(valor).every((clave) => permitidas.has(clave));
244
+ }
245
+
246
+ function validarObjetoTipos(valor, tipos) {
247
+ return Object.entries(tipos).every(([clave, tipo]) => {
248
+ if (tipo === 'array:string') {
249
+ return Array.isArray(valor[clave]) && valor[clave].every((item) => typeof item === 'string');
250
+ }
251
+ if (tipo === 'integer') return Number.isInteger(valor[clave]);
252
+ return typeof valor[clave] === tipo;
253
+ });
254
+ }
255
+
256
+ function validarRaizHooks(config) {
257
+ const claves = [
258
+ 'descripcion',
259
+ 'prioridad_hooks',
260
+ 'opciones_avanzadas_hooks',
261
+ 'riskThresholds',
262
+ 'costBudget',
263
+ 'circuitBreaker',
264
+ 'hooks',
265
+ ];
266
+ return clavesExactas(config, claves)
267
+ && typeof config.descripcion === 'string'
268
+ && clavesExactas(config.prioridad_hooks, ['descripcion', 'orden', 'regla'])
269
+ && validarObjetoTipos(config.prioridad_hooks, {
270
+ descripcion: 'string',
271
+ orden: 'array:string',
272
+ regla: 'string',
273
+ });
274
+ }
275
+
276
+ function validarOpcionesHooks(config) {
277
+ const opciones = config.opciones_avanzadas_hooks;
278
+ const thresholds = config.riskThresholds;
279
+ const budget = config.costBudget;
280
+ const breaker = config.circuitBreaker;
281
+ return clavesExactas(opciones, ['descripcion', 'timeout', 'async', 'once'])
282
+ && validarObjetoTipos(opciones, {
283
+ descripcion: 'string', timeout: 'string', async: 'string', once: 'string',
284
+ })
285
+ && clavesExactas(thresholds, ['allow', 'review', 'confirm'])
286
+ && validarObjetoTipos(thresholds, { allow: 'number', review: 'number', confirm: 'number' })
287
+ && clavesExactas(budget, ['maxUsd', 'maxTokens', 'alertAt'])
288
+ && validarObjetoTipos(budget, { maxUsd: 'number', maxTokens: 'integer', alertAt: 'number' })
289
+ && clavesExactas(breaker, ['maxConsecutiveFailures', 'halfOpenCooldownMs', 'auditThreshold'])
290
+ && validarObjetoTipos(breaker, {
291
+ maxConsecutiveFailures: 'integer',
292
+ halfOpenCooldownMs: 'integer',
293
+ auditThreshold: 'integer',
294
+ });
295
+ }
296
+
297
+ function validarEntradaHook(entrada) {
298
+ const requeridas = ['event', 'matcher', 'description', 'blocking'];
299
+ const opcionales = ['async', 'optIn', 'maxConsecutiveFailures', 'degradeOnFailure'];
300
+ if (!clavesExactas(entrada, requeridas, opcionales)) return false;
301
+ if (!validarObjetoTipos(entrada, {
302
+ event: 'string', matcher: 'string', description: 'string', blocking: 'boolean',
303
+ })) return false;
304
+ const tiposOpcionales = {
305
+ async: 'boolean',
306
+ optIn: 'string',
307
+ maxConsecutiveFailures: 'integer',
308
+ degradeOnFailure: 'string',
309
+ };
310
+ return Object.entries(tiposOpcionales).every(([clave, tipo]) => (
311
+ entrada[clave] === undefined || validarObjetoTipos(entrada, { [clave]: tipo })
312
+ ));
313
+ }
314
+
315
+ function validarHooksParseados(parsed) {
316
+ const config = parsed.valor;
317
+ const hooksValidos = validarRaizHooks(config)
318
+ && validarOpcionesHooks(config)
319
+ && clavesExactas(config.hooks, [], Object.keys(config.hooks))
320
+ && Object.values(config.hooks).every(validarEntradaHook);
321
+ if (!hooksValidos) throw crearErrorHarness('HOOKS_CONFIG_INVALID', 'Shape de hooks inválido');
322
+ return { config, propiedades: parsed.propiedades };
323
+ }
324
+
325
+ function locatorArchivo(texto) {
326
+ return {
327
+ kind: 'line-range',
328
+ startLine: 1,
329
+ endLine: Math.max(1, texto.split('\n').length),
330
+ };
331
+ }
332
+
333
+ function fuenteNodo(snapshot, locator) {
334
+ return { path: snapshot.path, sha256: snapshot.sha256, locator };
335
+ }
336
+
337
+ function fuenteCampo(registro, clave) {
338
+ const metadata = registro.parsed.campos[clave];
339
+ if (!metadata) return registro.node.source;
340
+ return fuenteNodo(registro.snapshot, {
341
+ kind: 'frontmatter-key',
342
+ keyHash: sha256(metadata.claveFuente),
343
+ startLine: metadata.locator.startLine,
344
+ endLine: metadata.locator.endLine,
345
+ });
346
+ }
347
+
348
+ function fuenteCuerpo(registro) {
349
+ const { cuerpo } = registro.parsed;
350
+ if (!cuerpo) return registro.node.source;
351
+ const prefijo = registro.snapshot.texto.slice(0, -cuerpo.length);
352
+ return fuenteNodo(registro.snapshot, {
353
+ kind: 'line-range',
354
+ startLine: prefijo.split('\n').length,
355
+ endLine: Math.max(1, registro.snapshot.texto.split('\n').length),
356
+ });
357
+ }
358
+
359
+ function crearDiagnostico(code, severity, nodeId, source) {
360
+ return { code, severity, blocksConsumption: true, nodeId, source };
361
+ }
362
+
363
+ function diagnosticar(registro, code, severity, source = registro.node.source) {
364
+ registro.diagnostics.push(crearDiagnostico(code, severity, registro.node.nodeId, source));
365
+ }
366
+
367
+ function escaparRegex(texto) {
368
+ return texto.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
369
+ }
370
+
371
+ function limpiarTaint(texto) {
372
+ return String(texto)
373
+ .replace(/\x1B\[[0-?]*[ -/]*[@-~]/gu, '')
374
+ .replace(/[\u200B-\u200D\u2060\uFEFF]/gu, '')
375
+ .normalize('NFKC')
376
+ .replace(/[`*_~]/gu, '');
377
+ }
378
+
379
+ function contieneTermino(texto) {
380
+ return TAINT_TERMS_V1.some((term) => new RegExp(
381
+ `(?<![\\p{L}\\p{N}])${escaparRegex(term)}(?![\\p{L}\\p{N}])`,
382
+ 'iu'
383
+ ).test(texto));
384
+ }
385
+
386
+ function crearSkeleton(texto) {
387
+ return [...texto].map((caracter) => CONFUSABLES_V1[caracter] || caracter).join('');
388
+ }
389
+
390
+ function detectarTaint(texto) {
391
+ const limpio = limpiarTaint(texto);
392
+ const directo = contieneTermino(limpio);
393
+ const porSkeleton = contieneTermino(crearSkeleton(limpio));
394
+ return { tainted: directo || porSkeleton, obfuscated: !directo && porSkeleton };
395
+ }
396
+
397
+ function clasificarLegacy(registro, payloads) {
398
+ const detecciones = payloads.map((payload) => ({ ...payload, ...detectarTaint(payload.text) }));
399
+ const detectada = detecciones.find((payload) => payload.tainted);
400
+ registro.node.legacyStatus = detectada ? 'tainted' : 'neutrality_unproven';
401
+ registro.node.providerTainted = Boolean(detectada);
402
+ diagnosticar(
403
+ registro,
404
+ detectada ? 'PROVIDER_TAINT_DETECTED' : 'LEGACY_NEUTRALITY_UNPROVEN',
405
+ 'warning',
406
+ detectada ? detectada.source : payloads[0].source
407
+ );
408
+ const ofuscada = detecciones.find((payload) => payload.obfuscated);
409
+ if (ofuscada) diagnosticar(
410
+ registro,
411
+ 'OBFUSCATED_NATIVE_REFERENCE',
412
+ 'warning',
413
+ ofuscada.source
414
+ );
415
+ }
416
+
417
+ function payloadsArchivo(registro, claves) {
418
+ const payloads = claves
419
+ .filter((clave) => registro.parsed.valor?.[clave] !== undefined)
420
+ .map((clave) => ({ text: registro.parsed.valor[clave], source: fuenteCampo(registro, clave) }));
421
+ payloads.push({ text: registro.parsed.cuerpo, source: fuenteCuerpo(registro) });
422
+ return payloads;
423
+ }
424
+
425
+ function validarAllowlist(registro) {
426
+ const permitidas = ALLOWLISTS[registro.node.kind];
427
+ for (const clave of Object.keys(registro.parsed.valor)) {
428
+ if (!permitidas.has(clave)) diagnosticar(
429
+ registro,
430
+ 'SOURCE_PROPERTY_UNKNOWN',
431
+ 'error',
432
+ fuenteCampo(registro, clave)
433
+ );
434
+ }
435
+ }
436
+
437
+ function registrarPropiedadesLegacy(registro) {
438
+ const locatorOnly = LOCATOR_ONLY[registro.node.kind];
439
+ for (const clave of Object.keys(registro.parsed.valor)) {
440
+ if (locatorOnly.has(clave)) diagnosticar(
441
+ registro,
442
+ 'LEGACY_PROPERTY_UNMAPPED',
443
+ 'warning',
444
+ fuenteCampo(registro, clave)
445
+ );
446
+ }
447
+ }
448
+
449
+ function mapearTools(registro, aliases, source) {
450
+ if (!Array.isArray(aliases)) {
451
+ diagnosticar(registro, 'TOOL_MAPPING_UNKNOWN', 'error', source);
452
+ return null;
453
+ }
454
+ const capabilities = new Set();
455
+ let esValido = true;
456
+ for (const alias of aliases) {
457
+ const capability = TOOL_MAP[alias];
458
+ if (!capability) {
459
+ esValido = false;
460
+ diagnosticar(registro, 'TOOL_MAPPING_UNKNOWN', 'error', source);
461
+ }
462
+ else capabilities.add(capability);
463
+ }
464
+ registro.node.capabilities = [...capabilities].sort();
465
+ return esValido ? registro.node.capabilities : null;
466
+ }
467
+
468
+ function mapearAgente(registro) {
469
+ const valor = registro.parsed.valor;
470
+ mapearTools(registro, valor.tools, fuenteCampo(registro, 'tools'));
471
+ registro.node.tier = TIER_MAP[valor.model] || null;
472
+ if (!registro.node.tier) diagnosticar(
473
+ registro,
474
+ 'MODEL_TIER_MAPPING_UNKNOWN',
475
+ 'error',
476
+ fuenteCampo(registro, 'model')
477
+ );
478
+ registro.node.risk = RISK_MAP[valor.nivelRiesgo] || null;
479
+ if (!registro.node.risk) diagnosticar(
480
+ registro,
481
+ 'RISK_MAPPING_UNKNOWN',
482
+ 'error',
483
+ fuenteCampo(registro, 'nivelRiesgo')
484
+ );
485
+ if (valor.modeloAlterno !== undefined) diagnosticar(
486
+ registro,
487
+ 'LEGACY_ALTERNATE_MODEL_DECLARED',
488
+ 'warning',
489
+ fuenteCampo(registro, 'modeloAlterno')
490
+ );
491
+ clasificarLegacy(registro, payloadsArchivo(registro, ['name', 'description']));
492
+ }
493
+
494
+ function toolsComando(registro) {
495
+ const valor = registro.parsed.valor;
496
+ const snake = Object.hasOwn(valor, 'allowed_tools');
497
+ const kebab = Object.hasOwn(valor, 'allowed-tools');
498
+ if (snake && kebab) {
499
+ diagnosticar(registro, 'COMMAND_TOOL_FIELD_CONFLICT', 'error', registro.node.source);
500
+ return;
501
+ }
502
+ if (!snake && !kebab) {
503
+ diagnosticar(registro, 'COMMAND_TOOL_FIELD_MISSING', 'error', registro.node.source);
504
+ return;
505
+ }
506
+ const clave = snake ? 'allowed_tools' : 'allowed-tools';
507
+ mapearTools(registro, valor[clave], fuenteCampo(registro, clave));
508
+ }
509
+
510
+ function mapearComando(registro) {
511
+ toolsComando(registro);
512
+ diagnosticar(registro, 'COMMAND_SEMANTICS_UNSTRUCTURED', 'warning', fuenteCuerpo(registro));
513
+ clasificarLegacy(
514
+ registro,
515
+ payloadsArchivo(registro, ['name', 'description', 'argument-hint'])
516
+ );
517
+ }
518
+
519
+ function mapearRecurso(registro) {
520
+ const claves = registro.node.kind === 'skill' ? ['name', 'description'] : [];
521
+ clasificarLegacy(registro, payloadsArchivo(registro, claves));
522
+ }
523
+
524
+ function aplicarSemanticaArchivo(registro) {
525
+ validarAllowlist(registro);
526
+ registrarPropiedadesLegacy(registro);
527
+ if (registro.node.kind === 'agent') mapearAgente(registro);
528
+ else if (registro.node.kind === 'command') mapearComando(registro);
529
+ else mapearRecurso(registro);
530
+ }
531
+
532
+ function nodoBase(kind, nodeId, source) {
533
+ return {
534
+ nodeId,
535
+ kind,
536
+ consumable: false,
537
+ legacyStatus: 'neutrality_unproven',
538
+ providerTainted: false,
539
+ sourceDigest: sha256(JSON.stringify(source)),
540
+ source,
541
+ selector: null,
542
+ capabilities: [],
543
+ events: [],
544
+ tier: null,
545
+ risk: null,
546
+ references: [],
547
+ policyReferences: [],
548
+ gates: [],
549
+ };
550
+ }
551
+
552
+ function compilarArchivo(entry) {
553
+ const descriptor = entry;
554
+ const snapshot = entry.source;
555
+ const parsed = entry.parsed;
556
+ const nodeId = `${descriptor.kind}:${sha256(descriptor.path)}`;
557
+ const node = nodoBase(
558
+ descriptor.kind,
559
+ nodeId,
560
+ fuenteNodo(snapshot, locatorArchivo(snapshot.texto))
561
+ );
562
+ const registro = { node, snapshot, parsed, diagnostics: [] };
563
+ aplicarSemanticaArchivo(registro);
564
+ return registro;
565
+ }
566
+
567
+ function mapearMatcher(registro, matcher) {
568
+ if (matcher === '') {
569
+ registro.node.selector = { kind: 'all_tools' };
570
+ return;
571
+ }
572
+ if (!/^[A-Za-z]+(?:\|[A-Za-z]+)*$/u.test(matcher)) {
573
+ diagnosticar(registro, 'HOOK_MATCHER_UNKNOWN', 'error');
574
+ return;
575
+ }
576
+ const capabilities = mapearTools(registro, matcher.split('|'), registro.node.source);
577
+ if (!capabilities) {
578
+ registro.diagnostics = registro.diagnostics.filter(
579
+ ({ code }) => code !== 'TOOL_MAPPING_UNKNOWN'
580
+ );
581
+ diagnosticar(registro, 'HOOK_MATCHER_UNKNOWN', 'error');
582
+ return;
583
+ }
584
+ registro.node.selector = { kind: 'capabilities', anyOf: capabilities };
585
+ }
586
+
587
+ function mapearEvento(registro, event) {
588
+ if (EVENT_MAP[event]) registro.node.events = [EVENT_MAP[event]];
589
+ else if (EVENTOS_FUERA_V1.has(event)) diagnosticar(
590
+ registro,
591
+ 'SOURCE_EVENT_OUTSIDE_IR_V1',
592
+ 'warning'
593
+ );
594
+ else diagnosticar(registro, 'EVENT_MAPPING_UNKNOWN', 'error');
595
+ }
596
+
597
+ function mapearHook(registro, entrada, clave) {
598
+ mapearEvento(registro, entrada.event);
599
+ mapearMatcher(registro, entrada.matcher);
600
+ clasificarLegacy(registro, [
601
+ { text: clave, source: registro.node.source },
602
+ { text: entrada.description, source: registro.node.source },
603
+ ]);
604
+ }
605
+
606
+ function compilarHooks(captura) {
607
+ const snapshot = captura.source;
608
+ const { config, propiedades } = validarHooksParseados(captura.parsed);
609
+ return Object.keys(config.hooks).map((clave) => {
610
+ const pointer = `/hooks/${clave.replaceAll('~', '~0').replaceAll('/', '~1')}`;
611
+ const nodeId = `hook:${sha256(`${HOOKS_CONFIG}\0${pointer}`)}`;
612
+ const locator = propiedades[pointer].locator;
613
+ const node = nodoBase('hook', nodeId, fuenteNodo(snapshot, locator));
614
+ const registro = { node, snapshot, parsed: null, diagnostics: [] };
615
+ mapearHook(registro, config.hooks[clave], clave);
616
+ return registro;
617
+ });
618
+ }
619
+
620
+ function normalizarReferencia(valor) {
621
+ return String(valor).normalize('NFKC').toLowerCase();
622
+ }
623
+
624
+ function indiceSkills(registros) {
625
+ const porPath = new Map();
626
+ const basenames = new Map();
627
+ for (const registro of registros.filter(({ node }) => node.kind === 'skill')) {
628
+ porPath.set(registro.node.source.path, registro);
629
+ const basename = registro.node.source.path.split('/')[1];
630
+ const normalizado = normalizarReferencia(basename);
631
+ basenames.set(normalizado, (basenames.get(normalizado) || 0) + 1);
632
+ }
633
+ return { porPath, basenames };
634
+ }
635
+
636
+ function referenciaHash(registro, referencia, code) {
637
+ const source = fuenteCampo(registro, 'skillsInvocables');
638
+ registro.node.policyReferences.push({ refHash: sha256(referencia), source });
639
+ diagnosticar(registro, code, 'warning', source);
640
+ }
641
+
642
+ function resolverReferenciaLocal(registro, referencia, skills) {
643
+ const sourcePath = `habilidades/${referencia}/SKILL.md`;
644
+ const destino = skills.porPath.get(sourcePath);
645
+ if (!destino) return false;
646
+ const basename = normalizarReferencia(referencia);
647
+ const nombre = normalizarReferencia(destino.parsed.valor.name);
648
+ if (skills.basenames.get(basename) !== 1 || nombre !== basename) return false;
649
+ registro.node.references.push(destino.node.nodeId);
650
+ return true;
651
+ }
652
+
653
+ function resolverReferencias(registros) {
654
+ const skills = indiceSkills(registros);
655
+ for (const registro of registros.filter(({ node }) => node.kind === 'agent')) {
656
+ const referencias = registro.parsed.valor.skillsInvocables;
657
+ if (!Array.isArray(referencias)) {
658
+ diagnosticar(
659
+ registro,
660
+ 'SKILL_REFERENCE_UNKNOWN',
661
+ 'error',
662
+ fuenteCampo(registro, 'skillsInvocables')
663
+ );
664
+ continue;
665
+ }
666
+ for (const referencia of referencias) {
667
+ if (resolverReferenciaLocal(registro, referencia, skills)) continue;
668
+ if (SKILLS_EXTERNAS_SET.has(referencia)) {
669
+ referenciaHash(registro, referencia, 'EXTERNAL_SKILL_REFERENCE');
670
+ } else if (referencia === CENTINELA_TODOS) {
671
+ referenciaHash(registro, referencia, 'LEGACY_SKILL_WILDCARD');
672
+ } else diagnosticar(
673
+ registro,
674
+ 'SKILL_REFERENCE_UNKNOWN',
675
+ 'error',
676
+ fuenteCampo(registro, 'skillsInvocables')
677
+ );
678
+ }
679
+ registro.node.references.sort();
680
+ registro.node.policyReferences.sort((a, b) => a.refHash.localeCompare(b.refHash));
681
+ }
682
+ }
683
+
684
+ function ordenarValor(valor) {
685
+ if (Array.isArray(valor)) return valor.map(ordenarValor);
686
+ if (!valor || typeof valor !== 'object') return valor;
687
+ return Object.fromEntries(
688
+ Object.keys(valor).sort().map((clave) => [clave, ordenarValor(valor[clave])])
689
+ );
690
+ }
691
+
692
+ function serializarVista(vista) {
693
+ return `${JSON.stringify(ordenarValor(vista), null, 2)}\n`;
694
+ }
695
+
696
+ function contarNodos(nodos, diagnostics) {
697
+ const counts = Object.fromEntries(TIPOS.map((tipo) => [tipo, 0]));
698
+ counts.hook = 0;
699
+ for (const nodo of nodos) counts[nodo.kind] += 1;
700
+ return {
701
+ agents: counts.agent,
702
+ commands: counts.command,
703
+ skills: counts.skill,
704
+ rules: counts.rule,
705
+ hooks: counts.hook,
706
+ total: nodos.length,
707
+ errors: diagnostics.filter(({ severity }) => severity === 'error').length,
708
+ warnings: diagnostics.filter(({ severity }) => severity === 'warning').length,
709
+ consumable: 0,
710
+ };
711
+ }
712
+
713
+ function catalogar(nodos, propiedad, ids) {
714
+ return ids.map((id) => ({
715
+ id,
716
+ declaredBy: nodos
717
+ .filter((nodo) => nodo[propiedad].includes(id))
718
+ .map(({ nodeId }) => nodeId)
719
+ .sort(),
720
+ }));
721
+ }
722
+
723
+ function compararDiagnosticos(a, b) {
724
+ return [a.code, a.nodeId, a.source.path, JSON.stringify(a.source.locator)]
725
+ .join('\0')
726
+ .localeCompare([b.code, b.nodeId, b.source.path, JSON.stringify(b.source.locator)].join('\0'));
727
+ }
728
+
729
+ function construirIR(nodos) {
730
+ return {
731
+ kind: 'harness-ir',
732
+ schemaVersion: '1.0.0',
733
+ nodes: [...nodos].sort((a, b) => a.nodeId.localeCompare(b.nodeId)),
734
+ capabilities: catalogar(nodos, 'capabilities', CAPABILITIES),
735
+ events: catalogar(nodos, 'events', Object.values(EVENT_MAP).sort()),
736
+ tiers: TIER_DEFINITIONS,
737
+ };
738
+ }
739
+
740
+ function construirVista(registros) {
741
+ const nodos = registros.map(({ node }) => node);
742
+ const diagnostics = registros
743
+ .flatMap((registro) => registro.diagnostics)
744
+ .sort(compararDiagnosticos);
745
+ const counts = contarNodos(nodos, diagnostics);
746
+ const compilado = construirIR(nodos);
747
+ const ir = counts.errors > 0 ? null : compilado;
748
+ const vista = {
749
+ kind: 'diagnostic-view',
750
+ schemaVersion: '1.0.0',
751
+ shadowStatus: 'diagnostic_only',
752
+ ir,
753
+ counts,
754
+ diagnostics,
755
+ corpusDigest: sha256(serializarVista({ ir, diagnostics })),
756
+ };
757
+ const validacion = validarContrato(vista);
758
+ if (!validacion.ok) throw crearErrorHarness(
759
+ 'HARNESS_CONTRACT_INVALID',
760
+ 'La vista generada viola el contrato',
761
+ { errors: validacion.errors }
762
+ );
763
+ return vista;
764
+ }
765
+
766
+ function compilarHarnessIR() {
767
+ const snapshot = capturarHarnessSourceSnapshot();
768
+ const registros = snapshot.entries.map(compilarArchivo);
769
+ registros.push(...compilarHooks(snapshot.hooks));
770
+ resolverReferencias(registros);
771
+ return construirVista(registros);
772
+ }
773
+
774
+ module.exports = {
775
+ compilarHarnessIR,
776
+ serializarVista,
777
+ validarContrato,
778
+ };