@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,1147 @@
1
+ 'use strict';
2
+
3
+ /** Ledger firmado y anclado fuera del workspace para el kernel W2. */
4
+
5
+ const crypto = require('node:crypto');
6
+ const fs = require('node:fs');
7
+ const path = require('node:path');
8
+ const util = require('node:util');
9
+
10
+ const {
11
+ canonicalizarIJson,
12
+ parsearIJson,
13
+ validarTimestampIso,
14
+ } = require('./signed-envelope');
15
+
16
+ const policyContextModule = require('./policy-context-provider');
17
+ const createPolicyContextProvider = policyContextModule.createPolicyContextProvider;
18
+ delete policyContextModule.createPolicyContextProvider;
19
+ Object.freeze(policyContextModule);
20
+ const singleUseModule = require('./single-use-store');
21
+ const createSingleUseStore = singleUseModule.createSingleUseStore;
22
+ delete singleUseModule.createSingleUseStore;
23
+ Object.freeze(singleUseModule);
24
+ const gateEngineModule = require('./gate-engine');
25
+ const createGateEngine = gateEngineModule.createGateEngine;
26
+ delete gateEngineModule.createGateEngine;
27
+ Object.freeze(gateEngineModule);
28
+ const policyBrokerPath = require.resolve('./policy-broker');
29
+ let policyBrokerModule = require(policyBrokerPath);
30
+ if (typeof policyBrokerModule.createPolicyBroker !== 'function') {
31
+ delete require.cache[policyBrokerPath];
32
+ policyBrokerModule = require(policyBrokerPath);
33
+ }
34
+ const createPolicyBroker = policyBrokerModule.createPolicyBroker;
35
+ delete policyBrokerModule.createPolicyBroker;
36
+ Object.freeze(policyBrokerModule);
37
+ const { compilarPolicyBundle } = require('./policy-bundle');
38
+ const { getContractValidators } = require('./policy-verifier-utils');
39
+
40
+ const ZERO = '0'.repeat(64);
41
+ const SHA256 = /^[a-f0-9]{64}$/u;
42
+ const IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
43
+ const EVENT_KEYS = [
44
+ 'schemaVersion', 'streamId', 'sequence', 'previousHash', 'eventType', 'payload',
45
+ 'payloadDigest', 'timestamp', 'trustEpoch', 'trustDigest', 'signerKeyId',
46
+ 'eventHash', 'signature',
47
+ ];
48
+ const ANCHOR_KEYS = [
49
+ 'schemaVersion', 'streamId', 'sequence', 'headHash', 'trustEpoch', 'trustDigest',
50
+ 'lastTrustedTime', 'generation',
51
+ ];
52
+ const TRUST_KEYS = [
53
+ 'schemaVersion', 'rootKeyDigest', 'trustEpoch', 'trustDigest', 'providers',
54
+ 'signerPath', 'anchorPath', 'integrityKeyId', 'integrityPublicKey',
55
+ ];
56
+ const APPEND_KEYS = ['expectedSequence', 'expectedHeadHash', 'eventType', 'payload'];
57
+ const PIN_KEYS = [
58
+ 'schemaVersion', 'rootKeyDigest', 'trustPath', 'signerPath', 'anchorPath', 'streamId',
59
+ ];
60
+ const PROCESS_FINGERPRINT = obtenerFingerprintProceso(process.pid);
61
+ const MAX_BYTES = Object.freeze({
62
+ anchor: 16 * 1024,
63
+ ledger: 64 * 1024 * 1024,
64
+ lock: 4 * 1024,
65
+ payload: 1024 * 1024,
66
+ provisioning: 16 * 1024,
67
+ signer: 16 * 1024,
68
+ trust: 256 * 1024,
69
+ });
70
+ const MAX_EVENTOS = 10000;
71
+ const LOCK_LECTURAS_MAX = 8;
72
+ const LOCK_ESPERA_BASE_MS = 1;
73
+ const LOCK_ESPERA_MAX_MS = 32;
74
+ const LOCK_ESPERA_BUFFER = new Int32Array(new SharedArrayBuffer(4));
75
+ const APPEND_RECEIPTS = new WeakSet();
76
+ const AUTHORITY_RECEIPTS = new WeakSet();
77
+ const RESERVED_EVENT_PREFIXES = Object.freeze([
78
+ 'approval.', 'authorization.', 'gate.', 'grant.', 'legacy.', 'policy.',
79
+ ]);
80
+
81
+ function crearError(codigo, mensaje) {
82
+ const error = new Error(mensaje);
83
+ error.codigo = codigo;
84
+ return error;
85
+ }
86
+
87
+ function fallar(codigo, mensaje) {
88
+ throw crearError(codigo, mensaje);
89
+ }
90
+
91
+ function validarObjeto(valor, codigo, etiqueta) {
92
+ if (!valor || typeof valor !== 'object' || Array.isArray(valor) || util.types.isProxy(valor)) {
93
+ fallar(codigo, `${etiqueta} inválido`);
94
+ }
95
+ const proto = Object.getPrototypeOf(valor);
96
+ if (proto !== Object.prototype && proto !== null) fallar(codigo, `${etiqueta} inválido`);
97
+ if (Object.getOwnPropertySymbols(valor).length > 0) fallar(codigo, `${etiqueta} inválido`);
98
+ const descriptores = Object.values(Object.getOwnPropertyDescriptors(valor));
99
+ if (descriptores.some((item) => !item.enumerable || !('value' in item))) {
100
+ fallar(codigo, `${etiqueta} inválido`);
101
+ }
102
+ }
103
+
104
+ function validarClaves(valor, claves, codigo, etiqueta) {
105
+ if (JSON.stringify(Object.keys(valor).sort()) !== JSON.stringify([...claves].sort())) {
106
+ fallar(codigo, `${etiqueta} inválido`);
107
+ }
108
+ }
109
+
110
+ function congelarProfundo(valor) {
111
+ if (!valor || typeof valor !== 'object' || Object.isFrozen(valor)) return valor;
112
+ Object.values(valor).forEach(congelarProfundo);
113
+ return Object.freeze(valor);
114
+ }
115
+
116
+ function hashBytes(bytes) {
117
+ return crypto.createHash('sha256').update(bytes).digest('hex');
118
+ }
119
+
120
+ function hitFault(punto) {
121
+ if (process.env.SWL_INTEGRITY_FAULT === punto) {
122
+ if (!esModoPruebas()) fallar('FAULT_CONFIG_INVALID', 'fault injection fuera de pruebas');
123
+ fallar('FAULT_INJECTED', `falla inyectada: ${punto}`);
124
+ }
125
+ }
126
+
127
+ function esModoPruebas() {
128
+ return process.env.NODE_ENV === 'test' && process.env.SWL_INTEGRITY_TEST_MODE === '1';
129
+ }
130
+
131
+ function obtenerFingerprintLinux(pid) {
132
+ try {
133
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
134
+ const cierre = stat.lastIndexOf(')');
135
+ const campos = stat.slice(cierre + 2).trim().split(/\s+/u);
136
+ const bootId = fs.readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim();
137
+ return cierre > 0 && campos[19] && bootId ? `${bootId}:${campos[19]}` : null;
138
+ } catch {
139
+ return null;
140
+ }
141
+ }
142
+
143
+ function obtenerFingerprintProceso(pid) {
144
+ const nativo = process.platform === 'linux' ? obtenerFingerprintLinux(pid) : null;
145
+ if (nativo) return nativo;
146
+ if (pid === process.pid) {
147
+ return `${process.pid}:${Math.round(Date.now() - process.uptime() * 1000)}`;
148
+ }
149
+ return null;
150
+ }
151
+
152
+ function validarBackendArchivos() {
153
+ if (process.env.SWL_INTEGRITY_FAULT && !esModoPruebas()) {
154
+ fallar('FAULT_CONFIG_INVALID', 'fault injection fuera de pruebas');
155
+ }
156
+ if (process.platform !== 'linux' && !esModoPruebas()) {
157
+ fallar('FILE_BACKEND_UNAVAILABLE', 'backend de archivos sin inspector nativo');
158
+ }
159
+ }
160
+
161
+ function mismaRuta(a, b) {
162
+ return path.relative(path.resolve(a), path.resolve(b)) === '';
163
+ }
164
+
165
+ function validarPermisos(stat, codigo, esDirectorio = false, privado = true) {
166
+ if (process.platform === 'win32') return;
167
+ if (typeof process.geteuid === 'function' && stat.uid !== process.geteuid()) {
168
+ fallar(codigo, 'propietario inseguro');
169
+ }
170
+ const permisos = stat.mode & 0o777;
171
+ const inseguros = esDirectorio && !privado ? (permisos & 0o022) !== 0 : permisos !== (
172
+ esDirectorio ? 0o700 : 0o600
173
+ );
174
+ if (inseguros) fallar(codigo, 'permisos inseguros');
175
+ }
176
+
177
+ function validarDirectorioSeguro(directorio, privado = false) {
178
+ const stat = fs.lstatSync(directorio);
179
+ if (stat.isSymbolicLink() || !stat.isDirectory()) fallar('PATH_INVALID', 'directorio inseguro');
180
+ if (!mismaRuta(fs.realpathSync(directorio), directorio)) {
181
+ fallar('PATH_INVALID', 'directorio redirigido');
182
+ }
183
+ validarPermisos(stat, 'PATH_INVALID', true, privado);
184
+ }
185
+
186
+ function esRutaInterna(ruta, workspaceRoot) {
187
+ const relativa = path.relative(path.resolve(workspaceRoot), path.resolve(ruta));
188
+ return relativa === '' || (!relativa.startsWith('..') && !path.isAbsolute(relativa));
189
+ }
190
+
191
+ function validarRutaExternaSegura(ruta, workspaceRoot) {
192
+ const root = path.parse(ruta).root;
193
+ const resto = ruta.slice(root.length);
194
+ const prohibida = typeof ruta !== 'string' || !path.isAbsolute(ruta) || ruta.includes('\0')
195
+ || /^[\\/]{2}/u.test(ruta) || ruta.normalize('NFKC') !== ruta
196
+ || /[\u200B-\u200F\u202A-\u202E\u2060-\u206F]/u.test(ruta)
197
+ || resto.includes(':') || esRutaInterna(ruta, workspaceRoot);
198
+ if (prohibida) fallar('PATH_INVALID', 'locator externo inseguro');
199
+ validarDirectorioSeguro(path.dirname(ruta), true);
200
+ }
201
+
202
+ function asegurarDirectorio(directorio, privado = true) {
203
+ if (!fs.existsSync(directorio)) fs.mkdirSync(directorio, { mode: 0o700 });
204
+ validarDirectorioSeguro(directorio, privado);
205
+ }
206
+
207
+ function validarArchivoRegular(ruta, codigo, maxBytes, privado = true) {
208
+ validarDirectorioSeguro(path.dirname(ruta), privado);
209
+ let stat;
210
+ try {
211
+ stat = fs.lstatSync(ruta);
212
+ } catch (error) {
213
+ if (error.code === 'ENOENT') fallar(codigo, 'archivo no disponible');
214
+ throw error;
215
+ }
216
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.nlink !== 1) {
217
+ fallar(codigo, 'archivo inseguro');
218
+ }
219
+ if (privado) validarPermisos(stat, codigo);
220
+ if (Number.isInteger(maxBytes) && stat.size > maxBytes) fallar(codigo, 'archivo excede límite');
221
+ return stat;
222
+ }
223
+
224
+ function leerBytesEstables(ruta, codigo, maxBytes, privado = true) {
225
+ const inicial = validarArchivoRegular(ruta, codigo, maxBytes, privado);
226
+ const descriptor = fs.openSync(ruta, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
227
+ try {
228
+ const bytes = fs.readFileSync(descriptor);
229
+ const final = fs.fstatSync(descriptor);
230
+ if (inicial.dev !== final.dev || inicial.ino !== final.ino || inicial.size !== final.size) {
231
+ fallar(codigo, 'archivo cambió durante lectura');
232
+ }
233
+ if (Number.isInteger(maxBytes) && bytes.length > maxBytes) {
234
+ fallar(codigo, 'archivo excede límite');
235
+ }
236
+ return bytes;
237
+ } finally {
238
+ fs.closeSync(descriptor);
239
+ }
240
+ }
241
+
242
+ function leerJson(ruta, codigo, maxBytes) {
243
+ try {
244
+ return parsearIJson(leerBytesEstables(ruta, codigo, maxBytes));
245
+ } catch (error) {
246
+ if (error.codigo === codigo) throw error;
247
+ fallar(codigo, 'JSON externo inválido');
248
+ }
249
+ }
250
+
251
+ function sincronizarDirectorio(directorio) {
252
+ const descriptor = fs.openSync(directorio, 'r');
253
+ try {
254
+ fs.fsyncSync(descriptor);
255
+ } catch (error) {
256
+ const tolerable = process.platform === 'win32'
257
+ && (error.code === 'EPERM' || error.code === 'EINVAL');
258
+ if (!tolerable) throw error;
259
+ } finally {
260
+ fs.closeSync(descriptor);
261
+ }
262
+ }
263
+
264
+ function escribirTemporal(ruta, bytes, punto) {
265
+ fs.writeFileSync(ruta, bytes, { flag: 'wx', mode: 0o600 });
266
+ hitFault(`after-${punto}-temp-write`);
267
+ const descriptor = fs.openSync(ruta, 'r+');
268
+ try {
269
+ fs.fsyncSync(descriptor);
270
+ } finally {
271
+ fs.closeSync(descriptor);
272
+ }
273
+ hitFault(`after-${punto}-temp-fsync`);
274
+ }
275
+
276
+ function sincronizarArchivo(ruta) {
277
+ const descriptor = fs.openSync(ruta, 'r+');
278
+ try {
279
+ fs.fsyncSync(descriptor);
280
+ } finally {
281
+ fs.closeSync(descriptor);
282
+ }
283
+ }
284
+
285
+ function eliminarSiExiste(ruta) {
286
+ try {
287
+ fs.unlinkSync(ruta);
288
+ } catch (error) {
289
+ if (error.code !== 'ENOENT') throw error;
290
+ }
291
+ }
292
+
293
+ function escrituraAtomica(ruta, bytes, puntoRename) {
294
+ const directorio = path.dirname(ruta);
295
+ const temporal = `${ruta}.tmp-${process.pid}-${crypto.randomBytes(8).toString('hex')}`;
296
+ validarDirectorioSeguro(directorio, true);
297
+ try {
298
+ escribirTemporal(temporal, bytes, puntoRename);
299
+ hitFault(`before-${puntoRename}-rename`);
300
+ validarDirectorioSeguro(directorio, true);
301
+ fs.renameSync(temporal, ruta);
302
+ hitFault(`after-${puntoRename}-rename`);
303
+ validarArchivoRegular(ruta, 'DURABILITY_INVALID', bytes.length);
304
+ sincronizarArchivo(ruta);
305
+ sincronizarDirectorio(directorio);
306
+ hitFault(`after-${puntoRename}-directory-fsync`);
307
+ } finally {
308
+ eliminarSiExiste(temporal);
309
+ }
310
+ }
311
+
312
+ function esperarLockBreve(intento) {
313
+ const espera = Math.min(LOCK_ESPERA_BASE_MS << intento, LOCK_ESPERA_MAX_MS);
314
+ Atomics.wait(LOCK_ESPERA_BUFFER, 0, 0, espera);
315
+ }
316
+
317
+ // Defensa en profundidad de la publicación atómica del escritor. persistirLockNuevo
318
+ // enlaza el lock con contenido completo, pero deja una ventana residual mínima donde
319
+ // el path final tiene nlink=2 (entre el link y el unlink del temporal): un lector
320
+ // concurrente que cae ahí ve validarArchivoRegular rechazarlo como transitorio. Es
321
+ // contención de creación en curso, no corrupción; se reintenta la lectura hasta que
322
+ // el escritor completa el unlink. Un fallo de VALIDACIÓN (campos malos sobre un lock
323
+ // ya completo) ocurre después, en parsearLock, y nunca se reintenta. Residuales
324
+ // benignos que también se reintentan sin daño (latencia acotada, nunca resultado
325
+ // incorrecto): ENOENT de un lock liberado durante la carrera y PATH_INVALID que
326
+ // leerJson normaliza a LOCK_INVALID.
327
+ function leerLockCrudo(ruta) {
328
+ let ultimoError;
329
+ for (let intento = 0; intento < LOCK_LECTURAS_MAX; intento += 1) {
330
+ try {
331
+ return leerJson(ruta, 'LOCK_INVALID', MAX_BYTES.lock);
332
+ } catch (error) {
333
+ // leerJson normaliza toda falla de lectura/parseo a LOCK_INVALID (ver su
334
+ // catch): un lock imparseable es contención de creación en curso, se reintenta.
335
+ ultimoError = error;
336
+ if (intento + 1 < LOCK_LECTURAS_MAX) esperarLockBreve(intento);
337
+ }
338
+ }
339
+ throw ultimoError;
340
+ }
341
+
342
+ function parsearLock(ruta) {
343
+ const lock = leerLockCrudo(ruta);
344
+ validarObjeto(lock, 'LOCK_INVALID', 'lock');
345
+ validarClaves(lock, ['ownerToken', 'pid', 'processFingerprint'], 'LOCK_INVALID', 'lock');
346
+ if (!SHA256.test(lock.ownerToken) || !Number.isInteger(lock.pid) || lock.pid <= 0) {
347
+ fallar('LOCK_INVALID', 'lock inválido');
348
+ }
349
+ if (typeof lock.processFingerprint !== 'string' || lock.processFingerprint.length > 256) {
350
+ fallar('LOCK_INVALID', 'lock inválido');
351
+ }
352
+ return lock;
353
+ }
354
+
355
+ function inspeccionarProceso(lock) {
356
+ if (lock.pid === process.pid) {
357
+ return { alive: true, fingerprint: PROCESS_FINGERPRINT };
358
+ }
359
+ try {
360
+ process.kill(lock.pid, 0);
361
+ } catch (error) {
362
+ if (error.code === 'ESRCH') return { alive: false, fingerprint: null };
363
+ }
364
+ return { alive: true, fingerprint: obtenerFingerprintProceso(lock.pid) };
365
+ }
366
+
367
+ function puedeReclamar(lock) {
368
+ const proceso = inspeccionarProceso(lock);
369
+ if (!proceso.alive) return true;
370
+ return proceso.fingerprint !== null && proceso.fingerprint !== lock.processFingerprint;
371
+ }
372
+
373
+ function locksIguales(a, b) {
374
+ return a.ownerToken === b.ownerToken
375
+ && a.pid === b.pid
376
+ && a.processFingerprint === b.processFingerprint;
377
+ }
378
+
379
+ function crearLockPropio() {
380
+ return {
381
+ ownerToken: crypto.randomBytes(32).toString('hex'),
382
+ pid: process.pid,
383
+ processFingerprint: PROCESS_FINGERPRINT,
384
+ };
385
+ }
386
+
387
+ function persistirLockNuevo(ruta, valor) {
388
+ // Publicación atómica-exclusiva: el contenido completo se escribe primero en un
389
+ // temporal por-proceso y luego se enlaza al path final con linkSync. link() falla
390
+ // con EEXIST si el lock ya existe —preserva la exclusión mutua que adquirirLock
391
+ // necesita— y el path final, una vez visible, SIEMPRE trae contenido: nunca la
392
+ // ventana vacía de un create-then-write. Un crash antes del link deja sólo el
393
+ // temporal (huérfano limpiable), nunca un lock de 0 bytes irreclamable. La ventana
394
+ // residual nlink=2 entre link y unlink la absorbe leerLockCrudo (reintento).
395
+ const temporal = `${ruta}.${crypto.randomBytes(12).toString('hex')}.tmp`;
396
+ fs.writeFileSync(temporal, `${canonicalizarIJson(valor)}\n`, { flag: 'wx', mode: 0o600 });
397
+ sincronizarArchivo(temporal);
398
+ try {
399
+ fs.linkSync(temporal, ruta);
400
+ } catch (error) {
401
+ eliminarSiExiste(temporal);
402
+ throw error;
403
+ }
404
+ eliminarSiExiste(temporal);
405
+ sincronizarDirectorio(path.dirname(ruta));
406
+ }
407
+
408
+ function eliminarLockVerificado(ruta, ownerToken) {
409
+ const actual = parsearLock(ruta);
410
+ if (actual.ownerToken !== ownerToken) fallar('LOCK_OWNER_MISMATCH', 'owner cambió');
411
+ fs.unlinkSync(ruta);
412
+ sincronizarDirectorio(path.dirname(ruta));
413
+ }
414
+
415
+ function cuarentenarLock(ruta, lock) {
416
+ const cuarentena = `${ruta}.orphan-${crypto.randomBytes(12).toString('hex')}`;
417
+ try {
418
+ fs.renameSync(ruta, cuarentena);
419
+ } catch (error) {
420
+ if (error.code === 'ENOENT') fallar('LOCK_CONFLICT', 'otro reclaimer ganó');
421
+ throw error;
422
+ }
423
+ const movido = parsearLock(cuarentena);
424
+ if (!locksIguales(lock, movido)) fallar('LOCK_CONFLICT', 'lock cambió durante reclaim');
425
+ fs.unlinkSync(cuarentena);
426
+ sincronizarDirectorio(path.dirname(ruta));
427
+ }
428
+
429
+ function recuperarGuardiaReclaim(guardia) {
430
+ const lock = parsearLock(guardia);
431
+ if (!puedeReclamar(lock)) fallar('LOCK_CONFLICT', 'reclaim ya está en curso');
432
+ cuarentenarLock(guardia, lock);
433
+ }
434
+
435
+ function adquirirGuardiaReclaim(ruta) {
436
+ const guardia = `${ruta}.reclaim`;
437
+ const owner = crearLockPropio();
438
+ try {
439
+ persistirLockNuevo(guardia, owner);
440
+ return { guardia, owner };
441
+ } catch (error) {
442
+ if (error.code !== 'EEXIST') throw error;
443
+ recuperarGuardiaReclaim(guardia);
444
+ return adquirirGuardiaReclaim(ruta);
445
+ }
446
+ }
447
+
448
+ function reclamarLock(ruta) {
449
+ const observado = parsearLock(ruta);
450
+ if (!puedeReclamar(observado)) fallar('LOCK_HELD', 'lock pertenece a proceso vivo');
451
+ const { guardia, owner } = adquirirGuardiaReclaim(ruta);
452
+ try {
453
+ const actual = parsearLock(ruta);
454
+ if (!locksIguales(observado, actual)) fallar('LOCK_CONFLICT', 'lock cambió antes de reclaim');
455
+ if (!puedeReclamar(actual)) fallar('LOCK_HELD', 'lock pertenece a proceso vivo');
456
+ cuarentenarLock(ruta, actual);
457
+ } finally {
458
+ eliminarLockVerificado(guardia, owner.ownerToken);
459
+ }
460
+ }
461
+
462
+ function bloquearSiReclaimEnCurso(ruta, ownerToken = null) {
463
+ const guardia = `${ruta}.reclaim`;
464
+ if (!fs.existsSync(guardia)) return;
465
+ try {
466
+ recuperarGuardiaReclaim(guardia);
467
+ } catch (error) {
468
+ if (ownerToken) liberarLock(ruta, ownerToken);
469
+ throw error;
470
+ }
471
+ }
472
+
473
+ function adquirirLock(ruta) {
474
+ hitFault('before-lock');
475
+ const valor = crearLockPropio();
476
+ validarDirectorioSeguro(path.dirname(ruta), true);
477
+ bloquearSiReclaimEnCurso(ruta);
478
+ try {
479
+ persistirLockNuevo(ruta, valor);
480
+ } catch (error) {
481
+ if (error.code !== 'EEXIST') throw error;
482
+ reclamarLock(ruta);
483
+ return adquirirLock(ruta);
484
+ }
485
+ bloquearSiReclaimEnCurso(ruta, valor.ownerToken);
486
+ hitFault('after-lock');
487
+ return valor;
488
+ }
489
+
490
+ function liberarLock(ruta, ownerToken) {
491
+ eliminarLockVerificado(ruta, ownerToken);
492
+ }
493
+
494
+ function liberarLockConCodigo(ruta, ownerToken) {
495
+ try {
496
+ liberarLock(ruta, ownerToken);
497
+ } catch (error) {
498
+ if (error.codigo !== 'LOCK_OWNER_MISMATCH') error.codigo = 'LOCK_RELEASE_FAILED';
499
+ throw error;
500
+ }
501
+ }
502
+
503
+ function conLock(ruta, accion) {
504
+ const owner = adquirirLock(ruta);
505
+ let resultado;
506
+ let falla;
507
+ try {
508
+ resultado = accion();
509
+ } catch (error) {
510
+ falla = error;
511
+ }
512
+ liberarLockConCodigo(ruta, owner.ownerToken);
513
+ if (falla) throw falla;
514
+ return resultado;
515
+ }
516
+
517
+ function validarProviders(actuales, esperados) {
518
+ validarObjeto(actuales, 'TRUST_INVALID', 'providers');
519
+ validarObjeto(esperados, 'TRUST_INVALID', 'providers');
520
+ const a = canonicalizarIJson(actuales);
521
+ const b = canonicalizarIJson(esperados);
522
+ if (a !== b) fallar('PROVIDER_BINDING_INVALID', 'providers no coinciden');
523
+ for (const provider of Object.values(actuales)) {
524
+ const esperado = hashBytes(Buffer.from(provider.implementation));
525
+ if (provider.fingerprint !== esperado) {
526
+ fallar('PROVIDER_BINDING_INVALID', 'fingerprint built-in inválido');
527
+ }
528
+ }
529
+ }
530
+
531
+ function validarPin(pin, config) {
532
+ validarObjeto(pin, 'PROVISIONING_INVALID', 'pin de provisioning');
533
+ validarClaves(pin, PIN_KEYS, 'PROVISIONING_INVALID', 'pin de provisioning');
534
+ if (pin.schemaVersion !== '1.0.0' || !SHA256.test(pin.rootKeyDigest)) {
535
+ fallar('PROVISIONING_INVALID', 'pin de provisioning inválido');
536
+ }
537
+ if (!IDENTIFIER.test(pin.streamId)) fallar('PROVISIONING_INVALID', 'streamId inválido');
538
+ const receipt = config.receipt;
539
+ if (pin.rootKeyDigest !== receipt.rootKeyDigest
540
+ || pin.trustPath !== receipt.trustPath
541
+ || pin.signerPath !== receipt.signerPath
542
+ || pin.anchorPath !== receipt.anchorPath) {
543
+ fallar('ROOT_BINDING_INVALID', 'receipt no coincide con provisioning externo');
544
+ }
545
+ }
546
+
547
+ function validarTrust(trust, config) {
548
+ const receipt = config.receipt;
549
+ validarObjeto(trust, 'TRUST_INVALID', 'trust externo');
550
+ validarClaves(trust, TRUST_KEYS, 'TRUST_INVALID', 'trust externo');
551
+ if (trust.schemaVersion !== '1.0.0' || trust.rootKeyDigest !== receipt.rootKeyDigest) {
552
+ fallar('ROOT_BINDING_INVALID', 'root externo no coincide');
553
+ }
554
+ if (trust.trustEpoch !== receipt.trustEpoch || trust.trustDigest !== receipt.trustDigest) {
555
+ fallar('TRUST_BINDING_INVALID', 'trust externo no coincide');
556
+ }
557
+ validarProviders(trust.providers, receipt.providers);
558
+ if (trust.signerPath !== receipt.signerPath || trust.anchorPath !== receipt.anchorPath) {
559
+ fallar('TRUST_BINDING_INVALID', 'locators externos no coinciden');
560
+ }
561
+ if (!IDENTIFIER.test(trust.integrityKeyId) || typeof trust.integrityPublicKey !== 'string') {
562
+ fallar('TRUST_INVALID', 'signer externo inválido');
563
+ }
564
+ if (trust.integrityKeyId !== config.signerKeyId) {
565
+ fallar('TRUST_BINDING_INVALID', 'keyId externo no coincide con receipt');
566
+ }
567
+ }
568
+
569
+ function validarAnchor(anchor, config) {
570
+ validarObjeto(anchor, 'ANCHOR_INVALID', 'anchor');
571
+ validarClaves(anchor, ANCHOR_KEYS, 'ANCHOR_INVALID', 'anchor');
572
+ if (anchor.schemaVersion !== '1.0.0' || anchor.streamId !== config.streamId) {
573
+ fallar('ANCHOR_INVALID', 'anchor de otro stream');
574
+ }
575
+ if (!Number.isInteger(anchor.sequence) || anchor.sequence < 0 || !SHA256.test(anchor.headHash)) {
576
+ fallar('ANCHOR_INVALID', 'head externo inválido');
577
+ }
578
+ if (!Number.isInteger(anchor.generation) || anchor.generation !== anchor.sequence) {
579
+ fallar('ANCHOR_INVALID', 'generación externa inválida');
580
+ }
581
+ if (anchor.trustEpoch !== config.receipt.trustEpoch
582
+ || anchor.trustDigest !== config.receipt.trustDigest) {
583
+ fallar('ANCHOR_TRUST_INVALID', 'anchor trust inválido');
584
+ }
585
+ try {
586
+ validarTimestampIso(anchor.lastTrustedTime, 'anchor lastTrustedTime');
587
+ } catch {
588
+ fallar('ANCHOR_INVALID', 'tiempo externo inválido');
589
+ }
590
+ return anchor;
591
+ }
592
+
593
+ function leerAnchor(config) {
594
+ return validarAnchor(leerJson(config.anchorPath, 'ANCHOR_UNAVAILABLE', MAX_BYTES.anchor), config);
595
+ }
596
+
597
+ function eventoSinPruebas(evento) {
598
+ const unsigned = { ...evento };
599
+ delete unsigned.eventHash;
600
+ delete unsigned.signature;
601
+ return unsigned;
602
+ }
603
+
604
+ function bytesFirmaEvento(unsigned) {
605
+ return Buffer.concat([
606
+ Buffer.from('swl-ses/integrity-ledger/v1\0', 'utf8'),
607
+ Buffer.from(canonicalizarIJson(unsigned), 'utf8'),
608
+ ]);
609
+ }
610
+
611
+ function validarCabeceraEvento(evento, config) {
612
+ if (evento.schemaVersion !== '1.0.0' || evento.streamId !== config.streamId) {
613
+ fallar('LEDGER_INVALID', 'evento de otro stream');
614
+ }
615
+ if (!Number.isInteger(evento.sequence) || evento.sequence < 1) {
616
+ fallar('LEDGER_INVALID', 'secuencia inválida');
617
+ }
618
+ }
619
+
620
+ function validarDigestsEvento(evento) {
621
+ const digests = [evento.previousHash, evento.payloadDigest, evento.trustDigest, evento.eventHash];
622
+ if (digests.some((digest) => !SHA256.test(digest))) {
623
+ fallar('LEDGER_INVALID', 'digest inválido');
624
+ }
625
+ }
626
+
627
+ function validarIdentidadEvento(evento, config) {
628
+ if (!IDENTIFIER.test(evento.eventType) || !IDENTIFIER.test(evento.signerKeyId)) {
629
+ fallar('LEDGER_INVALID', 'identificador inválido');
630
+ }
631
+ if (evento.signerKeyId !== config.trust.integrityKeyId) {
632
+ fallar('LEDGER_INVALID', 'signer keyId no coincide');
633
+ }
634
+ }
635
+
636
+ function validarTrustEvento(evento, config) {
637
+ if (evento.trustEpoch !== config.receipt.trustEpoch
638
+ || evento.trustDigest !== config.receipt.trustDigest) {
639
+ fallar('LEDGER_INVALID', 'trust de evento inválido');
640
+ }
641
+ }
642
+
643
+ function validarPayloadEvento(payload, codigo) {
644
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
645
+ fallar(codigo, 'payload inválido');
646
+ }
647
+ validarValorIJson(payload, 0);
648
+ const bytes = Buffer.byteLength(canonicalizarIJson(payload), 'utf8');
649
+ if (bytes > MAX_BYTES.payload) fallar(codigo, 'payload excede límite');
650
+ }
651
+
652
+ function validarEventoShape(evento, config) {
653
+ validarObjeto(evento, 'LEDGER_INVALID', 'evento');
654
+ validarClaves(evento, EVENT_KEYS, 'LEDGER_INVALID', 'evento');
655
+ validarCabeceraEvento(evento, config);
656
+ validarDigestsEvento(evento);
657
+ validarIdentidadEvento(evento, config);
658
+ validarPayloadEvento(evento.payload, 'LEDGER_INVALID');
659
+ validarTimestampIso(evento.timestamp, 'evento timestamp');
660
+ validarTrustEvento(evento, config);
661
+ }
662
+
663
+ function verificarEvento(evento, anterior, config) {
664
+ validarEventoShape(evento, config);
665
+ if (evento.sequence !== anterior.sequence + 1 || evento.previousHash !== anterior.headHash) {
666
+ fallar('LEDGER_INVALID', 'cadena no contigua');
667
+ }
668
+ if (anterior.lastTrustedTime && evento.timestamp < anterior.lastTrustedTime) {
669
+ fallar('CLOCK_ROLLBACK', 'tiempo del ledger retrocedió');
670
+ }
671
+ const unsigned = eventoSinPruebas(evento);
672
+ if (hashBytes(Buffer.from(canonicalizarIJson(evento.payload))) !== evento.payloadDigest) {
673
+ fallar('LEDGER_INVALID', 'payload alterado');
674
+ }
675
+ if (hashBytes(Buffer.from(canonicalizarIJson(unsigned))) !== evento.eventHash) {
676
+ fallar('LEDGER_INVALID', 'evento rehasheado');
677
+ }
678
+ let firmaValida = false;
679
+ try {
680
+ firmaValida = crypto.verify(
681
+ null, bytesFirmaEvento(unsigned), config.publicKey, Buffer.from(evento.signature, 'base64url')
682
+ );
683
+ } catch { /* firma inválida */ }
684
+ if (!firmaValida) fallar('SIGNATURE_INVALID', 'firma de evento inválida');
685
+ return {
686
+ sequence: evento.sequence,
687
+ headHash: evento.eventHash,
688
+ lastTrustedTime: evento.timestamp,
689
+ };
690
+ }
691
+
692
+ function parsearLedger(config) {
693
+ if (!fs.existsSync(config.ledgerPath)) return [];
694
+ const bytes = leerBytesEstables(config.ledgerPath, 'LEDGER_INVALID', MAX_BYTES.ledger);
695
+ if (bytes.length === 0) return [];
696
+ if (bytes[bytes.length - 1] !== 0x0A) fallar('LEDGER_INVALID', 'línea parcial');
697
+ try {
698
+ const lineas = dividirJsonl(bytes);
699
+ if (lineas.length > MAX_EVENTOS) fallar('LEDGER_INVALID', 'ledger excede eventos');
700
+ return lineas.map((linea) => parsearIJson(linea));
701
+ } catch {
702
+ fallar('LEDGER_INVALID', 'ledger JSONL inválido');
703
+ }
704
+ }
705
+
706
+ function dividirJsonl(bytes) {
707
+ const lineas = [];
708
+ let inicio = 0;
709
+ for (let indice = 0; indice < bytes.length; indice += 1) {
710
+ if (bytes[indice] !== 0x0A) continue;
711
+ if (indice === inicio) fallar('LEDGER_INVALID', 'línea vacía');
712
+ lineas.push(bytes.subarray(inicio, indice));
713
+ inicio = indice + 1;
714
+ }
715
+ return lineas;
716
+ }
717
+
718
+ function verificarLedger(config) {
719
+ const eventos = parsearLedger(config);
720
+ let tip = { sequence: 0, headHash: ZERO, lastTrustedTime: config.receipt.issuedAt };
721
+ for (const evento of eventos) tip = verificarEvento(evento, tip, config);
722
+ return { ...tip, events: eventos };
723
+ }
724
+
725
+ function anchorsIguales(anchor, tip) {
726
+ return anchor.sequence === tip.sequence
727
+ && anchor.headHash === tip.headHash
728
+ && anchor.lastTrustedTime >= tip.lastTrustedTime
729
+ && anchor.generation === tip.sequence;
730
+ }
731
+
732
+ function expectedAnchor(anchor) {
733
+ return {
734
+ streamId: anchor.streamId, sequence: anchor.sequence, headHash: anchor.headHash,
735
+ trustEpoch: anchor.trustEpoch, trustDigest: anchor.trustDigest,
736
+ lastTrustedTime: anchor.lastTrustedTime, generation: anchor.generation,
737
+ };
738
+ }
739
+
740
+ function anchorCoincide(anchor, expected) {
741
+ return Object.entries(expected).every(([clave, valor]) => anchor[clave] === valor);
742
+ }
743
+
744
+ function publicarAnchor(config, expected, siguiente) {
745
+ return conLock(`${config.anchorPath}.lock`, () => {
746
+ const actual = leerAnchor(config);
747
+ if (!anchorCoincide(actual, expected)) fallar('ANCHOR_CAS_CONFLICT', 'CAS externo rechazado');
748
+ escrituraAtomica(
749
+ config.anchorPath,
750
+ Buffer.from(`${canonicalizarIJson(siguiente)}\n`),
751
+ 'anchor'
752
+ );
753
+ hitFault('anchor-updated-before-response');
754
+ return siguiente;
755
+ });
756
+ }
757
+
758
+ function confirmarAnchor(config, expected, siguiente) {
759
+ try {
760
+ return publicarAnchor(config, expected, siguiente);
761
+ } catch (error) {
762
+ const noAmbiguo = ['ANCHOR_CAS_CONFLICT', 'LOCK_OWNER_MISMATCH', 'LOCK_RELEASE_FAILED'];
763
+ if (noAmbiguo.includes(error.codigo)) throw error;
764
+ try {
765
+ const observado = leerAnchor(config);
766
+ if (anchorCoincide(observado, expectedAnchor(siguiente))) return observado;
767
+ } catch { /* conservar la falla original si el resultado es ambiguo */ }
768
+ throw error;
769
+ }
770
+ }
771
+
772
+ function avanzarTiempoAutoridad(config, anchor, observedAt) {
773
+ validarVigencia(config.receipt, anchor, observedAt);
774
+ if (observedAt === anchor.lastTrustedTime) return anchor;
775
+ return confirmarAnchor(config, expectedAnchor(anchor), {
776
+ ...anchor, lastTrustedTime: observedAt,
777
+ });
778
+ }
779
+
780
+ function avanzarAnchor(config, anchor, state, observedAt) {
781
+ const primerPendiente = state.events[anchor.sequence];
782
+ if (!primerPendiente || primerPendiente.previousHash !== anchor.headHash) {
783
+ fallar('ANCHOR_DIVERGED', 'anchor no es prefijo del ledger');
784
+ }
785
+ const ultimo = state.events[state.events.length - 1];
786
+ if (primerPendiente.timestamp < anchor.lastTrustedTime) {
787
+ fallar('CLOCK_ROLLBACK', 'sufijo local reduce el tiempo confiable');
788
+ }
789
+ if (ultimo.timestamp > observedAt) fallar('CLOCK_FUTURE', 'sufijo local está en el futuro');
790
+ const siguiente = {
791
+ schemaVersion: '1.0.0', streamId: config.streamId,
792
+ sequence: state.sequence, headHash: state.headHash,
793
+ trustEpoch: config.receipt.trustEpoch, trustDigest: config.receipt.trustDigest,
794
+ lastTrustedTime: [anchor.lastTrustedTime, ultimo.timestamp].sort().at(-1),
795
+ generation: anchor.generation + (state.sequence - anchor.sequence),
796
+ };
797
+ return confirmarAnchor(config, expectedAnchor(anchor), siguiente);
798
+ }
799
+
800
+ function reconciliar(config, state, observedAt) {
801
+ const anchor = leerAnchor(config);
802
+ validarVigencia(config.receipt, anchor, observedAt);
803
+ if (anchorsIguales(anchor, state)) return anchor;
804
+ if (anchor.sequence > state.sequence) fallar('ANCHOR_AHEAD', 'workspace restaurado o stale');
805
+ if (anchor.sequence === state.sequence) fallar('ANCHOR_DIVERGED', 'anchor divergente');
806
+ return avanzarAnchor(config, anchor, state, observedAt);
807
+ }
808
+
809
+ function serializarSnapshot(config, state, anchor) {
810
+ return `${canonicalizarIJson({
811
+ schemaVersion: '1.0.0', streamId: config.streamId,
812
+ sequence: state.sequence, headHash: state.headHash,
813
+ anchorGeneration: anchor.generation, eventCount: state.events.length,
814
+ })}\n`;
815
+ }
816
+
817
+ function publicarSnapshot(config, state, anchor) {
818
+ escrituraAtomica(
819
+ config.snapshotPath,
820
+ Buffer.from(serializarSnapshot(config, state, anchor)),
821
+ 'snapshot'
822
+ );
823
+ }
824
+
825
+ function estadoPublico(config, state) {
826
+ const valor = {
827
+ streamId: config.streamId, sequence: state.sequence,
828
+ headHash: state.headHash, events: state.events.map((evento) => structuredClone(evento)),
829
+ };
830
+ return congelarProfundo(valor);
831
+ }
832
+
833
+ function leerVerificado(config) {
834
+ const observedAt = new Date().toISOString();
835
+ const state = verificarLedger(config);
836
+ hitFault('after-reread');
837
+ const anchor = reconciliar(config, state, observedAt);
838
+ validarVigencia(config.receipt, anchor, observedAt);
839
+ publicarSnapshot(config, state, anchor);
840
+ return estadoPublico(config, state);
841
+ }
842
+
843
+ function validarEntradaAppend(entrada, esAutoridad = false) {
844
+ validarObjeto(entrada, 'EVENT_INVALID', 'append');
845
+ validarClaves(entrada, APPEND_KEYS, 'EVENT_INVALID', 'append');
846
+ if (!Number.isInteger(entrada.expectedSequence) || entrada.expectedSequence < 0
847
+ || !SHA256.test(entrada.expectedHeadHash)) {
848
+ fallar('EVENT_INVALID', 'precondición CAS inválida');
849
+ }
850
+ if (!IDENTIFIER.test(entrada.eventType)) fallar('EVENT_INVALID', 'eventType inválido');
851
+ if (!esAutoridad && RESERVED_EVENT_PREFIXES.some(
852
+ (prefijo) => entrada.eventType.startsWith(prefijo)
853
+ )) {
854
+ fallar('EVENT_TYPE_RESERVED', 'eventType reservado para el kernel');
855
+ }
856
+ validarPayloadEvento(entrada.payload, 'EVENT_INVALID');
857
+ }
858
+
859
+ function crearEvento(config, previo, entrada, timestamp) {
860
+ const unsigned = {
861
+ schemaVersion: '1.0.0', streamId: config.streamId, sequence: previo.sequence + 1,
862
+ previousHash: previo.headHash, eventType: entrada.eventType,
863
+ payload: structuredClone(entrada.payload),
864
+ payloadDigest: hashBytes(Buffer.from(canonicalizarIJson(entrada.payload))),
865
+ timestamp, trustEpoch: config.receipt.trustEpoch, trustDigest: config.receipt.trustDigest,
866
+ signerKeyId: config.trust.integrityKeyId,
867
+ };
868
+ const eventHash = hashBytes(Buffer.from(canonicalizarIJson(unsigned)));
869
+ const signature = crypto.sign(
870
+ null, bytesFirmaEvento(unsigned), config.privateKey
871
+ ).toString('base64url');
872
+ return { ...unsigned, eventHash, signature };
873
+ }
874
+
875
+ function persistirLedger(config, events) {
876
+ const bytes = Buffer.from(events.map((evento) => canonicalizarIJson(evento)).join('\n') + '\n');
877
+ if (events.length > MAX_EVENTOS || bytes.length > MAX_BYTES.ledger) {
878
+ fallar('LEDGER_LIMIT_EXCEEDED', 'ledger excede límite');
879
+ }
880
+ escrituraAtomica(config.ledgerPath, bytes, 'ledger');
881
+ }
882
+
883
+ function crearReceiptAppend(config, expected, state, anchor) {
884
+ const receipt = congelarProfundo({
885
+ kind: 'integrity-ledger-append-receipt', streamId: config.streamId,
886
+ expectedSequence: expected.sequence, expectedHeadHash: expected.headHash,
887
+ expectedAnchorGeneration: expected.generation,
888
+ sequence: state.sequence, headHash: state.headHash,
889
+ anchorGeneration: anchor.generation,
890
+ trustEpoch: anchor.trustEpoch, trustDigest: anchor.trustDigest,
891
+ });
892
+ APPEND_RECEIPTS.add(receipt);
893
+ return receipt;
894
+ }
895
+
896
+ function append(config, entrada, esAutoridad = false) {
897
+ validarEntradaAppend(entrada, esAutoridad);
898
+ return conLock(config.lockPath, () => {
899
+ const observedAt = new Date().toISOString();
900
+ const previo = verificarLedger(config);
901
+ hitFault('after-reread');
902
+ const anchorPrevio = reconciliar(config, previo, observedAt);
903
+ if (entrada.expectedSequence !== previo.sequence
904
+ || entrada.expectedHeadHash !== previo.headHash) {
905
+ fallar('LEDGER_CAS_CONFLICT', 'precondición local cambió');
906
+ }
907
+ const evento = crearEvento(config, previo, entrada, observedAt);
908
+ const events = [...previo.events, evento];
909
+ persistirLedger(config, events);
910
+ hitFault('local-durable-before-anchor-cas');
911
+ const state = verificarLedger(config);
912
+ const anchor = avanzarAnchor(config, anchorPrevio, state, observedAt);
913
+ publicarSnapshot(config, state, anchor);
914
+ return crearReceiptAppend(config, anchorPrevio, state, anchor);
915
+ });
916
+ }
917
+
918
+ function mutarCasEnPruebas(entrada) {
919
+ if (process.env.SWL_INTEGRITY_FAULT !== 'before-transact-cas-check') return entrada;
920
+ return { ...entrada, expectedSequence: entrada.expectedSequence + 1 };
921
+ }
922
+
923
+ function transact(config, action) {
924
+ return conLock(config.lockPath, () => {
925
+ const observedAt = new Date().toISOString();
926
+ const previo = verificarLedger(config);
927
+ hitFault('after-reread');
928
+ const reconciliado = reconciliar(config, previo, observedAt);
929
+ const anchorPrevio = avanzarTiempoAutoridad(config, reconciliado, observedAt);
930
+ const authority = crearAuthorityReceipt(config, previo, anchorPrevio);
931
+ const entrada = mutarCasEnPruebas(action(estadoPublico(config, previo), authority));
932
+ validarEntradaAppend(entrada, true);
933
+ if (entrada.expectedSequence !== previo.sequence
934
+ || entrada.expectedHeadHash !== previo.headHash) {
935
+ fallar('LEDGER_CAS_CONFLICT', 'precondición semántica cambió');
936
+ }
937
+ const evento = crearEvento(config, previo, entrada, observedAt);
938
+ const events = [...previo.events, evento];
939
+ persistirLedger(config, events);
940
+ hitFault('local-durable-before-anchor-cas');
941
+ const state = verificarLedger(config);
942
+ const anchor = avanzarAnchor(config, anchorPrevio, state, observedAt);
943
+ publicarSnapshot(config, state, anchor);
944
+ return crearReceiptAppend(config, anchorPrevio, state, anchor);
945
+ });
946
+ }
947
+
948
+ function inspect(config, action) {
949
+ return conLock(config.lockPath, () => {
950
+ const observedAt = new Date().toISOString();
951
+ const state = verificarLedger(config);
952
+ hitFault('after-reread');
953
+ const reconciliado = reconciliar(config, state, observedAt);
954
+ const anchor = avanzarTiempoAutoridad(config, reconciliado, observedAt);
955
+ const authority = crearAuthorityReceipt(config, state, anchor);
956
+ const result = action(estadoPublico(config, state), authority);
957
+ publicarSnapshot(config, state, anchor);
958
+ return result;
959
+ });
960
+ }
961
+
962
+ function crearAuthorityReceipt(config, state, anchor) {
963
+ const receipt = congelarProfundo({
964
+ kind: 'kernel-authority-receipt', streamId: config.streamId,
965
+ rootKeyDigest: config.receipt.rootKeyDigest,
966
+ sequence: state.sequence, headHash: state.headHash,
967
+ trustEpoch: anchor.trustEpoch, trustDigest: anchor.trustDigest,
968
+ lastTrustedTime: anchor.lastTrustedTime, observedAt: anchor.lastTrustedTime,
969
+ });
970
+ AUTHORITY_RECEIPTS.add(receipt);
971
+ return receipt;
972
+ }
973
+
974
+ function leerAutoridad(config) {
975
+ const observedAt = new Date().toISOString();
976
+ const state = verificarLedger(config);
977
+ hitFault('after-reread');
978
+ const reconciliado = reconciliar(config, state, observedAt);
979
+ const anchor = avanzarTiempoAutoridad(config, reconciliado, observedAt);
980
+ validarVigencia(config.receipt, anchor, observedAt);
981
+ publicarSnapshot(config, state, anchor);
982
+ return crearAuthorityReceipt(config, state, anchor);
983
+ }
984
+
985
+ function validarVigencia(receipt, anchor, now) {
986
+ if (now < receipt.issuedAt || now > receipt.expiresAt) {
987
+ fallar('BOOTSTRAP_EXPIRED', 'bootstrap fuera de vigencia');
988
+ }
989
+ if (now < anchor.lastTrustedTime) fallar('CLOCK_ROLLBACK', 'reloj detrás del anchor');
990
+ }
991
+
992
+ function validarValorIJson(valor, profundidad) {
993
+ if (profundidad > 64) fallar('EVENT_INVALID', 'payload demasiado profundo');
994
+ if (valor === null || typeof valor === 'string' || typeof valor === 'boolean') return;
995
+ if (typeof valor === 'number' && Number.isFinite(valor)) return;
996
+ if (!valor || typeof valor !== 'object' || util.types.isProxy(valor)) {
997
+ fallar('EVENT_INVALID', 'payload inválido');
998
+ }
999
+ const proto = Object.getPrototypeOf(valor);
1000
+ const permitido = Array.isArray(valor)
1001
+ ? proto === Array.prototype
1002
+ : proto === Object.prototype || proto === null;
1003
+ if (!permitido || Object.getOwnPropertySymbols(valor).length > 0) {
1004
+ fallar('EVENT_INVALID', 'payload inválido');
1005
+ }
1006
+ for (const [clave, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(valor))) {
1007
+ if (Array.isArray(valor) && clave === 'length') continue;
1008
+ if (!descriptor.enumerable || !('value' in descriptor)) {
1009
+ fallar('EVENT_INVALID', 'payload inválido');
1010
+ }
1011
+ validarValorIJson(descriptor.value, profundidad + 1);
1012
+ }
1013
+ }
1014
+
1015
+ function cargarPrivateKey(config) {
1016
+ const privateBytes = leerBytesEstables(
1017
+ config.receipt.signerPath, 'SIGNER_UNAVAILABLE', MAX_BYTES.signer
1018
+ );
1019
+ try {
1020
+ const privateKey = crypto.createPrivateKey(privateBytes);
1021
+ if (privateKey.asymmetricKeyType !== 'ed25519') {
1022
+ fallar('SIGNER_INVALID', 'signer no es Ed25519');
1023
+ }
1024
+ return privateKey;
1025
+ } catch {
1026
+ fallar('SIGNER_INVALID', 'signer no es una llave privada');
1027
+ }
1028
+ }
1029
+
1030
+ function cargarPublicKey(trust) {
1031
+ try {
1032
+ const publicKey = crypto.createPublicKey(trust.integrityPublicKey);
1033
+ if (publicKey.asymmetricKeyType !== 'ed25519') {
1034
+ fallar('TRUST_INVALID', 'llave externa no Ed25519');
1035
+ }
1036
+ return publicKey;
1037
+ } catch {
1038
+ fallar('TRUST_INVALID', 'llave pública externa inválida');
1039
+ }
1040
+ }
1041
+
1042
+ function validarParFirmante(config, privateKey, publicKey) {
1043
+ const derivada = crypto.createPublicKey(privateKey).export({ format: 'der', type: 'spki' });
1044
+ const esperada = publicKey.export({ format: 'der', type: 'spki' });
1045
+ if (!Buffer.from(derivada).equals(Buffer.from(esperada))) {
1046
+ fallar('SIGNER_INVALID', 'signer no coincide con trust externo');
1047
+ }
1048
+ if (hashBytes(esperada) !== config.signerPublicKeyDigest) {
1049
+ fallar('TRUST_BINDING_INVALID', 'llave externa no coincide con receipt');
1050
+ }
1051
+ }
1052
+
1053
+ function cargarMaterial(config) {
1054
+ const provisioningPath = process.env.SWL_KERNEL_PROVISIONING_PATH;
1055
+ if (!provisioningPath || !path.isAbsolute(provisioningPath)) {
1056
+ fallar('PROVISIONING_UNAVAILABLE', 'provisioning externo no configurado');
1057
+ }
1058
+ validarRutaExternaSegura(provisioningPath, config.workspaceRoot);
1059
+ for (const ruta of [config.receipt.trustPath, config.receipt.signerPath, config.anchorPath]) {
1060
+ validarRutaExternaSegura(ruta, config.workspaceRoot);
1061
+ }
1062
+ const pin = leerJson(provisioningPath, 'PROVISIONING_UNAVAILABLE', MAX_BYTES.provisioning);
1063
+ validarPin(pin, config);
1064
+ const trust = leerJson(config.receipt.trustPath, 'TRUST_UNAVAILABLE', MAX_BYTES.trust);
1065
+ validarTrust(trust, config);
1066
+ const privateKey = cargarPrivateKey(config);
1067
+ const publicKey = cargarPublicKey(trust);
1068
+ validarParFirmante(config, privateKey, publicKey);
1069
+ return { pin, privateKey, publicKey, trust };
1070
+ }
1071
+
1072
+ function crearPaths(workspaceRoot, streamId) {
1073
+ const nombre = hashBytes(Buffer.from(streamId)).slice(0, 24);
1074
+ validarDirectorioSeguro(workspaceRoot);
1075
+ const planning = path.join(workspaceRoot, '.planning');
1076
+ asegurarDirectorio(planning, false);
1077
+ const directorio = path.join(planning, 'integrity');
1078
+ asegurarDirectorio(directorio);
1079
+ return {
1080
+ ledgerPath: path.join(directorio, `${nombre}.jsonl`),
1081
+ lockPath: path.join(directorio, `${nombre}.lock`),
1082
+ snapshotPath: path.join(directorio, `${nombre}.snapshot.json`),
1083
+ };
1084
+ }
1085
+
1086
+ function crearLedger(config) {
1087
+ const paths = congelarProfundo({
1088
+ ledger: config.ledgerPath, lock: config.lockPath, snapshot: config.snapshotPath,
1089
+ });
1090
+ return Object.freeze({
1091
+ append: (entrada) => append(config, entrada),
1092
+ isAppendReceipt: (receipt) => APPEND_RECEIPTS.has(receipt),
1093
+ isAuthorityReceipt: (receipt) => AUTHORITY_RECEIPTS.has(receipt),
1094
+ paths,
1095
+ read: () => conLock(config.lockPath, () => leerVerificado(config)),
1096
+ readAuthority: () => conLock(config.lockPath, () => leerAutoridad(config)),
1097
+ recover: () => conLock(config.lockPath, () => leerVerificado(config)),
1098
+ });
1099
+ }
1100
+
1101
+ function crearAuthorityWriter(config) {
1102
+ return Object.freeze({
1103
+ inspect: (action) => inspect(config, action),
1104
+ transact: (action) => transact(config, action),
1105
+ });
1106
+ }
1107
+
1108
+ function createBuiltInKernelRuntime({
1109
+ receipt, workspaceRoot, signerKeyId, signerPublicKeyDigest,
1110
+ }) {
1111
+ const validators = getContractValidators();
1112
+ validarBackendArchivos();
1113
+ const config = {
1114
+ receipt, workspaceRoot, signerKeyId, signerPublicKeyDigest,
1115
+ anchorPath: receipt.anchorPath,
1116
+ };
1117
+ Object.assign(config, cargarMaterial(config));
1118
+ config.streamId = config.pin.streamId;
1119
+ Object.assign(config, crearPaths(workspaceRoot, config.streamId));
1120
+ const anchor = leerAnchor(config);
1121
+ validarVigencia(receipt, anchor, new Date().toISOString());
1122
+ const integrityLedger = crearLedger(config);
1123
+ integrityLedger.read();
1124
+ const authorityWriter = crearAuthorityWriter(config);
1125
+ const contexts = createPolicyContextProvider(authorityWriter);
1126
+ const stores = createSingleUseStore(authorityWriter);
1127
+ const singleUseStore = stores.publicStore;
1128
+ const gates = createGateEngine(authorityWriter, singleUseStore, workspaceRoot);
1129
+ const policyBroker = createPolicyBroker({
1130
+ compileBundle: compilarPolicyBundle,
1131
+ contextReader: contexts.authorizationContextReader,
1132
+ gateReader: gates.authorizationGateReader,
1133
+ grantIssuer: stores.authorizationGrantIssuer,
1134
+ isVerifiedOperation: validators.isVerifiedOperation,
1135
+ workspaceRoot,
1136
+ writer: authorityWriter,
1137
+ });
1138
+ return congelarProfundo({
1139
+ gateEngine: gates.publicGateEngine, integrityLedger,
1140
+ policyContextProvider: contexts.publicProvider,
1141
+ policyBroker,
1142
+ providers: structuredClone(receipt.providers),
1143
+ singleUseStore,
1144
+ });
1145
+ }
1146
+
1147
+ module.exports = { createBuiltInKernelRuntime };