theus-cli-linux-x64 1.2.2 → 1.4.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 (759) hide show
  1. package/README.md +50 -11
  2. package/RELEASE.json +6 -6
  3. package/bin/theus +0 -0
  4. package/package.json +1 -1
  5. package/vendor/higiene-motor/PARCHES.md +244 -0
  6. package/vendor/higiene-motor/audit_dir.py +166 -0
  7. package/vendor/higiene-motor/audit_lib.py +333 -0
  8. package/vendor/higiene-motor/audit_website.py +635 -0
  9. package/vendor/higiene-motor/av_meta.py +498 -0
  10. package/vendor/higiene-motor/check_staged.py +71 -0
  11. package/vendor/higiene-motor/clean_ctrlregen.py +212 -0
  12. package/vendor/higiene-motor/clean_file.py +237 -0
  13. package/vendor/higiene-motor/clean_image.py +218 -0
  14. package/vendor/higiene-motor/clean_staged.py +143 -0
  15. package/vendor/higiene-motor/clean_text.py +108 -0
  16. package/vendor/higiene-motor/common.py +486 -0
  17. package/vendor/higiene-motor/container_meta.py +2522 -0
  18. package/vendor/higiene-motor/detect_gumbel.py +308 -0
  19. package/vendor/higiene-motor/detect_text_watermark.py +613 -0
  20. package/vendor/higiene-motor/format_dispatch.py +157 -0
  21. package/vendor/higiene-motor/hook_written_file.py +253 -0
  22. package/vendor/higiene-motor/image_meta.py +2171 -0
  23. package/vendor/higiene-motor/inspect_file.py +138 -0
  24. package/vendor/higiene-motor/inspect_image.py +72 -0
  25. package/vendor/higiene-motor/inspect_text.py +86 -0
  26. package/vendor/higiene-motor/markdiffusion_harness.py +533 -0
  27. package/vendor/higiene-motor/rewrite_text.py +737 -0
  28. package/vendor/higiene-motor/score_stylometry.py +460 -0
  29. package/vendor/higiene-motor/score_synthid.py +165 -0
  30. package/vendor/higiene-motor/server.py +1059 -0
  31. package/vendor/higiene-motor/synthid_score_server.py +176 -0
  32. package/vendor/higiene-motor/text_detectors.py +433 -0
  33. package/vendor/higiene-motor/text_unicode.py +730 -0
  34. package/vendor/theus-arsenal/.arsenal-nombres-ola2.json +0 -6
  35. package/vendor/theus-arsenal/.arsenal-nombres-ola3.json +0 -72
  36. package/vendor/theus-arsenal/.mailmap +0 -2
  37. package/vendor/theus-arsenal/.theus-plugin/marketplace.json +0 -25
  38. package/vendor/theus-arsenal/.theus-plugin/plugin.json +0 -20
  39. package/vendor/theus-arsenal/AUTHORS.md +0 -8
  40. package/vendor/theus-arsenal/CLEANROOM_REPLACEMENT_PLAN.md +0 -11
  41. package/vendor/theus-arsenal/LICENSE +0 -26
  42. package/vendor/theus-arsenal/PROVENANCE.md +0 -9
  43. package/vendor/theus-arsenal/README.md +0 -41
  44. package/vendor/theus-arsenal/THIRD_PARTY.md +0 -80
  45. package/vendor/theus-arsenal/agents/actualizador-docs.md +0 -123
  46. package/vendor/theus-arsenal/agents/analista-comentarios.md +0 -53
  47. package/vendor/theus-arsenal/agents/analista-conversaciones.md +0 -60
  48. package/vendor/theus-arsenal/agents/analista-tests-pr.md +0 -53
  49. package/vendor/theus-arsenal/agents/analista-tipos.md +0 -49
  50. package/vendor/theus-arsenal/agents/arquitecto-accesibilidad.md +0 -148
  51. package/vendor/theus-arsenal/agents/arquitecto-codigo.md +0 -79
  52. package/vendor/theus-arsenal/agents/arquitecto-homelab.md +0 -90
  53. package/vendor/theus-arsenal/agents/arquitecto-redes.md +0 -116
  54. package/vendor/theus-arsenal/agents/arquitecto-sistemas.md +0 -219
  55. package/vendor/theus-arsenal/agents/bifurcador-opensource.md +0 -206
  56. package/vendor/theus-arsenal/agents/cazador-fallos-silenciosos.md +0 -58
  57. package/vendor/theus-arsenal/agents/consultor-documentacion.md +0 -76
  58. package/vendor/theus-arsenal/agents/diagnosticador-redes.md +0 -135
  59. package/vendor/theus-arsenal/agents/ejecutor-e2e.md +0 -96
  60. package/vendor/theus-arsenal/agents/empaquetador-opensource.md +0 -257
  61. package/vendor/theus-arsenal/agents/escaner-secretos.md +0 -196
  62. package/vendor/theus-arsenal/agents/especialista-seo.md +0 -70
  63. package/vendor/theus-arsenal/agents/estratega-marketing.md +0 -158
  64. package/vendor/theus-arsenal/agents/evaluador-agentes.md +0 -214
  65. package/vendor/theus-arsenal/agents/evaluador-harness.md +0 -217
  66. package/vendor/theus-arsenal/agents/explorador-codigo.md +0 -79
  67. package/vendor/theus-arsenal/agents/extractor-specs.md +0 -214
  68. package/vendor/theus-arsenal/agents/generador-harness.md +0 -139
  69. package/vendor/theus-arsenal/agents/guia-tdd.md +0 -99
  70. package/vendor/theus-arsenal/agents/jefe-de-gabinete.md +0 -162
  71. package/vendor/theus-arsenal/agents/limpiador-refactors.md +0 -93
  72. package/vendor/theus-arsenal/agents/optimizador-rendimiento.md +0 -454
  73. package/vendor/theus-arsenal/agents/planificador-harness.md +0 -107
  74. package/vendor/theus-arsenal/agents/planificador.md +0 -221
  75. package/vendor/theus-arsenal/agents/resolutor-apps-harmonyos.md +0 -181
  76. package/vendor/theus-arsenal/agents/resolutor-builds-cpp.md +0 -98
  77. package/vendor/theus-arsenal/agents/resolutor-builds-dart.md +0 -209
  78. package/vendor/theus-arsenal/agents/resolutor-builds-django.md +0 -253
  79. package/vendor/theus-arsenal/agents/resolutor-builds-go.md +0 -102
  80. package/vendor/theus-arsenal/agents/resolutor-builds-java.md +0 -274
  81. package/vendor/theus-arsenal/agents/resolutor-builds-kotlin.md +0 -128
  82. package/vendor/theus-arsenal/agents/resolutor-builds-pytorch.md +0 -128
  83. package/vendor/theus-arsenal/agents/resolutor-builds-react.md +0 -214
  84. package/vendor/theus-arsenal/agents/resolutor-builds-rust.md +0 -156
  85. package/vendor/theus-arsenal/agents/resolutor-builds-swift.md +0 -169
  86. package/vendor/theus-arsenal/agents/resolutor-builds.md +0 -122
  87. package/vendor/theus-arsenal/agents/revisor-bd.md +0 -97
  88. package/vendor/theus-arsenal/agents/revisor-codigo.md +0 -291
  89. package/vendor/theus-arsenal/agents/revisor-config-red.md +0 -116
  90. package/vendor/theus-arsenal/agents/revisor-cpp.md +0 -80
  91. package/vendor/theus-arsenal/agents/revisor-csharp.md +0 -109
  92. package/vendor/theus-arsenal/agents/revisor-django.md +0 -168
  93. package/vendor/theus-arsenal/agents/revisor-fastapi.md +0 -82
  94. package/vendor/theus-arsenal/agents/revisor-flutter.md +0 -251
  95. package/vendor/theus-arsenal/agents/revisor-go.md +0 -84
  96. package/vendor/theus-arsenal/agents/revisor-java.md +0 -192
  97. package/vendor/theus-arsenal/agents/revisor-kotlin.md +0 -171
  98. package/vendor/theus-arsenal/agents/revisor-ml.md +0 -159
  99. package/vendor/theus-arsenal/agents/revisor-php.md +0 -108
  100. package/vendor/theus-arsenal/agents/revisor-python.md +0 -106
  101. package/vendor/theus-arsenal/agents/revisor-react.md +0 -166
  102. package/vendor/theus-arsenal/agents/revisor-rust.md +0 -102
  103. package/vendor/theus-arsenal/agents/revisor-seguridad.md +0 -116
  104. package/vendor/theus-arsenal/agents/revisor-software-clinico.md +0 -95
  105. package/vendor/theus-arsenal/agents/revisor-swift.md +0 -115
  106. package/vendor/theus-arsenal/agents/revisor-typescript.md +0 -123
  107. package/vendor/theus-arsenal/agents/revisor-vue.md +0 -205
  108. package/vendor/theus-arsenal/agents/simplificador-codigo.md +0 -55
  109. package/vendor/theus-arsenal/commands/actualizar-docs.md +0 -88
  110. package/vendor/theus-arsenal/commands/actualizar-mapas-codigo.md +0 -78
  111. package/vendor/theus-arsenal/commands/aprender-evaluar.md +0 -109
  112. package/vendor/theus-arsenal/commands/aprender.md +0 -74
  113. package/vendor/theus-arsenal/commands/arreglar-build.md +0 -66
  114. package/vendor/theus-arsenal/commands/bucle-multiperspectiva.md +0 -153
  115. package/vendor/theus-arsenal/commands/build-cpp.md +0 -173
  116. package/vendor/theus-arsenal/commands/build-flutter.md +0 -164
  117. package/vendor/theus-arsenal/commands/build-go.md +0 -183
  118. package/vendor/theus-arsenal/commands/build-gradle.md +0 -75
  119. package/vendor/theus-arsenal/commands/build-kotlin.md +0 -176
  120. package/vendor/theus-arsenal/commands/build-react.md +0 -187
  121. package/vendor/theus-arsenal/commands/build-rust.md +0 -187
  122. package/vendor/theus-arsenal/commands/campana-marketing.md +0 -125
  123. package/vendor/theus-arsenal/commands/checkpoint.md +0 -78
  124. package/vendor/theus-arsenal/commands/cobertura-tests.md +0 -73
  125. package/vendor/theus-arsenal/commands/configurar-gestor-paquetes.md +0 -86
  126. package/vendor/theus-arsenal/commands/consulta.md +0 -164
  127. package/vendor/theus-arsenal/commands/control-calidad.md +0 -50
  128. package/vendor/theus-arsenal/commands/crear-skill.md +0 -77
  129. package/vendor/theus-arsenal/commands/enrutar-modelo.md +0 -30
  130. package/vendor/theus-arsenal/commands/epica-desbloquear.md +0 -17
  131. package/vendor/theus-arsenal/commands/epica-descomponer.md +0 -22
  132. package/vendor/theus-arsenal/commands/epica-publicar.md +0 -21
  133. package/vendor/theus-arsenal/commands/epica-reclamar.md +0 -25
  134. package/vendor/theus-arsenal/commands/epica-revisar.md +0 -22
  135. package/vendor/theus-arsenal/commands/epica-sincronizar.md +0 -21
  136. package/vendor/theus-arsenal/commands/epica-validar.md +0 -21
  137. package/vendor/theus-arsenal/commands/evolucionar.md +0 -176
  138. package/vendor/theus-arsenal/commands/funcionalidad.md +0 -49
  139. package/vendor/theus-arsenal/commands/guardar-sesion.md +0 -278
  140. package/vendor/theus-arsenal/commands/harness-build.md +0 -111
  141. package/vendor/theus-arsenal/commands/harness-diseno.md +0 -46
  142. package/vendor/theus-arsenal/commands/informe-costos.md +0 -90
  143. package/vendor/theus-arsenal/commands/iniciar-bucle.md +0 -36
  144. package/vendor/theus-arsenal/commands/instintos-estado.md +0 -53
  145. package/vendor/theus-arsenal/commands/instintos-exportar.md +0 -69
  146. package/vendor/theus-arsenal/commands/instintos-importar.md +0 -120
  147. package/vendor/theus-arsenal/commands/lienzo-planes.md +0 -48
  148. package/vendor/theus-arsenal/commands/limpiar-refactor.md +0 -84
  149. package/vendor/theus-arsenal/commands/modo-seguro.md +0 -96
  150. package/vendor/theus-arsenal/commands/orq-agregar-funcionalidad.md +0 -36
  151. package/vendor/theus-arsenal/commands/orq-cambiar-funcionalidad.md +0 -38
  152. package/vendor/theus-arsenal/commands/orq-construir-mvp.md +0 -36
  153. package/vendor/theus-arsenal/commands/orq-corregir-defecto.md +0 -40
  154. package/vendor/theus-arsenal/commands/orq-refinar-codigo.md +0 -44
  155. package/vendor/theus-arsenal/commands/orq-revisar.md +0 -135
  156. package/vendor/theus-arsenal/commands/plan-prd.md +0 -160
  157. package/vendor/theus-arsenal/commands/plan.md +0 -198
  158. package/vendor/theus-arsenal/commands/podar.md +0 -31
  159. package/vendor/theus-arsenal/commands/pr.md +0 -181
  160. package/vendor/theus-arsenal/commands/promover.md +0 -41
  161. package/vendor/theus-arsenal/commands/proyectos.md +0 -33
  162. package/vendor/theus-arsenal/commands/prp-commit.md +0 -112
  163. package/vendor/theus-arsenal/commands/prp-implementar.md +0 -385
  164. package/vendor/theus-arsenal/commands/prp-planificar.md +0 -501
  165. package/vendor/theus-arsenal/commands/reanudar-sesion.md +0 -160
  166. package/vendor/theus-arsenal/commands/revisar-codigo.md +0 -289
  167. package/vendor/theus-arsenal/commands/revisar-cpp.md +0 -132
  168. package/vendor/theus-arsenal/commands/revisar-fastapi.md +0 -39
  169. package/vendor/theus-arsenal/commands/revisar-flutter.md +0 -115
  170. package/vendor/theus-arsenal/commands/revisar-go.md +0 -148
  171. package/vendor/theus-arsenal/commands/revisar-kotlin.md +0 -140
  172. package/vendor/theus-arsenal/commands/revisar-pr.md +0 -37
  173. package/vendor/theus-arsenal/commands/revisar-python.md +0 -297
  174. package/vendor/theus-arsenal/commands/revisar-react.md +0 -170
  175. package/vendor/theus-arsenal/commands/revisar-rust.md +0 -142
  176. package/vendor/theus-arsenal/commands/revisar-vue.md +0 -174
  177. package/vendor/theus-arsenal/commands/salud-skills.md +0 -52
  178. package/vendor/theus-arsenal/commands/sesiones.md +0 -345
  179. package/vendor/theus-arsenal/commands/test-cpp.md +0 -252
  180. package/vendor/theus-arsenal/commands/test-flutter.md +0 -143
  181. package/vendor/theus-arsenal/commands/test-go.md +0 -268
  182. package/vendor/theus-arsenal/commands/test-kotlin.md +0 -312
  183. package/vendor/theus-arsenal/commands/test-react.md +0 -265
  184. package/vendor/theus-arsenal/commands/test-rust.md +0 -309
  185. package/vendor/theus-arsenal/commands/vigilancia-canary.md +0 -43
  186. package/vendor/theus-arsenal/hooks/hooks.json +0 -274
  187. package/vendor/theus-arsenal/package.json +0 -6
  188. package/vendor/theus-arsenal/rules/angular/coding-style.md +0 -182
  189. package/vendor/theus-arsenal/rules/angular/hooks.md +0 -25
  190. package/vendor/theus-arsenal/rules/angular/patterns.md +0 -249
  191. package/vendor/theus-arsenal/rules/angular/security.md +0 -87
  192. package/vendor/theus-arsenal/rules/angular/testing.md +0 -164
  193. package/vendor/theus-arsenal/rules/arkts/coding-style.md +0 -153
  194. package/vendor/theus-arsenal/rules/arkts/hooks.md +0 -80
  195. package/vendor/theus-arsenal/rules/arkts/patterns.md +0 -236
  196. package/vendor/theus-arsenal/rules/arkts/security.md +0 -141
  197. package/vendor/theus-arsenal/rules/arkts/testing.md +0 -126
  198. package/vendor/theus-arsenal/rules/common/agents.md +0 -49
  199. package/vendor/theus-arsenal/rules/common/code-review.md +0 -123
  200. package/vendor/theus-arsenal/rules/common/coding-style.md +0 -90
  201. package/vendor/theus-arsenal/rules/common/development-workflow.md +0 -44
  202. package/vendor/theus-arsenal/rules/common/git-workflow.md +0 -24
  203. package/vendor/theus-arsenal/rules/common/hooks.md +0 -32
  204. package/vendor/theus-arsenal/rules/common/patterns.md +0 -31
  205. package/vendor/theus-arsenal/rules/common/performance.md +0 -53
  206. package/vendor/theus-arsenal/rules/common/security.md +0 -29
  207. package/vendor/theus-arsenal/rules/common/testing.md +0 -57
  208. package/vendor/theus-arsenal/rules/cpp/coding-style.md +0 -44
  209. package/vendor/theus-arsenal/rules/cpp/hooks.md +0 -39
  210. package/vendor/theus-arsenal/rules/cpp/patterns.md +0 -51
  211. package/vendor/theus-arsenal/rules/cpp/security.md +0 -51
  212. package/vendor/theus-arsenal/rules/cpp/testing.md +0 -44
  213. package/vendor/theus-arsenal/rules/csharp/coding-style.md +0 -72
  214. package/vendor/theus-arsenal/rules/csharp/hooks.md +0 -25
  215. package/vendor/theus-arsenal/rules/csharp/patterns.md +0 -50
  216. package/vendor/theus-arsenal/rules/csharp/security.md +0 -58
  217. package/vendor/theus-arsenal/rules/csharp/testing.md +0 -50
  218. package/vendor/theus-arsenal/rules/dart/coding-style.md +0 -159
  219. package/vendor/theus-arsenal/rules/dart/hooks.md +0 -68
  220. package/vendor/theus-arsenal/rules/dart/patterns.md +0 -261
  221. package/vendor/theus-arsenal/rules/dart/security.md +0 -135
  222. package/vendor/theus-arsenal/rules/dart/testing.md +0 -215
  223. package/vendor/theus-arsenal/rules/fsharp/coding-style.md +0 -112
  224. package/vendor/theus-arsenal/rules/fsharp/hooks.md +0 -26
  225. package/vendor/theus-arsenal/rules/fsharp/patterns.md +0 -111
  226. package/vendor/theus-arsenal/rules/fsharp/security.md +0 -76
  227. package/vendor/theus-arsenal/rules/fsharp/testing.md +0 -62
  228. package/vendor/theus-arsenal/rules/golang/coding-style.md +0 -32
  229. package/vendor/theus-arsenal/rules/golang/hooks.md +0 -17
  230. package/vendor/theus-arsenal/rules/golang/patterns.md +0 -45
  231. package/vendor/theus-arsenal/rules/golang/security.md +0 -34
  232. package/vendor/theus-arsenal/rules/golang/testing.md +0 -31
  233. package/vendor/theus-arsenal/rules/java/coding-style.md +0 -114
  234. package/vendor/theus-arsenal/rules/java/hooks.md +0 -18
  235. package/vendor/theus-arsenal/rules/java/patterns.md +0 -147
  236. package/vendor/theus-arsenal/rules/java/security.md +0 -101
  237. package/vendor/theus-arsenal/rules/java/testing.md +0 -133
  238. package/vendor/theus-arsenal/rules/kotlin/coding-style.md +0 -86
  239. package/vendor/theus-arsenal/rules/kotlin/hooks.md +0 -17
  240. package/vendor/theus-arsenal/rules/kotlin/patterns.md +0 -146
  241. package/vendor/theus-arsenal/rules/kotlin/security.md +0 -82
  242. package/vendor/theus-arsenal/rules/kotlin/testing.md +0 -128
  243. package/vendor/theus-arsenal/rules/nuxt/coding-style.md +0 -47
  244. package/vendor/theus-arsenal/rules/nuxt/hooks.md +0 -39
  245. package/vendor/theus-arsenal/rules/nuxt/patterns.md +0 -54
  246. package/vendor/theus-arsenal/rules/nuxt/security.md +0 -48
  247. package/vendor/theus-arsenal/rules/nuxt/testing.md +0 -49
  248. package/vendor/theus-arsenal/rules/php/coding-style.md +0 -40
  249. package/vendor/theus-arsenal/rules/php/hooks.md +0 -24
  250. package/vendor/theus-arsenal/rules/php/patterns.md +0 -33
  251. package/vendor/theus-arsenal/rules/php/security.md +0 -37
  252. package/vendor/theus-arsenal/rules/php/testing.md +0 -38
  253. package/vendor/theus-arsenal/rules/python/coding-style.md +0 -42
  254. package/vendor/theus-arsenal/rules/python/fastapi.md +0 -58
  255. package/vendor/theus-arsenal/rules/python/hooks.md +0 -19
  256. package/vendor/theus-arsenal/rules/python/patterns.md +0 -39
  257. package/vendor/theus-arsenal/rules/python/security.md +0 -30
  258. package/vendor/theus-arsenal/rules/python/testing.md +0 -38
  259. package/vendor/theus-arsenal/rules/react/coding-style.md +0 -109
  260. package/vendor/theus-arsenal/rules/react/hooks.md +0 -187
  261. package/vendor/theus-arsenal/rules/react/patterns.md +0 -194
  262. package/vendor/theus-arsenal/rules/react/security.md +0 -180
  263. package/vendor/theus-arsenal/rules/react/testing.md +0 -208
  264. package/vendor/theus-arsenal/rules/react-native/accessibility.md +0 -55
  265. package/vendor/theus-arsenal/rules/react-native/coding-style.md +0 -71
  266. package/vendor/theus-arsenal/rules/react-native/hooks.md +0 -28
  267. package/vendor/theus-arsenal/rules/react-native/patterns.md +0 -88
  268. package/vendor/theus-arsenal/rules/react-native/performance.md +0 -45
  269. package/vendor/theus-arsenal/rules/react-native/production-readiness.md +0 -51
  270. package/vendor/theus-arsenal/rules/react-native/security.md +0 -43
  271. package/vendor/theus-arsenal/rules/react-native/testing.md +0 -52
  272. package/vendor/theus-arsenal/rules/ruby/coding-style.md +0 -46
  273. package/vendor/theus-arsenal/rules/ruby/hooks.md +0 -37
  274. package/vendor/theus-arsenal/rules/ruby/patterns.md +0 -44
  275. package/vendor/theus-arsenal/rules/ruby/security.md +0 -51
  276. package/vendor/theus-arsenal/rules/ruby/testing.md +0 -51
  277. package/vendor/theus-arsenal/rules/rust/coding-style.md +0 -151
  278. package/vendor/theus-arsenal/rules/rust/hooks.md +0 -16
  279. package/vendor/theus-arsenal/rules/rust/patterns.md +0 -168
  280. package/vendor/theus-arsenal/rules/rust/security.md +0 -141
  281. package/vendor/theus-arsenal/rules/rust/testing.md +0 -154
  282. package/vendor/theus-arsenal/rules/swift/coding-style.md +0 -47
  283. package/vendor/theus-arsenal/rules/swift/hooks.md +0 -20
  284. package/vendor/theus-arsenal/rules/swift/patterns.md +0 -66
  285. package/vendor/theus-arsenal/rules/swift/security.md +0 -33
  286. package/vendor/theus-arsenal/rules/swift/testing.md +0 -45
  287. package/vendor/theus-arsenal/rules/typescript/coding-style.md +0 -199
  288. package/vendor/theus-arsenal/rules/typescript/hooks.md +0 -22
  289. package/vendor/theus-arsenal/rules/typescript/patterns.md +0 -52
  290. package/vendor/theus-arsenal/rules/typescript/security.md +0 -28
  291. package/vendor/theus-arsenal/rules/typescript/testing.md +0 -18
  292. package/vendor/theus-arsenal/rules/vue/coding-style.md +0 -54
  293. package/vendor/theus-arsenal/rules/vue/hooks.md +0 -45
  294. package/vendor/theus-arsenal/rules/vue/patterns.md +0 -56
  295. package/vendor/theus-arsenal/rules/vue/security.md +0 -46
  296. package/vendor/theus-arsenal/rules/vue/testing.md +0 -53
  297. package/vendor/theus-arsenal/rules/web/coding-style.md +0 -108
  298. package/vendor/theus-arsenal/rules/web/design-quality.md +0 -75
  299. package/vendor/theus-arsenal/rules/web/hooks.md +0 -141
  300. package/vendor/theus-arsenal/rules/web/patterns.md +0 -91
  301. package/vendor/theus-arsenal/rules/web/performance.md +0 -76
  302. package/vendor/theus-arsenal/rules/web/security.md +0 -69
  303. package/vendor/theus-arsenal/rules/web/testing.md +0 -67
  304. package/vendor/theus-arsenal/scripts/hooks/bash-hook-dispatcher.js +0 -192
  305. package/vendor/theus-arsenal/scripts/hooks/block-no-verify.js +0 -556
  306. package/vendor/theus-arsenal/scripts/hooks/check-console-log.js +0 -92
  307. package/vendor/theus-arsenal/scripts/hooks/check-hook-enabled.js +0 -16
  308. package/vendor/theus-arsenal/scripts/hooks/config-protection.js +0 -171
  309. package/vendor/theus-arsenal/scripts/hooks/design-quality-check.js +0 -132
  310. package/vendor/theus-arsenal/scripts/hooks/doc-file-warning.js +0 -110
  311. package/vendor/theus-arsenal/scripts/hooks/modo-seguro.js +0 -158
  312. package/vendor/theus-arsenal/scripts/hooks/notificacion-escritorio.js +0 -208
  313. package/vendor/theus-arsenal/scripts/hooks/plugin-hook-bootstrap.js +0 -280
  314. package/vendor/theus-arsenal/scripts/hooks/post-bash-command-log.js +0 -87
  315. package/vendor/theus-arsenal/scripts/hooks/post-bash-dispatcher.js +0 -24
  316. package/vendor/theus-arsenal/scripts/hooks/post-bash-pr-created.js +0 -60
  317. package/vendor/theus-arsenal/scripts/hooks/post-edit-accumulator.js +0 -94
  318. package/vendor/theus-arsenal/scripts/hooks/post-edit-console-warn.js +0 -54
  319. package/vendor/theus-arsenal/scripts/hooks/post-edit-format.js +0 -110
  320. package/vendor/theus-arsenal/scripts/hooks/post-edit-typecheck.js +0 -98
  321. package/vendor/theus-arsenal/scripts/hooks/pre-bash-commit-quality.js +0 -447
  322. package/vendor/theus-arsenal/scripts/hooks/pre-bash-dev-server-block.js +0 -232
  323. package/vendor/theus-arsenal/scripts/hooks/pre-bash-dispatcher.js +0 -27
  324. package/vendor/theus-arsenal/scripts/hooks/pre-compact.js +0 -101
  325. package/vendor/theus-arsenal/scripts/hooks/pretooluse-visible-output.js +0 -49
  326. package/vendor/theus-arsenal/scripts/hooks/quality-gate.js +0 -168
  327. package/vendor/theus-arsenal/scripts/hooks/run-with-flags.js +0 -271
  328. package/vendor/theus-arsenal/scripts/hooks/salud-mcp.js +0 -749
  329. package/vendor/theus-arsenal/scripts/hooks/seguimiento-costos.js +0 -161
  330. package/vendor/theus-arsenal/scripts/hooks/session-end.js +0 -340
  331. package/vendor/theus-arsenal/scripts/hooks/session-start.js +0 -906
  332. package/vendor/theus-arsenal/scripts/hooks/stop-format-typecheck.js +0 -263
  333. package/vendor/theus-arsenal/scripts/hooks/suggest-compact.js +0 -286
  334. package/vendor/theus-arsenal/scripts/hooks/theus-context-monitor.js +0 -289
  335. package/vendor/theus-arsenal/scripts/hooks/verificacion-factual.js +0 -1278
  336. package/vendor/theus-arsenal/scripts/lib/agent-data-home.js +0 -96
  337. package/vendor/theus-arsenal/scripts/lib/cost-estimate.js +0 -66
  338. package/vendor/theus-arsenal/scripts/lib/hook-flags.js +0 -79
  339. package/vendor/theus-arsenal/scripts/lib/llm-summary.js +0 -185
  340. package/vendor/theus-arsenal/scripts/lib/loopback-guard.js +0 -54
  341. package/vendor/theus-arsenal/scripts/lib/observer-sessions.js +0 -237
  342. package/vendor/theus-arsenal/scripts/lib/package-manager.d.ts +0 -120
  343. package/vendor/theus-arsenal/scripts/lib/package-manager.js +0 -434
  344. package/vendor/theus-arsenal/scripts/lib/path-safety.js +0 -86
  345. package/vendor/theus-arsenal/scripts/lib/plan-canvas/markdown.js +0 -285
  346. package/vendor/theus-arsenal/scripts/lib/plan-canvas/sdk.js +0 -238
  347. package/vendor/theus-arsenal/scripts/lib/plan-canvas/server.js +0 -534
  348. package/vendor/theus-arsenal/scripts/lib/plan-canvas/sessions.js +0 -274
  349. package/vendor/theus-arsenal/scripts/lib/plan-canvas/ui.js +0 -546
  350. package/vendor/theus-arsenal/scripts/lib/project-detect.js +0 -451
  351. package/vendor/theus-arsenal/scripts/lib/resolve-formatter.js +0 -193
  352. package/vendor/theus-arsenal/scripts/lib/resolve-theus-root.js +0 -101
  353. package/vendor/theus-arsenal/scripts/lib/session-aliases.d.ts +0 -138
  354. package/vendor/theus-arsenal/scripts/lib/session-aliases.js +0 -483
  355. package/vendor/theus-arsenal/scripts/lib/session-bridge.js +0 -155
  356. package/vendor/theus-arsenal/scripts/lib/session-manager.d.ts +0 -137
  357. package/vendor/theus-arsenal/scripts/lib/session-manager.js +0 -555
  358. package/vendor/theus-arsenal/scripts/lib/shell-split.js +0 -86
  359. package/vendor/theus-arsenal/scripts/lib/shell-substitution.js +0 -501
  360. package/vendor/theus-arsenal/scripts/lib/skill-evolution/dashboard.js +0 -414
  361. package/vendor/theus-arsenal/scripts/lib/skill-evolution/health.js +0 -285
  362. package/vendor/theus-arsenal/scripts/lib/skill-evolution/index.js +0 -22
  363. package/vendor/theus-arsenal/scripts/lib/skill-evolution/provenance.js +0 -200
  364. package/vendor/theus-arsenal/scripts/lib/skill-evolution/tracker.js +0 -157
  365. package/vendor/theus-arsenal/scripts/lib/skill-evolution/versioning.js +0 -246
  366. package/vendor/theus-arsenal/scripts/lib/transcript-context.js +0 -232
  367. package/vendor/theus-arsenal/scripts/lib/utils.d.ts +0 -205
  368. package/vendor/theus-arsenal/scripts/lib/utils.js +0 -658
  369. package/vendor/theus-arsenal/scripts/plan-canvas.js +0 -341
  370. package/vendor/theus-arsenal/scripts/setup-package-manager.js +0 -46
  371. package/vendor/theus-arsenal/scripts/skills-health.js +0 -143
  372. package/vendor/theus-arsenal/skills/a11y-frontend/SKILL.md +0 -444
  373. package/vendor/theus-arsenal/skills/accesibilidad/SKILL.md +0 -144
  374. package/vendor/theus-arsenal/skills/acelerador-throughput-datos/SKILL.md +0 -72
  375. package/vendor/theus-arsenal/skills/agente-scraper-datos/SKILL.md +0 -771
  376. package/vendor/theus-arsenal/skills/analisis-plataformas-competencia/SKILL.md +0 -137
  377. package/vendor/theus-arsenal/skills/api-x/SKILL.md +0 -233
  378. package/vendor/theus-arsenal/skills/aprendizaje-continuo-v2/SKILL.md +0 -335
  379. package/vendor/theus-arsenal/skills/aprendizaje-continuo-v2/agents/observer-loop.sh +0 -374
  380. package/vendor/theus-arsenal/skills/aprendizaje-continuo-v2/agents/observer.md +0 -188
  381. package/vendor/theus-arsenal/skills/aprendizaje-continuo-v2/agents/session-guardian.sh +0 -153
  382. package/vendor/theus-arsenal/skills/aprendizaje-continuo-v2/agents/start-observer.sh +0 -253
  383. package/vendor/theus-arsenal/skills/aprendizaje-continuo-v2/config.json +0 -8
  384. package/vendor/theus-arsenal/skills/aprendizaje-continuo-v2/hooks/observe.sh +0 -594
  385. package/vendor/theus-arsenal/skills/aprendizaje-continuo-v2/scripts/detect-project.sh +0 -325
  386. package/vendor/theus-arsenal/skills/aprendizaje-continuo-v2/scripts/instinct-cli.py +0 -1918
  387. package/vendor/theus-arsenal/skills/aprendizaje-continuo-v2/scripts/lib/arsenal-dir.sh +0 -23
  388. package/vendor/theus-arsenal/skills/aprendizaje-continuo-v2/scripts/test_parse_instinct.py +0 -1420
  389. package/vendor/theus-arsenal/skills/arquitectura-hexagonal/SKILL.md +0 -275
  390. package/vendor/theus-arsenal/skills/arquitectura-limpia-android/SKILL.md +0 -340
  391. package/vendor/theus-arsenal/skills/arquitectura-pipelines-recomendacion/SKILL.md +0 -112
  392. package/vendor/theus-arsenal/skills/atlas-datos-prediccion/SKILL.md +0 -53
  393. package/vendor/theus-arsenal/skills/auditoria-arquitectura-agentes/SKILL.md +0 -257
  394. package/vendor/theus-arsenal/skills/auditoria-produccion/SKILL.md +0 -180
  395. package/vendor/theus-arsenal/skills/auditoria-rutas-clic/SKILL.md +0 -243
  396. package/vendor/theus-arsenal/skills/autoevaluacion-agente/SKILL.md +0 -180
  397. package/vendor/theus-arsenal/skills/autoevaluacion-agente/examples/high-score-example.md +0 -89
  398. package/vendor/theus-arsenal/skills/autoevaluacion-agente/examples/low-score-example.md +0 -87
  399. package/vendor/theus-arsenal/skills/autoevaluacion-agente/references/evaluation-criteria.md +0 -71
  400. package/vendor/theus-arsenal/skills/autoevaluacion-agente/references/hook-integration.md +0 -90
  401. package/vendor/theus-arsenal/skills/autoevaluacion-agente/scripts/evaluate.py +0 -409
  402. package/vendor/theus-arsenal/skills/autoevaluacion-agente/templates/evaluation-report.md +0 -86
  403. package/vendor/theus-arsenal/skills/automatizacion-ssh-netmiko/SKILL.md +0 -176
  404. package/vendor/theus-arsenal/skills/base-datos-pubmed/SKILL.md +0 -174
  405. package/vendor/theus-arsenal/skills/base-datos-uspto/SKILL.md +0 -173
  406. package/vendor/theus-arsenal/skills/benchmark/SKILL.md +0 -92
  407. package/vendor/theus-arsenal/skills/bitacora-crecimiento/SKILL.md +0 -120
  408. package/vendor/theus-arsenal/skills/bucle-verificacion/SKILL.md +0 -125
  409. package/vendor/theus-arsenal/skills/buscar-primero/SKILL.md +0 -184
  410. package/vendor/theus-arsenal/skills/busqueda-exa/SKILL.md +0 -111
  411. package/vendor/theus-arsenal/skills/cache-por-hash/SKILL.md +0 -160
  412. package/vendor/theus-arsenal/skills/campana-marketing/SKILL.md +0 -118
  413. package/vendor/theus-arsenal/skills/capacidad-producto/SKILL.md +0 -138
  414. package/vendor/theus-arsenal/skills/cazador-vulnerabilidades/SKILL.md +0 -104
  415. package/vendor/theus-arsenal/skills/compactacion-estrategica/SKILL.md +0 -115
  416. package/vendor/theus-arsenal/skills/comparador-baskets-prediccion/SKILL.md +0 -69
  417. package/vendor/theus-arsenal/skills/compras-energia/SKILL.md +0 -206
  418. package/vendor/theus-arsenal/skills/concurrencia-swift-6-2/SKILL.md +0 -224
  419. package/vendor/theus-arsenal/skills/consejo/SKILL.md +0 -201
  420. package/vendor/theus-arsenal/skills/construccion-harness-agentes/SKILL.md +0 -78
  421. package/vendor/theus-arsenal/skills/constructor-conectores/SKILL.md +0 -119
  422. package/vendor/theus-arsenal/skills/constructor-equipos/SKILL.md +0 -169
  423. package/vendor/theus-arsenal/skills/consulta-documentacion/SKILL.md +0 -92
  424. package/vendor/theus-arsenal/skills/consultas-genomicas-gget/SKILL.md +0 -170
  425. package/vendor/theus-arsenal/skills/contacto-inversores/SKILL.md +0 -95
  426. package/vendor/theus-arsenal/skills/corrutinas-flows-kotlin/SKILL.md +0 -284
  427. package/vendor/theus-arsenal/skills/creacion-video-remotion/SKILL.md +0 -46
  428. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/3d.md +0 -86
  429. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/animations.md +0 -29
  430. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/assets/charts-bar-chart.tsx +0 -173
  431. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/assets/text-animations-typewriter.tsx +0 -100
  432. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/assets/text-animations-word-highlight.tsx +0 -108
  433. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/assets.md +0 -78
  434. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/audio.md +0 -172
  435. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/calculate-metadata.md +0 -104
  436. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/can-decode.md +0 -75
  437. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/charts.md +0 -58
  438. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/compositions.md +0 -146
  439. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/display-captions.md +0 -126
  440. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/extract-frames.md +0 -229
  441. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/fonts.md +0 -152
  442. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/get-audio-duration.md +0 -58
  443. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/get-video-dimensions.md +0 -68
  444. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/get-video-duration.md +0 -58
  445. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/gifs.md +0 -138
  446. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/images.md +0 -130
  447. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/import-srt-captions.md +0 -67
  448. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/lottie.md +0 -67
  449. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/measuring-dom-nodes.md +0 -34
  450. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/measuring-text.md +0 -143
  451. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/sequencing.md +0 -106
  452. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/tailwind.md +0 -11
  453. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/text-animations.md +0 -20
  454. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/timing.md +0 -179
  455. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/transcribe-captions.md +0 -19
  456. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/transitions.md +0 -122
  457. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/trimming.md +0 -52
  458. package/vendor/theus-arsenal/skills/creacion-video-remotion/rules/videos.md +0 -171
  459. package/vendor/theus-arsenal/skills/cumplimiento-aduanero/SKILL.md +0 -270
  460. package/vendor/theus-arsenal/skills/cumplimiento-hipaa/SKILL.md +0 -78
  461. package/vendor/theus-arsenal/skills/datos-sensibles-salud/SKILL.md +0 -149
  462. package/vendor/theus-arsenal/skills/decimales-tokens-evm/SKILL.md +0 -128
  463. package/vendor/theus-arsenal/skills/decisiones-arquitectura/SKILL.md +0 -206
  464. package/vendor/theus-arsenal/skills/demos-ui/SKILL.md +0 -469
  465. package/vendor/theus-arsenal/skills/desarrollo-por-intencion/SKILL.md +0 -369
  466. package/vendor/theus-arsenal/skills/descubrimiento-marca/SKILL.md +0 -149
  467. package/vendor/theus-arsenal/skills/descubrimiento-marca/references/10_proposito-porque.md +0 -42
  468. package/vendor/theus-arsenal/skills/descubrimiento-marca/references/20_posicionamiento.md +0 -47
  469. package/vendor/theus-arsenal/skills/descubrimiento-marca/references/30_audiencia-nicho.md +0 -53
  470. package/vendor/theus-arsenal/skills/descubrimiento-marca/references/40_personalidad-arquetipo.md +0 -61
  471. package/vendor/theus-arsenal/skills/descubrimiento-marca/references/50_voz-tono.md +0 -62
  472. package/vendor/theus-arsenal/skills/descubrimiento-marca/references/60_narrativa-historia.md +0 -54
  473. package/vendor/theus-arsenal/skills/descubrimiento-marca/references/70_tension-fundador.md +0 -50
  474. package/vendor/theus-arsenal/skills/descubrimiento-marca/references/90_SINTESIS.md +0 -133
  475. package/vendor/theus-arsenal/skills/descubrimiento-plugins-laravel/SKILL.md +0 -230
  476. package/vendor/theus-arsenal/skills/destilado-reglas/SKILL.md +0 -263
  477. package/vendor/theus-arsenal/skills/destilado-reglas/scripts/scan-rules.sh +0 -58
  478. package/vendor/theus-arsenal/skills/destilado-reglas/scripts/scan-skills.sh +0 -129
  479. package/vendor/theus-arsenal/skills/diagnostico-bgp/SKILL.md +0 -170
  480. package/vendor/theus-arsenal/skills/direccion-estetica/SKILL.md +0 -220
  481. package/vendor/theus-arsenal/skills/direccion-estetica/references/taxonomia-generos.md +0 -89
  482. package/vendor/theus-arsenal/skills/diseno-api/SKILL.md +0 -522
  483. package/vendor/theus-arsenal/skills/diseno-liquid-glass/SKILL.md +0 -282
  484. package/vendor/theus-arsenal/skills/e2e-escritorio-windows/SKILL.md +0 -879
  485. package/vendor/theus-arsenal/skills/edicion-video/SKILL.md +0 -289
  486. package/vendor/theus-arsenal/skills/enfoque-producto/SKILL.md +0 -91
  487. package/vendor/theus-arsenal/skills/entornos-flox/SKILL.md +0 -493
  488. package/vendor/theus-arsenal/skills/estandares-codigo/SKILL.md +0 -548
  489. package/vendor/theus-arsenal/skills/estandares-cpp/SKILL.md +0 -727
  490. package/vendor/theus-arsenal/skills/estandares-java/SKILL.md +0 -389
  491. package/vendor/theus-arsenal/skills/estilo-legado/SKILL.md +0 -149
  492. package/vendor/theus-arsenal/skills/estructura-informes-competencia/SKILL.md +0 -95
  493. package/vendor/theus-arsenal/skills/evaluacion-academica/SKILL.md +0 -165
  494. package/vendor/theus-arsenal/skills/explorador-skills/SKILL.md +0 -129
  495. package/vendor/theus-arsenal/skills/flujo-git/SKILL.md +0 -714
  496. package/vendor/theus-arsenal/skills/flujo-ingenieria-ml/SKILL.md +0 -343
  497. package/vendor/theus-arsenal/skills/flujo-tdd/SKILL.md +0 -584
  498. package/vendor/theus-arsenal/skills/forja-personas/SKILL.md +0 -298
  499. package/vendor/theus-arsenal/skills/forja-personas/gacha.py +0 -224
  500. package/vendor/theus-arsenal/skills/forja-personas/gacha.sh +0 -5
  501. package/vendor/theus-arsenal/skills/forja-personas/references/avatar-style.md +0 -123
  502. package/vendor/theus-arsenal/skills/forja-personas/references/boundary-rules.md +0 -53
  503. package/vendor/theus-arsenal/skills/forja-personas/references/error-handling.md +0 -53
  504. package/vendor/theus-arsenal/skills/forja-personas/references/identity-tension.md +0 -48
  505. package/vendor/theus-arsenal/skills/forja-personas/references/naming-system.md +0 -39
  506. package/vendor/theus-arsenal/skills/forja-personas/references/output-template.md +0 -166
  507. package/vendor/theus-arsenal/skills/fundamentos-animacion/SKILL.md +0 -296
  508. package/vendor/theus-arsenal/skills/generacion-iconos-ios/SKILL.md +0 -156
  509. package/vendor/theus-arsenal/skills/generacion-iconos-ios/scripts/generate_icons.swift +0 -258
  510. package/vendor/theus-arsenal/skills/generacion-iconos-ios/scripts/iconify_gen.sh +0 -235
  511. package/vendor/theus-arsenal/skills/gestion-excepciones-logisticas/SKILL.md +0 -208
  512. package/vendor/theus-arsenal/skills/gestion-transportistas/SKILL.md +0 -204
  513. package/vendor/theus-arsenal/skills/guia-adopcion-ml/SKILL.md +0 -64
  514. package/vendor/theus-arsenal/skills/harness-agente-autonomo/SKILL.md +0 -252
  515. package/vendor/theus-arsenal/skills/harness-eval-clinico/SKILL.md +0 -212
  516. package/vendor/theus-arsenal/skills/harness-evaluacion/SKILL.md +0 -296
  517. package/vendor/theus-arsenal/skills/harness-generador-evaluador/SKILL.md +0 -254
  518. package/vendor/theus-arsenal/skills/homelab-diseno-red/SKILL.md +0 -120
  519. package/vendor/theus-arsenal/skills/homelab-dns-pihole/SKILL.md +0 -264
  520. package/vendor/theus-arsenal/skills/homelab-preparacion-red/SKILL.md +0 -144
  521. package/vendor/theus-arsenal/skills/homelab-segmentacion-vlan/SKILL.md +0 -307
  522. package/vendor/theus-arsenal/skills/homelab-vpn-wireguard/SKILL.md +0 -299
  523. package/vendor/theus-arsenal/skills/ingenieria-agentica/SKILL.md +0 -96
  524. package/vendor/theus-arsenal/skills/inspeccion-animaciones-blender/SKILL.md +0 -164
  525. package/vendor/theus-arsenal/skills/instaladores-python/SKILL.md +0 -820
  526. package/vendor/theus-arsenal/skills/integracion-jira/SKILL.md +0 -307
  527. package/vendor/theus-arsenal/skills/inteligencia-leads/SKILL.md +0 -312
  528. package/vendor/theus-arsenal/skills/inteligencia-leads/agents/agente-enriquecimiento.md +0 -87
  529. package/vendor/theus-arsenal/skills/inteligencia-leads/agents/mapeador-mutuos.md +0 -76
  530. package/vendor/theus-arsenal/skills/inteligencia-leads/agents/puntuador-senales.md +0 -60
  531. package/vendor/theus-arsenal/skills/inteligencia-leads/agents/redactor-outreach.md +0 -102
  532. package/vendor/theus-arsenal/skills/inteligencia-mercados-prediccion/SKILL.md +0 -53
  533. package/vendor/theus-arsenal/skills/introspeccion-agente/SKILL.md +0 -150
  534. package/vendor/theus-arsenal/skills/inventario-skills/SKILL.md +0 -194
  535. package/vendor/theus-arsenal/skills/inventario-skills/scripts/quick-diff.sh +0 -87
  536. package/vendor/theus-arsenal/skills/inventario-skills/scripts/save-results.sh +0 -57
  537. package/vendor/theus-arsenal/skills/inventario-skills/scripts/scan.sh +0 -170
  538. package/vendor/theus-arsenal/skills/investigacion-mercado/SKILL.md +0 -87
  539. package/vendor/theus-arsenal/skills/investigacion-oraculos-prediccion/SKILL.md +0 -59
  540. package/vendor/theus-arsenal/skills/investigacion-profunda/SKILL.md +0 -161
  541. package/vendor/theus-arsenal/skills/keccak256-nodejs/SKILL.md +0 -100
  542. package/vendor/theus-arsenal/skills/libro-decisiones-recursivo/SKILL.md +0 -82
  543. package/vendor/theus-arsenal/skills/lienzo-planes/SKILL.md +0 -111
  544. package/vendor/theus-arsenal/skills/limpieza-configuracion/SKILL.md +0 -116
  545. package/vendor/theus-arsenal/skills/logistica-inversa-devoluciones/SKILL.md +0 -241
  546. package/vendor/theus-arsenal/skills/manejo-errores/SKILL.md +0 -375
  547. package/vendor/theus-arsenal/skills/materiales-inversores/SKILL.md +0 -101
  548. package/vendor/theus-arsenal/skills/memoria-por-proyecto/SKILL.md +0 -170
  549. package/vendor/theus-arsenal/skills/memoria-por-proyecto/commands/forget.mjs +0 -44
  550. package/vendor/theus-arsenal/skills/memoria-por-proyecto/commands/info.mjs +0 -24
  551. package/vendor/theus-arsenal/skills/memoria-por-proyecto/commands/init.mjs +0 -152
  552. package/vendor/theus-arsenal/skills/memoria-por-proyecto/commands/list.mjs +0 -40
  553. package/vendor/theus-arsenal/skills/memoria-por-proyecto/commands/migrate.mjs +0 -214
  554. package/vendor/theus-arsenal/skills/memoria-por-proyecto/commands/resume.mjs +0 -36
  555. package/vendor/theus-arsenal/skills/memoria-por-proyecto/commands/save.mjs +0 -210
  556. package/vendor/theus-arsenal/skills/memoria-por-proyecto/commands/shared.mjs +0 -402
  557. package/vendor/theus-arsenal/skills/memoria-por-proyecto/hooks/session-start.mjs +0 -238
  558. package/vendor/theus-arsenal/skills/metodologia-benchmarks/SKILL.md +0 -131
  559. package/vendor/theus-arsenal/skills/migraciones-bd/SKILL.md +0 -430
  560. package/vendor/theus-arsenal/skills/modelos-fundacionales-en-dispositivo/SKILL.md +0 -244
  561. package/vendor/theus-arsenal/skills/modo-seguro/SKILL.md +0 -86
  562. package/vendor/theus-arsenal/skills/motion-avanzado/SKILL.md +0 -592
  563. package/vendor/theus-arsenal/skills/motor-de-contenido/SKILL.md +0 -136
  564. package/vendor/theus-arsenal/skills/no-conformidades-calidad/SKILL.md +0 -249
  565. package/vendor/theus-arsenal/skills/onboarding-codigo/SKILL.md +0 -244
  566. package/vendor/theus-arsenal/skills/operaciones-agentes-empresariales/SKILL.md +0 -51
  567. package/vendor/theus-arsenal/skills/operaciones-conocimiento/SKILL.md +0 -159
  568. package/vendor/theus-arsenal/skills/operaciones-correo/SKILL.md +0 -123
  569. package/vendor/theus-arsenal/skills/operaciones-facturacion/SKILL.md +0 -142
  570. package/vendor/theus-arsenal/skills/operaciones-flujo-proyectos/SKILL.md +0 -110
  571. package/vendor/theus-arsenal/skills/operaciones-github/SKILL.md +0 -143
  572. package/vendor/theus-arsenal/skills/operaciones-google-workspace/SKILL.md +0 -100
  573. package/vendor/theus-arsenal/skills/operaciones-investigacion/SKILL.md +0 -124
  574. package/vendor/theus-arsenal/skills/operaciones-mensajes/SKILL.md +0 -103
  575. package/vendor/theus-arsenal/skills/operaciones-terminal/SKILL.md +0 -110
  576. package/vendor/theus-arsenal/skills/optimizacion-benchmark/SKILL.md +0 -70
  577. package/vendor/theus-arsenal/skills/optimizacion-costos-llm/SKILL.md +0 -182
  578. package/vendor/theus-arsenal/skills/optimizador-conexiones/SKILL.md +0 -191
  579. package/vendor/theus-arsenal/skills/optimizador-paralelismo/SKILL.md +0 -75
  580. package/vendor/theus-arsenal/skills/optimizador-prompts/SKILL.md +0 -374
  581. package/vendor/theus-arsenal/skills/orq-agregar-funcionalidad/SKILL.md +0 -37
  582. package/vendor/theus-arsenal/skills/orq-cambiar-funcionalidad/SKILL.md +0 -36
  583. package/vendor/theus-arsenal/skills/orq-construir-mvp/SKILL.md +0 -38
  584. package/vendor/theus-arsenal/skills/orq-corregir-defecto/SKILL.md +0 -36
  585. package/vendor/theus-arsenal/skills/orq-pipeline/SKILL.md +0 -134
  586. package/vendor/theus-arsenal/skills/orq-refinar-codigo/SKILL.md +0 -49
  587. package/vendor/theus-arsenal/skills/orquestacion-equipos-agentes/SKILL.md +0 -117
  588. package/vendor/theus-arsenal/skills/pagos-agentes-x402/SKILL.md +0 -237
  589. package/vendor/theus-arsenal/skills/patrones-angular/SKILL.md +0 -153
  590. package/vendor/theus-arsenal/skills/patrones-angular/references/angular-animations.md +0 -160
  591. package/vendor/theus-arsenal/skills/patrones-angular/references/angular-aria.md +0 -410
  592. package/vendor/theus-arsenal/skills/patrones-angular/references/cli.md +0 -86
  593. package/vendor/theus-arsenal/skills/patrones-angular/references/component-harnesses.md +0 -59
  594. package/vendor/theus-arsenal/skills/patrones-angular/references/component-styling.md +0 -91
  595. package/vendor/theus-arsenal/skills/patrones-angular/references/components.md +0 -117
  596. package/vendor/theus-arsenal/skills/patrones-angular/references/creating-services.md +0 -97
  597. package/vendor/theus-arsenal/skills/patrones-angular/references/data-resolvers.md +0 -69
  598. package/vendor/theus-arsenal/skills/patrones-angular/references/define-routes.md +0 -67
  599. package/vendor/theus-arsenal/skills/patrones-angular/references/defining-providers.md +0 -72
  600. package/vendor/theus-arsenal/skills/patrones-angular/references/di-fundamentals.md +0 -120
  601. package/vendor/theus-arsenal/skills/patrones-angular/references/e2e-testing.md +0 -56
  602. package/vendor/theus-arsenal/skills/patrones-angular/references/effects.md +0 -83
  603. package/vendor/theus-arsenal/skills/patrones-angular/references/hierarchical-injectors.md +0 -43
  604. package/vendor/theus-arsenal/skills/patrones-angular/references/host-elements.md +0 -80
  605. package/vendor/theus-arsenal/skills/patrones-angular/references/injection-context.md +0 -63
  606. package/vendor/theus-arsenal/skills/patrones-angular/references/inputs.md +0 -101
  607. package/vendor/theus-arsenal/skills/patrones-angular/references/linked-signal.md +0 -59
  608. package/vendor/theus-arsenal/skills/patrones-angular/references/loading-strategies.md +0 -61
  609. package/vendor/theus-arsenal/skills/patrones-angular/references/mcp.md +0 -67
  610. package/vendor/theus-arsenal/skills/patrones-angular/references/navigate-to-routes.md +0 -69
  611. package/vendor/theus-arsenal/skills/patrones-angular/references/outputs.md +0 -86
  612. package/vendor/theus-arsenal/skills/patrones-angular/references/reactive-forms.md +0 -122
  613. package/vendor/theus-arsenal/skills/patrones-angular/references/rendering-strategies.md +0 -44
  614. package/vendor/theus-arsenal/skills/patrones-angular/references/resource.md +0 -77
  615. package/vendor/theus-arsenal/skills/patrones-angular/references/route-animations.md +0 -56
  616. package/vendor/theus-arsenal/skills/patrones-angular/references/route-guards.md +0 -52
  617. package/vendor/theus-arsenal/skills/patrones-angular/references/router-lifecycle.md +0 -45
  618. package/vendor/theus-arsenal/skills/patrones-angular/references/router-testing.md +0 -87
  619. package/vendor/theus-arsenal/skills/patrones-angular/references/show-routes-with-outlets.md +0 -68
  620. package/vendor/theus-arsenal/skills/patrones-angular/references/signal-forms.md +0 -795
  621. package/vendor/theus-arsenal/skills/patrones-angular/references/signals-overview.md +0 -94
  622. package/vendor/theus-arsenal/skills/patrones-angular/references/tailwind-css.md +0 -69
  623. package/vendor/theus-arsenal/skills/patrones-angular/references/template-driven-forms.md +0 -114
  624. package/vendor/theus-arsenal/skills/patrones-angular/references/testing-fundamentals.md +0 -65
  625. package/vendor/theus-arsenal/skills/patrones-animacion/SKILL.md +0 -432
  626. package/vendor/theus-arsenal/skills/patrones-backend/SKILL.md +0 -560
  627. package/vendor/theus-arsenal/skills/patrones-cdss-clinico/SKILL.md +0 -249
  628. package/vendor/theus-arsenal/skills/patrones-cisco-ios/SKILL.md +0 -148
  629. package/vendor/theus-arsenal/skills/patrones-clickhouse/SKILL.md +0 -443
  630. package/vendor/theus-arsenal/skills/patrones-compose-multiplatform/SKILL.md +0 -298
  631. package/vendor/theus-arsenal/skills/patrones-dart-flutter/SKILL.md +0 -566
  632. package/vendor/theus-arsenal/skills/patrones-despliegue/SKILL.md +0 -426
  633. package/vendor/theus-arsenal/skills/patrones-django/SKILL.md +0 -739
  634. package/vendor/theus-arsenal/skills/patrones-django-celery/SKILL.md +0 -456
  635. package/vendor/theus-arsenal/skills/patrones-docker/SKILL.md +0 -363
  636. package/vendor/theus-arsenal/skills/patrones-dotnet/SKILL.md +0 -321
  637. package/vendor/theus-arsenal/skills/patrones-emr-clinico/SKILL.md +0 -168
  638. package/vendor/theus-arsenal/skills/patrones-fastapi/SKILL.md +0 -513
  639. package/vendor/theus-arsenal/skills/patrones-frontend/SKILL.md +0 -655
  640. package/vendor/theus-arsenal/skills/patrones-go/SKILL.md +0 -674
  641. package/vendor/theus-arsenal/skills/patrones-jpa/SKILL.md +0 -156
  642. package/vendor/theus-arsenal/skills/patrones-kotlin/SKILL.md +0 -717
  643. package/vendor/theus-arsenal/skills/patrones-kotlin-exposed/SKILL.md +0 -724
  644. package/vendor/theus-arsenal/skills/patrones-kotlin-ktor/SKILL.md +0 -694
  645. package/vendor/theus-arsenal/skills/patrones-kubernetes/SKILL.md +0 -754
  646. package/vendor/theus-arsenal/skills/patrones-laravel/SKILL.md +0 -414
  647. package/vendor/theus-arsenal/skills/patrones-mcp/SKILL.md +0 -66
  648. package/vendor/theus-arsenal/skills/patrones-mysql/SKILL.md +0 -420
  649. package/vendor/theus-arsenal/skills/patrones-nestjs/SKILL.md +0 -229
  650. package/vendor/theus-arsenal/skills/patrones-nextjs/SKILL.md +0 -56
  651. package/vendor/theus-arsenal/skills/patrones-nuxt4/SKILL.md +0 -99
  652. package/vendor/theus-arsenal/skills/patrones-perl/SKILL.md +0 -508
  653. package/vendor/theus-arsenal/skills/patrones-postgres/SKILL.md +0 -141
  654. package/vendor/theus-arsenal/skills/patrones-prisma/SKILL.md +0 -399
  655. package/vendor/theus-arsenal/skills/patrones-python/SKILL.md +0 -750
  656. package/vendor/theus-arsenal/skills/patrones-pytorch/SKILL.md +0 -400
  657. package/vendor/theus-arsenal/skills/patrones-quarkus/SKILL.md +0 -729
  658. package/vendor/theus-arsenal/skills/patrones-react/SKILL.md +0 -339
  659. package/vendor/theus-arsenal/skills/patrones-react-native/SKILL.md +0 -325
  660. package/vendor/theus-arsenal/skills/patrones-redis/SKILL.md +0 -401
  661. package/vendor/theus-arsenal/skills/patrones-rust/SKILL.md +0 -504
  662. package/vendor/theus-arsenal/skills/patrones-springboot/SKILL.md +0 -314
  663. package/vendor/theus-arsenal/skills/patrones-swiftui/SKILL.md +0 -261
  664. package/vendor/theus-arsenal/skills/patrones-tinystruct/SKILL.md +0 -281
  665. package/vendor/theus-arsenal/skills/patrones-tinystruct/references/architecture.md +0 -90
  666. package/vendor/theus-arsenal/skills/patrones-tinystruct/references/data-handling.md +0 -60
  667. package/vendor/theus-arsenal/skills/patrones-tinystruct/references/database.md +0 -99
  668. package/vendor/theus-arsenal/skills/patrones-tinystruct/references/routing.md +0 -64
  669. package/vendor/theus-arsenal/skills/patrones-tinystruct/references/system-usage.md +0 -97
  670. package/vendor/theus-arsenal/skills/patrones-tinystruct/references/testing.md +0 -72
  671. package/vendor/theus-arsenal/skills/patrones-vite/SKILL.md +0 -449
  672. package/vendor/theus-arsenal/skills/patrones-vue/SKILL.md +0 -469
  673. package/vendor/theus-arsenal/skills/persistencia-actores-swift/SKILL.md +0 -148
  674. package/vendor/theus-arsenal/skills/pipeline-opensource/SKILL.md +0 -254
  675. package/vendor/theus-arsenal/skills/planificacion-demanda-inventario/SKILL.md +0 -236
  676. package/vendor/theus-arsenal/skills/planificador-trades-prediccion/SKILL.md +0 -60
  677. package/vendor/theus-arsenal/skills/plano-tecnico/SKILL.md +0 -102
  678. package/vendor/theus-arsenal/skills/presentaciones-html/SKILL.md +0 -189
  679. package/vendor/theus-arsenal/skills/presentaciones-html/STYLE_PRESETS.md +0 -330
  680. package/vendor/theus-arsenal/skills/presentaciones-html/animation-patterns.md +0 -122
  681. package/vendor/theus-arsenal/skills/presentaciones-html/html-template.md +0 -419
  682. package/vendor/theus-arsenal/skills/presentaciones-html/scripts/export-pdf.sh +0 -418
  683. package/vendor/theus-arsenal/skills/presentaciones-html/scripts/extract-pptx.py +0 -96
  684. package/vendor/theus-arsenal/skills/presentaciones-html/viewport-base.css +0 -153
  685. package/vendor/theus-arsenal/skills/presupuesto-contexto/SKILL.md +0 -263
  686. package/vendor/theus-arsenal/skills/procesamiento-documentos-nutrient/SKILL.md +0 -168
  687. package/vendor/theus-arsenal/skills/programacion-produccion/SKILL.md +0 -220
  688. package/vendor/theus-arsenal/skills/publicacion-cruzada/SKILL.md +0 -117
  689. package/vendor/theus-arsenal/skills/publicador-social/SKILL.md +0 -121
  690. package/vendor/theus-arsenal/skills/puerta-de-entrega/SKILL.md +0 -164
  691. package/vendor/theus-arsenal/skills/puerta-de-entrega/hooks/puerta-entrega.py +0 -242
  692. package/vendor/theus-arsenal/skills/pulir-interfaces/SKILL.md +0 -126
  693. package/vendor/theus-arsenal/skills/qa-navegador/SKILL.md +0 -103
  694. package/vendor/theus-arsenal/skills/ranking-grafo-social/SKILL.md +0 -153
  695. package/vendor/theus-arsenal/skills/recuperacion-iterativa/SKILL.md +0 -236
  696. package/vendor/theus-arsenal/skills/redaccion-articulos/SKILL.md +0 -81
  697. package/vendor/theus-arsenal/skills/regex-vs-llm/SKILL.md +0 -221
  698. package/vendor/theus-arsenal/skills/regresion-codigo-ia/SKILL.md +0 -388
  699. package/vendor/theus-arsenal/skills/rendimiento-react/SKILL.md +0 -567
  700. package/vendor/theus-arsenal/skills/revision-codigo-flutter-dart/SKILL.md +0 -442
  701. package/vendor/theus-arsenal/skills/revision-literatura-cientifica/SKILL.md +0 -191
  702. package/vendor/theus-arsenal/skills/revision-multiperspectiva/SKILL.md +0 -302
  703. package/vendor/theus-arsenal/skills/revision-riesgo-prediccion/SKILL.md +0 -56
  704. package/vendor/theus-arsenal/skills/revision-seguridad/SKILL.md +0 -505
  705. package/vendor/theus-arsenal/skills/revision-seguridad/cloud-infrastructure-security.md +0 -361
  706. package/vendor/theus-arsenal/skills/runtime-bun/SKILL.md +0 -83
  707. package/vendor/theus-arsenal/skills/salud-codigo-codescene/SKILL.md +0 -163
  708. package/vendor/theus-arsenal/skills/salud-interfaces-red/SKILL.md +0 -143
  709. package/vendor/theus-arsenal/skills/seguimiento-costos/SKILL.md +0 -122
  710. package/vendor/theus-arsenal/skills/seguridad-agentes-trading/SKILL.md +0 -145
  711. package/vendor/theus-arsenal/skills/seguridad-amm-defi/SKILL.md +0 -166
  712. package/vendor/theus-arsenal/skills/seguridad-django/SKILL.md +0 -648
  713. package/vendor/theus-arsenal/skills/seguridad-laravel/SKILL.md +0 -945
  714. package/vendor/theus-arsenal/skills/seguridad-perl/SKILL.md +0 -507
  715. package/vendor/theus-arsenal/skills/seguridad-quarkus/SKILL.md +0 -474
  716. package/vendor/theus-arsenal/skills/seguridad-springboot/SKILL.md +0 -279
  717. package/vendor/theus-arsenal/skills/seo/SKILL.md +0 -166
  718. package/vendor/theus-arsenal/skills/sistema-diseno/SKILL.md +0 -81
  719. package/vendor/theus-arsenal/skills/sistema-operativo-agentico/SKILL.md +0 -375
  720. package/vendor/theus-arsenal/skills/sistemas-latencia-critica/SKILL.md +0 -65
  721. package/vendor/theus-arsenal/skills/tdd-django/SKILL.md +0 -735
  722. package/vendor/theus-arsenal/skills/tdd-laravel/SKILL.md +0 -673
  723. package/vendor/theus-arsenal/skills/tdd-quarkus/SKILL.md +0 -817
  724. package/vendor/theus-arsenal/skills/tdd-springboot/SKILL.md +0 -165
  725. package/vendor/theus-arsenal/skills/testing-cpp/SKILL.md +0 -328
  726. package/vendor/theus-arsenal/skills/testing-csharp/SKILL.md +0 -321
  727. package/vendor/theus-arsenal/skills/testing-e2e/SKILL.md +0 -325
  728. package/vendor/theus-arsenal/skills/testing-go/SKILL.md +0 -719
  729. package/vendor/theus-arsenal/skills/testing-kotlin/SKILL.md +0 -829
  730. package/vendor/theus-arsenal/skills/testing-perl/SKILL.md +0 -479
  731. package/vendor/theus-arsenal/skills/testing-protocolos-di-swift/SKILL.md +0 -196
  732. package/vendor/theus-arsenal/skills/testing-python/SKILL.md +0 -815
  733. package/vendor/theus-arsenal/skills/testing-react/SKILL.md +0 -421
  734. package/vendor/theus-arsenal/skills/testing-rust/SKILL.md +0 -506
  735. package/vendor/theus-arsenal/skills/tours-de-codigo/SKILL.md +0 -252
  736. package/vendor/theus-arsenal/skills/traduccion-documentos-visado/SKILL.md +0 -121
  737. package/vendor/theus-arsenal/skills/ui-a-vue/SKILL.md +0 -141
  738. package/vendor/theus-arsenal/skills/validacion-config-red/SKILL.md +0 -211
  739. package/vendor/theus-arsenal/skills/verificacion-django/SKILL.md +0 -470
  740. package/vendor/theus-arsenal/skills/verificacion-factual/SKILL.md +0 -142
  741. package/vendor/theus-arsenal/skills/verificacion-laravel/SKILL.md +0 -184
  742. package/vendor/theus-arsenal/skills/verificacion-quarkus/SKILL.md +0 -485
  743. package/vendor/theus-arsenal/skills/verificacion-springboot/SKILL.md +0 -237
  744. package/vendor/theus-arsenal/skills/videodb/SKILL.md +0 -374
  745. package/vendor/theus-arsenal/skills/videodb/reference/api-reference.md +0 -550
  746. package/vendor/theus-arsenal/skills/videodb/reference/capture-reference.md +0 -407
  747. package/vendor/theus-arsenal/skills/videodb/reference/capture.md +0 -101
  748. package/vendor/theus-arsenal/skills/videodb/reference/editor.md +0 -443
  749. package/vendor/theus-arsenal/skills/videodb/reference/generative.md +0 -331
  750. package/vendor/theus-arsenal/skills/videodb/reference/rtstream-reference.md +0 -564
  751. package/vendor/theus-arsenal/skills/videodb/reference/rtstream.md +0 -65
  752. package/vendor/theus-arsenal/skills/videodb/reference/search.md +0 -230
  753. package/vendor/theus-arsenal/skills/videodb/reference/streaming.md +0 -406
  754. package/vendor/theus-arsenal/skills/videodb/reference/use-cases.md +0 -118
  755. package/vendor/theus-arsenal/skills/videodb/scripts/ws_listener.py +0 -279
  756. package/vendor/theus-arsenal/skills/videos-manim/SKILL.md +0 -91
  757. package/vendor/theus-arsenal/skills/videos-manim/assets/network_graph_scene.py +0 -52
  758. package/vendor/theus-arsenal/skills/vigilancia-canary/SKILL.md +0 -108
  759. package/vendor/theus-arsenal/skills/voz-de-marca/SKILL.md +0 -106
@@ -1,1918 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- CLI de instintos - Gestiona los instintos de Aprendizaje continuo v2
4
-
5
- v2.1: Instintos con ámbito de proyecto — cada proyecto tiene sus propios
6
- instintos, y los globales aplican universalmente.
7
-
8
- Comandos:
9
- status - Muestra todos los instintos (proyecto + global) y su estado
10
- import - Importa instintos desde archivo o URL
11
- export - Exporta instintos a un archivo
12
- evolve - Agrupa instintos en skills/comandos/agentes
13
- promote - Promueve instintos de proyecto al ámbito global
14
- projects - Lista los proyectos conocidos y sus recuentos de instintos
15
- prune - Elimina instintos pendientes con más de 30 días (TTL)
16
- """
17
-
18
- import argparse
19
- import json
20
- import hashlib
21
- import os
22
- import subprocess
23
- import sys
24
- import re
25
- import shutil
26
- import ipaddress
27
- import socket
28
- import urllib.parse
29
- import urllib.request
30
- from contextlib import contextmanager
31
- from pathlib import Path
32
- from datetime import datetime, timedelta, timezone
33
- from collections import defaultdict
34
- from typing import Optional
35
-
36
- if sys.platform == "win32":
37
- try:
38
- sys.stdout.reconfigure(encoding="utf-8")
39
- sys.stderr.reconfigure(encoding="utf-8")
40
- except Exception:
41
- pass
42
-
43
- try:
44
- import fcntl
45
- _HAS_FCNTL = True
46
- except ImportError:
47
- _HAS_FCNTL = False # Windows — sin bloqueo de archivos
48
-
49
- # ─────────────────────────────────────────────
50
- # Configuración
51
- # ─────────────────────────────────────────────
52
-
53
- def _resolve_arsenal_dir() -> Path:
54
- override = os.environ.get("THEUS_AGENT_DATA_HOME")
55
- if override:
56
- if Path(override).is_absolute():
57
- return Path(override)
58
- print(f"[arsenal] THEUS_AGENT_DATA_HOME={override!r} no es una ruta absoluta; se ignora", file=sys.stderr)
59
-
60
- return Path.home() / ".theus" / "arsenal"
61
-
62
-
63
- def _strip_remote_credentials(remote_url: str) -> str:
64
- return re.sub(r"://[^@]+@", "://", remote_url or "")
65
-
66
-
67
- def _normalize_remote_url(remote_url: str) -> str:
68
- if not remote_url:
69
- return ""
70
-
71
- is_network = (
72
- not remote_url.startswith("file://")
73
- and ("://" in remote_url or re.match(r"^[^@/:]+@[^:/]+:", remote_url) is not None)
74
- )
75
- normalized = _strip_remote_credentials(remote_url)
76
- normalized = re.sub(r"^[A-Za-z][A-Za-z0-9+.-]*://", "", normalized)
77
- normalized = re.sub(r"^[^@/:]+@([^:/]+):", r"\1/", normalized)
78
- normalized = re.sub(r"\.git/?$", "", normalized)
79
- normalized = re.sub(r"/+$", "", normalized)
80
-
81
- return normalized.lower() if is_network else normalized
82
-
83
-
84
- def _stream_can_encode(text: str, stream=None) -> bool:
85
- stream = stream or sys.stdout
86
- encoding = getattr(stream, "encoding", None) or sys.getdefaultencoding()
87
- try:
88
- text.encode(encoding)
89
- except (LookupError, UnicodeEncodeError):
90
- return False
91
- return True
92
-
93
-
94
- def _confidence_bar(confidence, stream=None) -> str:
95
- try:
96
- filled = int(float(confidence) * 10)
97
- except (TypeError, ValueError):
98
- filled = 5
99
- filled = max(0, min(10, filled))
100
-
101
- full, empty = ("\u2588", "\u2591") if _stream_can_encode("\u2588\u2591", stream) else ("#", ".")
102
- return full * filled + empty * (10 - filled)
103
-
104
-
105
- def _project_hash(value: str) -> str:
106
- return hashlib.sha256(value.encode("utf-8")).hexdigest()[:12]
107
-
108
-
109
- ARSENAL_DIR = _resolve_arsenal_dir()
110
- PROJECTS_DIR = ARSENAL_DIR / "projects"
111
- REGISTRY_FILE = ARSENAL_DIR / "projects.json"
112
-
113
- # Rutas globales (sin ámbito de proyecto)
114
- GLOBAL_INSTINCTS_DIR = ARSENAL_DIR / "instincts"
115
- GLOBAL_PERSONAL_DIR = GLOBAL_INSTINCTS_DIR / "personal"
116
- GLOBAL_INHERITED_DIR = GLOBAL_INSTINCTS_DIR / "inherited"
117
- GLOBAL_EVOLVED_DIR = ARSENAL_DIR / "evolved"
118
- GLOBAL_OBSERVATIONS_FILE = ARSENAL_DIR / "observations.jsonl"
119
-
120
- # Umbrales para la autopromoción
121
- PROMOTE_CONFIDENCE_THRESHOLD = 0.8
122
- PROMOTE_MIN_PROJECTS = 2
123
- ALLOWED_INSTINCT_EXTENSIONS = (".yaml", ".yml", ".md")
124
-
125
- # TTL por defecto de los instintos pendientes (días)
126
- PENDING_TTL_DAYS = 30
127
- # Umbral de aviso: mostrar la alerta de caducidad cuando el instinto caduque dentro de estos días
128
- PENDING_EXPIRY_WARNING_DAYS = 7
129
-
130
- # Asegurar que existan los directorios globales (diferido para evitar efectos al importar)
131
- def _ensure_global_dirs():
132
- for d in [GLOBAL_PERSONAL_DIR, GLOBAL_INHERITED_DIR,
133
- GLOBAL_EVOLVED_DIR / "skills", GLOBAL_EVOLVED_DIR / "commands", GLOBAL_EVOLVED_DIR / "agents",
134
- PROJECTS_DIR]:
135
- d.mkdir(parents=True, exist_ok=True)
136
-
137
-
138
- # ─────────────────────────────────────────────
139
- # Validación de rutas
140
- # ─────────────────────────────────────────────
141
-
142
- def _validate_file_path(path_str: str, must_exist: bool = False) -> Path:
143
- """Valida y resuelve una ruta de archivo, protegiendo contra path traversal.
144
-
145
- Lanza ValueError si la ruta es inválida o sospechosa.
146
- """
147
- path = Path(path_str).expanduser().resolve()
148
-
149
- # Bloquear rutas que escapan hacia directorios del sistema
150
- # Se bloquean rutas de sistema concretas pero se permiten dirs temporales (/var/folders en macOS)
151
- blocked_prefixes = [
152
- "/etc", "/usr", "/bin", "/sbin", "/proc", "/sys",
153
- "/var/log", "/var/run", "/var/lib", "/var/spool",
154
- # macOS resuelve /etc → /private/etc
155
- "/private/etc",
156
- "/private/var/log", "/private/var/run", "/private/var/db",
157
- ]
158
- path_s = str(path)
159
- for prefix in blocked_prefixes:
160
- if path_s.startswith(prefix + "/") or path_s == prefix:
161
- raise ValueError(f"La ruta '{path}' apunta a un directorio del sistema")
162
-
163
- if must_exist and not path.exists():
164
- raise ValueError(f"La ruta no existe: {path}")
165
-
166
- return path
167
-
168
-
169
- def _validate_instinct_id(instinct_id: str) -> bool:
170
- """Valida los IDs de instinto antes de usarlos en nombres de archivo."""
171
- if not instinct_id or len(instinct_id) > 128:
172
- return False
173
- if "/" in instinct_id or "\\" in instinct_id:
174
- return False
175
- if ".." in instinct_id:
176
- return False
177
- if instinct_id.startswith("."):
178
- return False
179
- return bool(re.match(r"^[A-Za-z0-9][A-Za-z0-9._-]*$", instinct_id))
180
-
181
-
182
- def _validate_import_url(source: str) -> str:
183
- """Valida las importaciones remotas de instintos antes de abrir una conexión de red."""
184
- parsed = urllib.parse.urlparse(source)
185
- if parsed.scheme != "https":
186
- raise ValueError("las importaciones remotas de instintos requieren URLs https")
187
- if not parsed.hostname:
188
- raise ValueError("la URL de importación remota no tiene hostname")
189
-
190
- try:
191
- addr_infos = socket.getaddrinfo(parsed.hostname, parsed.port or 443, type=socket.SOCK_STREAM)
192
- except socket.gaierror as exc:
193
- raise ValueError(f"no se pudo resolver el host de importación remota: {parsed.hostname}") from exc
194
-
195
- for family, _, _, _, sockaddr in addr_infos:
196
- host = sockaddr[0]
197
- try:
198
- ip = ipaddress.ip_address(host)
199
- except ValueError:
200
- continue
201
- if (
202
- ip.is_private
203
- or ip.is_loopback
204
- or ip.is_link_local
205
- or ip.is_multicast
206
- or ip.is_reserved
207
- or ip.is_unspecified
208
- ):
209
- raise ValueError(f"el host de importación remota resuelve a una dirección no pública: {host}")
210
-
211
- return urllib.parse.urlunparse(parsed)
212
-
213
-
214
- def _fetch_import_url(source: str, *, max_bytes: int = 2 * 1024 * 1024) -> str:
215
- """Descarga un archivo remoto de instintos validado, con tamaño y timeout acotados."""
216
- url = _validate_import_url(source)
217
- req = urllib.request.Request(url, headers={"User-Agent": "Theus-instinct-import/2"})
218
- with urllib.request.urlopen(req, timeout=15) as response:
219
- content_type = response.headers.get("Content-Type", "")
220
- if content_type and not any(
221
- allowed in content_type.lower()
222
- for allowed in ("text/", "markdown", "yaml", "json", "octet-stream")
223
- ):
224
- raise ValueError(f"tipo de contenido remoto no soportado: {content_type}")
225
- data = response.read(max_bytes + 1)
226
- if len(data) > max_bytes:
227
- raise ValueError(f"la importación remota supera {max_bytes} bytes")
228
- return data.decode("utf-8")
229
-
230
-
231
- def _yaml_quote(value: str) -> str:
232
- """Entrecomilla una cadena para serializarla de forma segura en el frontmatter YAML.
233
-
234
- Usa comillas dobles y escapa las comillas dobles embebidas para evitar
235
- YAML malformado cuando el valor contiene comillas.
236
- """
237
- escaped = value.replace('\\', '\\\\').replace('"', '\\"')
238
- return f'"{escaped}"'
239
-
240
-
241
- # ─────────────────────────────────────────────
242
- # Detección de proyecto (equivalente en Python de detect-project.sh)
243
- # ─────────────────────────────────────────────
244
-
245
- def _git_repo_root(cwd: Optional[str] = None) -> Optional[str]:
246
- args = ["git"]
247
- if cwd:
248
- args.extend(["-C", cwd])
249
- args.extend(["rev-parse", "--show-toplevel"])
250
- try:
251
- result = subprocess.run(args, capture_output=True, text=True, timeout=5)
252
- if result.returncode == 0:
253
- return result.stdout.strip()
254
- except (subprocess.TimeoutExpired, FileNotFoundError):
255
- pass
256
- return None
257
-
258
-
259
- def _main_worktree_root(project_root: str) -> str:
260
- """Devuelve la raíz del worktree principal cuando project_root es un worktree enlazado."""
261
- try:
262
- result = subprocess.run(
263
- ["git", "-C", project_root, "worktree", "list", "--porcelain"],
264
- capture_output=True, text=True, timeout=5
265
- )
266
- except (subprocess.TimeoutExpired, FileNotFoundError):
267
- return project_root
268
-
269
- if result.returncode != 0:
270
- return project_root
271
-
272
- for line in result.stdout.splitlines():
273
- if line.startswith("worktree "):
274
- main_root = line.split(" ", 1)[1].strip()
275
- return main_root or project_root
276
- return project_root
277
-
278
-
279
- def detect_project() -> dict:
280
- """Detecta el contexto del proyecto actual. Devuelve un dict con id, name, root, project_dir."""
281
- project_root = None
282
-
283
- if os.environ.get("ACV2_NO_PROJECT") == "1":
284
- return {
285
- "id": "global",
286
- "name": "global",
287
- "root": "",
288
- "project_dir": ARSENAL_DIR,
289
- "instincts_personal": GLOBAL_PERSONAL_DIR,
290
- "instincts_inherited": GLOBAL_INHERITED_DIR,
291
- "evolved_dir": GLOBAL_EVOLVED_DIR,
292
- "observations_file": GLOBAL_OBSERVATIONS_FILE,
293
- }
294
-
295
- # 1. Variable de entorno THEUS_PROJECT_DIR
296
- env_dir = os.environ.get("THEUS_PROJECT_DIR")
297
- if env_dir and os.path.isdir(env_dir):
298
- project_root = _git_repo_root(env_dir)
299
-
300
- # 2. Raíz del repo git
301
- if not project_root:
302
- project_root = _git_repo_root()
303
-
304
- # Normalizar: quitar barras finales para mantener estables el basename y el hash
305
- if project_root:
306
- project_root = project_root.rstrip("/")
307
-
308
- # 3. Sin proyecto — fallback global
309
- if not project_root:
310
- return {
311
- "id": "global",
312
- "name": "global",
313
- "root": "",
314
- "project_dir": ARSENAL_DIR,
315
- "instincts_personal": GLOBAL_PERSONAL_DIR,
316
- "instincts_inherited": GLOBAL_INHERITED_DIR,
317
- "evolved_dir": GLOBAL_EVOLVED_DIR,
318
- "observations_file": GLOBAL_OBSERVATIONS_FILE,
319
- }
320
-
321
- project_name = os.path.basename(project_root)
322
-
323
- # Derivar el ID del proyecto de la URL del remoto git o de la ruta
324
- remote_url = ""
325
- try:
326
- result = subprocess.run(
327
- ["git", "-C", project_root, "remote", "get-url", "origin"],
328
- capture_output=True, text=True, timeout=5
329
- )
330
- if result.returncode == 0:
331
- remote_url = result.stdout.strip()
332
- except (subprocess.TimeoutExpired, FileNotFoundError):
333
- pass
334
-
335
- raw_remote_url = remote_url
336
- if remote_url:
337
- remote_url = _strip_remote_credentials(remote_url)
338
-
339
- fallback_root = _main_worktree_root(project_root) if not remote_url else project_root
340
- legacy_hash_source = remote_url if remote_url else project_root
341
- normalized_remote = _normalize_remote_url(remote_url) if remote_url else ""
342
- hash_source = normalized_remote if normalized_remote else (remote_url if remote_url else fallback_root)
343
- project_id = _project_hash(hash_source)
344
-
345
- project_dir = PROJECTS_DIR / project_id
346
-
347
- if not project_dir.exists():
348
- legacy_sources = []
349
- if legacy_hash_source and legacy_hash_source != hash_source:
350
- legacy_sources.append(legacy_hash_source)
351
- if raw_remote_url and raw_remote_url not in {hash_source, legacy_hash_source}:
352
- legacy_sources.append(raw_remote_url)
353
-
354
- for legacy_source in legacy_sources:
355
- legacy_id = _project_hash(legacy_source)
356
- legacy_dir = PROJECTS_DIR / legacy_id
357
- if legacy_id != project_id and legacy_dir.exists():
358
- try:
359
- legacy_dir.rename(project_dir)
360
- except OSError:
361
- project_id = legacy_id
362
- project_dir = legacy_dir
363
- break
364
-
365
- # Asegurar la estructura de directorios del proyecto
366
- for d in [
367
- project_dir / "instincts" / "personal",
368
- project_dir / "instincts" / "inherited",
369
- project_dir / "observations.archive",
370
- project_dir / "evolved" / "skills",
371
- project_dir / "evolved" / "commands",
372
- project_dir / "evolved" / "agents",
373
- ]:
374
- d.mkdir(parents=True, exist_ok=True)
375
-
376
- # Actualizar el registro
377
- _update_registry(project_id, project_name, project_root, remote_url)
378
-
379
- return {
380
- "id": project_id,
381
- "name": project_name,
382
- "root": project_root,
383
- "remote": remote_url,
384
- "project_dir": project_dir,
385
- "instincts_personal": project_dir / "instincts" / "personal",
386
- "instincts_inherited": project_dir / "instincts" / "inherited",
387
- "evolved_dir": project_dir / "evolved",
388
- "observations_file": project_dir / "observations.jsonl",
389
- }
390
-
391
-
392
- @contextmanager
393
- def _registry_lock():
394
- """Serializa el read-modify-write del registro entre sesiones concurrentes.
395
-
396
- Adquiere el mismo lock consultivo para todo escritor del registro
397
- (``_update_registry`` y ``_write_registry``) para que ``projects
398
- delete/gc/merge`` no pueda intercalarse con una actualización concurrente
399
- del hook de observación y corromper ``projects.json``. No hace nada en
400
- plataformas sin ``fcntl`` (Windows).
401
- """
402
- REGISTRY_FILE.parent.mkdir(parents=True, exist_ok=True)
403
- lock_path = REGISTRY_FILE.parent / f".{REGISTRY_FILE.name}.lock"
404
- lock_fd = None
405
- try:
406
- if _HAS_FCNTL:
407
- lock_fd = open(lock_path, "w")
408
- fcntl.flock(lock_fd, fcntl.LOCK_EX)
409
- yield
410
- finally:
411
- if lock_fd is not None:
412
- fcntl.flock(lock_fd, fcntl.LOCK_UN)
413
- lock_fd.close()
414
-
415
-
416
- def _update_registry(pid: str, pname: str, proot: str, premote: str) -> None:
417
- """Actualiza el registro projects.json.
418
-
419
- Usa bloqueo de archivos (donde está disponible) para evitar que sesiones
420
- concurrentes pisen las actualizaciones de las demás.
421
- """
422
- with _registry_lock():
423
- try:
424
- with open(REGISTRY_FILE, encoding="utf-8") as f:
425
- registry = json.load(f)
426
- except (FileNotFoundError, json.JSONDecodeError):
427
- registry = {}
428
- # Un registro que es JSON válido pero no un mapa (p. ej. una lista de un
429
- # projects.json corrupto) no debe romper la actualización antes de la
430
- # guarda por entrada de abajo: se cae a un dict vacío para sanar el archivo.
431
- if not isinstance(registry, dict):
432
- registry = {}
433
-
434
- # Espeja al equivalente shell en detect-project.sh: la entrada lleva
435
- # "id" y "created_at" junto a los demás campos para que un registro de
436
- # projects.json tenga la misma forma sin importar qué vía (CLI Python o
437
- # hook shell) lo escribió por última vez. "created_at" se preserva de
438
- # cualquier entrada existente; solo "last_seen" avanza al actualizar.
439
- now = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
440
- existing = registry.get(pid, {})
441
- # Un registro malformado (p. ej. un valor no-dict para este id) no debe
442
- # romper la actualización: se cae a un dict vacío para que la reescritura
443
- # sane la entrada corrupta, igual que el antiguo sobrescribir incondicional.
444
- if not isinstance(existing, dict):
445
- existing = {}
446
- registry[pid] = {
447
- "id": pid,
448
- "name": pname,
449
- "root": proot,
450
- "remote": premote,
451
- "created_at": existing.get("created_at", now),
452
- "last_seen": now,
453
- }
454
-
455
- tmp_file = REGISTRY_FILE.parent / f".{REGISTRY_FILE.name}.tmp.{os.getpid()}"
456
- with open(tmp_file, "w", encoding="utf-8") as f:
457
- json.dump(registry, f, indent=2)
458
- f.flush()
459
- os.fsync(f.fileno())
460
- os.replace(tmp_file, REGISTRY_FILE)
461
-
462
-
463
- def load_registry() -> dict:
464
- """Carga el registro de proyectos."""
465
- try:
466
- with open(REGISTRY_FILE, encoding="utf-8") as f:
467
- return json.load(f)
468
- except (FileNotFoundError, json.JSONDecodeError):
469
- return {}
470
-
471
-
472
- def _write_registry(registry: dict) -> None:
473
- """Escribe el registro de proyectos de forma atómica.
474
-
475
- Mantiene el mismo lock consultivo que ``_update_registry`` para que
476
- ``projects delete/gc/merge`` concurrentes y las actualizaciones del hook de
477
- observación no puedan corromper el archivo.
478
- """
479
- with _registry_lock():
480
- tmp_file = REGISTRY_FILE.parent / f".{REGISTRY_FILE.name}.tmp.{os.getpid()}"
481
- with open(tmp_file, "w", encoding="utf-8") as f:
482
- json.dump(registry, f, indent=2)
483
- f.write("\n")
484
- f.flush()
485
- os.fsync(f.fileno())
486
- os.replace(tmp_file, REGISTRY_FILE)
487
-
488
-
489
- def _validate_project_id(project_id: str) -> bool:
490
- if not project_id or len(project_id) > 128:
491
- return False
492
- if "/" in project_id or "\\" in project_id or ".." in project_id:
493
- return False
494
- return bool(re.match(r"^[A-Za-z0-9][A-Za-z0-9._-]*$", project_id))
495
-
496
-
497
- # ─────────────────────────────────────────────
498
- # Parser de instintos
499
- # ─────────────────────────────────────────────
500
-
501
- def parse_instinct_file(content: str) -> list[dict]:
502
- """Parsea el formato de archivo de instintos tipo YAML.
503
-
504
- Cada instinto está delimitado por un par de marcadores ``---`` (frontmatter
505
- YAML). Nota: ``---`` siempre se trata como frontera del frontmatter; el
506
- cuerpo del instinto debe usar ``***`` o ``___`` para las reglas horizontales
507
- y así evitar ambigüedad.
508
- """
509
- instincts = []
510
- current = {}
511
- in_frontmatter = False
512
- content_lines = []
513
-
514
- for line in content.split('\n'):
515
- if line.strip() == '---':
516
- if in_frontmatter:
517
- # Fin del frontmatter - a continuación viene el contenido
518
- in_frontmatter = False
519
- else:
520
- # Inicio de un nuevo bloque de frontmatter
521
- in_frontmatter = True
522
- if current:
523
- current['content'] = '\n'.join(content_lines).strip()
524
- instincts.append(current)
525
- current = {}
526
- content_lines = []
527
- elif in_frontmatter:
528
- # Parsear el frontmatter tipo YAML
529
- if ':' in line:
530
- key, value = line.split(':', 1)
531
- key = key.strip()
532
- value = value.strip()
533
- # Des-escapar cadenas YAML entrecomilladas
534
- if value.startswith('"') and value.endswith('"'):
535
- value = value[1:-1].replace('\\"', '"').replace('\\\\', '\\')
536
- elif value.startswith("'") and value.endswith("'"):
537
- value = value[1:-1].replace("''", "'")
538
- if key == 'confidence':
539
- try:
540
- current[key] = float(value)
541
- except ValueError:
542
- current[key] = 0.5 # valor por defecto si la confianza está malformada
543
- else:
544
- current[key] = value
545
- else:
546
- content_lines.append(line)
547
-
548
- # No olvidar el último instinto
549
- if current:
550
- current['content'] = '\n'.join(content_lines).strip()
551
- instincts.append(current)
552
-
553
- return [i for i in instincts if i.get('id')]
554
-
555
-
556
- def _load_instincts_from_dir(directory: Path, source_type: str, scope_label: str) -> list[dict]:
557
- """Carga los instintos de un único directorio."""
558
- instincts = []
559
- if not directory.exists():
560
- return instincts
561
- files = [
562
- file for file in sorted(directory.iterdir())
563
- if file.is_file() and file.suffix.lower() in ALLOWED_INSTINCT_EXTENSIONS
564
- ]
565
- for file in files:
566
- try:
567
- content = file.read_text(encoding="utf-8")
568
- parsed = parse_instinct_file(content)
569
- for inst in parsed:
570
- inst['_source_file'] = str(file)
571
- inst['_source_type'] = source_type
572
- inst['_scope_label'] = scope_label
573
- # Ámbito por defecto si el frontmatter no lo define
574
- if 'scope' not in inst:
575
- inst['scope'] = scope_label
576
- instincts.extend(parsed)
577
- except Exception as e:
578
- print(f"Aviso: no se pudo analizar {file}: {e}", file=sys.stderr)
579
- return instincts
580
-
581
-
582
- def _project_counts(project_id: str) -> dict:
583
- project_dir = PROJECTS_DIR / project_id
584
- personal_dir = project_dir / "instincts" / "personal"
585
- inherited_dir = project_dir / "instincts" / "inherited"
586
- observations_file = project_dir / "observations.jsonl"
587
-
588
- personal_count = len(_load_instincts_from_dir(personal_dir, "personal", "project"))
589
- inherited_count = len(_load_instincts_from_dir(inherited_dir, "inherited", "project"))
590
- observations_count = 0
591
- if observations_file.exists():
592
- try:
593
- with open(observations_file, encoding="utf-8") as f:
594
- observations_count = sum(1 for _ in f)
595
- except OSError:
596
- observations_count = 0
597
-
598
- return {
599
- "personal": personal_count,
600
- "inherited": inherited_count,
601
- "observations": observations_count,
602
- "total": personal_count + inherited_count + observations_count,
603
- }
604
-
605
-
606
- def _remove_project_storage(project_id: str) -> None:
607
- # Defensa en profundidad: resolver y confirmar que el objetivo está
608
- # contenido en PROJECTS_DIR antes de borrar recursivamente, aunque los
609
- # llamadores validen el id del proyecto. Un validador laxo o un llamador
610
- # futuro jamás deben poder convertir esto en un borrado de directorios
611
- # arbitrarios.
612
- projects_root = PROJECTS_DIR.resolve()
613
- project_dir = (PROJECTS_DIR / project_id).resolve()
614
- if project_dir == projects_root or projects_root not in project_dir.parents:
615
- raise ValueError(f"se rechaza eliminar {project_dir}: escapa de {projects_root}")
616
- if project_dir.exists():
617
- shutil.rmtree(project_dir)
618
-
619
-
620
- def _project_instinct_ids(project_dir: Path, source_type: str) -> set[str]:
621
- instinct_dir = project_dir / "instincts" / source_type
622
- return {
623
- inst.get("id")
624
- for inst in _load_instincts_from_dir(instinct_dir, source_type, "project")
625
- if inst.get("id")
626
- }
627
-
628
-
629
- def _merge_instinct_dir(from_dir: Path, into_dir: Path, existing_ids: set[str]) -> tuple[int, int]:
630
- moved = 0
631
- skipped = 0
632
- if not from_dir.exists():
633
- return moved, skipped
634
-
635
- into_dir.mkdir(parents=True, exist_ok=True)
636
- for file_path in sorted(from_dir.iterdir()):
637
- if not file_path.is_file() or file_path.suffix.lower() not in ALLOWED_INSTINCT_EXTENSIONS:
638
- continue
639
- try:
640
- instincts = parse_instinct_file(file_path.read_text(encoding="utf-8"))
641
- except (OSError, UnicodeDecodeError):
642
- instincts = []
643
- instinct_ids = [inst.get("id") for inst in instincts if inst.get("id")]
644
- if any(instinct_id in existing_ids for instinct_id in instinct_ids):
645
- skipped += 1
646
- continue
647
-
648
- target_path = into_dir / file_path.name
649
- if target_path.exists():
650
- target_path = into_dir / f"{file_path.stem}-{_project_hash(str(file_path))}{file_path.suffix}"
651
- shutil.copy2(file_path, target_path)
652
- existing_ids.update(instinct_ids)
653
- moved += 1
654
-
655
- return moved, skipped
656
-
657
-
658
- def _append_observations(from_project_dir: Path, into_project_dir: Path) -> int:
659
- from_file = from_project_dir / "observations.jsonl"
660
- if not from_file.exists():
661
- return 0
662
-
663
- into_file = into_project_dir / "observations.jsonl"
664
- into_file.parent.mkdir(parents=True, exist_ok=True)
665
- try:
666
- lines = from_file.read_text(encoding="utf-8").splitlines()
667
- except (OSError, UnicodeDecodeError):
668
- return 0
669
-
670
- if not lines:
671
- return 0
672
-
673
- with open(into_file, "a", encoding="utf-8") as f:
674
- for line in lines:
675
- if line.strip():
676
- f.write(line.rstrip("\n") + "\n")
677
- return len([line for line in lines if line.strip()])
678
-
679
-
680
- def load_all_instincts(project: dict, include_global: bool = True) -> list[dict]:
681
- """Carga todos los instintos: de proyecto + globales.
682
-
683
- Los instintos de proyecto tienen precedencia sobre los globales cuando los
684
- IDs colisionan.
685
- """
686
- instincts = []
687
-
688
- # 1. Cargar los instintos de proyecto (si no estamos ya en global)
689
- if project["id"] != "global":
690
- instincts.extend(_load_instincts_from_dir(
691
- project["instincts_personal"], "personal", "project"
692
- ))
693
- instincts.extend(_load_instincts_from_dir(
694
- project["instincts_inherited"], "inherited", "project"
695
- ))
696
-
697
- # 2. Cargar los instintos globales
698
- if include_global:
699
- global_instincts = []
700
- global_instincts.extend(_load_instincts_from_dir(
701
- GLOBAL_PERSONAL_DIR, "personal", "global"
702
- ))
703
- global_instincts.extend(_load_instincts_from_dir(
704
- GLOBAL_INHERITED_DIR, "inherited", "global"
705
- ))
706
-
707
- # Deduplicar: el de proyecto gana al global cuando el ID coincide
708
- project_ids = {i.get('id') for i in instincts}
709
- for gi in global_instincts:
710
- if gi.get('id') not in project_ids:
711
- instincts.append(gi)
712
-
713
- return instincts
714
-
715
-
716
- def load_project_only_instincts(project: dict) -> list[dict]:
717
- """Carga solo los instintos de ámbito de proyecto (sin globales).
718
-
719
- En modo de fallback global (sin proyecto git), devuelve los globales.
720
- """
721
- if project.get("id") == "global":
722
- instincts = _load_instincts_from_dir(GLOBAL_PERSONAL_DIR, "personal", "global")
723
- instincts += _load_instincts_from_dir(GLOBAL_INHERITED_DIR, "inherited", "global")
724
- return instincts
725
- return load_all_instincts(project, include_global=False)
726
-
727
-
728
- # ─────────────────────────────────────────────
729
- # Comando status
730
- # ─────────────────────────────────────────────
731
-
732
- def cmd_status(args) -> int:
733
- """Muestra el estado de todos los instintos (proyecto + global)."""
734
- project = detect_project()
735
- instincts = load_all_instincts(project)
736
-
737
- if not instincts:
738
- print("No se encontraron instintos.")
739
- print(f"\nProyecto: {project['name']} ({project['id']})")
740
- print(f" Instintos del proyecto: {project['instincts_personal']}")
741
- print(f" Instintos globales: {GLOBAL_PERSONAL_DIR}")
742
- else:
743
- # Separar por ámbito
744
- project_instincts = [i for i in instincts if i.get('_scope_label') == 'project']
745
- global_instincts = [i for i in instincts if i.get('_scope_label') == 'global']
746
-
747
- # Imprimir la cabecera
748
- print(f"\n{'='*60}")
749
- print(f" ESTADO DE INSTINTOS - {len(instincts)} en total")
750
- print(f"{'='*60}\n")
751
-
752
- print(f" Proyecto: {project['name']} ({project['id']})")
753
- print(f" Instintos del proyecto: {len(project_instincts)}")
754
- print(f" Instintos globales: {len(global_instincts)}")
755
- print()
756
-
757
- # Imprimir los instintos de proyecto
758
- if project_instincts:
759
- print(f"## ÁMBITO DE PROYECTO ({project['name']})")
760
- print()
761
- _print_instincts_by_domain(project_instincts)
762
-
763
- # Imprimir los instintos globales
764
- if global_instincts:
765
- print("## GLOBALES (aplican a todos los proyectos)")
766
- print()
767
- _print_instincts_by_domain(global_instincts)
768
-
769
- # Estadísticas de observaciones
770
- obs_file = project.get("observations_file")
771
- if obs_file and Path(obs_file).exists():
772
- with open(obs_file, encoding="utf-8") as f:
773
- obs_count = sum(1 for _ in f)
774
- print(f"-" * 60)
775
- print(f" Observaciones: {obs_count} eventos registrados")
776
- print(f" Archivo: {obs_file}")
777
-
778
- # Estadísticas de instintos pendientes
779
- pending = _collect_pending_instincts()
780
- if pending:
781
- print(f"\n{'-'*60}")
782
- print(f" Instintos pendientes: {len(pending)} a la espera de revisión")
783
-
784
- if len(pending) >= 5:
785
- print(f"\n \u26a0 {len(pending)} instintos pendientes de revisión."
786
- f" Los instintos sin revisar se eliminan automáticamente tras {PENDING_TTL_DAYS} días.")
787
-
788
- # Mostrar los instintos que caducan dentro de PENDING_EXPIRY_WARNING_DAYS
789
- expiry_threshold = PENDING_TTL_DAYS - PENDING_EXPIRY_WARNING_DAYS
790
- expiring_soon = [p for p in pending
791
- if p["age_days"] >= expiry_threshold and p["age_days"] < PENDING_TTL_DAYS]
792
- if expiring_soon:
793
- print(f"\n Caducan en menos de {PENDING_EXPIRY_WARNING_DAYS} días:")
794
- for item in expiring_soon:
795
- days_left = max(0, PENDING_TTL_DAYS - item["age_days"])
796
- print(f" - {item['name']} ({days_left} días restantes)")
797
-
798
- print(f"\n{'='*60}\n")
799
- return 0
800
-
801
-
802
- def _print_instincts_by_domain(instincts: list[dict]) -> None:
803
- """Helper para imprimir los instintos agrupados por dominio."""
804
- by_domain = defaultdict(list)
805
- for inst in instincts:
806
- domain = inst.get('domain', 'general')
807
- by_domain[domain].append(inst)
808
-
809
- for domain in sorted(by_domain.keys()):
810
- domain_instincts = by_domain[domain]
811
- print(f" ### {domain.upper()} ({len(domain_instincts)})")
812
- print()
813
-
814
- for inst in sorted(domain_instincts, key=lambda x: -x.get('confidence', 0.5)):
815
- conf = inst.get('confidence', 0.5)
816
- conf_bar = _confidence_bar(conf)
817
- trigger = inst.get('trigger', 'disparador desconocido')
818
- scope_tag = f"[{inst.get('scope', '?')}]"
819
-
820
- print(f" {conf_bar} {int(conf*100):3d}% {inst.get('id', 'unnamed')} {scope_tag}")
821
- print(f" disparador: {trigger}")
822
-
823
- # Extraer la acción del contenido
824
- content = inst.get('content', '')
825
- action_match = re.search(r'## Action\s*\n\s*(.+?)(?:\n\n|\n##|$)', content, re.DOTALL)
826
- if action_match:
827
- action = action_match.group(1).strip().split('\n')[0]
828
- print(f" acción: {action[:60]}{'...' if len(action) > 60 else ''}")
829
-
830
- print()
831
-
832
-
833
- # ─────────────────────────────────────────────
834
- # Comando import
835
- # ─────────────────────────────────────────────
836
-
837
- def cmd_import(args) -> int:
838
- """Importa instintos desde un archivo o URL."""
839
- project = detect_project()
840
- source = args.source
841
-
842
- # Determinar el ámbito destino
843
- target_scope = args.scope or "project"
844
- if target_scope == "project" and project["id"] == "global":
845
- print("No se detectó proyecto. Se importa con ámbito global.")
846
- target_scope = "global"
847
-
848
- # Obtener el contenido
849
- if source.startswith('http://') or source.startswith('https://'):
850
- print(f"Descargando desde URL: {source}")
851
- try:
852
- content = _fetch_import_url(source)
853
- except Exception as e:
854
- print(f"Error al descargar la URL: {e}", file=sys.stderr)
855
- return 1
856
- else:
857
- try:
858
- path = _validate_file_path(source, must_exist=True)
859
- except ValueError as e:
860
- print(f"Ruta inválida: {e}", file=sys.stderr)
861
- return 1
862
- if not path.is_file():
863
- print(f"Error: '{path}' no es un archivo regular.", file=sys.stderr)
864
- return 1
865
- content = path.read_text(encoding="utf-8")
866
-
867
- # Parsear los instintos
868
- new_instincts = parse_instinct_file(content)
869
- if not new_instincts:
870
- print("No se encontraron instintos válidos en el origen.")
871
- return 1
872
-
873
- print(f"\nSe encontraron {len(new_instincts)} instintos para importar.")
874
- print(f"Ámbito destino: {target_scope}")
875
- if target_scope == "project":
876
- print(f"Proyecto destino: {project['name']} ({project['id']})")
877
- print()
878
-
879
- # Cargar los instintos existentes para deduplicar, acotado al destino para
880
- # evitar sombras entre ámbitos (instintos de proyecto ocultando globales o al revés)
881
- if target_scope == "global":
882
- existing = _load_instincts_from_dir(GLOBAL_PERSONAL_DIR, "personal", "global")
883
- existing += _load_instincts_from_dir(GLOBAL_INHERITED_DIR, "inherited", "global")
884
- else:
885
- existing = load_project_only_instincts(project)
886
- existing_ids = {i.get('id') for i in existing}
887
-
888
- # Deduplicar dentro del origen de importación: conservar la mayor confianza por ID
889
- best_by_id = {}
890
- for inst in new_instincts:
891
- inst_id = inst.get('id')
892
- if inst_id not in best_by_id or inst.get('confidence', 0.5) > best_by_id[inst_id].get('confidence', 0.5):
893
- best_by_id[inst_id] = inst
894
- deduped_instincts = list(best_by_id.values())
895
-
896
- # Clasificar contra los instintos existentes en disco
897
- to_add = []
898
- duplicates = []
899
- to_update = []
900
-
901
- for inst in deduped_instincts:
902
- inst_id = inst.get('id')
903
- if inst_id in existing_ids:
904
- existing_inst = next((e for e in existing if e.get('id') == inst_id), None)
905
- if existing_inst:
906
- if inst.get('confidence', 0) > existing_inst.get('confidence', 0):
907
- to_update.append(inst)
908
- else:
909
- duplicates.append(inst)
910
- else:
911
- to_add.append(inst)
912
-
913
- # Filtrar por confianza mínima
914
- min_conf = args.min_confidence if args.min_confidence is not None else 0.0
915
- to_add = [i for i in to_add if i.get('confidence', 0.5) >= min_conf]
916
- to_update = [i for i in to_update if i.get('confidence', 0.5) >= min_conf]
917
-
918
- # Mostrar el resumen
919
- if to_add:
920
- print(f"NUEVOS ({len(to_add)}):")
921
- for inst in to_add:
922
- print(f" + {inst.get('id')} (confianza: {inst.get('confidence', 0.5):.2f})")
923
-
924
- if to_update:
925
- print(f"\nACTUALIZAR ({len(to_update)}):")
926
- for inst in to_update:
927
- print(f" ~ {inst.get('id')} (confianza: {inst.get('confidence', 0.5):.2f})")
928
-
929
- if duplicates:
930
- print(f"\nOMITIDOS ({len(duplicates)} - ya existen con confianza igual o superior):")
931
- for inst in duplicates[:5]:
932
- print(f" - {inst.get('id')}")
933
- if len(duplicates) > 5:
934
- print(f" ... y {len(duplicates) - 5} más")
935
-
936
- if args.dry_run:
937
- print("\n[DRY RUN] Sin cambios.")
938
- return 0
939
-
940
- if not to_add and not to_update:
941
- print("\nNada que importar.")
942
- return 0
943
-
944
- # Confirmar
945
- if not args.force:
946
- response = input(f"\n¿Importar {len(to_add)} nuevos y actualizar {len(to_update)}? [s/N] ")
947
- if response.lower() not in ('y', 's'):
948
- print("Cancelado.")
949
- return 0
950
-
951
- # Determinar el directorio de salida según el ámbito
952
- if target_scope == "global":
953
- output_dir = GLOBAL_INHERITED_DIR
954
- else:
955
- output_dir = project["instincts_inherited"]
956
-
957
- output_dir.mkdir(parents=True, exist_ok=True)
958
-
959
- # Recolectar los archivos obsoletos de los instintos que se actualizan (se
960
- # borran después de escribir el archivo nuevo). Se permite borrar de cualquier
961
- # subdirectorio (personal/ o inherited/) dentro del ámbito destino para evitar
962
- # que el mismo ID exista en ambos sitios. Se protege contra borrados entre
963
- # ámbitos restringiendo a la raíz de instintos del ámbito.
964
- if target_scope == "global":
965
- scope_root = GLOBAL_INSTINCTS_DIR.resolve()
966
- else:
967
- scope_root = (project["project_dir"] / "instincts").resolve() if project["id"] != "global" else GLOBAL_INSTINCTS_DIR.resolve()
968
- stale_paths = []
969
- for inst in to_update:
970
- inst_id = inst.get('id')
971
- stale = next((e for e in existing if e.get('id') == inst_id), None)
972
- if stale and stale.get('_source_file'):
973
- stale_path = Path(stale['_source_file']).resolve()
974
- if stale_path.exists() and str(stale_path).startswith(str(scope_root) + os.sep):
975
- stale_paths.append(stale_path)
976
-
977
- # Escribir primero el archivo nuevo (seguro: si falla, los obsoletos se conservan)
978
- timestamp = datetime.now().strftime('%Y%m%d-%H%M%S')
979
- source_name = Path(source).stem if not source.startswith('http') else 'web-import'
980
- output_file = output_dir / f"{source_name}-{timestamp}.yaml"
981
-
982
- all_to_write = to_add + to_update
983
- output_content = f"# Importado desde {source}\n# Fecha: {datetime.now().isoformat()}\n# Ámbito: {target_scope}\n"
984
- if target_scope == "project":
985
- output_content += f"# Proyecto: {project['name']} ({project['id']})\n"
986
- output_content += "\n"
987
-
988
- for inst in all_to_write:
989
- output_content += "---\n"
990
- output_content += f"id: {inst.get('id')}\n"
991
- output_content += f"trigger: {_yaml_quote(inst.get('trigger', 'unknown'))}\n"
992
- output_content += f"confidence: {inst.get('confidence', 0.5)}\n"
993
- output_content += f"domain: {inst.get('domain', 'general')}\n"
994
- output_content += "source: inherited\n"
995
- output_content += f"scope: {target_scope}\n"
996
- output_content += f"imported_from: {_yaml_quote(source)}\n"
997
- if target_scope == "project":
998
- output_content += f"project_id: {project['id']}\n"
999
- output_content += f"project_name: {project['name']}\n"
1000
- if inst.get('source_repo'):
1001
- output_content += f"source_repo: {inst.get('source_repo')}\n"
1002
- output_content += "---\n\n"
1003
- output_content += inst.get('content', '') + "\n\n"
1004
-
1005
- output_file.write_text(output_content, encoding="utf-8")
1006
-
1007
- # Eliminar los archivos obsoletos solo tras escribir con éxito el archivo nuevo
1008
- for stale_path in stale_paths:
1009
- try:
1010
- stale_path.unlink()
1011
- except OSError:
1012
- pass # eliminación de mejor esfuerzo
1013
-
1014
- print(f"\n¡Importación completada!")
1015
- print(f" Ámbito: {target_scope}")
1016
- print(f" Añadidos: {len(to_add)}")
1017
- print(f" Actualizados: {len(to_update)}")
1018
- print(f" Guardado en: {output_file}")
1019
-
1020
- return 0
1021
-
1022
-
1023
- # ─────────────────────────────────────────────
1024
- # Comando export
1025
- # ─────────────────────────────────────────────
1026
-
1027
- def cmd_export(args) -> int:
1028
- """Exporta los instintos a un archivo."""
1029
- project = detect_project()
1030
-
1031
- # Determinar qué exportar según el filtro de ámbito
1032
- if args.scope == "project":
1033
- instincts = load_project_only_instincts(project)
1034
- elif args.scope == "global":
1035
- instincts = _load_instincts_from_dir(GLOBAL_PERSONAL_DIR, "personal", "global")
1036
- instincts += _load_instincts_from_dir(GLOBAL_INHERITED_DIR, "inherited", "global")
1037
- else:
1038
- instincts = load_all_instincts(project)
1039
-
1040
- if not instincts:
1041
- print("No hay instintos para exportar.")
1042
- return 1
1043
-
1044
- # Filtrar por dominio si se especifica
1045
- if args.domain:
1046
- instincts = [i for i in instincts if i.get('domain') == args.domain]
1047
-
1048
- # Filtrar por confianza mínima
1049
- if args.min_confidence:
1050
- instincts = [i for i in instincts if i.get('confidence', 0.5) >= args.min_confidence]
1051
-
1052
- if not instincts:
1053
- print("Ningún instinto cumple los criterios.")
1054
- return 1
1055
-
1056
- # Generar la salida
1057
- output = f"# Exportación de instintos\n# Fecha: {datetime.now().isoformat()}\n# Total: {len(instincts)}\n"
1058
- if args.scope:
1059
- output += f"# Ámbito: {args.scope}\n"
1060
- if project["id"] != "global":
1061
- output += f"# Proyecto: {project['name']} ({project['id']})\n"
1062
- output += "\n"
1063
-
1064
- for inst in instincts:
1065
- output += "---\n"
1066
- for key in ['id', 'trigger', 'confidence', 'domain', 'source', 'scope',
1067
- 'project_id', 'project_name', 'source_repo']:
1068
- if inst.get(key):
1069
- value = inst[key]
1070
- if key == 'trigger':
1071
- output += f'{key}: {_yaml_quote(value)}\n'
1072
- else:
1073
- output += f"{key}: {value}\n"
1074
- output += "---\n\n"
1075
- output += inst.get('content', '') + "\n\n"
1076
-
1077
- # Escribir al archivo o a stdout
1078
- if args.output:
1079
- try:
1080
- out_path = _validate_file_path(args.output)
1081
- except ValueError as e:
1082
- print(f"Ruta de salida inválida: {e}", file=sys.stderr)
1083
- return 1
1084
- if out_path.is_dir():
1085
- print(f"Error: '{out_path}' es un directorio, no un archivo.", file=sys.stderr)
1086
- return 1
1087
- out_path.parent.mkdir(parents=True, exist_ok=True)
1088
- out_path.write_text(output, encoding="utf-8")
1089
- print(f"Se exportaron {len(instincts)} instintos a {out_path}")
1090
- else:
1091
- print(output)
1092
-
1093
- return 0
1094
-
1095
-
1096
- # ─────────────────────────────────────────────
1097
- # Comando evolve
1098
- # ─────────────────────────────────────────────
1099
-
1100
- def cmd_evolve(args) -> int:
1101
- """Analiza los instintos y sugiere evoluciones a skills/comandos/agentes."""
1102
- project = detect_project()
1103
- instincts = load_all_instincts(project)
1104
-
1105
- if len(instincts) < 3:
1106
- print("Se necesitan al menos 3 instintos para analizar patrones.")
1107
- print(f"Actualmente hay: {len(instincts)}")
1108
- return 1
1109
-
1110
- project_instincts = [i for i in instincts if i.get('_scope_label') == 'project']
1111
- global_instincts = [i for i in instincts if i.get('_scope_label') == 'global']
1112
-
1113
- print(f"\n{'='*60}")
1114
- print(f" ANÁLISIS DE EVOLUCIÓN - {len(instincts)} instintos")
1115
- print(f" Proyecto: {project['name']} ({project['id']})")
1116
- print(f" De proyecto: {len(project_instincts)} | Globales: {len(global_instincts)}")
1117
- print(f"{'='*60}\n")
1118
-
1119
- # Agrupar por dominio
1120
- by_domain = defaultdict(list)
1121
- for inst in instincts:
1122
- domain = inst.get('domain', 'general')
1123
- by_domain[domain].append(inst)
1124
-
1125
- # Instintos de alta confianza por dominio (candidatos a skills)
1126
- high_conf = [i for i in instincts if i.get('confidence', 0) >= 0.8]
1127
- print(f"Instintos de alta confianza (>=80%): {len(high_conf)}")
1128
-
1129
- # Buscar clústeres (instintos con disparadores similares)
1130
- trigger_clusters = defaultdict(list)
1131
- for inst in instincts:
1132
- trigger = inst.get('trigger', '')
1133
- # Normalizar el disparador
1134
- trigger_key = trigger.lower()
1135
- for keyword in ['when', 'creating', 'writing', 'adding', 'implementing', 'testing']:
1136
- trigger_key = trigger_key.replace(keyword, '').strip()
1137
- trigger_clusters[trigger_key].append(inst)
1138
-
1139
- # Buscar clústeres con 2+ instintos (buenos candidatos a skill)
1140
- skill_candidates = []
1141
- for trigger, cluster in trigger_clusters.items():
1142
- if len(cluster) >= 2:
1143
- avg_conf = sum(i.get('confidence', 0.5) for i in cluster) / len(cluster)
1144
- skill_candidates.append({
1145
- 'trigger': trigger,
1146
- 'instincts': cluster,
1147
- 'avg_confidence': avg_conf,
1148
- 'domains': list(set(i.get('domain', 'general') for i in cluster)),
1149
- 'scopes': list(set(i.get('scope', 'project') for i in cluster)),
1150
- })
1151
-
1152
- # Ordenar por tamaño del clúster y confianza
1153
- skill_candidates.sort(key=lambda x: (-len(x['instincts']), -x['avg_confidence']))
1154
-
1155
- print(f"\nClústeres de skill potenciales: {len(skill_candidates)}")
1156
-
1157
- if skill_candidates:
1158
- print(f"\n## CANDIDATOS A SKILL\n")
1159
- for i, cand in enumerate(skill_candidates[:5], 1):
1160
- scope_info = ', '.join(cand['scopes'])
1161
- print(f"{i}. Clúster: \"{cand['trigger']}\"")
1162
- print(f" Instintos: {len(cand['instincts'])}")
1163
- print(f" Confianza media: {cand['avg_confidence']:.0%}")
1164
- print(f" Dominios: {', '.join(cand['domains'])}")
1165
- print(f" Ámbitos: {scope_info}")
1166
- print(f" Instintos:")
1167
- for inst in cand['instincts'][:3]:
1168
- print(f" - {inst.get('id')} [{inst.get('scope', '?')}]")
1169
- print()
1170
-
1171
- # Candidatos a comando (instintos de workflow con alta confianza)
1172
- workflow_instincts = [i for i in instincts if i.get('domain') == 'workflow' and i.get('confidence', 0) >= 0.7]
1173
- if workflow_instincts:
1174
- print(f"\n## CANDIDATOS A COMANDO ({len(workflow_instincts)})\n")
1175
- for inst in workflow_instincts[:5]:
1176
- trigger = inst.get('trigger', 'unknown')
1177
- cmd_name = trigger.replace('when ', '').replace('implementing ', '').replace('a ', '')
1178
- cmd_name = cmd_name.replace(' ', '-')[:20]
1179
- print(f" /{cmd_name}")
1180
- print(f" Desde: {inst.get('id')} [{inst.get('scope', '?')}]")
1181
- print(f" Confianza: {inst.get('confidence', 0.5):.0%}")
1182
- print()
1183
-
1184
- # Candidatos a agente (patrones complejos de varios pasos)
1185
- agent_candidates = [c for c in skill_candidates if len(c['instincts']) >= 3 and c['avg_confidence'] >= 0.75]
1186
- if agent_candidates:
1187
- print(f"\n## CANDIDATOS A AGENTE ({len(agent_candidates)})\n")
1188
- for cand in agent_candidates[:3]:
1189
- agent_name = cand['trigger'].replace(' ', '-')[:20] + '-agent'
1190
- print(f" {agent_name}")
1191
- print(f" Abarca {len(cand['instincts'])} instintos")
1192
- print(f" Confianza media: {cand['avg_confidence']:.0%}")
1193
- print()
1194
-
1195
- # Candidatos a promoción (instintos de proyecto que podrían ser globales)
1196
- _show_promotion_candidates(project)
1197
-
1198
- if args.generate:
1199
- evolved_dir = project["evolved_dir"] if project["id"] != "global" else GLOBAL_EVOLVED_DIR
1200
- generated = _generate_evolved(skill_candidates, workflow_instincts, agent_candidates, evolved_dir)
1201
- if generated:
1202
- print(f"\nSe generaron {len(generated)} estructuras evolucionadas:")
1203
- for path in generated:
1204
- print(f" {path}")
1205
- else:
1206
- print("\nNo se generaron estructuras (se necesitan clústeres de mayor confianza).")
1207
-
1208
- print(f"\n{'='*60}\n")
1209
- return 0
1210
-
1211
-
1212
- # ─────────────────────────────────────────────
1213
- # Comando promote
1214
- # ─────────────────────────────────────────────
1215
-
1216
- def _find_cross_project_instincts() -> dict:
1217
- """Encuentra instintos que aparecen en varios proyectos (candidatos a promoción).
1218
-
1219
- Devuelve un dict que mapea ID de instinto → lista de tuplas (project_id, instinto).
1220
- """
1221
- registry = load_registry()
1222
- cross_project = defaultdict(list)
1223
-
1224
- for pid, pinfo in registry.items():
1225
- project_dir = PROJECTS_DIR / pid
1226
- personal_dir = project_dir / "instincts" / "personal"
1227
- inherited_dir = project_dir / "instincts" / "inherited"
1228
-
1229
- # Registrar los IDs de instinto ya vistos en este proyecto para no contar
1230
- # el mismo instinto dos veces (p. ej. en personal/ y en inherited/)
1231
- seen_in_project = set()
1232
- for d, stype in [(personal_dir, "personal"), (inherited_dir, "inherited")]:
1233
- for inst in _load_instincts_from_dir(d, stype, "project"):
1234
- iid = inst.get('id')
1235
- if iid and iid not in seen_in_project:
1236
- seen_in_project.add(iid)
1237
- cross_project[iid].append((pid, pinfo.get('name', pid), inst))
1238
-
1239
- # Filtrar solo a los que aparecen en 2+ proyectos distintos
1240
- return {iid: entries for iid, entries in cross_project.items() if len(entries) >= 2}
1241
-
1242
-
1243
- def _show_promotion_candidates(project: dict) -> None:
1244
- """Muestra los instintos que podrían promoverse de proyecto a global."""
1245
- cross = _find_cross_project_instincts()
1246
-
1247
- if not cross:
1248
- return
1249
-
1250
- # Filtrar a los de alta confianza que aún no son globales
1251
- global_instincts = _load_instincts_from_dir(GLOBAL_PERSONAL_DIR, "personal", "global")
1252
- global_instincts += _load_instincts_from_dir(GLOBAL_INHERITED_DIR, "inherited", "global")
1253
- global_ids = {i.get('id') for i in global_instincts}
1254
-
1255
- candidates = []
1256
- for iid, entries in cross.items():
1257
- if iid in global_ids:
1258
- continue
1259
- avg_conf = sum(e[2].get('confidence', 0.5) for e in entries) / len(entries)
1260
- if avg_conf >= PROMOTE_CONFIDENCE_THRESHOLD:
1261
- candidates.append({
1262
- 'id': iid,
1263
- 'projects': [(pid, pname) for pid, pname, _ in entries],
1264
- 'avg_confidence': avg_conf,
1265
- 'sample': entries[0][2],
1266
- })
1267
-
1268
- if candidates:
1269
- print(f"\n## CANDIDATOS A PROMOCIÓN (proyecto -> global)\n")
1270
- print(f" Estos instintos aparecen en {PROMOTE_MIN_PROJECTS}+ proyectos con alta confianza:\n")
1271
- for cand in candidates[:10]:
1272
- proj_names = ', '.join(pname for _, pname in cand['projects'])
1273
- print(f" * {cand['id']} (avg: {cand['avg_confidence']:.0%})")
1274
- print(f" Presente en: {proj_names}")
1275
- print()
1276
- print(f" Ejecuta `instinct-cli.py promote` para promoverlos a ámbito global.\n")
1277
-
1278
-
1279
- def cmd_promote(args) -> int:
1280
- """Promueve instintos de ámbito de proyecto al ámbito global."""
1281
- project = detect_project()
1282
-
1283
- if args.instinct_id:
1284
- # Promover un instinto concreto
1285
- return _promote_specific(project, args.instinct_id, args.force, args.dry_run)
1286
- else:
1287
- # Autodetectar candidatos a promoción
1288
- return _promote_auto(project, args.force, args.dry_run)
1289
-
1290
-
1291
- def _promote_specific(project: dict, instinct_id: str, force: bool, dry_run: bool = False) -> int:
1292
- """Promueve un instinto concreto por ID del proyecto actual al ámbito global."""
1293
- if not _validate_instinct_id(instinct_id):
1294
- print(f"ID de instinto inválido: '{instinct_id}'.", file=sys.stderr)
1295
- return 1
1296
-
1297
- project_instincts = load_project_only_instincts(project)
1298
- target = next((i for i in project_instincts if i.get('id') == instinct_id), None)
1299
-
1300
- if not target:
1301
- print(f"No se encontró el instinto '{instinct_id}' en el proyecto {project['name']}.")
1302
- return 1
1303
-
1304
- # Comprobar si ya es global
1305
- global_instincts = _load_instincts_from_dir(GLOBAL_PERSONAL_DIR, "personal", "global")
1306
- global_instincts += _load_instincts_from_dir(GLOBAL_INHERITED_DIR, "inherited", "global")
1307
- if any(i.get('id') == instinct_id for i in global_instincts):
1308
- print(f"El instinto '{instinct_id}' ya existe en el ámbito global.")
1309
- return 1
1310
-
1311
- print(f"\nPromoviendo: {instinct_id}")
1312
- print(f" Desde: proyecto '{project['name']}'")
1313
- print(f" Confianza: {target.get('confidence', 0.5):.0%}")
1314
- print(f" Dominio: {target.get('domain', 'general')}")
1315
-
1316
- if dry_run:
1317
- print("\n[DRY RUN] Sin cambios.")
1318
- return 0
1319
-
1320
- if not force:
1321
- response = input(f"\n¿Promover a global? [s/N] ")
1322
- if response.lower() not in ('y', 's'):
1323
- print("Cancelado.")
1324
- return 0
1325
-
1326
- # Escribir en el directorio personal global
1327
- output_file = GLOBAL_PERSONAL_DIR / f"{instinct_id}.yaml"
1328
- output_content = "---\n"
1329
- output_content += f"id: {target.get('id')}\n"
1330
- output_content += f"trigger: {_yaml_quote(target.get('trigger', 'unknown'))}\n"
1331
- output_content += f"confidence: {target.get('confidence', 0.5)}\n"
1332
- output_content += f"domain: {target.get('domain', 'general')}\n"
1333
- output_content += f"source: {target.get('source', 'promoted')}\n"
1334
- output_content += f"scope: global\n"
1335
- output_content += f"promoted_from: {project['id']}\n"
1336
- output_content += f"promoted_date: {datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')}\n"
1337
- output_content += "---\n\n"
1338
- output_content += target.get('content', '') + "\n"
1339
-
1340
- output_file.write_text(output_content, encoding="utf-8")
1341
- print(f"\nInstinto '{instinct_id}' promovido a ámbito global.")
1342
- print(f" Guardado en: {output_file}")
1343
- return 0
1344
-
1345
-
1346
- def _promote_auto(project: dict, force: bool, dry_run: bool) -> int:
1347
- """Autopromueve los instintos encontrados en varios proyectos."""
1348
- cross = _find_cross_project_instincts()
1349
-
1350
- global_instincts = _load_instincts_from_dir(GLOBAL_PERSONAL_DIR, "personal", "global")
1351
- global_instincts += _load_instincts_from_dir(GLOBAL_INHERITED_DIR, "inherited", "global")
1352
- global_ids = {i.get('id') for i in global_instincts}
1353
-
1354
- candidates = []
1355
- for iid, entries in cross.items():
1356
- if iid in global_ids:
1357
- continue
1358
- avg_conf = sum(e[2].get('confidence', 0.5) for e in entries) / len(entries)
1359
- if avg_conf >= PROMOTE_CONFIDENCE_THRESHOLD and len(entries) >= PROMOTE_MIN_PROJECTS:
1360
- candidates.append({
1361
- 'id': iid,
1362
- 'entries': entries,
1363
- 'avg_confidence': avg_conf,
1364
- })
1365
-
1366
- if not candidates:
1367
- print("Ningún instinto califica para promoción automática.")
1368
- print(f" Criterios: aparece en {PROMOTE_MIN_PROJECTS}+ proyectos, confianza media >= {PROMOTE_CONFIDENCE_THRESHOLD:.0%}")
1369
- return 0
1370
-
1371
- print(f"\n{'='*60}")
1372
- print(f" CANDIDATOS A PROMOCIÓN AUTOMÁTICA - {len(candidates)}")
1373
- print(f"{'='*60}\n")
1374
-
1375
- for cand in candidates:
1376
- proj_names = ', '.join(pname for _, pname, _ in cand['entries'])
1377
- print(f" {cand['id']} (avg: {cand['avg_confidence']:.0%})")
1378
- print(f" Presente en {len(cand['entries'])} proyectos: {proj_names}")
1379
-
1380
- if dry_run:
1381
- print(f"\n[DRY RUN] Sin cambios.")
1382
- return 0
1383
-
1384
- if not force:
1385
- response = input(f"\n¿Promover {len(candidates)} instintos a global? [s/N] ")
1386
- if response.lower() not in ('y', 's'):
1387
- print("Cancelado.")
1388
- return 0
1389
-
1390
- promoted = 0
1391
- for cand in candidates:
1392
- if not _validate_instinct_id(cand['id']):
1393
- print(f"Se omite un ID de instinto inválido durante la promoción: {cand['id']}", file=sys.stderr)
1394
- continue
1395
-
1396
- # Usar la versión de mayor confianza
1397
- best_entry = max(cand['entries'], key=lambda e: e[2].get('confidence', 0.5))
1398
- inst = best_entry[2]
1399
-
1400
- output_file = GLOBAL_PERSONAL_DIR / f"{cand['id']}.yaml"
1401
- output_content = "---\n"
1402
- output_content += f"id: {inst.get('id')}\n"
1403
- output_content += f"trigger: {_yaml_quote(inst.get('trigger', 'unknown'))}\n"
1404
- output_content += f"confidence: {cand['avg_confidence']}\n"
1405
- output_content += f"domain: {inst.get('domain', 'general')}\n"
1406
- output_content += f"source: auto-promoted\n"
1407
- output_content += f"scope: global\n"
1408
- output_content += f"promoted_date: {datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')}\n"
1409
- output_content += f"seen_in_projects: {len(cand['entries'])}\n"
1410
- output_content += "---\n\n"
1411
- output_content += inst.get('content', '') + "\n"
1412
-
1413
- output_file.write_text(output_content, encoding="utf-8")
1414
- promoted += 1
1415
-
1416
- print(f"\nSe promovieron {promoted} instintos a ámbito global.")
1417
- return 0
1418
-
1419
-
1420
- # ─────────────────────────────────────────────
1421
- # Comando projects
1422
- # ─────────────────────────────────────────────
1423
-
1424
- def cmd_projects(args) -> int:
1425
- """Lista o mantiene los proyectos conocidos y sus recuentos de instintos."""
1426
- if getattr(args, "project_action", None) == "delete":
1427
- return _cmd_projects_delete(args)
1428
- if getattr(args, "project_action", None) == "merge":
1429
- return _cmd_projects_merge(args)
1430
- if getattr(args, "project_action", None) == "gc":
1431
- return _cmd_projects_gc(args)
1432
-
1433
- registry = load_registry()
1434
-
1435
- if not registry:
1436
- print("Aún no hay proyectos registrados.")
1437
- print("Los proyectos se detectan automáticamente cuando usas el CLI en un repo git.")
1438
- return 0
1439
-
1440
- print(f"\n{'='*60}")
1441
- print(f" PROYECTOS CONOCIDOS - {len(registry)} en total")
1442
- print(f"{'='*60}\n")
1443
-
1444
- for pid, pinfo in sorted(registry.items(), key=lambda x: x[1].get('last_seen', ''), reverse=True):
1445
- project_dir = PROJECTS_DIR / pid
1446
- personal_dir = project_dir / "instincts" / "personal"
1447
- inherited_dir = project_dir / "instincts" / "inherited"
1448
-
1449
- personal_count = len(_load_instincts_from_dir(personal_dir, "personal", "project"))
1450
- inherited_count = len(_load_instincts_from_dir(inherited_dir, "inherited", "project"))
1451
- obs_file = project_dir / "observations.jsonl"
1452
- if obs_file.exists():
1453
- with open(obs_file, encoding="utf-8") as f:
1454
- obs_count = sum(1 for _ in f)
1455
- else:
1456
- obs_count = 0
1457
-
1458
- print(f" {pinfo.get('name', pid)} [{pid}]")
1459
- print(f" Raíz: {pinfo.get('root', 'desconocida')}")
1460
- if pinfo.get('remote'):
1461
- print(f" Remoto: {pinfo['remote']}")
1462
- print(f" Instintos: {personal_count} personales, {inherited_count} heredados")
1463
- print(f" Observaciones: {obs_count} eventos")
1464
- print(f" Visto por última vez: {pinfo.get('last_seen', 'desconocido')}")
1465
- print()
1466
-
1467
- # Estadísticas globales
1468
- global_personal = len(_load_instincts_from_dir(GLOBAL_PERSONAL_DIR, "personal", "global"))
1469
- global_inherited = len(_load_instincts_from_dir(GLOBAL_INHERITED_DIR, "inherited", "global"))
1470
- print(f" GLOBAL")
1471
- print(f" Instintos: {global_personal} personales, {global_inherited} heredados")
1472
-
1473
- print(f"\n{'='*60}\n")
1474
- return 0
1475
-
1476
-
1477
- def _cmd_projects_delete(args) -> int:
1478
- registry = load_registry()
1479
- project_id = args.project_id
1480
-
1481
- if not _validate_project_id(project_id):
1482
- print(f"ID de proyecto inválido: {project_id}", file=sys.stderr)
1483
- return 1
1484
- if project_id not in registry and not (PROJECTS_DIR / project_id).exists():
1485
- print(f"No se encontró el proyecto '{project_id}'.", file=sys.stderr)
1486
- return 1
1487
-
1488
- counts = _project_counts(project_id)
1489
- print(f"Proyecto: {project_id}")
1490
- print(f" Instintos: {counts['personal']} personales, {counts['inherited']} heredados")
1491
- print(f" Observaciones: {counts['observations']} eventos")
1492
-
1493
- if args.dry_run:
1494
- print(f"\n[DRY RUN] Se eliminaría el proyecto '{project_id}' del registro y del almacenamiento.")
1495
- return 0
1496
-
1497
- if not args.force:
1498
- if counts["total"] > 0:
1499
- print("\nAviso: este proyecto tiene instintos u observaciones.")
1500
- response = input(f"¿Eliminar el proyecto '{project_id}'? [s/N] ")
1501
- if response.lower() not in ("y", "s"):
1502
- print("Cancelado.")
1503
- return 0
1504
-
1505
- registry.pop(project_id, None)
1506
- _write_registry(registry)
1507
- _remove_project_storage(project_id)
1508
- print(f"\nProyecto '{project_id}' eliminado.")
1509
- return 0
1510
-
1511
-
1512
- def _cmd_projects_gc(args) -> int:
1513
- registry = load_registry()
1514
- candidates = [
1515
- project_id
1516
- for project_id in sorted(registry)
1517
- if _validate_project_id(project_id) and _project_counts(project_id)["total"] == 0
1518
- ]
1519
-
1520
- if not candidates:
1521
- print("No se encontraron entradas de proyecto vacías.")
1522
- return 0
1523
-
1524
- print(f"Entradas de proyecto vacías: {len(candidates)}")
1525
- for project_id in candidates:
1526
- pinfo = registry.get(project_id, {})
1527
- print(f" - {pinfo.get('name', project_id)} [{project_id}]")
1528
-
1529
- if args.dry_run:
1530
- print(f"\n[DRY RUN] Se eliminarían {len(candidates)} entrada(s) de proyecto.")
1531
- return 0
1532
-
1533
- if not args.force:
1534
- response = input(f"\n¿Eliminar {len(candidates)} entrada(s) de proyecto vacía(s)? [s/N] ")
1535
- if response.lower() not in ("y", "s"):
1536
- print("Cancelado.")
1537
- return 0
1538
-
1539
- for project_id in candidates:
1540
- registry.pop(project_id, None)
1541
- _remove_project_storage(project_id)
1542
- _write_registry(registry)
1543
- print(f"\nSe eliminaron {len(candidates)} entrada(s) de proyecto vacía(s).")
1544
- return 0
1545
-
1546
-
1547
- def _cmd_projects_merge(args) -> int:
1548
- from_id = args.from_id
1549
- into_id = args.into_id
1550
-
1551
- if not _validate_project_id(from_id) or not _validate_project_id(into_id):
1552
- print("ID de proyecto inválido.", file=sys.stderr)
1553
- return 1
1554
- if from_id == into_id:
1555
- print("No se puede fusionar un proyecto consigo mismo.", file=sys.stderr)
1556
- return 1
1557
-
1558
- registry = load_registry()
1559
- if from_id not in registry:
1560
- print(f"No se encontró el proyecto de origen '{from_id}'.", file=sys.stderr)
1561
- return 1
1562
- if into_id not in registry:
1563
- print(f"No se encontró el proyecto de destino '{into_id}'.", file=sys.stderr)
1564
- return 1
1565
-
1566
- from_counts = _project_counts(from_id)
1567
- into_counts = _project_counts(into_id)
1568
- print(f"Fusión: {from_id} -> {into_id}")
1569
- print(f" Origen: {from_counts['personal']} personales, {from_counts['inherited']} heredados, {from_counts['observations']} observaciones")
1570
- print(f" Destino antes de la fusión: {into_counts['personal']} personales, {into_counts['inherited']} heredados, {into_counts['observations']} observaciones")
1571
-
1572
- if args.dry_run:
1573
- print("\n[DRY RUN] Se fusionaría el proyecto de origen en el destino y se eliminaría el origen.")
1574
- return 0
1575
-
1576
- if not args.force:
1577
- response = input(f"\n¿Fusionar '{from_id}' en '{into_id}' y eliminar el origen? [s/N] ")
1578
- if response.lower() not in ("y", "s"):
1579
- print("Cancelado.")
1580
- return 0
1581
-
1582
- from_project_dir = PROJECTS_DIR / from_id
1583
- into_project_dir = PROJECTS_DIR / into_id
1584
- into_project_dir.mkdir(parents=True, exist_ok=True)
1585
-
1586
- personal_existing = _project_instinct_ids(into_project_dir, "personal")
1587
- inherited_existing = _project_instinct_ids(into_project_dir, "inherited")
1588
- personal_moved, personal_skipped = _merge_instinct_dir(
1589
- from_project_dir / "instincts" / "personal",
1590
- into_project_dir / "instincts" / "personal",
1591
- personal_existing,
1592
- )
1593
- inherited_moved, inherited_skipped = _merge_instinct_dir(
1594
- from_project_dir / "instincts" / "inherited",
1595
- into_project_dir / "instincts" / "inherited",
1596
- inherited_existing,
1597
- )
1598
- observations_moved = _append_observations(from_project_dir, into_project_dir)
1599
-
1600
- registry.pop(from_id, None)
1601
- destination = registry.get(into_id, {})
1602
- destination["last_seen"] = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
1603
- registry[into_id] = destination
1604
- _write_registry(registry)
1605
- _remove_project_storage(from_id)
1606
-
1607
- print("\nEntrada de registro del proyecto fusionada.")
1608
- print(f" Instintos movidos: {personal_moved + inherited_moved}")
1609
- print(f" Instintos duplicados omitidos: {personal_skipped + inherited_skipped}")
1610
- print(f" Observaciones añadidas: {observations_moved}")
1611
- return 0
1612
-
1613
-
1614
- # ─────────────────────────────────────────────
1615
- # Generación de estructuras evolucionadas
1616
- # ─────────────────────────────────────────────
1617
-
1618
- def _generate_evolved(skill_candidates: list, workflow_instincts: list, agent_candidates: list, evolved_dir: Path) -> list[str]:
1619
- """Genera archivos de skill/comando/agente a partir de los clústeres de instintos analizados."""
1620
- generated = []
1621
-
1622
- # Generar skills desde los mejores candidatos
1623
- for cand in skill_candidates[:5]:
1624
- trigger = cand['trigger'].strip()
1625
- if not trigger:
1626
- continue
1627
- name = re.sub(r'[^a-z0-9]+', '-', trigger.lower()).strip('-')[:30]
1628
- if not name:
1629
- continue
1630
-
1631
- skill_dir = evolved_dir / "skills" / name
1632
- skill_dir.mkdir(parents=True, exist_ok=True)
1633
-
1634
- content = f"# {name}\n\n"
1635
- content += f"Generado a partir de {len(cand['instincts'])} instintos "
1636
- content += f"(confianza media: {cand['avg_confidence']:.0%})\n\n"
1637
- content += f"## Cuándo aplicar\n\n"
1638
- content += f"Disparador: {trigger}\n\n"
1639
- content += f"## Acciones\n\n"
1640
- for inst in cand['instincts']:
1641
- inst_content = inst.get('content', '')
1642
- action_match = re.search(r'## Action\s*\n\s*(.+?)(?:\n\n|\n##|$)', inst_content, re.DOTALL)
1643
- action = action_match.group(1).strip() if action_match else inst.get('id', 'unnamed')
1644
- content += f"- {action}\n"
1645
-
1646
- (skill_dir / "SKILL.md").write_text(content, encoding="utf-8")
1647
- generated.append(str(skill_dir / "SKILL.md"))
1648
-
1649
- # Generar comandos desde los instintos de workflow
1650
- for inst in workflow_instincts[:5]:
1651
- trigger = inst.get('trigger', 'unknown')
1652
- cmd_name = re.sub(r'[^a-z0-9]+', '-', trigger.lower().replace('when ', '').replace('implementing ', ''))
1653
- cmd_name = cmd_name.strip('-')[:20]
1654
- if not cmd_name:
1655
- continue
1656
-
1657
- cmd_file = evolved_dir / "commands" / f"{cmd_name}.md"
1658
- content = f"# {cmd_name}\n\n"
1659
- content += f"Generado a partir del instinto: {inst.get('id', 'unnamed')}\n"
1660
- content += f"Confianza: {inst.get('confidence', 0.5):.0%}\n\n"
1661
- content += inst.get('content', '')
1662
-
1663
- cmd_file.write_text(content, encoding="utf-8")
1664
- generated.append(str(cmd_file))
1665
-
1666
- # Generar agentes desde los clústeres complejos
1667
- for cand in agent_candidates[:3]:
1668
- trigger = cand['trigger'].strip()
1669
- agent_name = re.sub(r'[^a-z0-9]+', '-', trigger.lower()).strip('-')[:20]
1670
- if not agent_name:
1671
- continue
1672
-
1673
- agent_file = evolved_dir / "agents" / f"{agent_name}.md"
1674
- domains = ', '.join(cand['domains'])
1675
- instinct_ids = [i.get('id', 'unnamed') for i in cand['instincts']]
1676
-
1677
- content = f"---\ntools: Read, Grep, Glob\n---\n"
1678
- content += f"# {agent_name}\n\n"
1679
- content += f"Generado a partir de {len(cand['instincts'])} instintos "
1680
- content += f"(confianza media: {cand['avg_confidence']:.0%})\n"
1681
- content += f"Dominios: {domains}\n\n"
1682
- content += f"## Instintos de origen\n\n"
1683
- for iid in instinct_ids:
1684
- content += f"- {iid}\n"
1685
-
1686
- agent_file.write_text(content, encoding="utf-8")
1687
- generated.append(str(agent_file))
1688
-
1689
- return generated
1690
-
1691
-
1692
- # ─────────────────────────────────────────────
1693
- # Helpers de instintos pendientes
1694
- # ─────────────────────────────────────────────
1695
-
1696
- def _collect_pending_dirs() -> list[Path]:
1697
- """Devuelve todos los directorios de instintos pendientes (global + por proyecto)."""
1698
- dirs = []
1699
- global_pending = GLOBAL_INSTINCTS_DIR / "pending"
1700
- if global_pending.is_dir():
1701
- dirs.append(global_pending)
1702
- if PROJECTS_DIR.is_dir():
1703
- for project_dir in sorted(PROJECTS_DIR.iterdir()):
1704
- if project_dir.is_dir():
1705
- pending = project_dir / "instincts" / "pending"
1706
- if pending.is_dir():
1707
- dirs.append(pending)
1708
- return dirs
1709
-
1710
-
1711
- def _parse_created_date(file_path: Path) -> Optional[datetime]:
1712
- """Parsea la fecha 'created' del frontmatter YAML de un archivo de instinto.
1713
-
1714
- Cae al mtime del archivo si no encuentra el campo 'created'.
1715
- """
1716
- try:
1717
- content = file_path.read_text(encoding="utf-8")
1718
- except (OSError, UnicodeDecodeError):
1719
- return None
1720
-
1721
- in_frontmatter = False
1722
- for line in content.split('\n'):
1723
- stripped = line.strip()
1724
- if stripped == '---':
1725
- if in_frontmatter:
1726
- break # fin del frontmatter sin encontrar created
1727
- in_frontmatter = True
1728
- continue
1729
- if in_frontmatter and ':' in line:
1730
- key, value = line.split(':', 1)
1731
- if key.strip() == 'created':
1732
- date_str = value.strip().strip('"').strip("'")
1733
- for fmt in (
1734
- "%Y-%m-%dT%H:%M:%S%z",
1735
- "%Y-%m-%dT%H:%M:%SZ",
1736
- "%Y-%m-%dT%H:%M:%S",
1737
- "%Y-%m-%d",
1738
- ):
1739
- try:
1740
- dt = datetime.strptime(date_str, fmt)
1741
- if dt.tzinfo is None:
1742
- dt = dt.replace(tzinfo=timezone.utc)
1743
- return dt
1744
- except ValueError:
1745
- continue
1746
-
1747
- # Fallback: hora de modificación del archivo
1748
- try:
1749
- mtime = file_path.stat().st_mtime
1750
- return datetime.fromtimestamp(mtime, tz=timezone.utc)
1751
- except OSError:
1752
- return None
1753
-
1754
-
1755
- def _collect_pending_instincts() -> list[dict]:
1756
- """Recorre todos los directorios de pendientes y devuelve información de cada instinto pendiente.
1757
-
1758
- Cada dict contiene: path, created, age_days, name, parent_dir.
1759
- """
1760
- now = datetime.now(timezone.utc)
1761
- results = []
1762
- for pending_dir in _collect_pending_dirs():
1763
- files = [
1764
- f for f in sorted(pending_dir.iterdir())
1765
- if f.is_file() and f.suffix.lower() in ALLOWED_INSTINCT_EXTENSIONS
1766
- ]
1767
- for file_path in files:
1768
- created = _parse_created_date(file_path)
1769
- if created is None:
1770
- print(f"Aviso: no se pudo determinar la antigüedad del instinto pendiente: {file_path.name}", file=sys.stderr)
1771
- continue
1772
- age = now - created
1773
- results.append({
1774
- "path": file_path,
1775
- "created": created,
1776
- "age_days": age.days,
1777
- "name": file_path.stem,
1778
- "parent_dir": str(pending_dir),
1779
- })
1780
- return results
1781
-
1782
-
1783
- # ─────────────────────────────────────────────
1784
- # Comando prune
1785
- # ─────────────────────────────────────────────
1786
-
1787
- def cmd_prune(args) -> int:
1788
- """Elimina los instintos pendientes que superan el umbral de TTL."""
1789
- max_age = args.max_age
1790
- dry_run = args.dry_run
1791
- quiet = args.quiet
1792
-
1793
- pending = _collect_pending_instincts()
1794
-
1795
- expired = [p for p in pending if p["age_days"] >= max_age]
1796
- remaining = [p for p in pending if p["age_days"] < max_age]
1797
-
1798
- if dry_run:
1799
- if not quiet:
1800
- if expired:
1801
- print(f"\n[DRY RUN] Se podarían {len(expired)} instinto(s) pendiente(s) con más de {max_age} días:\n")
1802
- for item in expired:
1803
- print(f" - {item['name']} (antigüedad: {item['age_days']} días) — {item['path']}")
1804
- else:
1805
- print(f"No hay instintos pendientes con más de {max_age} días.")
1806
- print(f"\nResumen: {len(expired)} se podarían, {len(remaining)} restantes")
1807
- return 0
1808
-
1809
- pruned = 0
1810
- pruned_items = []
1811
- for item in expired:
1812
- try:
1813
- item["path"].unlink()
1814
- pruned += 1
1815
- pruned_items.append(item)
1816
- except OSError as e:
1817
- if not quiet:
1818
- print(f"Aviso: no se pudo eliminar {item['path']}: {e}", file=sys.stderr)
1819
-
1820
- if not quiet:
1821
- if pruned > 0:
1822
- print(f"\nSe podaron {pruned} instinto(s) pendiente(s) con más de {max_age} días.")
1823
- for item in pruned_items:
1824
- print(f" - {item['name']} (antigüedad: {item['age_days']} días)")
1825
- else:
1826
- print(f"No hay instintos pendientes con más de {max_age} días.")
1827
- failed = len(expired) - pruned
1828
- remaining_total = len(remaining) + failed
1829
- print(f"\nResumen: {pruned} podados, {remaining_total} restantes")
1830
-
1831
- return 0
1832
-
1833
-
1834
- # ─────────────────────────────────────────────
1835
- # Principal
1836
- # ─────────────────────────────────────────────
1837
-
1838
- def main() -> int:
1839
- _ensure_global_dirs()
1840
- parser = argparse.ArgumentParser(description='CLI de instintos para Aprendizaje continuo v2.1 (con ámbito de proyecto)')
1841
- subparsers = parser.add_subparsers(dest='command', help='Comandos disponibles')
1842
-
1843
- # Status
1844
- status_parser = subparsers.add_parser('status', help='Muestra el estado de los instintos (proyecto + global)')
1845
-
1846
- # Import
1847
- import_parser = subparsers.add_parser('import', help='Importa instintos')
1848
- import_parser.add_argument('source', help='Ruta de archivo o URL')
1849
- import_parser.add_argument('--dry-run', action='store_true', help='Vista previa sin importar')
1850
- import_parser.add_argument('--force', action='store_true', help='Omite la confirmación')
1851
- import_parser.add_argument('--min-confidence', type=float, help='Umbral mínimo de confianza')
1852
- import_parser.add_argument('--scope', choices=['project', 'global'], default='project',
1853
- help='Ámbito de importación (por defecto: project)')
1854
-
1855
- # Export
1856
- export_parser = subparsers.add_parser('export', help='Exporta instintos')
1857
- export_parser.add_argument('--output', '-o', help='Archivo de salida')
1858
- export_parser.add_argument('--domain', help='Filtra por dominio')
1859
- export_parser.add_argument('--min-confidence', type=float, help='Confianza mínima')
1860
- export_parser.add_argument('--scope', choices=['project', 'global', 'all'], default='all',
1861
- help='Ámbito de exportación (por defecto: all)')
1862
-
1863
- # Evolve
1864
- evolve_parser = subparsers.add_parser('evolve', help='Analiza y evoluciona los instintos')
1865
- evolve_parser.add_argument('--generate', action='store_true', help='Genera las estructuras evolucionadas')
1866
-
1867
- # Promote (nuevo en v2.1)
1868
- promote_parser = subparsers.add_parser('promote', help='Promueve instintos de proyecto al ámbito global')
1869
- promote_parser.add_argument('instinct_id', nargs='?', help='ID del instinto concreto a promover')
1870
- promote_parser.add_argument('--force', action='store_true', help='Omite la confirmación')
1871
- promote_parser.add_argument('--dry-run', action='store_true', help='Vista previa sin promover')
1872
-
1873
- # Projects (nuevo en v2.1)
1874
- projects_parser = subparsers.add_parser('projects', help='Lista los proyectos conocidos y sus recuentos de instintos')
1875
- projects_subparsers = projects_parser.add_subparsers(dest='project_action')
1876
- projects_delete = projects_subparsers.add_parser('delete', help='Elimina una entrada del registro de proyectos')
1877
- projects_delete.add_argument('project_id', help='ID del proyecto a eliminar')
1878
- projects_delete.add_argument('--dry-run', action='store_true', help='Vista previa sin eliminar')
1879
- projects_delete.add_argument('--force', action='store_true', help='Omite la confirmación')
1880
- projects_merge = projects_subparsers.add_parser('merge', help='Fusiona una entrada del registro de proyectos en otra')
1881
- projects_merge.add_argument('from_id', help='ID del proyecto de origen')
1882
- projects_merge.add_argument('into_id', help='ID del proyecto de destino')
1883
- projects_merge.add_argument('--dry-run', action='store_true', help='Vista previa sin fusionar')
1884
- projects_merge.add_argument('--force', action='store_true', help='Omite la confirmación')
1885
- projects_gc = projects_subparsers.add_parser('gc', help='Elimina las entradas de proyecto vacías del registro')
1886
- projects_gc.add_argument('--dry-run', action='store_true', help='Vista previa sin eliminar')
1887
- projects_gc.add_argument('--force', action='store_true', help='Omite la confirmación')
1888
-
1889
- # Prune (TTL de instintos pendientes)
1890
- prune_parser = subparsers.add_parser('prune', help='Elimina los instintos pendientes que superan el TTL')
1891
- prune_parser.add_argument('--max-age', type=int, default=PENDING_TTL_DAYS,
1892
- help=f'Antigüedad máxima en días antes de podar (por defecto: {PENDING_TTL_DAYS})')
1893
- prune_parser.add_argument('--dry-run', action='store_true', help='Vista previa sin eliminar')
1894
- prune_parser.add_argument('--quiet', action='store_true', help='Suprime la salida (para uso automatizado)')
1895
-
1896
- args = parser.parse_args()
1897
-
1898
- if args.command == 'status':
1899
- return cmd_status(args)
1900
- elif args.command == 'import':
1901
- return cmd_import(args)
1902
- elif args.command == 'export':
1903
- return cmd_export(args)
1904
- elif args.command == 'evolve':
1905
- return cmd_evolve(args)
1906
- elif args.command == 'promote':
1907
- return cmd_promote(args)
1908
- elif args.command == 'projects':
1909
- return cmd_projects(args)
1910
- elif args.command == 'prune':
1911
- return cmd_prune(args)
1912
- else:
1913
- parser.print_help()
1914
- return 1
1915
-
1916
-
1917
- if __name__ == '__main__':
1918
- sys.exit(main())