nexakit 0.10.0 → 0.13.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 (479) hide show
  1. package/README.md +13 -6
  2. package/assets/runtime/package-lock.json +415 -6
  3. package/bench/casos/arquitectura/alta-usuarios/base/controladores/usuarios.js +16 -0
  4. package/bench/casos/arquitectura/alta-usuarios/base/db.js +14 -0
  5. package/bench/casos/arquitectura/alta-usuarios/base/docs/adr/0003-capas.md +15 -0
  6. package/bench/casos/arquitectura/alta-usuarios/base/errores.js +3 -0
  7. package/bench/casos/arquitectura/alta-usuarios/base/repositorios/usuarios.js +14 -0
  8. package/bench/casos/arquitectura/alta-usuarios/base/servicios/usuarios.js +20 -0
  9. package/bench/casos/arquitectura/alta-usuarios/cambio/controladores/usuarios.js +47 -0
  10. package/bench/casos/arquitectura/alta-usuarios/cambio/repositorios/usuarios.js +21 -0
  11. package/bench/casos/arquitectura/alta-usuarios/cambio/servicios/perfil.js +14 -0
  12. package/bench/casos/arquitectura/alta-usuarios/esperado.json +53 -0
  13. package/bench/casos/arquitectura/pedidos-facturacion/base/docs/adr/0001-capas.md +18 -0
  14. package/bench/casos/arquitectura/pedidos-facturacion/base/src/aplicacion/confirmar.ts +8 -0
  15. package/bench/casos/arquitectura/pedidos-facturacion/base/src/dominio/pedido.ts +15 -0
  16. package/bench/casos/arquitectura/pedidos-facturacion/base/src/dominio/puertos.ts +6 -0
  17. package/bench/casos/arquitectura/pedidos-facturacion/base/src/infra/db.ts +14 -0
  18. package/bench/casos/arquitectura/pedidos-facturacion/base/src/main.ts +9 -0
  19. package/bench/casos/arquitectura/pedidos-facturacion/cambio/src/aplicacion/facturar.ts +19 -0
  20. package/bench/casos/arquitectura/pedidos-facturacion/cambio/src/dominio/informe.ts +7 -0
  21. package/bench/casos/arquitectura/pedidos-facturacion/cambio/src/dominio/pedido.ts +21 -0
  22. package/bench/casos/arquitectura/pedidos-facturacion/cambio/src/infra/db.ts +22 -0
  23. package/bench/casos/arquitectura/pedidos-facturacion/esperado.json +53 -0
  24. package/bench/casos/arquitectura/resumen-cliente/base/docs/adr/0001-capas.md +18 -0
  25. package/bench/casos/arquitectura/resumen-cliente/base/src/aplicacion/confirmar.ts +8 -0
  26. package/bench/casos/arquitectura/resumen-cliente/base/src/dominio/pedido.ts +15 -0
  27. package/bench/casos/arquitectura/resumen-cliente/base/src/dominio/puertos.ts +6 -0
  28. package/bench/casos/arquitectura/resumen-cliente/base/src/infra/db.ts +14 -0
  29. package/bench/casos/arquitectura/resumen-cliente/base/src/main.ts +9 -0
  30. package/bench/casos/arquitectura/resumen-cliente/cambio/src/aplicacion/resumen.ts +6 -0
  31. package/bench/casos/arquitectura/resumen-cliente/cambio/src/dominio/pedido.ts +33 -0
  32. package/bench/casos/arquitectura/resumen-cliente/cambio/src/dominio/puertos.ts +7 -0
  33. package/bench/casos/arquitectura/resumen-cliente/cambio/src/infra/db.ts +18 -0
  34. package/bench/casos/arquitectura/resumen-cliente/cambio/src/main.ts +14 -0
  35. package/bench/casos/arquitectura/resumen-cliente/esperado.json +23 -0
  36. package/bench/casos/documentacion/comentario-obsoleto/base/README.md +18 -0
  37. package/bench/casos/documentacion/comentario-obsoleto/base/src/usuarios.ts +35 -0
  38. package/bench/casos/documentacion/comentario-obsoleto/cambio/src/copia.ts +8 -0
  39. package/bench/casos/documentacion/comentario-obsoleto/cambio/src/usuarios.ts +43 -0
  40. package/bench/casos/documentacion/comentario-obsoleto/esperado.json +42 -0
  41. package/bench/casos/documentacion/reportes-config/base/README.md +23 -0
  42. package/bench/casos/documentacion/reportes-config/base/src/cli.js +33 -0
  43. package/bench/casos/documentacion/reportes-config/base/src/config.js +15 -0
  44. package/bench/casos/documentacion/reportes-config/base/src/envio.js +23 -0
  45. package/bench/casos/documentacion/reportes-config/cambio/src/cli.js +35 -0
  46. package/bench/casos/documentacion/reportes-config/cambio/src/config.js +15 -0
  47. package/bench/casos/documentacion/reportes-config/esperado.json +42 -0
  48. package/bench/casos/documentacion/tiempo-espera/base/README.md +10 -0
  49. package/bench/casos/documentacion/tiempo-espera/base/src/config.js +8 -0
  50. package/bench/casos/documentacion/tiempo-espera/cambio/README.md +10 -0
  51. package/bench/casos/documentacion/tiempo-espera/cambio/src/config.js +8 -0
  52. package/bench/casos/documentacion/tiempo-espera/esperado.json +16 -0
  53. package/bench/casos/pruebas/calendario-laboral/base/src/fechas.js +3 -0
  54. package/bench/casos/pruebas/calendario-laboral/base/test/fechas.test.js +7 -0
  55. package/bench/casos/pruebas/calendario-laboral/cambio/src/fechas.js +37 -0
  56. package/bench/casos/pruebas/calendario-laboral/cambio/test/calendario.test.js +31 -0
  57. package/bench/casos/pruebas/calendario-laboral/esperado.json +49 -0
  58. package/bench/casos/pruebas/fin-de-semana/base/src/fechas.js +3 -0
  59. package/bench/casos/pruebas/fin-de-semana/base/test/fechas.test.js +7 -0
  60. package/bench/casos/pruebas/fin-de-semana/cambio/src/fechas.js +8 -0
  61. package/bench/casos/pruebas/fin-de-semana/cambio/test/fines-de-semana.test.js +13 -0
  62. package/bench/casos/pruebas/fin-de-semana/esperado.json +16 -0
  63. package/bench/casos/pruebas/precios-carrito/base/src/precio.ts +3 -0
  64. package/bench/casos/pruebas/precios-carrito/base/test/precio.test.js +11 -0
  65. package/bench/casos/pruebas/precios-carrito/cambio/src/precio.ts +34 -0
  66. package/bench/casos/pruebas/precios-carrito/cambio/test/precio.test.js +42 -0
  67. package/bench/casos/pruebas/precios-carrito/esperado.json +42 -0
  68. package/bench/casos/rendimiento/boletin-correo/base/src/correo.html +1 -0
  69. package/bench/casos/rendimiento/boletin-correo/base/src/plantilla.ts +11 -0
  70. package/bench/casos/rendimiento/boletin-correo/cambio/src/envios.ts +44 -0
  71. package/bench/casos/rendimiento/boletin-correo/cambio/src/plantilla.ts +10 -0
  72. package/bench/casos/rendimiento/boletin-correo/esperado.json +42 -0
  73. package/bench/casos/rendimiento/clientes-por-lote/base/src/informe.js +8 -0
  74. package/bench/casos/rendimiento/clientes-por-lote/cambio/src/informe.js +6 -0
  75. package/bench/casos/rendimiento/clientes-por-lote/esperado.json +14 -0
  76. package/bench/casos/rendimiento/informe-ventas/base/src/informe.js +6 -0
  77. package/bench/casos/rendimiento/informe-ventas/base/src/tasas.json +1 -0
  78. package/bench/casos/rendimiento/informe-ventas/cambio/src/informe.js +33 -0
  79. package/bench/casos/rendimiento/informe-ventas/cambio/src/tasas.js +7 -0
  80. package/bench/casos/rendimiento/informe-ventas/esperado.json +42 -0
  81. package/bench/casos/seguridad/inyeccion-orden/base/src/respaldo.ts +13 -0
  82. package/bench/casos/seguridad/inyeccion-orden/cambio/src/respaldo.ts +69 -0
  83. package/bench/casos/seguridad/inyeccion-orden/esperado.json +42 -0
  84. package/bench/casos/seguridad/limpio-validacion/base/servidor.js +11 -0
  85. package/bench/casos/seguridad/limpio-validacion/cambio/servidor.js +39 -0
  86. package/bench/casos/seguridad/limpio-validacion/esperado.json +14 -0
  87. package/bench/casos/seguridad/servidor-archivos/base/servidor.js +21 -0
  88. package/bench/casos/seguridad/servidor-archivos/cambio/servidor.js +79 -0
  89. package/bench/casos/seguridad/servidor-archivos/esperado.json +42 -0
  90. package/bin/nexakit-fabrica-mcp.js +12 -0
  91. package/dist/fabrica/banco/casos.js +304 -0
  92. package/dist/fabrica/banco/ejecutar.js +483 -0
  93. package/dist/fabrica/banco/medir.js +120 -0
  94. package/dist/fabrica/cli.js +737 -0
  95. package/dist/fabrica/conectores/antigravity.js +1040 -0
  96. package/dist/fabrica/conectores/codex.js +967 -0
  97. package/dist/fabrica/conectores/tipos.js +8 -0
  98. package/dist/fabrica/config.js +44 -0
  99. package/dist/fabrica/consolidar.js +218 -0
  100. package/dist/fabrica/decision.js +210 -0
  101. package/dist/fabrica/diff.js +247 -0
  102. package/dist/fabrica/disco.js +356 -0
  103. package/dist/fabrica/ejecutor.js +597 -0
  104. package/dist/fabrica/encargo/candado.js +274 -0
  105. package/dist/fabrica/encargo/ejecutar.js +827 -0
  106. package/dist/fabrica/encargo/evidencia.js +308 -0
  107. package/dist/fabrica/encargo/parche.js +146 -0
  108. package/dist/fabrica/encargo/worktree.js +394 -0
  109. package/dist/fabrica/enrutador.js +425 -0
  110. package/dist/fabrica/errores.js +14 -0
  111. package/dist/fabrica/esquemas.js +57 -0
  112. package/dist/fabrica/estaciones.js +75 -0
  113. package/dist/fabrica/evidencia.js +406 -0
  114. package/dist/fabrica/indice.js +1 -0
  115. package/dist/fabrica/jsonrpc.js +274 -0
  116. package/dist/fabrica/lecciones.js +363 -0
  117. package/dist/fabrica/mcp.js +376 -0
  118. package/dist/fabrica/preferencias.js +56 -0
  119. package/dist/fabrica/protocolos/codex/AbsolutePathBuf.js +2 -0
  120. package/dist/fabrica/protocolos/codex/ApplyPatchApprovalResponse.js +2 -0
  121. package/dist/fabrica/protocolos/codex/ClientInfo.js +2 -0
  122. package/dist/fabrica/protocolos/codex/ExecCommandApprovalParams.js +2 -0
  123. package/dist/fabrica/protocolos/codex/ExecCommandApprovalResponse.js +2 -0
  124. package/dist/fabrica/protocolos/codex/ExecPolicyAmendment.js +2 -0
  125. package/dist/fabrica/protocolos/codex/FunctionCallOutputBody.js +2 -0
  126. package/dist/fabrica/protocolos/codex/FunctionCallOutputContentItem.js +2 -0
  127. package/dist/fabrica/protocolos/codex/ImageDetail.js +2 -0
  128. package/dist/fabrica/protocolos/codex/InitializeCapabilities.js +2 -0
  129. package/dist/fabrica/protocolos/codex/InitializeParams.js +2 -0
  130. package/dist/fabrica/protocolos/codex/InitializeResponse.js +2 -0
  131. package/dist/fabrica/protocolos/codex/InputModality.js +2 -0
  132. package/dist/fabrica/protocolos/codex/LegacyAppPathString.js +2 -0
  133. package/dist/fabrica/protocolos/codex/NetworkPolicyAmendment.js +2 -0
  134. package/dist/fabrica/protocolos/codex/NetworkPolicyRuleAction.js +2 -0
  135. package/dist/fabrica/protocolos/codex/ParsedCommand.js +2 -0
  136. package/dist/fabrica/protocolos/codex/Personality.js +2 -0
  137. package/dist/fabrica/protocolos/codex/ReasoningEffort.js +2 -0
  138. package/dist/fabrica/protocolos/codex/ReasoningSummary.js +2 -0
  139. package/dist/fabrica/protocolos/codex/ReviewDecision.js +2 -0
  140. package/dist/fabrica/protocolos/codex/ThreadId.js +2 -0
  141. package/dist/fabrica/protocolos/codex/serde_json/JsonValue.js +2 -0
  142. package/dist/fabrica/protocolos/codex/v2/AdditionalFileSystemPermissions.js +2 -0
  143. package/dist/fabrica/protocolos/codex/v2/AdditionalNetworkPermissions.js +2 -0
  144. package/dist/fabrica/protocolos/codex/v2/ApprovalsReviewer.js +2 -0
  145. package/dist/fabrica/protocolos/codex/v2/AskForApproval.js +2 -0
  146. package/dist/fabrica/protocolos/codex/v2/ByteRange.js +2 -0
  147. package/dist/fabrica/protocolos/codex/v2/CommandAction.js +2 -0
  148. package/dist/fabrica/protocolos/codex/v2/CommandExecutionApprovalDecision.js +2 -0
  149. package/dist/fabrica/protocolos/codex/v2/CommandExecutionApprovalKind.js +2 -0
  150. package/dist/fabrica/protocolos/codex/v2/CommandExecutionRequestApprovalParams.js +2 -0
  151. package/dist/fabrica/protocolos/codex/v2/CommandExecutionRequestApprovalResponse.js +2 -0
  152. package/dist/fabrica/protocolos/codex/v2/ConfigReadParams.js +2 -0
  153. package/dist/fabrica/protocolos/codex/v2/CyberAccessProgram.js +2 -0
  154. package/dist/fabrica/protocolos/codex/v2/ExecPolicyAmendment.js +2 -0
  155. package/dist/fabrica/protocolos/codex/v2/FileChangeApprovalDecision.js +2 -0
  156. package/dist/fabrica/protocolos/codex/v2/FileChangeRequestApprovalResponse.js +2 -0
  157. package/dist/fabrica/protocolos/codex/v2/FileSystemAccessMode.js +2 -0
  158. package/dist/fabrica/protocolos/codex/v2/FileSystemPath.js +2 -0
  159. package/dist/fabrica/protocolos/codex/v2/FileSystemSandboxEntry.js +2 -0
  160. package/dist/fabrica/protocolos/codex/v2/FileSystemSpecialPath.js +2 -0
  161. package/dist/fabrica/protocolos/codex/v2/GrantedPermissionProfile.js +2 -0
  162. package/dist/fabrica/protocolos/codex/v2/ListMcpServerStatusParams.js +2 -0
  163. package/dist/fabrica/protocolos/codex/v2/McpServerElicitationAction.js +2 -0
  164. package/dist/fabrica/protocolos/codex/v2/McpServerElicitationRequestResponse.js +2 -0
  165. package/dist/fabrica/protocolos/codex/v2/McpServerStatusDetail.js +2 -0
  166. package/dist/fabrica/protocolos/codex/v2/Model.js +2 -0
  167. package/dist/fabrica/protocolos/codex/v2/ModelAccessPrograms.js +2 -0
  168. package/dist/fabrica/protocolos/codex/v2/ModelAvailabilityNux.js +2 -0
  169. package/dist/fabrica/protocolos/codex/v2/ModelListParams.js +2 -0
  170. package/dist/fabrica/protocolos/codex/v2/ModelListResponse.js +2 -0
  171. package/dist/fabrica/protocolos/codex/v2/ModelServiceTier.js +2 -0
  172. package/dist/fabrica/protocolos/codex/v2/ModelUpgradeInfo.js +2 -0
  173. package/dist/fabrica/protocolos/codex/v2/MultiAgentVersion.js +2 -0
  174. package/dist/fabrica/protocolos/codex/v2/NetworkAccess.js +2 -0
  175. package/dist/fabrica/protocolos/codex/v2/NetworkApprovalContext.js +2 -0
  176. package/dist/fabrica/protocolos/codex/v2/NetworkApprovalProtocol.js +2 -0
  177. package/dist/fabrica/protocolos/codex/v2/NetworkPolicyAmendment.js +2 -0
  178. package/dist/fabrica/protocolos/codex/v2/NetworkPolicyRuleAction.js +2 -0
  179. package/dist/fabrica/protocolos/codex/v2/PermissionGrantScope.js +2 -0
  180. package/dist/fabrica/protocolos/codex/v2/PermissionsRequestApprovalResponse.js +2 -0
  181. package/dist/fabrica/protocolos/codex/v2/ReasoningEffortOption.js +2 -0
  182. package/dist/fabrica/protocolos/codex/v2/SandboxMode.js +2 -0
  183. package/dist/fabrica/protocolos/codex/v2/SandboxPolicy.js +2 -0
  184. package/dist/fabrica/protocolos/codex/v2/TextElement.js +2 -0
  185. package/dist/fabrica/protocolos/codex/v2/ThreadSource.js +2 -0
  186. package/dist/fabrica/protocolos/codex/v2/ThreadStartParams.js +2 -0
  187. package/dist/fabrica/protocolos/codex/v2/ThreadStartSource.js +2 -0
  188. package/dist/fabrica/protocolos/codex/v2/ThreadTokenUsage.js +2 -0
  189. package/dist/fabrica/protocolos/codex/v2/ThreadTokenUsageUpdatedNotification.js +2 -0
  190. package/dist/fabrica/protocolos/codex/v2/TokenUsageBreakdown.js +2 -0
  191. package/dist/fabrica/protocolos/codex/v2/ToolRequestUserInputAnswer.js +2 -0
  192. package/dist/fabrica/protocolos/codex/v2/ToolRequestUserInputResponse.js +2 -0
  193. package/dist/fabrica/protocolos/codex/v2/TurnInterruptParams.js +2 -0
  194. package/dist/fabrica/protocolos/codex/v2/TurnStartParams.js +2 -0
  195. package/dist/fabrica/protocolos/codex/v2/TurnToolOutput.js +2 -0
  196. package/dist/fabrica/protocolos/codex/v2/UserInput.js +2 -0
  197. package/dist/fabrica/rastro.js +487 -0
  198. package/dist/fabrica/sesion.js +230 -0
  199. package/dist/fabrica/tabla-modelos.json +29 -0
  200. package/dist/fabrica/veredictos.js +327 -0
  201. package/package.json +16 -8
  202. package/plugins/huellas.json +6 -6
  203. package/plugins/nexakit-lecciones/.claude-plugin/plugin.json +1 -1
  204. package/plugins/nexakit-lecciones/README.md +6 -5
  205. package/plugins/nexakit-lecciones/hooks/lecciones.js +29 -5
  206. package/plugins/nexakit-lecciones/hooks/register.js +7 -3
  207. package/plugins/nexakit-modelo/.claude-plugin/plugin.json +1 -1
  208. package/plugins/nexakit-modelo/hooks/barra.js +100 -4
  209. package/plugins/nexakit-modelo/hooks/decidir.js +2 -2
  210. package/plugins/nexakit-modelo/hooks/recomendar.js +1 -1
  211. package/plugins/nexakit-modelo/hooks/register.js +122 -7
  212. package/plugins/nexakit-modelo/tests/register.test.ts +301 -0
  213. package/plugins/niveles/.claude-plugin/plugin.json +1 -1
  214. package/plugins/niveles/agents/cazador-de-flakes.md +1 -0
  215. package/plugins/niveles/agents/cierre-de-memoria.md +1 -0
  216. package/plugins/niveles/agents/investigador.md +1 -0
  217. package/plugins/niveles/agents/nivel-alto.md +1 -0
  218. package/plugins/niveles/agents/nivel-exigente.md +1 -0
  219. package/plugins/niveles/agents/nivel-ligero.md +1 -0
  220. package/plugins/niveles/agents/nivel-normal.md +1 -0
  221. package/plugins/niveles/agents/revisor-de-calidad.md +1 -0
  222. package/plugins/niveles/agents/sincronizador-docs.md +1 -0
  223. package/plugins/niveles/agents/subir-al-repo.md +1 -0
  224. package/skills/elegir-modelo/SKILL.md +4 -3
  225. package/skills/elegir-modelo/modelos.mjs +100 -1
  226. package/skills/fabrica/SKILL.md +55 -0
  227. package/skills/gemini/SKILL.md +2 -3
  228. package/skills/quality-gate/SKILL.md +2 -2
  229. package/src/agent-models.js +6 -4
  230. package/src/antigravity-barra.js +64 -12
  231. package/src/antigravity-command.js +4 -2
  232. package/src/antigravity-models.js +61 -0
  233. package/src/antigravity-pre-tool.js +11 -3
  234. package/src/antigravity-recommendation.js +15 -9
  235. package/src/antigravity-setup.js +4 -31
  236. package/src/cli-executable.d.ts +11 -0
  237. package/src/codex-pre-tool.js +3 -3
  238. package/src/codex-recommendation.js +1 -2
  239. package/src/codex-setup.js +3 -20
  240. package/src/codex-team.js +31 -4
  241. package/src/fabrica/banco/casos.ts +315 -0
  242. package/src/fabrica/banco/ejecutar.ts +587 -0
  243. package/src/fabrica/banco/medir.ts +160 -0
  244. package/src/fabrica/cli.ts +781 -0
  245. package/src/fabrica/conectores/antigravity.ts +1090 -0
  246. package/src/fabrica/conectores/codex.ts +1013 -0
  247. package/src/fabrica/conectores/tipos.ts +54 -0
  248. package/src/fabrica/config.ts +43 -0
  249. package/src/fabrica/consolidar.ts +277 -0
  250. package/src/fabrica/decision.ts +285 -0
  251. package/src/fabrica/diff.ts +294 -0
  252. package/src/fabrica/disco.ts +380 -0
  253. package/src/fabrica/ejecutor.ts +716 -0
  254. package/src/fabrica/encargo/candado.ts +287 -0
  255. package/src/fabrica/encargo/ejecutar.ts +953 -0
  256. package/src/fabrica/encargo/evidencia.ts +301 -0
  257. package/src/fabrica/encargo/parche.ts +151 -0
  258. package/src/fabrica/encargo/worktree.ts +427 -0
  259. package/src/fabrica/enrutador.ts +494 -0
  260. package/src/fabrica/errores.ts +15 -0
  261. package/src/fabrica/esquemas.ts +92 -0
  262. package/src/fabrica/estaciones.ts +83 -0
  263. package/src/fabrica/evidencia.ts +445 -0
  264. package/src/fabrica/indice.ts +1 -0
  265. package/src/fabrica/jsonrpc.ts +314 -0
  266. package/src/fabrica/lecciones.ts +411 -0
  267. package/src/fabrica/mcp.ts +450 -0
  268. package/src/fabrica/preferencias.ts +66 -0
  269. package/src/fabrica/protocolos/codex/AbsolutePathBuf.ts +14 -0
  270. package/src/fabrica/protocolos/codex/ApplyPatchApprovalResponse.ts +6 -0
  271. package/src/fabrica/protocolos/codex/ClientInfo.ts +5 -0
  272. package/src/fabrica/protocolos/codex/ExecCommandApprovalParams.ts +16 -0
  273. package/src/fabrica/protocolos/codex/ExecCommandApprovalResponse.ts +6 -0
  274. package/src/fabrica/protocolos/codex/ExecPolicyAmendment.ts +12 -0
  275. package/src/fabrica/protocolos/codex/FunctionCallOutputBody.ts +6 -0
  276. package/src/fabrica/protocolos/codex/FunctionCallOutputContentItem.ts +10 -0
  277. package/src/fabrica/protocolos/codex/ImageDetail.ts +5 -0
  278. package/src/fabrica/protocolos/codex/InitializeCapabilities.ts +42 -0
  279. package/src/fabrica/protocolos/codex/InitializeParams.ts +7 -0
  280. package/src/fabrica/protocolos/codex/InitializeResponse.ts +20 -0
  281. package/src/fabrica/protocolos/codex/InputModality.ts +8 -0
  282. package/src/fabrica/protocolos/codex/LegacyAppPathString.ts +27 -0
  283. package/src/fabrica/protocolos/codex/NetworkPolicyAmendment.ts +6 -0
  284. package/src/fabrica/protocolos/codex/NetworkPolicyRuleAction.ts +5 -0
  285. package/src/fabrica/protocolos/codex/ParsedCommand.ts +12 -0
  286. package/src/fabrica/protocolos/codex/Personality.ts +8 -0
  287. package/src/fabrica/protocolos/codex/ReasoningEffort.ts +8 -0
  288. package/src/fabrica/protocolos/codex/ReasoningSummary.ts +10 -0
  289. package/src/fabrica/protocolos/codex/ReviewDecision.ts +10 -0
  290. package/src/fabrica/protocolos/codex/ThreadId.ts +10 -0
  291. package/src/fabrica/protocolos/codex/VERSION +1 -0
  292. package/src/fabrica/protocolos/codex/serde_json/JsonValue.ts +5 -0
  293. package/src/fabrica/protocolos/codex/v2/AdditionalFileSystemPermissions.ts +15 -0
  294. package/src/fabrica/protocolos/codex/v2/AdditionalNetworkPermissions.ts +5 -0
  295. package/src/fabrica/protocolos/codex/v2/ApprovalsReviewer.ts +12 -0
  296. package/src/fabrica/protocolos/codex/v2/AskForApproval.ts +5 -0
  297. package/src/fabrica/protocolos/codex/v2/ByteRange.ts +5 -0
  298. package/src/fabrica/protocolos/codex/v2/CommandAction.ts +6 -0
  299. package/src/fabrica/protocolos/codex/v2/CommandExecutionApprovalDecision.ts +7 -0
  300. package/src/fabrica/protocolos/codex/v2/CommandExecutionApprovalKind.ts +8 -0
  301. package/src/fabrica/protocolos/codex/v2/CommandExecutionRequestApprovalParams.ts +51 -0
  302. package/src/fabrica/protocolos/codex/v2/CommandExecutionRequestApprovalResponse.ts +6 -0
  303. package/src/fabrica/protocolos/codex/v2/ConfigReadParams.ts +11 -0
  304. package/src/fabrica/protocolos/codex/v2/CyberAccessProgram.ts +9 -0
  305. package/src/fabrica/protocolos/codex/v2/ExecPolicyAmendment.ts +5 -0
  306. package/src/fabrica/protocolos/codex/v2/FileChangeApprovalDecision.ts +5 -0
  307. package/src/fabrica/protocolos/codex/v2/FileChangeRequestApprovalResponse.ts +6 -0
  308. package/src/fabrica/protocolos/codex/v2/FileSystemAccessMode.ts +5 -0
  309. package/src/fabrica/protocolos/codex/v2/FileSystemPath.ts +7 -0
  310. package/src/fabrica/protocolos/codex/v2/FileSystemSandboxEntry.ts +7 -0
  311. package/src/fabrica/protocolos/codex/v2/FileSystemSpecialPath.ts +6 -0
  312. package/src/fabrica/protocolos/codex/v2/GrantedPermissionProfile.ts +7 -0
  313. package/src/fabrica/protocolos/codex/v2/ListMcpServerStatusParams.ts +23 -0
  314. package/src/fabrica/protocolos/codex/v2/McpServerElicitationAction.ts +5 -0
  315. package/src/fabrica/protocolos/codex/v2/McpServerElicitationRequestResponse.ts +17 -0
  316. package/src/fabrica/protocolos/codex/v2/McpServerStatusDetail.ts +5 -0
  317. package/src/fabrica/protocolos/codex/v2/Model.ts +33 -0
  318. package/src/fabrica/protocolos/codex/v2/ModelAccessPrograms.ts +13 -0
  319. package/src/fabrica/protocolos/codex/v2/ModelAvailabilityNux.ts +5 -0
  320. package/src/fabrica/protocolos/codex/v2/ModelListParams.ts +17 -0
  321. package/src/fabrica/protocolos/codex/v2/ModelListResponse.ts +11 -0
  322. package/src/fabrica/protocolos/codex/v2/ModelServiceTier.ts +5 -0
  323. package/src/fabrica/protocolos/codex/v2/ModelUpgradeInfo.ts +9 -0
  324. package/src/fabrica/protocolos/codex/v2/MultiAgentVersion.ts +8 -0
  325. package/src/fabrica/protocolos/codex/v2/NetworkAccess.ts +5 -0
  326. package/src/fabrica/protocolos/codex/v2/NetworkApprovalContext.ts +6 -0
  327. package/src/fabrica/protocolos/codex/v2/NetworkApprovalProtocol.ts +5 -0
  328. package/src/fabrica/protocolos/codex/v2/NetworkPolicyAmendment.ts +6 -0
  329. package/src/fabrica/protocolos/codex/v2/NetworkPolicyRuleAction.ts +5 -0
  330. package/src/fabrica/protocolos/codex/v2/PermissionGrantScope.ts +5 -0
  331. package/src/fabrica/protocolos/codex/v2/PermissionsRequestApprovalResponse.ts +11 -0
  332. package/src/fabrica/protocolos/codex/v2/ReasoningEffortOption.ts +6 -0
  333. package/src/fabrica/protocolos/codex/v2/SandboxMode.ts +5 -0
  334. package/src/fabrica/protocolos/codex/v2/SandboxPolicy.ts +7 -0
  335. package/src/fabrica/protocolos/codex/v2/TextElement.ts +14 -0
  336. package/src/fabrica/protocolos/codex/v2/ThreadSource.ts +5 -0
  337. package/src/fabrica/protocolos/codex/v2/ThreadStartParams.ts +22 -0
  338. package/src/fabrica/protocolos/codex/v2/ThreadStartSource.ts +5 -0
  339. package/src/fabrica/protocolos/codex/v2/ThreadTokenUsage.ts +6 -0
  340. package/src/fabrica/protocolos/codex/v2/ThreadTokenUsageUpdatedNotification.ts +6 -0
  341. package/src/fabrica/protocolos/codex/v2/TokenUsageBreakdown.ts +5 -0
  342. package/src/fabrica/protocolos/codex/v2/ToolRequestUserInputAnswer.ts +8 -0
  343. package/src/fabrica/protocolos/codex/v2/ToolRequestUserInputResponse.ts +9 -0
  344. package/src/fabrica/protocolos/codex/v2/TurnInterruptParams.ts +5 -0
  345. package/src/fabrica/protocolos/codex/v2/TurnStartParams.ts +75 -0
  346. package/src/fabrica/protocolos/codex/v2/TurnToolOutput.ts +10 -0
  347. package/src/fabrica/protocolos/codex/v2/UserInput.ts +11 -0
  348. package/src/fabrica/rastro.ts +508 -0
  349. package/src/fabrica/sesion.ts +280 -0
  350. package/src/fabrica/tabla-modelos.json +29 -0
  351. package/src/fabrica/veredictos.ts +365 -0
  352. package/src/gemini-cli.js +15 -12
  353. package/src/gemini-tools.js +1 -1
  354. package/src/gemini-usage-store.js +32 -0
  355. package/src/instructions-block.js +69 -0
  356. package/src/lecciones-command.js +105 -4
  357. package/src/lecciones-instructions.js +178 -0
  358. package/src/legacy-repair.js +1 -1
  359. package/src/level-agents.js +5 -3
  360. package/src/memory-mcp-policy.js +1 -1
  361. package/src/missing-dependencies.js +5 -0
  362. package/src/model-command.d.ts +29 -0
  363. package/src/model-command.js +4 -27
  364. package/src/regla-ordenes-simples.d.ts +2 -0
  365. package/src/regla-ordenes-simples.js +4 -0
  366. package/src/review-instructions.js +69 -81
  367. package/src/safe-paths.js +38 -0
  368. package/src/setup-apply.js +24 -2
  369. package/src/setup-plan.js +57 -1
  370. package/src/setup-state.js +14 -0
  371. package/src/shell-quote.js +2 -0
  372. package/src/skill-recommendations.js +101 -28
  373. package/src/stable-command.js +2 -2
  374. package/src/stable-install.js +4 -2
  375. package/src/superpowers.js +0 -7
  376. package/src/task-document.js +59 -0
  377. package/src/terminal-text.js +2 -19
  378. package/src/toolkit-cli.js +63 -8
  379. package/src/toolkit-setup.js +192 -37
  380. package/templates/agent-team/README.md +7 -19
  381. package/bin/agent-task.js +0 -14
  382. package/bin/agent-toolkit-inbox.js +0 -14
  383. package/bin/agent-toolkit-mcp.js +0 -17
  384. package/schemas/agent-client-adapter.schema.json +0 -786
  385. package/schemas/agent-client-auth-diagnostic.schema.json +0 -801
  386. package/schemas/agent-client-isolated-variant.schema.json +0 -105
  387. package/schemas/agent-client-isolated-verification.schema.json +0 -99
  388. package/schemas/agent-client-managed-preferences-invocation.schema.json +0 -67
  389. package/schemas/agent-client-managed-preferences.schema.json +0 -63
  390. package/schemas/agent-client-native-diagnostics.schema.json +0 -85
  391. package/schemas/agent-client-native-evaluation.schema.json +0 -171
  392. package/schemas/agent-client-native-preflight.schema.json +0 -90
  393. package/schemas/agent-client-output.schema.json +0 -551
  394. package/schemas/agent-client-runtime-fixture.schema.json +0 -90
  395. package/schemas/agent-client-runtime-local.schema.json +0 -95
  396. package/schemas/agent-client-runtime.schema.json +0 -1288
  397. package/schemas/agent-client-selective-config.schema.json +0 -77
  398. package/schemas/agent-client-supervised-local.schema.json +0 -135
  399. package/schemas/agent-client-supervised.schema.json +0 -186
  400. package/schemas/agent-task-approvals.schema.json +0 -362
  401. package/schemas/agent-task-prepare.schema.json +0 -1324
  402. package/schemas/agent-task-verify.schema.json +0 -198
  403. package/schemas/task-workflow-plan-output.schema.json +0 -35
  404. package/skills/revisar/SKILL.md +0 -51
  405. package/src/claude-code-runner.js +0 -642
  406. package/src/client-adapter-plan.js +0 -271
  407. package/src/client-auth-diagnostic-parser.js +0 -211
  408. package/src/client-auth-diagnostic.js +0 -257
  409. package/src/client-isolated-variant.js +0 -106
  410. package/src/client-isolated-verification.js +0 -130
  411. package/src/client-local-platform.js +0 -14
  412. package/src/client-managed-preferences-invocation.js +0 -209
  413. package/src/client-managed-preferences.js +0 -78
  414. package/src/client-native-access.js +0 -134
  415. package/src/client-native-diagnostics.js +0 -253
  416. package/src/client-native-evaluation.js +0 -106
  417. package/src/client-native-preflight-files.js +0 -68
  418. package/src/client-native-preflight.js +0 -95
  419. package/src/client-output-parser.js +0 -278
  420. package/src/client-runtime-admission.js +0 -80
  421. package/src/client-runtime-coordinator.js +0 -70
  422. package/src/client-runtime-core.js +0 -92
  423. package/src/client-runtime-fixture-permit.js +0 -20
  424. package/src/client-runtime-fixture-protocol.js +0 -39
  425. package/src/client-runtime-state.js +0 -67
  426. package/src/client-runtime-store-files.js +0 -91
  427. package/src/client-runtime-store.js +0 -239
  428. package/src/client-runtime-supervisor.js +0 -146
  429. package/src/client-selective-config.js +0 -195
  430. package/src/client-selective-files.js +0 -126
  431. package/src/client-supervised-codes.js +0 -32
  432. package/src/client-supervised-contract.js +0 -52
  433. package/src/client-supervised-coordinator.js +0 -36
  434. package/src/client-supervised-permit.js +0 -20
  435. package/src/client-supervised-protocol.js +0 -37
  436. package/src/client-supervised-store.js +0 -167
  437. package/src/client-supervised-supervisor.js +0 -167
  438. package/src/client-supervised.js +0 -160
  439. package/src/codex-cli-runner.js +0 -358
  440. package/src/codex-delivery.js +0 -101
  441. package/src/memory-connection-artifacts.js +0 -192
  442. package/src/memory-connection-descriptor.js +0 -158
  443. package/src/memory-connection-diagnostic.js +0 -177
  444. package/src/memory-connection-files.js +0 -191
  445. package/src/memory-connection-manifest.js +0 -118
  446. package/src/memory-connection-package.js +0 -176
  447. package/src/memory-connection-plan.js +0 -217
  448. package/src/memory-connection-skill.js +0 -211
  449. package/src/memory-connection-toml.js +0 -153
  450. package/src/native/managed-preferences.c +0 -100
  451. package/src/native/managed-preferences.h +0 -17
  452. package/src/package-lock-path.js +0 -13
  453. package/src/peer-handoff.js +0 -27
  454. package/src/peer-inbox-cli.js +0 -211
  455. package/src/peer-review-mcp.js +0 -210
  456. package/src/peer-review-store.js +0 -532
  457. package/src/review-policy.js +0 -35
  458. package/src/revision-adapters.js +0 -158
  459. package/src/revision-context.js +0 -86
  460. package/src/revision-isolation.js +0 -222
  461. package/src/revision-process.js +0 -103
  462. package/src/revision-provenance.js +0 -89
  463. package/src/revision-snapshot.js +0 -120
  464. package/src/revision.js +0 -242
  465. package/src/runtime-fixtures/runtime-supervisor/child.cjs +0 -3
  466. package/src/runtime-fixtures/runtime-supervisor/fixture.cjs +0 -49
  467. package/src/runtime-fixtures/supervised/child.cjs +0 -3
  468. package/src/runtime-fixtures/supervised/fixture.cjs +0 -47
  469. package/src/task-approvals.js +0 -367
  470. package/src/task-cli.js +0 -79
  471. package/src/task-external-verifier.js +0 -584
  472. package/src/task-prepare-files.js +0 -115
  473. package/src/task-prepare.js +0 -180
  474. package/src/task-verify-cli.js +0 -67
  475. package/src/task-verify-files.js +0 -188
  476. package/src/task-verify.js +0 -118
  477. package/src/task-workflow-mcp.js +0 -544
  478. package/src/task-workflow-store.js +0 -254
  479. package/src/toolkit-commands-guide.js +0 -115
@@ -1,115 +0,0 @@
1
- import fs from "node:fs/promises";
2
- import { constants } from "node:fs";
3
- import path from "node:path";
4
- import { createHash } from "node:crypto";
5
- import { decode, copyBytes, parseEventJson } from "./client-output-json.js";
6
- import { copyTaskJson, TASK_LIMITS } from "./task-prepare.js";
7
- import { containsSensitiveData, isCredentialPath } from "./sensitive-data.js";
8
- import { IS_WINDOWS, warnPlatformPermissions, toGitPath, isPortableAbsolutePath } from "./platform.js";
9
-
10
- export class TaskInputError extends Error {
11
- constructor(code) { super("Task input rejected"); this.code = code; }
12
- }
13
- const reject = code => { throw new TaskInputError(code); };
14
- const signature = s => JSON.stringify([s.dev, s.ino, s.uid, s.gid, s.mode, s.nlink, s.size, s.mtimeMs, s.ctimeMs, s.mtimeNs, s.ctimeNs], (_key, value) => typeof value === "bigint" ? String(value) : value);
15
- // NTFS file ids may exceed Number.MAX_SAFE_INTEGER. Preserve exact device/inode ids;
16
- // the bounded sizes and permission fields remain numbers for existing read budgets.
17
- function metadata(stat) {
18
- if (typeof stat.mode !== "bigint") return stat;
19
- const result = { ...stat };
20
- // BigIntStats methods require their original bigint mode; bind to that object.
21
- for (const method of ["isFile", "isDirectory", "isSymbolicLink", "isFIFO", "isSocket", "isBlockDevice", "isCharacterDevice"]) result[method] = stat[method].bind(stat);
22
- for (const key of ["uid", "gid", "mode", "nlink", "size", "mtimeMs", "ctimeMs"]) result[key] = Number(stat[key]);
23
- return result;
24
- }
25
- export const taskLstat = async (io, full) => metadata(await io.lstat(full, IS_WINDOWS ? { bigint: true } : undefined));
26
- export const taskHandleStat = async handle => metadata(await handle.stat(IS_WINDOWS ? { bigint: true } : undefined));
27
- const forbiddenInput = value => {
28
- const p = toGitPath(value);
29
- return isCredentialPath(p) || /(?:^|\/)(?:\.git|\.obsidian|\.claude|\.codex|\.gemini|\.agents|\.(?:credentials?|secrets?)(?:\.[^/]*)?)(?:\/|$)/i.test(p) || /\.keychain(?:-db)?$/i.test(p);
30
- };
31
-
32
- // Compare decimal values after their shortest JSON round trip, not binary-rational exactness.
33
- function decimalIdentity(token) {
34
- const [m, exp = "0"] = token.toLowerCase().split("e");
35
- const minus = m.startsWith("-"), fraction = m.split(".")[1]?.length ?? 0;
36
- let digits = m.replace(/[-.]/g, "").replace(/^0+/, ""); if (!digits) return "0";
37
- let scale = Number(exp) - fraction;
38
- if (!Number.isSafeInteger(scale)) reject("task-file-format");
39
- const trailing = digits.length - digits.replace(/0+$/, "").length;
40
- digits = digits.slice(0, digits.length - trailing); scale += trailing;
41
- return (minus ? "-" : "") + digits + "e" + scale;
42
- }
43
- function checkNumbers(text) {
44
- let string = false, escape = false;
45
- for (let i = 0; i < text.length; i++) {
46
- const c = text[i];
47
- if (string) { if (escape) escape = false; else if (c === "\\") escape = true; else if (c === '"') string = false; continue; }
48
- if (c === '"') { string = true; continue; }
49
- if (c === "-" || /[0-9]/.test(c)) {
50
- const m = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/.exec(text.slice(i)); if (!m) reject("task-file-format");
51
- const n = Number(m[0]);
52
- if (!Number.isFinite(n) || Number.isInteger(n) && !Number.isSafeInteger(n) || decimalIdentity(m[0]) !== decimalIdentity(String(n))) reject("task-file-format");
53
- i += m[0].length - 1;
54
- }
55
- }
56
- }
57
- export function parseTaskDocument(bytes) {
58
- try {
59
- const text = decode(copyBytes(bytes, TASK_LIMITS.fileBytes)); checkNumbers(text);
60
- return copyTaskJson(parseEventJson(text));
61
- } catch { reject("task-file-format"); }
62
- }
63
-
64
- /** Only explicit source files; no referenced paths, credentials, config, Git or writes. */
65
- export async function readTaskInputs(paths, cwd, dependencies = {}) {
66
- warnPlatformPermissions();
67
- const names = ["task", "request", "catalog", "policy"], io = { ...fs, ...dependencies.io }, uid = process.getuid?.();
68
- let entries;
69
- try {
70
- const p = copyTaskJson(paths);
71
- if (!path.isAbsolute(cwd) || (!IS_WINDOWS && typeof uid !== "number") || !["darwin", "linux", "win32"].includes(process.platform) ||
72
- !p || Array.isArray(p) || Object.keys(p).sort().join() !== [...names].sort().join()) reject("task-file-path");
73
- entries = names.map(name => {
74
- const value = p[name];
75
- if (typeof value !== "string" || !value || value !== value.trim() || value.length > 4096 || /[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/u.test(value)) reject("task-file-path");
76
- const full = path.resolve(cwd, value);
77
- if ((IS_WINDOWS && !isPortableAbsolutePath(full)) || forbiddenInput(full) || containsSensitiveData(full)) reject("task-file-path");
78
- return { name, full };
79
- });
80
- if (new Set(entries.map(e => e.full.normalize("NFC").toLowerCase())).size !== 4) reject("task-file-path");
81
- } catch { reject("task-file-path"); }
82
- const physical = async full => {
83
- let curr = path.parse(full).root;
84
- const parts = full.slice(curr.length).split(path.sep).filter(Boolean); if (parts.length > 64) reject("task-file-path");
85
- for (const [index, part] of parts.entries()) {
86
- curr = path.join(curr, part); const s = await taskLstat(io, curr);
87
- if (s.isSymbolicLink() || index !== parts.length - 1 && !s.isDirectory()) reject("task-file-unsafe");
88
- }
89
- };
90
- const safe = s => {
91
- if (!s.isFile() || s.isSymbolicLink() || s.nlink !== 1 || (!IS_WINDOWS && (s.uid !== uid || s.mode & 0o7022))) reject("task-file-unsafe");
92
- if (s.size < 1 || s.size > TASK_LIMITS.fileBytes) reject("task-file-limit");
93
- };
94
- const data = {}, byteHashes = {}; let total = 0;
95
- try {
96
- for (const { name, full } of entries) {
97
- await physical(full); const before = await taskLstat(io, full); safe(before);
98
- const handle = await io.open(full, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
99
- try {
100
- const start = await taskHandleStat(handle); safe(start); if (signature(start) !== signature(before)) reject("task-file-changed");
101
- const buffer = Buffer.alloc(before.size + 1); let offset = 0;
102
- while (offset < buffer.length) {
103
- const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, offset); if (!bytesRead) break; offset += bytesRead;
104
- if (offset > before.size || total + offset > TASK_LIMITS.totalBytes) reject("task-file-limit");
105
- }
106
- const after = await taskHandleStat(handle), named = await taskLstat(io, full); safe(after); safe(named);
107
- if (offset !== before.size || signature(before) !== signature(after) || signature(before) !== signature(named)) reject("task-file-changed");
108
- await physical(full); total += offset;
109
- const bytes = buffer.subarray(0, offset); data[name] = parseTaskDocument(bytes);
110
- byteHashes[name] = createHash("sha256").update(bytes).digest("hex");
111
- } finally { await handle.close(); }
112
- }
113
- return { data: copyTaskJson(data), byteHashes };
114
- } catch (e) { reject(e instanceof TaskInputError ? e.code : "task-file-read-failed"); }
115
- }
@@ -1,180 +0,0 @@
1
- import { isPortableAbsolutePath, toGitPath } from './platform.js';
2
- import path from "node:path";
3
- import { createHash } from "node:crypto";
4
- import Ajv2020 from "ajv/dist/2020.js";
5
- import { copyInertJson } from "./client-output-json.js";
6
- import { createModelSelector } from "./model-selection.js";
7
- import { containsSensitiveData, isCredentialPath } from "./sensitive-data.js";
8
-
9
- export const TASK_SCHEMA_ID = "https://agent-toolkit.local/schemas/agent-task-prepare.schema.json";
10
- export const TASK_LIMITS = Object.freeze({ fileBytes: 524288, totalBytes: 2097152, nodes: 30000, depth: 32,
11
- textBytes: 2000000, briefBytes: 131072, summaryBytes: 8192 });
12
- export const TASK_FACTS = Object.freeze({ executed: false, sent: false, wrote: false, permissionVerified: false,
13
- sourceBaseVerified: false, runtimeReady: false, verifiedAdmission: false, modelVerification: "unknown" });
14
- const BASE_ID = "https://agent-toolkit.local/schemas/agent-model-selection.schema.json";
15
- const PREF_ID = "https://agent-toolkit.local/schemas/agent-model-preference.schema.json";
16
- const canonical = v => v === null || typeof v !== "object" ? JSON.stringify(v) : Array.isArray(v) ?
17
- `[${v.map(canonical).join(",")}]` : `{${Object.keys(v).sort().map(k => `${JSON.stringify(k)}:${canonical(v[k])}`).join(",")}}`;
18
- export const taskHash = v => createHash("sha256").update(canonical(v)).digest("hex");
19
- const control = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/u;
20
- const pathKey = s => s.normalize("NFC").toLowerCase();
21
- const credentialReference = value => { const s = toGitPath(value); return isCredentialPath(s) || /(?:^|\/)(?:\.(?:credentials?|secrets?)(?:\.[^/]*)?)(?:\/|$)/i.test(s) || /\.keychain(?:-db)?$/i.test(s); };
22
- export function taskRelativePath(s, dot = false) {
23
- return typeof s === "string" && (dot && s === "." || s.length > 0 && s.length <= 512 && s === s.trim() &&
24
- !/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069\\:*?\[\]<>|`]/u.test(s) &&
25
- s.split("/").every(p => p && ![".", "..", ".git", ".obsidian"].includes(p.toLowerCase())) &&
26
- !credentialReference(s) && !containsSensitiveData(s));
27
- }
28
- export function copyTaskJson(input) {
29
- const v = copyInertJson(input); let nodes = 0, textBytes = 0;
30
- function walk(x, depth) {
31
- if (++nodes > TASK_LIMITS.nodes || depth > TASK_LIMITS.depth) throw Error("Task data limit");
32
- if (typeof x === "string") {
33
- textBytes += Buffer.byteLength(x); if (Buffer.from(x, "utf8").toString("utf8") !== x || control.test(x)) throw Error("Task text invalid");
34
- } else if (x !== null && typeof x === "object") for (const k of Object.keys(x)) {
35
- textBytes += Buffer.byteLength(k); if (control.test(k) || Buffer.from(k, "utf8").toString("utf8") !== k) throw Error("Task key invalid");
36
- walk(x[k], depth + 1);
37
- }
38
- if (textBytes > TASK_LIMITS.textBytes) throw Error("Task data limit");
39
- }
40
- walk(v, 0); return v;
41
- }
42
- function sensitive(v) {
43
- return typeof v === "string" ? containsSensitiveData(v) : v !== null && typeof v === "object" &&
44
- Object.keys(v).some(k => containsSensitiveData(k) || sensitive(v[k]));
45
- }
46
- const timestamp = v => /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(v) && Number.isFinite(Date.parse(v)) &&
47
- new Date(Date.parse(v)).toISOString() === v.replace(/Z$/, ".000Z");
48
- function semanticReasons(t, r) {
49
- const invalid = [], blocked = [], add = (list, code) => { if (!list.includes(code)) list.push(code); };
50
- if (["projectId", "taskId", "revision", "role", "mode"].some(k => t.identity[k] !== r[k])) add(invalid, "task-identity-conflict");
51
- const root = t.base.repositoryRoot;
52
- if (!isPortableAbsolutePath(root) || /[\x00-\x1f]/.test(root) || credentialReference(root)) add(invalid, "task-path-invalid");
53
- const checkPaths = (entries, key = "path") => {
54
- const seen = new Set(); for (const e of entries) {
55
- if (!taskRelativePath(e[key]) || seen.has(pathKey(e[key]))) add(invalid, "task-path-invalid");
56
- seen.add(pathKey(e[key]));
57
- }
58
- };
59
- checkPaths(t.scope.files); checkPaths(t.base.initialGitState);
60
- if (t.checks.some(c => !taskRelativePath(c.directory, true))) add(invalid, "task-path-invalid");
61
- if (t.scope.files.some(f => (f.operation === "create") !== (f.expectedBase === "absent"))) add(invalid, "task-base-conflict");
62
- const ids = new Set(); for (const c of [...t.base.instructionRefs, ...t.contextRefs]) {
63
- if (ids.has(c.id)) add(invalid, "task-reference-conflict"); ids.add(c.id);
64
- if (credentialReference(c.locator)) add(blocked, "task-credential-reference");
65
- }
66
- if (t.base.instructionRefs.some(c => c.kind !== "instructions")) add(invalid, "task-reference-conflict");
67
- if (new Set(t.criteria.map(c => c.id)).size !== t.criteria.length) add(invalid, "task-criteria-conflict");
68
- const revision = Number(t.identity.revision.slice(1));
69
- for (const d of [...t.previousDeliveries, ...(t.proposalRef ? [t.proposalRef] : [])]) {
70
- if (Number(d.revision.slice(1)) > revision) add(invalid, "task-history-conflict");
71
- if (credentialReference(d.locator)) add(blocked, "task-credential-reference");
72
- }
73
- if (!t.projectRules.allowedModes.includes(t.identity.mode)) add(blocked, "task-mode-not-permitted");
74
- if (t.identity.mode === "tutor" && (!t.step || t.projectRules.activeWriter !== "user" || t.identity.role === "executor")) add(blocked, "task-tutor-authorship-conflict");
75
- if (t.identity.mode === "autonomous" && t.step !== null) add(invalid, "task-step-conflict");
76
- if (t.identity.purpose === "external-verifier") {
77
- const actions = r.authorizationContext?.allowedActions ?? [];
78
- const listedPaths = new Set(t.scope.files.map(f => pathKey(f.path)));
79
- const references = [...t.base.instructionRefs, ...t.contextRefs, ...t.previousDeliveries, ...(t.proposalRef ? [t.proposalRef] : [])];
80
- const referencesListed = references.every(ref => taskRelativePath(ref.locator) && listedPaths.has(pathKey(ref.locator)));
81
- if (t.identity.role !== "reviewer" || t.identity.mode !== "autonomous") add(invalid, "task-external-verifier-identity");
82
- if (t.scope.files.some(f => f.operation !== "inspect") || !referencesListed || t.checks.length ||
83
- actions.length !== 2 || !actions.includes("read") || !actions.includes("verify") ||
84
- !t.projectRules.forbiddenActions.includes("apply") || !t.projectRules.forbiddenActions.includes("propose")) {
85
- add(blocked, "task-external-verifier-scope");
86
- }
87
- }
88
- if (r.authorizationContext) {
89
- const a = r.authorizationContext;
90
- if (a.activeWriter !== t.projectRules.activeWriter) add(blocked, "task-writer-conflict");
91
- if (a.allowedActions.some(action => t.projectRules.forbiddenActions.includes(action))) add(blocked, "task-action-not-permitted");
92
- }
93
- if (r.history && (r.history.executionsUsed || r.history.durationUsedSeconds || r.history.correctionRound) && !t.previousDeliveries.length) add(blocked, "task-history-reference-required");
94
- if (t.identity.role === "executor" && !t.proposalRef) add(blocked, "task-proposal-reference-required");
95
- if (t.scope.files.some(f => f.operation !== "inspect" && t.base.initialGitState.some(s => pathKey(s.path) === pathKey(f.path) && s.owner !== "task"))) add(blocked, "task-local-overlap");
96
- return { invalid, blocked };
97
- }
98
- // No data string can introduce headings, HTML, fences, links or terminal controls.
99
- const dataBlock = v => "```json\n" + JSON.stringify(v, null, 2).replace(/"(?:\\.|[^"\\])*"/gu,
100
- token => token.replace(/[<>&`()\[\]\u2028\u2029]/gu,
101
- c => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0"))) + "\n```\n";
102
- function render(t, r, selection) {
103
- const section = (title, value) => `\n## ${title}\n\n${dataBlock(value)}`;
104
- const externalVerifier = t.identity.purpose === "external-verifier";
105
- return "# Encargo — borrador pendiente de revisión\n\n" +
106
- "No enviado ni autorizado por esta herramienta. Datos declarados: revisar permiso directo, instrucciones y base antes de actuar. No cambiar de proveedor para evadir bloqueos.\n" +
107
- section("Identidad y estado", { ...t.identity, status: "draft", step: t.step }) +
108
- section("Objetivo, alcance y exclusiones", { title: t.title, objective: t.objective, scope: t.scope }) +
109
- section("Base e instrucciones declaradas — no verificadas", { ...t.base, projectRules: t.projectRules }) +
110
- section("Contexto por referencia — no leído", t.contextRefs) +
111
- section("Autorización declarada — no demuestra permiso", { declared: r.authorizationContext, permissionVerified: false,
112
- gitMemoryDeploymentBilling: "not-authorized-by-preparation" }) +
113
- section("Selección por destinatario — elegir manualmente", { ...selection, observedModels: [], modelVerification: "unknown",
114
- availabilityCurrentVerified: false, evaluationTimeDeclared: r.evaluationTime, decisionFileSha256: null }) +
115
- section("Historial y límites — no reiniciados", { history: r.history, previousDeliveries: t.previousDeliveries, proposalRef: t.proposalRef }) +
116
- section("Criterios y comprobaciones declaradas — no ejecutadas", { criteria: t.criteria, checks: t.checks }) +
117
- section("Entrega solicitada", { instructions: externalVerifier ?
118
- "Entrega únicamente hallazgos basados en los archivos enumerados. No edites, crees ni borres archivos; no ejecutes comandos. Si el cliente no puede imponer acceso de solo lectura, no ejecutes este encargo." : t.deliveryInstructions,
119
- modeRule: externalVerifier ?
120
- "Verificador externo: rol reviewer, modo autonomous, acciones limitadas a read y verify, archivos únicamente inspect. El borrador no impone controles al cliente receptor; el sistema de ejecución debe aplicar solo lectura." :
121
- t.identity.mode === "tutor" ?
122
- "Un único paso; el usuario escribe y se revisa antes de avanzar. El tutor no aplica código." :
123
- "Propuesta, aplicación y revisión necesitan decisiones separadas y permiso directo para cada rol. Sin envío ni ejecución automática." });
124
- }
125
- export function createTaskPreparer(taskSchema, baseSchema, preferenceSchema) {
126
- let s, b, p, validInput, validReport, validSummary, validSelection, select;
127
- try {
128
- [s, b, p] = [taskSchema, baseSchema, preferenceSchema].map(copyInertJson);
129
- if (s.$id !== TASK_SCHEMA_ID || b.$id !== BASE_ID || p.$id !== PREF_ID) throw Error();
130
- const ajv = new Ajv2020({ strict: true, allErrors: false }); ajv.addFormat("date-time", { type: "string", validate: timestamp });
131
- [b, p, s].forEach(x => ajv.addSchema(x));
132
- validInput = ajv.compile({ $ref: TASK_SCHEMA_ID + "#/$defs/input" });
133
- validReport = ajv.compile({ $ref: TASK_SCHEMA_ID + "#/$defs/report" });
134
- validSummary = ajv.compile({ $ref: TASK_SCHEMA_ID + "#/$defs/summary" });
135
- validSelection = ajv.compile({ $ref: TASK_SCHEMA_ID + "#/$defs/selection" });
136
- select = createModelSelector(b, p);
137
- } catch { throw Error("Invalid trusted task schemas"); }
138
- const auditBase = { taskSchemaSha256: taskHash(s), baseSchemaSha256: taskHash(b), preferenceSchemaSha256: taskHash(p) };
139
- const prepare = input => {
140
- const out = { command: "agent-task prepare", schemaVersion: "1.0.0", state: "invalid", selectionState: null,
141
- identity: null, selection: null, brief: null, reasons: [], missing: [],
142
- audit: { ...auditBase, taskSha256: null, sourceByteHashes: null }, ...TASK_FACTS, observedModels: [] };
143
- const finish = (state, codes) => {
144
- out.state = state; out.reasons = [...new Set(codes)].sort();
145
- if (state !== "prepared-draft") out.brief = null;
146
- if (!validReport(out)) throw Error("Task preparation invariant failed"); return out;
147
- };
148
- let data;
149
- try { data = copyTaskJson(input); } catch { return finish("invalid", ["task-invalid-input"]); }
150
- if (!validInput(data)) return finish("invalid", ["task-invalid-input"]);
151
- if (sensitive(data)) return finish("blocked", ["task-sensitive-input"]);
152
- const { task, request, catalog, policy } = data;
153
- out.identity = copyInertJson(task.identity); out.audit.taskSha256 = taskHash(task);
154
- const reasons = semanticReasons(task, request);
155
- if (reasons.invalid.length) return finish("invalid", reasons.invalid);
156
- if (reasons.blocked.length) return finish("blocked", reasons.blocked);
157
- const result = select({ request, catalog, policy }); out.selectionState = result.state;
158
- // Project only the v2 contract, not arbitrary unknown input properties.
159
- out.selection = Object.fromEntries(["state", "selectorVersion", "recommendation", "constraints", "audit", "reasons", "missing", "issues", "excluded", "effortExcluded"].map(k => [k, result[k]]));
160
- try { copyTaskJson(out.selection); if (!validSelection(out.selection)) throw Error(); }
161
- catch { out.selection = null; return finish("invalid", ["task-output-limit"]); }
162
- out.missing = [...result.missing];
163
- if (result.state !== "recommended") return finish(result.state, ["task-selection-" + result.state]);
164
- try {
165
- const text = render(task, request, out.selection);
166
- if (Buffer.byteLength(text) > TASK_LIMITS.briefBytes) throw Error();
167
- out.brief = text;
168
- } catch { out.selection = null; return finish("invalid", ["task-output-limit"]); }
169
- return finish("prepared-draft", ["task-prepared-draft"]);
170
- };
171
- return Object.freeze({ prepareTask: prepare, summarize(report) {
172
- const r = copyInertJson(report); if (!validReport(r)) throw Error("Invalid task preparation report");
173
- const m = r.selection?.recommendation;
174
- const summary = { command: r.command, state: r.state, selectionState: r.selectionState, identity: r.identity,
175
- recommended: m ? Object.fromEntries(["provider", "client", "requestedModel", "familyId", "versionOrdinal", "effort"].map(k => [k, m[k]])) : null,
176
- reasons: r.reasons, missing: r.missing, availabilityCurrentVerified: false, ...TASK_FACTS, observedModels: [] };
177
- if (!validSummary(summary) || Buffer.byteLength(JSON.stringify(summary)) > TASK_LIMITS.summaryBytes) throw Error("Task summary limit");
178
- return summary;
179
- } });
180
- }
@@ -1,67 +0,0 @@
1
- import fs from "node:fs/promises";
2
- import { fileURLToPath } from "node:url";
3
- import { createTaskVerifier, VERIFY_LIMITS } from "./task-verify.js";
4
- import { verifyLocal } from "./task-verify-files.js";
5
- import { parseTaskDocument } from "./task-prepare-files.js";
6
-
7
- export const VERIFY_HELP = `agent-task verify — comprobación de huellas, sin ejecución ni escritura
8
-
9
- Uso local:
10
- node bin/agent-task.js verify --contract <json> --expect <sha256> --source <raíz> --handoff <raíz> --phase <before|after> [--json]
11
- node bin/agent-task.js verify --help
12
-
13
- --expect: SHA-256 de los bytes del contrato ya revisado; no se calcula ni se lee del contrato.
14
- --source/--handoff: raíces absolutas explícitas; handoff privado (0700); distintas y no anidadas.
15
- Solo compara los archivos listados; los no listados quedan sin verificar.
16
- matched no aprueba código, pruebas, Git, modelos, consumo ni permiso. Requiere revisión humana.
17
- No ejecuta comandos, no lee .git, no escribe ni envía nada.
18
- Exit: 0 matched/ayuda; 1 mismatched; 2 blocked/invalid o fallo de lectura/salida.
19
- `;
20
- const schemaPath = fileURLToPath(new URL("../schemas/agent-task-verify.schema.json", import.meta.url));
21
- const VALUES = ["contract", "expect", "source", "handoff", "phase"];
22
- function options(args) {
23
- if (args.length === 1 && ["--help", "-h"].includes(args[0])) return { help: true };
24
- const values = {}; let json = false;
25
- for (let i = 0; i < args.length; i++) {
26
- const a = args[i];
27
- if (a === "--json") { if (json) throw Error(); json = true; continue; }
28
- const key = a.startsWith("--") ? a.slice(2) : "";
29
- if (!VALUES.includes(key) || Object.hasOwn(values, key) || typeof args[i + 1] !== "string" || !args[i + 1] || args[i + 1].startsWith("-")) throw Error();
30
- values[key] = args[++i];
31
- }
32
- if (Object.keys(values).length !== VALUES.length || !["before", "after"].includes(values.phase) || !/^[a-f0-9]{64}$/.test(values.expect)) throw Error();
33
- return { values, json };
34
- }
35
- function text(r) {
36
- const id = r.identity ? `${r.identity.projectId}/${r.identity.taskId}/${r.identity.revision}` : "no validada";
37
- const lines = [`agent-task verify: ${r.state}`, `Fase: ${r.phase ?? "no validada"}`, `Identidad: ${id}`,
38
- `Procedencia: ${r.provenance}`, `Motivos: ${r.reasons.join(", ")}`];
39
- for (const e of r.results) lines.push(`- ${e.id} [${e.root}/${e.operation}] ${e.outcome}; esperado ${e.expected ?? "ausente"}; observado ${
40
- e.observed ?? (e.outcome === "unexpected-present" ? "presente sin abrir" : "ausente")}`);
41
- lines.push("Alcance: solo archivos listados; cambios no listados sin verificar.",
42
- "No aprueba calidad, pruebas, Git, modelos, consumo ni permiso. No ejecutado, enviado ni escrito.",
43
- "Revisión humana requerida, también con matched.");
44
- return lines.join("\n") + "\n";
45
- }
46
- /** IO callbacks/dependencies are trusted hosts, not fields in input JSON. */
47
- export async function runVerifyCli(args, io, dependencies = {}) {
48
- const fail = async code => { try { await io.err(`agent-task: ${code}\n`); } catch {} return 2; };
49
- let opts;
50
- try { opts = options(args); } catch { return fail("verify-invalid-option"); }
51
- if (opts.help) {
52
- try { await io.out(VERIFY_HELP); return 0; } catch { return fail("verify-output-failed"); }
53
- }
54
- let report;
55
- try {
56
- const readSchema = dependencies.readVerifySchema ?? (p => fs.readFile(p));
57
- const verifier = createTaskVerifier(parseTaskDocument(await readSchema(schemaPath)));
58
- report = await verifyLocal(opts.values, dependencies.cwd ?? process.cwd(), verifier,
59
- { io: dependencies.fileIo, home: dependencies.home, platform: dependencies.platform });
60
- } catch { return fail("verify-preparation-failed"); }
61
- try {
62
- const output = opts.json ? JSON.stringify(report, null, 2) + "\n" : text(report);
63
- if (Buffer.byteLength(output) > VERIFY_LIMITS.reportBytes) throw Error();
64
- await io.out(output);
65
- return report.state === "matched" ? 0 : report.state === "mismatched" ? 1 : 2;
66
- } catch { return fail("verify-output-failed"); }
67
- }
@@ -1,188 +0,0 @@
1
- import fs from "node:fs/promises";
2
- import { constants } from "node:fs";
3
- import os from "node:os";
4
- import path from "node:path";
5
- import { createHash } from "node:crypto";
6
- import { parseTaskDocument, taskLstat, taskHandleStat } from "./task-prepare-files.js";
7
- import { containsSensitiveData, isCredentialPath } from "./sensitive-data.js";
8
- import { VERIFY_LIMITS, LOCAL_READ } from "./task-verify.js";
9
- import { IS_WINDOWS, warnPlatformPermissions, toGitPath, isPortableAbsolutePath } from "./platform.js";
10
-
11
- export class VerifyInputError extends Error {
12
- constructor(code) { super("Verify input rejected"); this.code = code; }
13
- }
14
- const reject = code => { throw new VerifyInputError(code); };
15
- export const VERIFY_OPEN_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
16
- const signature = s => JSON.stringify([s.dev, s.ino, s.uid, s.gid, s.mode, s.nlink, s.size, s.mtimeMs, s.ctimeMs, s.mtimeNs, s.ctimeNs], (_key, value) => typeof value === "bigint" ? String(value) : value);
17
- // Directory mtime changes with siblings; identity, owner and mode must stay stable.
18
- const dirSignature = s => JSON.stringify([s.dev, s.ino, s.uid, s.gid, s.mode], (_key, value) => typeof value === "bigint" ? String(value) : value);
19
- const control = /[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/u;
20
- const pathKey = s => s.normalize("NFC").toLowerCase();
21
- const errno = e => e instanceof Error && typeof e.code === "string" ? e.code : "";
22
- const forbidden = value => {
23
- const p = toGitPath(value);
24
- return isCredentialPath(p) || containsSensitiveData(p) || /\.keychain(?:-db)?$/i.test(p) ||
25
- /(?:^|\/)(?:\.git|\.obsidian|\.claude|\.codex|\.gemini|\.agents|\.(?:credentials?|secrets?)(?:\.[^/]*)?)(?:\/|$)/i.test(p);
26
- };
27
- const pathText = v => typeof v === "string" && v.length > 0 && v.length <= 4096 && v === v.trim() && !control.test(v);
28
- const validRead = (n, room) => Number.isSafeInteger(n) && n >= 0 && n <= room;
29
-
30
- // Every existing component is checked with lstat; none may be a symlink.
31
- async function physical(io, full) {
32
- const top = path.parse(full).root, parts = full.slice(top.length).split(path.sep).filter(Boolean);
33
- if (!parts.length || parts.length > 64) reject("verify-path-unsafe");
34
- let curr = top, last;
35
- for (const [i, part] of parts.entries()) {
36
- curr = path.join(curr, part); last = await taskLstat(io, curr);
37
- if (last.isSymbolicLink() || i < parts.length - 1 && !last.isDirectory()) reject("verify-path-unsafe");
38
- }
39
- return last;
40
- }
41
- function rootPath(value, home) {
42
- if (!pathText(value) || !path.isAbsolute(value) || path.normalize(value) !== value || (IS_WINDOWS && !isPortableAbsolutePath(value)) || value.endsWith(path.sep) || forbidden(value) ||
43
- typeof home === "string" && home && pathKey(path.resolve(home)) === pathKey(value)) reject("verify-root-unsafe");
44
- return value;
45
- }
46
- async function readContract(io, full, uid) {
47
- const safe = s => {
48
- if (!s.isFile() || s.isSymbolicLink() || s.nlink !== 1 || (!IS_WINDOWS && (s.uid !== uid || s.mode & 0o7022))) reject("verify-contract-unsafe");
49
- if (s.size < 1 || s.size > VERIFY_LIMITS.contractBytes) reject("verify-contract-limit");
50
- };
51
- const walk = async () => {
52
- try { return await physical(io, full); } catch (e) { reject(e instanceof VerifyInputError ? "verify-contract-unsafe" : "verify-contract-unreadable"); }
53
- };
54
- const before = await walk(); safe(before);
55
- let handle;
56
- try { handle = await io.open(full, VERIFY_OPEN_FLAGS); } catch (e) { reject(errno(e) === "ELOOP" ? "verify-contract-unsafe" : "verify-contract-unreadable"); }
57
- try {
58
- const start = await taskHandleStat(handle); safe(start);
59
- if (signature(start) !== signature(before)) reject("verify-contract-changed");
60
- // Exactly the pinned size in requests of at most 64 KiB: no sentinel byte and no EOF probe past the cap.
61
- const buffer = Buffer.alloc(before.size); let offset = 0;
62
- while (offset < before.size) {
63
- const request = Math.min(VERIFY_LIMITS.chunkBytes, before.size - offset);
64
- const { bytesRead } = await handle.read(buffer, offset, request, offset);
65
- if (!validRead(bytesRead, request)) reject("verify-contract-unreadable");
66
- if (!bytesRead) reject("verify-contract-changed");
67
- offset += bytesRead;
68
- }
69
- // Growth, truncation or replacement after the last requested byte must show in descriptor/name metadata.
70
- const after = await taskHandleStat(handle), named = await taskLstat(io, full);
71
- if (signature(after) !== signature(before) || signature(named) !== signature(before)) reject("verify-contract-changed");
72
- await walk();
73
- const bytes = buffer.subarray(0, offset);
74
- return { bytes, sha256: createHash("sha256").update(bytes).digest("hex") };
75
- } finally { await handle.close(); }
76
- }
77
- async function checkRoot(io, full, uid, privateRoot) {
78
- let s;
79
- try { s = await physical(io, full); } catch (e) { reject(e instanceof VerifyInputError ? "verify-root-unsafe" : "verify-root-unreadable"); }
80
- // handoff must be exactly 0700: setuid/setgid/sticky bits also make it non-private for this contract.
81
- if (!s.isDirectory() || (!IS_WINDOWS && (s.uid !== uid || s.mode & 0o022 || privateRoot && (s.mode & 0o7777) !== 0o700))) reject("verify-root-unsafe");
82
- return { full, signature: dirSignature(s) };
83
- }
84
- async function recheckRoot(io, pinned) {
85
- let s;
86
- try { s = await physical(io, pinned.full); } catch { reject("verify-root-changed"); }
87
- if (dirSignature(s) !== pinned.signature) reject("verify-root-changed");
88
- }
89
- async function recheckDirs(io, dirs) {
90
- for (const d of dirs) {
91
- let s;
92
- try { s = await taskLstat(io, d.full); } catch { reject("verify-entry-changed"); }
93
- if (s.isSymbolicLink() || dirSignature(s) !== d.signature) reject("verify-entry-changed");
94
- }
95
- }
96
- // One listed entry: ENOENT is absence; any other error or unsafe component blocks.
97
- async function observe(io, rootFull, entry, expected, uid, budget) {
98
- const parts = entry.path.split("/"), dirs = [];
99
- let curr = rootFull, s;
100
- for (const [i, part] of parts.entries()) {
101
- curr = path.join(curr, part);
102
- try { s = await taskLstat(io, curr); } catch (e) {
103
- if (errno(e) !== "ENOENT") reject("verify-entry-unreadable");
104
- await recheckDirs(io, dirs);
105
- return { id: entry.id, status: "absent", sha256: null };
106
- }
107
- if (i < parts.length - 1) {
108
- if (s.isSymbolicLink() || !s.isDirectory() || (!IS_WINDOWS && (s.uid !== uid || s.mode & 0o022))) reject("verify-entry-unsafe");
109
- dirs.push({ full: curr, signature: dirSignature(s) });
110
- }
111
- }
112
- const safe = st => { if (!st.isFile() || st.isSymbolicLink() || st.nlink !== 1 || (!IS_WINDOWS && (st.uid !== uid || st.mode & 0o7022))) reject("verify-entry-unsafe"); };
113
- safe(s);
114
- if (expected === null) { await recheckDirs(io, dirs); return { id: entry.id, status: "present", sha256: null }; }
115
- if (s.size > VERIFY_LIMITS.fileBytes) reject("verify-file-limit");
116
- if (budget.total + s.size > VERIFY_LIMITS.totalBytes) reject("verify-total-limit");
117
- let handle;
118
- try { handle = await io.open(curr, VERIFY_OPEN_FLAGS); } catch (e) { reject(errno(e) === "ELOOP" ? "verify-entry-unsafe" : "verify-entry-unreadable"); }
119
- let digest;
120
- try {
121
- const start = await taskHandleStat(handle); safe(start);
122
- if (signature(start) !== signature(s)) reject("verify-entry-changed");
123
- const chunk = Buffer.alloc(VERIFY_LIMITS.chunkBytes), hash = createHash("sha256");
124
- let offset = 0;
125
- // Requests never exceed the pinned size or the remaining budget; reaching the size ends reading without an EOF probe.
126
- while (offset < s.size) {
127
- const request = Math.min(chunk.length, s.size - offset, VERIFY_LIMITS.totalBytes - budget.total);
128
- if (request <= 0) reject("verify-total-limit");
129
- const { bytesRead } = await handle.read(chunk, 0, request, offset);
130
- if (!validRead(bytesRead, request)) reject("verify-entry-unreadable");
131
- budget.total += bytesRead; // counted before any later rejection
132
- if (!bytesRead) reject("verify-entry-changed");
133
- offset += bytesRead;
134
- hash.update(chunk.subarray(0, bytesRead));
135
- }
136
- // Growth, truncation or replacement after the last requested byte must show in descriptor/name metadata.
137
- const after = await taskHandleStat(handle), named = await taskLstat(io, curr);
138
- if (signature(after) !== signature(s) || signature(named) !== signature(s)) reject("verify-entry-changed");
139
- digest = hash.digest("hex");
140
- } finally { await handle.close(); }
141
- await recheckDirs(io, dirs);
142
- return { id: entry.id, status: "present", sha256: digest };
143
- }
144
-
145
- /**
146
- * Reads only the explicit contract and its listed entries; never writes, executes, follows links or reads Git.
147
- * Before the pin matches, the only IO is lstat of the contract's own path components and a bounded read of
148
- * its bytes, even when the contract lives inside source/handoff. No listed entry or JSON-referenced path is
149
- * touched before the pin and contract validation.
150
- */
151
- export async function verifyLocal(options, cwd, verifier, dependencies = {}) {
152
- warnPlatformPermissions();
153
- const io = { ...fs, ...dependencies.io }, uid = process.getuid?.(), home = dependencies.home ?? os.homedir();
154
- const audit = { contractByteSha256: null, expectedPinSha256: null };
155
- const phase = options?.phase === "before" || options?.phase === "after" ? options.phase : null;
156
- const fail = (state, codes, contract = null) => verifier.failure(state, codes, { phase, contract, audit });
157
- if (!["darwin", "linux", "win32"].includes(dependencies.platform ?? process.platform) || (!IS_WINDOWS && typeof uid !== "number")) return fail("blocked", ["verify-platform-unsupported"]);
158
- if (!phase || typeof options.expect !== "string" || !/^[a-f0-9]{64}$/.test(options.expect)) return fail("invalid", ["verify-invalid-input"]);
159
- audit.expectedPinSha256 = options.expect;
160
- let contractFull, roots;
161
- try {
162
- if (!pathText(options.contract) || !path.isAbsolute(cwd)) reject("verify-contract-path");
163
- contractFull = path.resolve(cwd, options.contract);
164
- if ((IS_WINDOWS && !isPortableAbsolutePath(contractFull)) || forbidden(contractFull)) reject("verify-contract-path");
165
- roots = { source: rootPath(options.source, home), handoff: rootPath(options.handoff, home) };
166
- const a = pathKey(roots.source), b = pathKey(roots.handoff);
167
- if (a === b || a.startsWith(b + path.sep) || b.startsWith(a + path.sep)) reject("verify-root-overlap");
168
- } catch (e) { return fail("blocked", [e instanceof VerifyInputError ? e.code : "verify-invalid-input"]); }
169
- let read;
170
- try { read = await readContract(io, contractFull, uid); }
171
- catch (e) { return fail("blocked", [e instanceof VerifyInputError ? e.code : "verify-contract-unreadable"]); }
172
- // Pin before parsing, root checks or any listed entry. The actual hash is not echoed on mismatch.
173
- if (read.sha256 !== options.expect) return fail("blocked", ["verify-pin-mismatch"]);
174
- audit.contractByteSha256 = read.sha256;
175
- let parsed;
176
- try { parsed = parseTaskDocument(read.bytes); } catch { return fail("invalid", ["verify-contract-format"]); }
177
- const checked = verifier.checkContract(parsed);
178
- if (!checked.ok) return fail("invalid", checked.reasons);
179
- const contract = checked.contract, observations = [];
180
- try {
181
- const pinned = { source: await checkRoot(io, roots.source, uid, false), handoff: await checkRoot(io, roots.handoff, uid, true) };
182
- if (pinned.source.signature === pinned.handoff.signature) reject("verify-root-overlap");
183
- const budget = { total: 0 };
184
- for (const entry of contract.entries) observations.push(await observe(io, roots[entry.root], entry, entry[phase], uid, budget));
185
- for (const pin of Object.values(pinned)) await recheckRoot(io, pin);
186
- } catch (e) { return fail("blocked", [e instanceof VerifyInputError ? e.code : "verify-entry-unreadable"], contract); }
187
- return verifier[LOCAL_READ]({ contract, phase, observations }, audit);
188
- }