Skip to content
Back to search

alfred-dev

Tu equipo de desarrolladores en un plugin. 10 agentes, 11 skills planas, 18 comandos /alfred-dev:*. Memoria persistente, quality gates con evidencia y MCP local.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/686f6c61/alfred-dev with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/686f6c61/alfred-dev'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/686f6c61--alfred-dev/badge.svg)](/listings/686f6c61--alfred-dev)

HTML

<a href="/listings/686f6c61--alfred-dev"><img src="/api/listings/686f6c61--alfred-dev/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 20 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. {
  2. "name": "alfred-dev",
  3. "description": "Marketplace no oficial de Alfred Dev para Claude Code.",
  4. "owner": {
  5. "name": "686f6c61"
  6. },
  7. "plugins": [
  8. {
  9. "name": "alfred-dev",
  10. "displayName": "Alfred Dev",
  11. "description": "Plugin de ingeniería de software: 10 agentes, 11 skills planas, memoria persistente y flujos con quality gates.",
  12. "source": "./",
  13. "author": {
  14. "name": "686f6c61"
  15. },
  16. "category": "development",
  17. "homepage": "https://alfred-dev.com/"
  18. }
  19. ]
  20. }
README.md · README · 479 lines · 5 findings marked

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. ```text
  2. █████╗ ██╗ ███████╗██████╗ ███████╗██████╗ ██████╗ ███████╗██╗ ██╗
  3. ██╔══██╗██║ ██╔════╝██╔══██╗██╔════╝██╔══██╗ ██╔══██╗██╔════╝██║ ██║
  4. ███████║██║ █████╗ ██████╔╝█████╗ ██║ ██║ ██║ ██║█████╗ ██║ ██║
  5. ██╔══██║██║ ██╔══╝ ██╔══██╗██╔══╝ ██║ ██║ ██║ ██║██╔══╝ ╚██╗ ██╔╝
  6. ██║ ██║███████╗██║ ██║ ██║███████╗██████╔╝ ██████╔╝███████╗ ╚████╔╝
  7. ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝╚══════╝╚═════╝ ╚═════╝ ╚══════╝ ╚═══╝
  8. ```
  9. **Plugin de ingeniería de software automatizada para [Claude Code](https://code.claude.com/docs/en/overview).**
  10. 10 agentes (8 de núcleo, Selina si hay frontend y Lucius bajo demanda), catálogo de 11 skills de proceso, memoria persistente de decisiones por proyecto, 6 flujos de trabajo con quality gates verificables con evidencia, fase de estilo visual condicional, modo autopilot y compliance europeo (RGPD, NIS2, CRA) integrado desde el diseño.
  11. [Documentación completa](https://alfred-dev.com/) -- [Instalar](#instalación) -- [Equipo](#el-equipo) -- [Comandos](#comandos) -- [Arquitectura](#arquitectura)
  12. ---
  13. ## Qué es Alfred Dev
  14. Alfred Dev es un plugin que orquesta el ciclo de desarrollo de software con agentes autónomos. Cada agente tiene un rol concreto, un ámbito delimitado y quality gates que impiden avanzar a la siguiente fase sin evidencia. El sistema está pensado para que ningún artefacto llegue a producción sin haber pasado por producto, arquitectura, desarrollo con TDD, revisión de seguridad, QA y documentación.
  15. El runtime detecta el stack del proyecto con `config_loader.detect_stack()` (Node.js/TypeScript, Python, Rust, Go, Ruby, Elixir, Java/Kotlin, PHP, C#/.NET, Swift) y adapta artefactos al ecosistema real: frameworks, gestores de paquetes, runners de tests y estructura de directorios cuando esos manifiestos existen.
  16. La documentación viva del proyecto auditado vive en `docs/project/` (índice, arquitectura, compliance, threat-model, dependencias, mapa y estado). Los ADRs van a `docs/adr/`. Esos ficheros no son este repositorio: los crea el plugin en el repo donde trabajas.
  17. ## El equipo
  18. Alfred Dev no es un agente monolítico que intenta saberlo todo. Es un equipo de **10 especialistas**, cada uno con un rol delimitado, personalidad propia y quality gates verificables con evidencia. Un modelo generalista rinde mejor con un rol concreto e instrucciones focalizadas que cuando se le pide que sea todo a la vez.
  19. Cada agente se invoca como un subproceso de Claude Code mediante la herramienta **Agent**. Arranca con su propio system prompt, sin heredar sesgos ni ruido de conversaciones anteriores. El resultado no se promete determinista, pero sí más controlable: el mismo rol, las mismas instrucciones y los mismos artefactos reducen la variabilidad y facilitan revisar si cumplió su contrato.
  20. Tres principios de diseño:
  21. - **Responsabilidad única.** El Artesano escribe código; El Paranoico audita seguridad. Ninguno invade el territorio del otro.
  22. - **Herramientas restringidas.** No todos los agentes necesitan el sistema de ficheros o la terminal. Limitar herramientas reduce la superficie de error.
  23. - **Quality gates entre fases.** Ningún artefacto pasa de fase sin un punto de control. Las gates pueden ser automáticas (tests verdes), manuales (aprobación del usuario) o combinadas (automático + seguridad).
  24. Frontera del núcleo:
  25. - **`product-owner`** decide **qué** problema se resuelve y **por qué**.
  26. - **`architect`** decide **cómo** se implementa técnicamente.
  27. - **`alfred`** decide **cuándo** interviene cada uno, en qué orden y con qué gate.
  28. Si esas tres responsabilidades se mezclan, el flujo deja de ser previsible. Alfred coordina; no redefine alcance ni diseño por su cuenta.
  29. ### Flujo feature: cronología de fases
  30. El flujo `feature` es el más completo: hasta siete fases secuenciales. La fase `estilo_visual` solo aparece si el proyecto tiene frontend. El `security-officer` interviene en arquitectura, calidad y entrega: la seguridad no es un paso final.
  31. ```mermaid
  32. timeline
  33. title Flujo feature - fases y agentes
  34. producto
  35. : product-owner
  36. : Análisis de requisitos
  37. : Gate - aprobación del usuario
  38. estilo visual
  39. : selina
  40. : Dirección de estilo visual (solo con frontend)
  41. : Gate - elección del usuario
  42. arquitectura
  43. : architect + security-officer
  44. : Diseño técnico y threat model
  45. : Gate - aprobación del usuario
  46. desarrollo
  47. : senior-dev
  48. : Implementación TDD
  49. : Gate - tests verdes (automático)
  50. calidad
  51. : qa-engineer + security-officer
  52. : Tests y auditoría de seguridad
  53. : Gate - automático + seguridad
  54. documentación
  55. : tech-writer
  56. : Documentación técnica y de usuario
  57. : Gate - libre (sin bloqueo)
  58. entrega
  59. : devops-engineer + security-officer
  60. : Changelog y validación final
  61. : Gate - usuario + seguridad
  62. ```
  63. El `security-officer` valida el threat model en arquitectura, audita el código en calidad y da el visto bueno en entrega. Detectar un problema de seguridad pronto sale más barato que detectarlo en producción.
  64. ## Instalación
  65. Una sola línea. El script verifica el entorno, registra en Claude Code una
  66. fuente GitHub global para Alfred Dev e instala el plugin con la CLI nativa de Claude Code.
  67. No pisa `~/.claude/skills` ni crea `~/.claude/skills/alfred/SKILL.md` ni
  68. `~/.claude/commands/alfred.md`. La entrada es `/alfred-dev:alfred`.
  69. Parchea hooks y `.mcp.json` si el `python3` por defecto no es compatible.
  70. Antes de instalar, limpia el checkout local del marketplace
  71. (`~/.claude/plugins/marketplaces/alfred-dev`) y lo vuelve a registrar, para no
  72. materializar una caché antigua. La instalación soportada es siempre global de
  73. usuario: si existían rastros `local` o `project` del propio Alfred Dev, el
  74. instalador los normaliza y reinstala con `--scope user`. No usa un marketplace
  75. oficial de Anthropic: usa la CLI nativa para registrar una fuente propia no oficial.
  76. ```bash
  77. curl -fsSL https://raw.githubusercontent.com/686f6c61/alfred-dev/main/install.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 101 on GitHub
  78. ```
  79. Si ya tienes este repo clonado localmente, también puedes invocarlo así:
  80. ```bash
  81. bash ./install.sh
  82. ```
  83. Después de instalar, en una sesión abierta ejecuta `/reload-plugins` para cargar
  84. Alfred Dev sin reiniciar. Si Claude Code avisa por coste/caché de MCP o el
  85. plugin no aparece, reinicia Claude Code. Verifica con:
  86. ```bash
  87. /alfred-dev:alfred
  88. ```
  89. En Windows (PowerShell):
  90. ```powershell
  91. irm https://raw.githubusercontent.com/686f6c61/alfred-dev/main/install.ps1 | iex
  92. ```
  93. Requisitos:
  94. - [Claude Code](https://code.claude.com/docs/en/overview) instalado, configurado y actualizado. Alfred Dev 0.7.0 requiere una CLI con plugins, skills, hooks y MCP.
  95. - Python 3.10+ (para hooks, core y MCP en macOS, Linux y Windows).
  96. Para desinstalar:
  97. ```bash
  98. # macOS / Linux
  99. curl -fsSL https://raw.githubusercontent.com/686f6c61/alfred-dev/main/uninstall.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 133 on GitHub
  100. ```
  101. ```bash
  102. # macOS / Linux, desde el repo clonado
  103. bash ./uninstall.sh
  104. ```
  105. ```powershell
  106. # Windows
  107. irm https://raw.githubusercontent.com/686f6c61/alfred-dev/main/uninstall.ps1 | iex
  108. ```
  109. El desinstalador retira el plugin y la fuente del marketplace en scope `user`.
  110. Si queda un alias global `/alfred` de instalaciones 0.6, también lo limpia.
  111. No borra `.claude/` del proyecto (config, memoria SQLite, handoff).
  112. `/alfred-dev:update` compara la versión instalada con el último GitHub Release
  113. y guía la actualización. Añadir el marketplace `686f6c61/alfred-dev` instala
  114. lo que haya en la rama por defecto `main`.
  115. ## Inicio rápido
  116. Una vez instalado, habla en castellano. No hace falta memorizar slash commands.
  117. ```text
  118. sigue donde lo dejé
  119. el login peta con eñes
  120. cambia el texto del botón
  121. ```
  122. El hook `prompt-route.py` sugiere la ruta si el texto no trae slash. `/alfred-dev:alfred`
  123. decide si toca mapear, discutir, retomar, abrir UAT o arrancar un flujo.
  124. Si quieres el flujo largo:
  125. ```text
  126. /alfred-dev:feature sistema de login con email y password
  127. ```
  128. `/alfred-dev:ajustes` cambia autonomía y Lucius. `/alfred-dev:feature` recorre
  129. hasta 7 fases (producto, estilo visual, arquitectura, desarrollo, calidad,
  130. documentación, entrega). Autopilot solo resuelve gates de usuario configuradas;
  131. no salta tests, seguridad, evidencia ni confirmación humana de despliegue.
  132. La fase de estilo visual se activa solo si hay interfaz.
  133. ## Novedades en v0.7.0
  134. Recorte alineado con el SDK de Claude Code: 10 agentes (`inherit`), 11 skills planas, 18 comandos publicados. La entrada es `/alfred-dev:alfred`. Continuidad pública: `alfred`, `progress` y `retomar`. Sin alias global `/alfred`, sin stop-hook Ralph y sin reescribir `settings.json`. El servidor de memoria usa MCP stdio moderno y arranca `mcp/memory_server.py` con FastMCP si el paquete `mcp` está instalado. Secret-guard cubre Write, Edit, Bash y tools MCP de escritura. Agent Teams solo si el usuario ya lo tiene activo. La auditoría viva está en [docs/release.md](docs/release.md). El histórico de 0.6.x está en el [changelog](CHANGELOG.md).
  135. ## Comandos
  136. Toda la interfaz se controla desde la línea de comandos de Claude Code. La entrada principal es `/alfred-dev:alfred`. El resto usa el mismo prefijo `/alfred-dev:`. No hay alias global `/alfred`. `plugin.json` publica 18 comandos. En `commands/` quedan helpers internos que no se listan como slash: `next`, `search`, `_composicion.md` y `_docs_vivas.md`.
  137. ### Core
  138. | Comando | Descripción |
  139. |---------|-------------|
  140. | `/alfred-dev:alfred` | Entrada contextual: decide si toca mapear, discutir, retomar, abrir UAT o arrancar un flujo multiagente. |
  141. | `/alfred-dev:feature <desc>` | Ciclo completo de hasta 7 fases. Alfred pregunta desde qué fase arrancar. |
  142. | `/alfred-dev:quick <desc>` | Flujo ligero para cambios pequeños con menos ceremonia que `feature`. |
  143. | `/alfred-dev:fix <desc>` | Corrección de bugs en 3 fases: diagnóstico, corrección TDD, validación. |
  144. | `/alfred-dev:spike <tema>` | Investigación técnica sin compromiso: prototipos, benchmarks, hallazgos. |
  145. | `/alfred-dev:discuss <desc>` | Refina una idea o fase y deja `docs/project/discovery.md` antes de abrir `feature`. |
  146. | `/alfred-dev:map-codebase` | Analiza un repo existente y deja `docs/project/codebase-map.md` y `docs/project/current.md`. |
  147. | `/alfred-dev:progress` | Resume kanban, bloqueos, trazabilidad, UAT y estado operativo. |
  148. | `/alfred-dev:uat` | Crea o cierra la validación humana, separada de los tests automáticos. |
  149. | `/alfred-dev:audit` | Auditoría con 4 agentes en paralelo: calidad, seguridad, arquitectura, documentación. |
  150. | `/alfred-dev:ship` | Release: auditoría final, changelog, versionado semántico, despliegue. |
  151. | `/alfred-dev:memory-ui` | Abre o cierra la UI local de la memoria SQLite. |
  152. | `/alfred-dev:ajustes` | Configurar autonomía, stack, Lucius, memoria y personalidad. |
  153. ### Operativos
  154. | Comando | Descripción |
  155. |---------|-------------|
  156. | `/alfred-dev:retomar` | Retoma una sesión pausada usando el handoff y el estado guardado. |
  157. | `/alfred-dev:pause` | Pausa el trabajo en curso y genera handoff persistente. |
  158. | `/alfred-dev:sync-github [owner/repo]` | Refleja el tablero local en GitHub Issues usando `gh`. |
  159. | `/alfred-dev:lucius [dir] [--scope X]` | Segunda opinión técnica vía Codex CLI. |
  160. | `/alfred-dev:update` | Comprueba si hay versión nueva (GitHub Releases) y actualiza el plugin. |
  161. ### Ejemplo de uso
  162. ```
  163. > /alfred-dev:feature sistema de autenticación con OAuth2
  164. Alfred activa el flujo de hasta 7 fases:
  165. 1. Producto -- PRD con historias de usuario y criterios de aceptación
  166. 2. Estilo visual -- Tres propuestas en navegador (solo si hay UI)
  167. 3. Arquitectura -- Diseño de componentes, ADRs, threat model en paralelo
  168. 4. Desarrollo -- Implementación TDD (rojo-verde-refactor)
  169. 5. Calidad -- Code review + OWASP + compliance + SBOM
  170. 6. Documentación -- API docs, guía de usuario, changelog
  171. 7. Entrega -- Pipeline CI/CD, Docker, deploy
  172. Cada transición entre fases requiere superar la quality gate correspondiente.
  173. ```
  174. Los 6 flujos del orquestador son `feature` (hasta 7 fases), `fix` (3), `spike` (2),
  175. `ship` (4), `audit` (1) y `quick` (2).
  176. ## Arquitectura
  177. ### Agentes de núcleo (8 + Selina)
  178. El plugin publica 10 agentes: 8 de núcleo, Selina si hay frontend y Lucius bajo demanda. La configuración del proyecto no desactiva el núcleo, pero Alfred no los invoca todos a la vez: cada flujo activa el rol de la fase, las señales del proyecto y las gates pendientes. El kanban y la trazabilidad los escribe el runtime, no un agente de project manager.
  179. | Agente | Rol | Modelo | Responsabilidad |
  180. |--------|-----|--------|-----------------|
  181. | **Alfred** | Orquestador | inherit | Coordina flujos, activa agentes, evalúa gates entre fases |
  182. | **El Buscador de Problemas** | Product Owner | inherit | PRDs, historias de usuario, criterios de aceptación, análisis competitivo |
  183. | **Selina** | Dirección visual | inherit | Tres propuestas en navegador, artefacto `docs/style-direction.md`, gate de estilo |
  184. | **El Dibujante de Cajas** | Arquitecto | inherit | Diseño de sistemas, ADRs, diagramas Mermaid, matrices de decisión |
  185. | **El Artesano** | Senior Dev | inherit | Implementación TDD, refactoring, commits atómicos |
  186. | **El Paranoico** | Security Officer | inherit | OWASP Top 10, threat modeling STRIDE, SBOM, compliance RGPD/NIS2/CRA |
  187. | **El Rompe-cosas** | QA Engineer | inherit | Test plans, code review, exploratorio, integración, E2E, regresión |
  188. | **El Fontanero** | DevOps Engineer | inherit | Docker multi-stage, CI/CD, deploy, monitoring, observabilidad |
  189. | **El Escriba** | Tech Writer | inherit | Sync corto por fase (cabeceras, docstrings, `docs/project/`); en documentación: API docs, arquitectura, guías, changelogs |
  190. Los 10 agentes declaran `model: inherit` y usan el modelo de la sesión. Selina ocupa la fase condicional entre producto y arquitectura. Solo se activa si `has_frontend(stack)` es verdadero.
  191. ### Agente opcional (Lucius)
  192. El único opcional del runtime es **Lucius**, segunda opinión vía Codex CLI. Se activa con `/alfred-dev:ajustes` o al pedir una auditoría externa. No hay data-engineer, ux-reviewer, github-manager, librarian ni el resto del catálogo 0.6. Más detalles en la [documentación de configuración](docs/configuration.md#composicion-dinamica-de-equipo).
  193. ### Skills (11)
  194. Cada skill es una habilidad plana en `skills/*/SKILL.md`. El catálogo publicado es:
  195. ```
  196. skills/
  197. compliance-check/
  198. evaluate-dependency/
  199. incident-response/
  200. memory/
  201. pr-workflow/
  202. sbom-generate/
  203. sonarqube/
  204. style-direction/
  205. sync-project-docs/
  206. threat-model/
  207. write-adr/
  208. ```
  209. Los skills con side effects (`style-direction`, `sonarqube`, `incident-response`, `pr-workflow`) declaran `disable-model-invocation: true`.
  210. ### Hooks (10)
  211. Los hooks interceptan eventos del ciclo de vida de Claude Code. Este plugin registra 10 scripts en `SessionStart`, `SessionEnd`, `UserPromptSubmit`, `PreToolUse` y `PostToolUse`. `activity-capture.py` está en tres matchers (12 registros en total). No registra Stop, UserPromptExpansion ni PreCompact.
  212. | Hook | Evento | Función |
  213. |------|--------|---------|
  214. | `session-bootstrap.sh` | `SessionStart` | Bootstrap síncrono: config local, memoria, permisos y wrapper de continuidad |
  215. | `session-start.sh` | `SessionStart` | Briefing de sesión, protocolo de hablar sin slash y contexto de continuidad |
  216. | `session-end.py` | `SessionEnd` | Detiene Memory UI y escribe el cierre de sesión (fail-open) |
  217. | `prompt-route.py` | `UserPromptSubmit` | Si el texto no trae slash, sugiere fix/quick/retomar según la petición |
  218. | `secret-guard.py` | `PreToolUse` (Write/Edit/Bash/MCP) | Bloquea escritura de secretos |
  219. | `dangerous-command-guard.py` | `PreToolUse` (Bash) | Bloquea comandos destructivos (`rm -rf /`, force push, DROP DATABASE) |
    • Dismissed after review: Runs `rm -rf` against a root or home-directory path
    • Line 290 on GitHub
  220. | `sensitive-read-guard.py` | `PreToolUse` (Read) | Avisa al leer ficheros sensibles (claves privadas, `.env`, credenciales) |
  221. | `quality-gate.py` | `PostToolUse` (Bash) | Avisa cuando un runner de tests falla, usando salida y exit code |
  222. | `evidence-guard.py` | `PostToolUse` (Bash) | Registra evidencia de ejecución de tests para verificación de gates |
  223. | `activity-capture.py` | `PostToolUse` + `UserPromptSubmit` | Captura automática de actividad, commits e iteraciones |
  224. ### Templates (8)
  225. Plantillas que los agentes usan para generar artefactos con estructura estable:
  226. - `prd.md` -- Product Requirements Document
  227. - `adr.md` -- Architecture Decision Record
  228. - `test-plan.md` -- Plan de testing por riesgo
  229. - `threat-model.md` -- Modelado de amenazas STRIDE
  230. - `sbom.md` -- Software Bill of Materials
  231. - `changelog-entry.md` -- Entrada de changelog (Keep a Changelog)
  232. - `release-notes.md` -- Notas de release con resumen ejecutivo
  233. - `compliance.md` -- Checklist de cumplimiento del proyecto
  234. ### Core Python
  235. El núcleo del plugin está implementado en Python con tests unitarios. Los
  236. módulos se agrupan por responsabilidad para no prometer un contador fijo
  237. que quede obsoleto cuando crece el runtime:
  238. | Familia | Módulos principales | Función |
  239. |---------|---------------------|---------|
  240. | Orquestación | `orchestrator.py` | Máquina de estados de 6 flujos, sesiones, gates, autopilot, loop iterativo |
  241. | Personalidad | `personality.py` | Frases, tono, anuncios y formato de veredicto |
  242. | Configuración | `config_loader.py`, `optional_agents.py`, `config_cli.py` | Carga de config, detección de stack, menús de `/alfred-dev:ajustes` y Lucius |
  243. | Continuidad | `continuity.py`, `session_report.py`, `session_brief.py`, `hygiene.py` | Helpers, pausa/reanudación, briefing, higiene de ship y UAT |
  244. | Docs vivas | `project_docs.py` | Esqueleto y comprobación de `docs/project/` y `docs/adr/` |
  245. | Enrutado | `prompt_route.py` | Clasifica prompts sin slash (fix, quick, retomar, map-codebase) |
  246. | Memoria | `memory.py`, `memory_config.py`, `memory_sync.py`, `memory_ui_server.py` | SQLite local, sync Markdown y UI local GET |
  247. | Seguridad | `secrets.py` | Sanitización y detección de secretos reutilizada por memoria, empaquetado y guards |
  248. | Selina visual | `selina_visual.py`, `selina_style_*.py` | Dirección visual condicional, catálogo, opciones y selector |
  249. ```bash
  250. # Ejecutar tests
  251. python3 -m pytest tests/ -v
  252. ```
  253. ## Quality gates
  254. Las quality gates son puntos de control verificables entre fases. Si las condiciones de una gate no se cumplen, el flujo se detiene o queda pendiente con una siguiente acción clara. Autopilot solo resuelve gates de usuario configuradas; no salta tests, seguridad, evidencia ni confirmación humana de despliegue.
  255. El orquestador define 5 tipos: `libre`, `usuario`, `automatico`, `usuario+seguridad` y `automatico+seguridad`.
  256. | Gate | Condición |
  257. |------|-----------|
  258. | PRD aprobado | El usuario valida el PRD antes de pasar a arquitectura |
  259. | Diseño aprobado | El usuario aprueba el diseño Y el security officer lo valida |
  260. | Tests en verde | Todos los tests pasan antes de pasar a calidad |
  261. | Evidencia verificada | Las afirmaciones de tests deben estar respaldadas por salida real registrada por `evidence-guard.py` |
  262. | Loop iterativo | Si una gate falla, se reintenta hasta 5 veces con feedback antes de escalar al usuario |
  263. | QA + seguridad | El QA engineer y el security officer aprueban en paralelo |
  264. | Documentación completa | Todos los artefactos están documentados con checklist/evidencia revisable |
  265. | Pipeline verde | CI/CD verde, sin usuario root en contenedor, sin secretos en imagen |
  266. Cada gate produce un veredicto formal: **APROBADO**, **APROBADO CON CONDICIONES** o **RECHAZADO**, con hallazgos bloqueantes y próxima acción recomendada.
  267. ## Compliance
  268. El plugin integra verificaciones de compliance europeo en el flujo de desarrollo:
  269. - **RGPD** -- Protección de datos desde el diseño. Verificación de base legal, minimización de datos, derechos de los interesados.
  270. - **NIS2** -- Directiva de ciberseguridad para operadores esenciales. Gestión de riesgos, notificación de incidentes, cadena de suministro.
  271. - **CRA** -- Cyber Resilience Act. Requisitos de ciber-resiliencia para productos digitales con componentes conectados.
  272. - **OWASP Top 10** -- Verificación sistemática de las 10 vulnerabilidades más explotadas en cada revisión de seguridad.
  273. - **SBOM** -- Generación automática del Software Bill of Materials con inventario de dependencias, licencias y CVEs conocidos.
  274. ## Detección de stack
  275. `core/config_loader.py` (`detect_stack()`) analiza el directorio del proyecto al cargar la configuración. El bootstrap de `SessionStart` materializa `.claude/alfred-dev.local.md` con ese resultado. No lo hace `session-start.sh`: ese hook inyecta el briefing y el protocolo de hablar sin slash.
  276. | Lenguaje | Señales | Qué detecta además |
  277. |----------|---------|-------------------|
  278. | Node.js / TypeScript | `package.json` (+ `tsconfig.json` eleva a TypeScript) | Frameworks: Next, Nuxt, Astro, Remix, Gatsby, Svelte, Solid, Qwik, Vue, React, Angular, Hono, Express, Fastify, Koa, Nest. ORM, runner y bundler si están en dependencias. |
  279. | Python | `pyproject.toml`, `setup.py`, `requirements.txt` | FastAPI, Django, Flask, Starlette, Litestar, Sanic, Tornado, aiohttp. ORM y runner si aparecen en manifiestos. |
  280. | Rust | `Cargo.toml` | Runtime y lenguaje. No infiere framework. |
  281. | Go | `go.mod` | Runtime y lenguaje. No infiere framework. |
  282. | Ruby | `Gemfile` | Runtime y lenguaje. No infiere framework. |
  283. | Elixir | `mix.exs` | Runtime y lenguaje. No infiere framework. |
  284. | Java / Kotlin | `pom.xml`, `build.gradle`, `build.gradle.kts` | Spring Boot, Quarkus, Micronaut. Kotlin si hay `.kt` o Gradle Kotlin. |
  285. | PHP | `composer.json` | Laravel, Symfony, Slim. |
  286. | C# / .NET | `*.csproj`, `*.sln` | ASP.NET o Blazor. |
  287. | Swift | `Package.swift` | Vapor si aparece en el manifiesto. |
  288. Selina solo entra si el framework detectado está en el conjunto frontend (Next, Nuxt, Astro, Remix, Gatsby, Svelte, Solid, Qwik, Vue, React, Angular).
  289. ## Memoria persistente
  290. Alfred Dev recuerda decisiones, commits e iteraciones entre sesiones. La memoria se almacena en SQLite local (`.claude/alfred-memory.db`) dentro de cada proyecto, sin servicios remotos.
  291. `load_config()` parte de `memoria.enabled: false` si no hay fichero local. En la primera sesión, `session-bootstrap.sh` siembra `.claude/alfred-dev.local.md` con memoria activa. A partir de ahí, `/alfred-dev:ajustes` puede desactivarla. Si está apagada, los flujos siguen; las sesiones futuras no tendrán histórico.
  292. Con la memoria activa, `activity-capture.py` registra eventos en `UserPromptSubmit` y `PostToolUse` (Write, Edit, Bash): iteraciones, fases, commits (SHA, autor, ficheros) y actividad de la sesión. Las decisiones se consultan con el servidor MCP y `/alfred-dev:memory-ui`. No hay agente Bibliotecario.
  293. Funcionalidades principales:
  294. - **Trazabilidad**: problema, decisión, commit y validación enlazados con IDs.
  295. - **Búsqueda**: texto completo con FTS5, filtros `since`/`until`, etiquetas y estado (`active`/`superseded`/`deprecated`).
  296. - **Servidor MCP** (`alfred-memory`): 15 herramientas (buscar, registrar, consultar, estadísticas, iteraciones, ciclo de vida de decisiones, integridad, export/import). Habla MCP stdio moderno (JSON por línea) y mantiene lectura compatible con el framing `Content-Length` antiguo.
  297. - **Memory UI**: visor local GET en loopback sobre `.claude/alfred-memory.db`. No importa el historial de Git al abrir. `POST` no está implementado. `/alfred-dev:memory-ui stop` y `SessionEnd` detienen el servidor.
  298. - **Importación MCP**: la tool `memory_import` sí puede cargar commits de Git o ADRs de `docs/adr/` cuando un agente la invoca; eso no ocurre al abrir la UI.
  299. - **Contexto de sesión**: `session-start.sh` inyecta un briefing de estado, última decisión y ADRs aceptados.
  300. - **Exportación**: `memory_export` escribe decisiones a Markdown con formato ADR.
  301. - **Seguridad**: sanitización de secretos con los mismos patrones que `secret-guard.py`, permisos `0600` en la base de datos.
  302. - **Migración**: el esquema se actualiza con backup previo al abrir bases antiguas.
  303. ## Estructura del proyecto
  304. ```
  305. alfred-dev/
  306. .claude-plugin/
  307. plugin.json # Manifiesto del plugin (version, 18 comandos)
  308. marketplace.json # Metadatos de la fuente no oficial
  309. .mcp.json # Servidor MCP alfred-memory (stdio)
  310. agents/ # 10 agentes (8 de núcleo + Selina + Lucius)
  311. commands/ # 18 comandos publicados + helpers internos
  312. skills/ # Catálogo publicado de 11 skills planas
  313. hooks/ # 10 scripts + hooks.json
  314. core/ # Motor de orquestación, memoria e informes (Python)
  315. mcp/ # Servidor MCP stdio (memoria persistente)
  316. templates/ # 8 plantillas de artefactos
  317. visual/ # Companion local de Selina (servidor y HTML)
  318. tests/ # Tests y contratos de release (pytest)
  319. docs/ # Documentación técnica del plugin
  320. scripts/ # Auditoría de release y smokes
  321. install.sh / install.ps1
  322. uninstall.sh / uninstall.ps1
  323. ```
  324. La landing pública se mantiene en la rama `Alfred-Astro` y se despliega desde Coolify sobre el VPS. La rama `main` contiene solo el plugin, su runtime y sus tests.
  325. ## Configuracion
  326. El plugin se configura por proyecto con `.claude/alfred-dev.local.md` en la raíz del proyecto. En la primera sesión, `SessionStart` lo crea si falta con autonomía por fases en `autonomo` y memoria activa; después `/alfred-dev:ajustes` permite cambiarlo a `interactivo` o `semi-autonomo`. El único opcional es Lucius:
  327. ```yaml
  328. ---
  329. autonomia:
  330. producto: autonomo
  331. arquitectura: autonomo
  332. desarrollo: autonomo
  333. calidad: autonomo
  334. documentacion: autonomo
  335. entrega: autonomo
  336. agentes_opcionales:
  337. lucius: false
  338. memoria:
  339. enabled: true
  340. sync_to_native: true
  341. sync_commits_limit: 10
  342. capture_decisions: true
  343. capture_commits: true
  344. retention_days: 365
  345. personalidad:
  346. nivel_sarcasmo: 3
  347. verbosidad: normal
  348. idioma: es
  349. celebrar_victorias: true
  350. insultar_malas_practicas: true
  351. ---
  352. Notas adicionales del proyecto que Alfred debe tener en cuenta.
  353. ```
  354. Los tres niveles de autonomía por fase son `interactivo` (pide confirmación), `semi-autonomo` y `autonomo`. Autopilot no salta tests, seguridad, evidencia ni el deploy.
  355. ## Descargo de responsabilidad
  356. **Alfred Dev** es un proyecto independiente de código abierto. No está afiliado, patrocinado ni respaldado por **Anthropic** ni por el equipo de **Claude Code**.
  357. El software se entrega en su estado actual, sin garantías de ningún tipo, expresas o implícitas, incluidas las de comerciabilidad, adecuación a un fin concreto y ausencia de infracción. En ningún caso los autores o titulares de los derechos de autor serán responsables de reclamaciones, daños u otras responsabilidades derivadas del uso del software.
  358. Alfred Dev ejecuta agentes que pueden crear, modificar y eliminar ficheros, ejecutar comandos en terminal e interactuar con servicios externos (GitHub, Docker, etc.). El usuario es responsable de revisar y aprobar las acciones que el plugin propone antes de su ejecución.
  359. Los agentes utilizan modelos de lenguaje que pueden generar contenido incorrecto, incompleto o inadecuado. Las salidas del plugin son sugerencias que requieren revisión humana, no resultados definitivos.
  360. ## Licencia
  361. MIT
  362. ---
  363. [Documentación completa](https://alfred-dev.com/) | [Código fuente](https://github.com/686f6c61/alfred-dev)
hooks/dangerous-command-guard.py · Bundled script · 600 lines · 1 finding marked
  1. #!/usr/bin/env python3
  2. """
  3. Hook PreToolUse para Bash: guardia de comandos peligrosos.
  4. Intercepta las ejecuciones de Bash y analiza el comando en busca de patrones
  5. potencialmente destructivos (borrado catastrofico, force push, destruccion de
  6. datos, fork bombs, etc.). Si detecta un patron peligroso, bloquea la operacion
  7. (exit 2) con un aviso explicativo.
  8. Politica de seguridad: fail-closed. Si no se puede parsear la entrada del hook
  9. o se produce cualquier error inesperado, se bloquea la operacion (exit 2).
  10. Un hook de seguridad que permite la operacion cuando falla equivale a
  11. desactivar la proteccion justo cuando mas se necesita. Esta politica es
  12. coherente con secret-guard.sh, que tambien es fail-closed.
  13. Patrones vigilados:
  14. - rm -rf / (o ~, o $HOME): borrado catastrofico del sistema o del home.
    • Dismissed after review: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 17 on GitHub
  15. - git push --force a main/master: perdida de historial en ramas protegidas.
  16. - DROP DATABASE / DROP TABLE: destruccion de datos en base de datos.
  17. - docker system prune -af: eliminacion de volumenes y datos de contenedores.
  18. - chmod -R 777: permisos inseguros en todo un arbol de directorios.
  19. - fork bombs: denegacion de servicio local.
  20. - mkfs / dd sobre dispositivos: destruccion de disco.
  21. - Escritura directa a dispositivos de bloque.
  22. """
  23. import json
  24. import os
  25. import re
  26. import shlex
  27. import sys
  28. # --- Patrones peligrosos ---------------------------------------------------
  29. # Cada tupla contiene (patron_compilado, descripcion_del_riesgo).
  30. # Los patrones se evaluan en orden; la primera coincidencia bloquea.
  31. _DANGEROUS_PATTERNS = [
  32. # Borrado catastrofico: rm -rf aplicado a raiz, home o rutas de sistema.
  33. # Cubre: flags juntas (-rf, -fr), separadas (-r -f), con sudo, y flags largas.
  34. (
  35. re.compile(
  36. r"(?:sudo\s+)?rm\s+"
  37. r"(?:-[a-zA-Z]*\s+)*"
  38. r"(?:--\w[\w-]*\s+)*"
  39. r"(?=-[a-zA-Z]*r)(?=.*-[a-zA-Z]*f)"
  40. r".*\s+(/\s|/\*|/$|~\s|~$|~\/|\$HOME|\$\{HOME\}|/usr|/etc|/var|/boot|/System)"
  41. ),
  42. "Borrado catastrofico: rm -rf sobre directorio raiz o de sistema",
  43. ),
  44. # Force push a ramas protegidas
  45. (
  46. re.compile(
  47. r"git\s+push\s+.*"
  48. r"(--force\b|-f\b)"
  49. r".*\b(main|master)\b"
  50. ),
  51. "Force push a rama protegida (main/master): riesgo de perdida de historial",
  52. ),
  53. # Variante: force push sin rama explicita (se asume rama actual)
  54. (
  55. re.compile(
  56. r"git\s+push\s+--force-with-lease\s*$"
  57. r"|git\s+push\s+-f\s*$"
  58. r"|git\s+push\s+--force\s*$"
  59. ),
  60. "Force push sin rama explicita: verifica que no estas en main/master",
  61. ),
  62. # Destruccion de base de datos
  63. (
  64. re.compile(r"DROP\s+(DATABASE|TABLE|SCHEMA)\s", re.IGNORECASE),
  65. "Destruccion de datos: DROP DATABASE/TABLE/SCHEMA",
  66. ),
  67. # Docker prune agresivo (cubre -af, -fa, -a -f, -f -a y combinaciones con otros flags)
  68. (
  69. re.compile(
  70. r"docker\s+system\s+prune\s+.*(-af|-fa)\b"
  71. r"|docker\s+system\s+prune\s+.*-a\b.*-f\b"
  72. r"|docker\s+system\s+prune\s+.*-f\b.*-a\b"
  73. ),
  74. "Docker system prune con -af: elimina todos los datos de contenedores",
  75. ),
  76. # Permisos inseguros
  77. (
  78. re.compile(r"chmod\s+(-R\s+)?777\s+/"),
  79. "Permisos inseguros: chmod 777 recursivo sobre directorio raiz",
  80. ),
  81. # Fork bomb (variantes comunes en bash)
  82. (
  83. re.compile(r":\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;?\s*:"),
  84. "Fork bomb: denegacion de servicio local",
  85. ),
  86. # Formateo de disco
  87. (
  88. re.compile(r"mkfs\.\w+\s+/dev/"),
  89. "Formateo de disco: mkfs sobre dispositivo de bloque",
  90. ),
  91. # dd sobre dispositivo de bloque
  92. (
  93. re.compile(r"dd\s+.*of=/dev/(sd|hd|nvme|vd|xvd)"),
  94. "Escritura directa a dispositivo de bloque con dd",
  95. ),
  96. # Escritura a dispositivo via redireccion
  97. (
  98. re.compile(r">\s*/dev/(sd|hd|nvme|vd|xvd)"),
  99. "Redireccion de salida a dispositivo de bloque",
  100. ),
  101. # git reset --hard a remote (destructivo en combinacion con push)
  102. (
  103. re.compile(r"git\s+reset\s+--hard\s+origin/(main|master)"),
  104. "git reset --hard a origin/main: descarta todos los cambios locales",
  105. ),
  106. ]
  107. _SAFE_ALFRED_HELPER_SUBCOMMANDS = frozenset({
  108. "allow-stop-once",
  109. "blocked",
  110. "consume-prefetch",
  111. "discuss",
  112. "in-progress",
  113. "map-codebase",
  114. "memory-ui",
  115. "next",
  116. "pause",
  117. "progress",
  118. "quick",
  119. "resume",
  120. "search",
  121. "standup",
  122. "validate",
  123. "verify",
  124. })
  125. _SHELL_CONTROL_TOKENS = frozenset({
  126. ";",
  127. "&&",
  128. "||",
  129. "|",
  130. ">",
  131. ">>",
  132. "<",
  133. "<<",
  134. "2>",
  135. "&>",
  136. "&>>",
  137. })
  138. _SHELL_CONTROL_SUBSTRINGS = (
  139. "$(",
  140. "`",
  141. )
  142. _SAFE_CAPTURE_SUFFIXES = (
  143. "2>&1",
  144. "2>/dev/null",
  145. "2>/dev/null 2>&1",
  146. )
  147. _DROP_SQL_REGEX = re.compile(r"\bDROP\s+(DATABASE|TABLE|SCHEMA)\b", re.IGNORECASE)
  148. _DEVICE_REDIRECT_REGEX = re.compile(r">\s*/dev/(sd|hd|nvme|vd|xvd)\w*", re.IGNORECASE)
  149. _SHELL_WRAPPERS = frozenset({"sh", "bash", "zsh"})
  150. _SQL_CLIENTS = frozenset({"psql", "mysql", "mariadb", "sqlite3", "duckdb"})
  151. def _command_basename(token: str) -> str:
  152. return os.path.basename(token or "")
  153. def _strip_leading_wrappers(tokens):
  154. """Elimina wrappers neutros al principio: sudo, env y variables inline."""
  155. idx = 0
  156. while idx < len(tokens):
  157. token = tokens[idx]
  158. base = _command_basename(token)
  159. if base == "sudo":
  160. idx += 1
  161. while idx < len(tokens) and tokens[idx].startswith("-"):
  162. idx += 1
  163. continue
  164. if base == "env":
  165. idx += 1
  166. while idx < len(tokens) and "=" in tokens[idx] and not tokens[idx].startswith("-"):
  167. idx += 1
  168. continue
  169. if "=" in token and not token.startswith("-"):
  170. name, _value = token.split("=", 1)
  171. if name.replace("_", "").isalnum():
  172. idx += 1
  173. continue
  174. break
  175. return tokens[idx:]
  176. def _strip_quoted_content(command: str) -> str:
  177. """Reemplaza el contenido entre comillas por espacios preservando operadores."""
  178. result = []
  179. in_single = False
  180. in_double = False
  181. escaped = False
  182. for char in command:
  183. if escaped:
  184. result.append(" " if (in_single or in_double) else char)
  185. escaped = False
  186. continue
  187. if char == "\\":
  188. escaped = True
  189. result.append(" " if (in_single or in_double) else char)
  190. continue
  191. if char == "'" and not in_double:
  192. in_single = not in_single
  193. result.append(" ")
  194. continue
  195. if char == '"' and not in_single:
  196. in_double = not in_double
  197. result.append(" ")
  198. continue
  199. result.append(" " if (in_single or in_double) else char)
  200. return "".join(result)
  201. def _has_shell_controls_outside_quotes(command: str) -> bool:
  202. """Detecta operadores de shell reales ignorando texto dentro de comillas.
  203. Permitimos helpers con argumentos quoted como:
  204. `--raw "login | signup"` o `--raw "funnel A > B"`.
  205. Lo que seguimos bloqueando es el uso real de operadores fuera de quotes,
  206. como `;`, `&&`, `||`, pipes y redirecciones.
  207. """
  208. in_single = False
  209. in_double = False
  210. escaped = False
  211. idx = 0
  212. while idx < len(command):
  213. char = command[idx]
  214. if escaped:
  215. escaped = False
  216. idx += 1
  217. continue
  218. if char == "\\":
  219. escaped = True
  220. idx += 1
  221. continue
  222. if char == "'" and not in_double:
  223. in_single = not in_single
  224. idx += 1
  225. continue
  226. if char == '"' and not in_single:
  227. in_double = not in_double
  228. idx += 1
  229. continue
  230. if in_single or in_double:
  231. idx += 1
  232. continue
  233. next_two = command[idx : idx + 2]
  234. if next_two in {"&&", "||", ">>", "<<"}:
  235. return True
  236. if char in {";", "|", ">", "<"}:
  237. return True
  238. idx += 1
  239. return False
  240. def _extract_shell_c_command(tokens):
  241. """Extrae el comando embebido en shell wrappers tipo sh -c / bash -lc."""
  242. core_tokens = _strip_leading_wrappers(tokens)
  243. if not core_tokens:
  244. return None
  245. base = _command_basename(core_tokens[0])
  246. if base not in _SHELL_WRAPPERS:
  247. return None
  248. idx = 1
  249. while idx < len(core_tokens):
  250. token = core_tokens[idx]
  251. if token == "-c" and idx + 1 < len(core_tokens):
  252. return core_tokens[idx + 1]
  253. if token.startswith("-") and "c" in token and idx + 1 < len(core_tokens):
  254. return core_tokens[idx + 1]
  255. idx += 1
  256. return None
  257. def _is_recursive_force_rm(tokens):
  258. has_recursive = False
  259. has_force = False
  260. for token in tokens:
  261. if token == "--recursive":
  262. has_recursive = True
  263. elif token == "--force":
  264. has_force = True
  265. elif token.startswith("-") and token != "-":
  266. flags = token[1:]
  267. has_recursive = has_recursive or ("r" in flags)
  268. has_force = has_force or ("f" in flags)
  269. return has_recursive and has_force
  270. def _is_sensitive_rm_target(target: str) -> bool:
  271. sensitive_roots = ("/", "/etc", "/usr", "/var", "/boot", "/System")
  272. home_markers = {"~", "~/", "$HOME", "${HOME}"}
  273. if target in home_markers or target.startswith("~/"):
  274. return True
  275. if target in {"/*", "~/*"}:
  276. return True
  277. if target in {"$HOME/*", "${HOME}/*"}:
  278. return True
  279. for root in sensitive_roots:
  280. if target == root or target == f"{root}/*":
  281. return True
  282. if root != "/" and target.startswith(root + "/"):
  283. return True
  284. return False
  285. def _is_absolute_permission_target(target: str) -> bool:
  286. return target == "/" or target.startswith("/")
  287. def _detect_rm(tokens):
  288. core_tokens = _strip_leading_wrappers(tokens)
  289. if not core_tokens or _command_basename(core_tokens[0]) != "rm":
  290. return None
  291. if not _is_recursive_force_rm(core_tokens[1:]):
  292. return None
  293. targets = [token for token in core_tokens[1:] if not token.startswith("-")]
  294. if any(_is_sensitive_rm_target(target) for target in targets):
  295. return "Borrado catastrofico: rm -rf sobre directorio raiz o de sistema"
  296. return None
  297. def _detect_git_push(tokens):
  298. core_tokens = _strip_leading_wrappers(tokens)
  299. if len(core_tokens) < 2:
  300. return None
  301. if _command_basename(core_tokens[0]) != "git" or core_tokens[1] != "push":
  302. return None
  303. force = any(
  304. token in {"--force", "--force-with-lease", "-f"}
  305. or (token.startswith("-") and "f" in token[1:])
  306. for token in core_tokens[2:]
  307. )
  308. if not force:
  309. return None
  310. protected_refs = {"main", "master", "origin/main", "origin/master", "refs/heads/main", "refs/heads/master"}
  311. if any(token in protected_refs for token in core_tokens[2:] if not token.startswith("-")):
  312. return "Force push a rama protegida (main/master): riesgo de perdida de historial"
  313. return "Force push sin rama explicita: verifica que no estas en main/master"
  314. def _detect_sql_drop(tokens):
  315. core_tokens = _strip_leading_wrappers(tokens)
  316. if not core_tokens:
  317. return None
  318. first = _command_basename(core_tokens[0]).lower()
  319. if first == "drop":
  320. if len(core_tokens) > 1 and core_tokens[1].upper() in {"DATABASE", "TABLE", "SCHEMA"}:
  321. return "Destruccion de datos: DROP DATABASE/TABLE/SCHEMA"
  322. return None
  323. if _command_basename(core_tokens[0]) not in _SQL_CLIENTS:
  324. return None
  325. if any(_DROP_SQL_REGEX.search(token) for token in core_tokens[1:]):
  326. return "Destruccion de datos: DROP DATABASE/TABLE/SCHEMA"
  327. return None
  328. def _detect_docker_prune(tokens):
  329. core_tokens = _strip_leading_wrappers(tokens)
  330. if len(core_tokens) < 3:
  331. return None
  332. if (
  333. _command_basename(core_tokens[0]) != "docker"
  334. or core_tokens[1] != "system"
  335. or core_tokens[2] != "prune"
  336. ):
  337. return None
  338. has_all = any(
  339. token in {"-a", "--all"} or (token.startswith("-") and "a" in token[1:])
  340. for token in core_tokens[3:]
  341. )
  342. has_force = any(
  343. token in {"-f", "--force"} or (token.startswith("-") and "f" in token[1:])
  344. for token in core_tokens[3:]
  345. )
  346. if has_all and has_force:
  347. return "Docker system prune con -af: elimina todos los datos de contenedores"
  348. return None
  349. def _detect_chmod(tokens):
  350. core_tokens = _strip_leading_wrappers(tokens)
  351. if len(core_tokens) < 3 or _command_basename(core_tokens[0]) != "chmod":
  352. return None
  353. mode_tokens = [token for token in core_tokens[1:] if not token.startswith("-")]
  354. if not mode_tokens or mode_tokens[0] != "777":
  355. return None
  356. targets = mode_tokens[1:]
  357. if any(_is_absolute_permission_target(target) for target in targets):
  358. return "Permisos inseguros: chmod 777 recursivo sobre directorio raiz"
  359. return None
  360. def _detect_fork_bomb(tokens):
  361. core_tokens = _strip_leading_wrappers(tokens)
  362. if core_tokens[:3] == [":(){", ":|:&", "};:"]:
  363. return "Fork bomb: denegacion de servicio local"
  364. return None
  365. def _detect_mkfs(tokens):
  366. core_tokens = _strip_leading_wrappers(tokens)
  367. if len(core_tokens) < 2:
  368. return None
  369. if not _command_basename(core_tokens[0]).startswith("mkfs."):
  370. return None
  371. if any(token.startswith("/dev/") for token in core_tokens[1:]):
  372. return "Formateo de disco: mkfs sobre dispositivo de bloque"
  373. return None
  374. def _detect_dd(tokens):
  375. core_tokens = _strip_leading_wrappers(tokens)
  376. if not core_tokens or _command_basename(core_tokens[0]) != "dd":
  377. return None
  378. if any(re.match(r"of=/dev/(sd|hd|nvme|vd|xvd)\w*", token) for token in core_tokens[1:]):
  379. return "Escritura directa a dispositivo de bloque con dd"
  380. return None
  381. def _detect_redirection_to_device(command: str):
  382. stripped = _strip_quoted_content(command)
  383. if _DEVICE_REDIRECT_REGEX.search(stripped):
  384. return "Redireccion de salida a dispositivo de bloque"
  385. return None
  386. def _detect_git_reset(tokens):
  387. core_tokens = _strip_leading_wrappers(tokens)
  388. if len(core_tokens) < 4:
  389. return None
  390. if _command_basename(core_tokens[0]) != "git" or core_tokens[1] != "reset":
  391. return None
  392. if "--hard" in core_tokens[2:] and any(
  393. token in {"origin/main", "origin/master"} for token in core_tokens[2:]
  394. ):
  395. return "git reset --hard a origin/main: descarta todos los cambios locales"
  396. return None
  397. def _find_dangerous_reason(command: str):
  398. """Devuelve la razon de bloqueo si el comando es realmente peligroso."""
  399. try:
  400. tokens = shlex.split(command)
  401. except ValueError:
  402. tokens = []
  403. embedded = _extract_shell_c_command(tokens) if tokens else None
  404. if embedded:
  405. return _find_dangerous_reason(embedded)
  406. detectors = (
  407. _detect_rm,
  408. _detect_git_push,
  409. _detect_sql_drop,
  410. _detect_docker_prune,
  411. _detect_chmod,
  412. _detect_fork_bomb,
  413. _detect_mkfs,
  414. _detect_dd,
  415. _detect_git_reset,
  416. )
  417. for detector in detectors:
  418. reason = detector(tokens)
  419. if reason:
  420. return reason
  421. return _detect_redirection_to_device(command)
  422. def _is_safe_alfred_helper_command(command: str) -> bool:
  423. """Reconoce helpers deterministas locales que Alfred puede autoaprobar.
  424. El objetivo es destrabar la primera ejecución headless de Claude Code para
  425. los comandos operativos helper-first. La allowlist es estrecha:
  426. - `python3`
  427. - wrapper local `.claude/alfred-continuity.py`
  428. - solo subcomandos deterministas y operativos
  429. - sin operadores de control de shell
  430. """
  431. normalized = command.strip()
  432. for suffix in _SAFE_CAPTURE_SUFFIXES:
  433. if normalized.endswith(suffix):
  434. normalized = normalized[: -len(suffix)].rstrip()
  435. break
  436. if any(marker in normalized for marker in _SHELL_CONTROL_SUBSTRINGS):
  437. return False
  438. if _has_shell_controls_outside_quotes(normalized):
  439. return False
  440. try:
  441. tokens = shlex.split(normalized)
  442. except ValueError:
  443. return False
  444. if len(tokens) < 3:
  445. return False
  446. if tokens[0] != "python3":
  447. return False
  448. if tokens[1] != ".claude/alfred-continuity.py":
  449. return False
  450. if tokens[2] not in _SAFE_ALFRED_HELPER_SUBCOMMANDS:
  451. return False
  452. if any(token in _SHELL_CONTROL_TOKENS for token in tokens):
  453. return False
  454. return True
  455. def main():
  456. """Punto de entrada del hook.
  457. Lee el JSON de stdin proporcionado por PreToolUse, extrae el comando
  458. de ``tool_input.command`` y lo compara contra la lista de patrones
  459. peligrosos. Si alguno coincide, bloquea la operacion con exit 2.
  460. """
  461. try:
  462. data = json.load(sys.stdin)
  463. except (ValueError, json.JSONDecodeError) as e:
  464. # Fail-closed: si no podemos parsear, bloquear por precaucion.
  465. # Un guard de seguridad que falla en abierto equivale a no tenerlo.
  466. print(
  467. f"[Alfred Dev] BLOQUEADO: no se pudo parsear la entrada del hook: {e}. "
  468. f"La guardia de comandos peligrosos bloquea por precaucion.",
  469. file=sys.stderr,
  470. )
  471. sys.exit(2)
  472. tool_input = data.get("tool_input", {})
  473. command = tool_input.get("command", "")
  474. if not command:
  475. sys.exit(0)
  476. if _is_safe_alfred_helper_command(command):
  477. json.dump(
  478. {
  479. "hookSpecificOutput": {
  480. "hookEventName": "PreToolUse",
  481. "permissionDecision": "allow",
  482. }
  483. },
  484. sys.stdout,
  485. )
  486. sys.exit(0)
  487. description = _find_dangerous_reason(command)
  488. if description:
  489. # Bloquear con aviso explicativo
  490. print(
  491. f"\n[Alfred Dev] COMANDO PELIGROSO BLOQUEADO\n\n"
  492. f" Comando: {command[:200]}\n"
  493. f" Riesgo: {description}\n\n"
  494. f" Si realmente necesitas ejecutar este comando, pidele\n"
  495. f" al usuario que lo ejecute manualmente en su terminal.\n",
  496. file=sys.stderr,
  497. )
  498. sys.exit(2)
  499. # Comando seguro, permitir
  500. sys.exit(0)
  501. if __name__ == "__main__":
  502. main()
install.ps1 · Bundled script · 441 lines · 1 finding marked
  1. # ---------------------------------------------------------------------------
  2. # Alfred Dev -- script de instalacion para Claude Code (Windows)
  3. #
  4. # Uso:
  5. # irm https://raw.githubusercontent.com/686f6c61/alfred-dev/main/install.ps1 | iex
    • Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
    • Line 5 on GitHub
  6. #
  7. # Que hace:
  8. # 1. Verifica que Claude Code esta instalado
  9. # 2. Registra globalmente en Claude Code la fuente GitHub del plugin
  10. # 3. Instala el plugin con claude plugin install
  11. # 4. No pisa ~/.claude/skills ni instala alias global /alfred
  12. # 5. Listo para usar: /alfred-dev:alfred
  13. #
  14. # El script delega toda la gestion en la CLI nativa de Claude Code
  15. # (claude plugin marketplace / claude plugin install) para registrar una
  16. # fuente GitHub personalizada, no oficial, y mantener compatibilidad futura.
  17. # ---------------------------------------------------------------------------
  18. $ErrorActionPreference = 'Stop'
  19. $Repo = "686f6c61/alfred-dev"
  20. $PluginName = "alfred-dev"
  21. $Version = "0.7.0"
  22. # -- Funciones auxiliares ---------------------------------------------------
  23. function Write-Info { param([string]$Msg) Write-Host ">" $Msg -ForegroundColor Blue }
  24. function Write-Ok { param([string]$Msg) Write-Host "+" $Msg -ForegroundColor Green }
  25. function Write-Err { param([string]$Msg) Write-Host "x" $Msg -ForegroundColor Red }
  26. function Get-CompatiblePython {
  27. $candidates = @(
  28. @{ Display = "py -3.13"; Command = "py"; LauncherArg = "-3.13" },
  29. @{ Display = "py -3.12"; Command = "py"; LauncherArg = "-3.12" },
  30. @{ Display = "py -3.11"; Command = "py"; LauncherArg = "-3.11" },
  31. @{ Display = "py -3.10"; Command = "py"; LauncherArg = "-3.10" },
  32. @{ Display = "python3"; Command = "python3" },
  33. @{ Display = "python"; Command = "python" }
  34. )
  35. foreach ($candidate in $candidates) {
  36. if (-not (Get-Command $candidate.Command -ErrorAction SilentlyContinue)) {
  37. continue
  38. }
  39. try {
  40. $args = @()
  41. if ($candidate.ContainsKey("LauncherArg")) {
  42. $args += $candidate.LauncherArg
  43. }
  44. $args += @(
  45. "-c",
  46. 'import sys; print(sys.executable); print("{}.{}".format(sys.version_info.major, sys.version_info.minor))'
  47. )
  48. $output = & $candidate.Command @args 2>$null
  49. if ($LASTEXITCODE -ne 0 -or $null -eq $output -or $output.Count -lt 2) {
  50. continue
  51. }
  52. $pythonPath = "$($output[0])".Trim()
  53. $version = "$($output[1])".Trim()
  54. $parts = $version -split '\.'
  55. if ($parts.Count -lt 2) {
  56. continue
  57. }
  58. $major = [int]$parts[0]
  59. $minor = [int]$parts[1]
  60. if ($major -gt 3 -or ($major -eq 3 -and $minor -ge 10)) {
  61. return @{
  62. DisplayCommand = $candidate.Display
  63. ExecutablePath = $pythonPath
  64. Version = $version
  65. }
  66. }
  67. }
  68. catch {
  69. continue
  70. }
  71. }
  72. return $null
  73. }
  74. function Write-TextFileAtomic {
  75. param([string]$Path, [string]$Content)
  76. $targetDir = Split-Path $Path -Parent
  77. $tmpFile = Join-Path $targetDir ".tmp-$([System.IO.Path]::GetRandomFileName())"
  78. try {
  79. [System.IO.File]::WriteAllText($tmpFile, $Content, [System.Text.Encoding]::UTF8)
  80. Move-Item -Path $tmpFile -Destination $Path -Force
  81. }
  82. catch {
  83. if (Test-Path $tmpFile) { Remove-Item $tmpFile -Force -ErrorAction SilentlyContinue }
  84. throw
  85. }
  86. }
  87. function Get-InstalledPluginRoot {
  88. param(
  89. [string]$ClaudeDir,
  90. [string]$PluginName,
  91. [string]$Version
  92. )
  93. $cacheDir = Join-Path $ClaudeDir "plugins/cache/$PluginName"
  94. $exact = Join-Path $cacheDir "$PluginName/$Version"
  95. $legacy = Join-Path $cacheDir $Version
  96. if (Test-Path $exact -PathType Container) { return $exact }
  97. if (Test-Path $legacy -PathType Container) { return $legacy }
  98. if (-not (Test-Path $cacheDir -PathType Container)) { return $null }
  99. $candidates = Get-ChildItem -Path $cacheDir -Filter plugin.json -Recurse -ErrorAction SilentlyContinue |
  100. Where-Object { $_.FullName -like "*\.claude-plugin\*" } |
  101. Sort-Object LastWriteTimeUtc -Descending
  102. foreach ($candidate in $candidates) {
  103. try {
  104. $data = (Get-Content $candidate.FullName -Raw -Encoding UTF8) | ConvertFrom-Json
  105. }
  106. catch {
  107. continue
  108. }
  109. if ($data.version -ne $Version) {
  110. continue
  111. }
  112. return Split-Path (Split-Path $candidate.FullName -Parent) -Parent
  113. }
  114. return $null
  115. }
  116. function Test-GlobalSourceRegistration {
  117. param(
  118. [string]$ClaudeDir,
  119. [string]$PluginName,
  120. [string]$Repo
  121. )
  122. $knownMarketplaces = Join-Path $ClaudeDir "plugins/known_marketplaces.json"
  123. if (-not (Test-Path $knownMarketplaces -PathType Leaf)) {
  124. return $false
  125. }
  126. try {
  127. $data = (Get-Content $knownMarketplaces -Raw -Encoding UTF8) | ConvertFrom-Json
  128. }
  129. catch {
  130. return $false
  131. }
  132. if (-not $data.PSObject.Properties.Name.Contains($PluginName)) {
  133. return $false
  134. }
  135. $entry = $data.$PluginName
  136. return $entry.source.source -eq "github" -and $entry.source.repo -eq $Repo
  137. }
  138. function Normalize-ToUserScopeInstallation {
  139. param(
  140. [string]$PluginName,
  141. [string]$PluginKey
  142. )
  143. # Alfred Dev solo soporta instalacion global de usuario. Si alguien lo
  144. # instalo antes en local/project, limpiamos ese rastro en el contexto actual
  145. # antes de reinstalar con --scope user.
  146. & claude plugin uninstall $PluginKey --scope local 2>&1 | Out-Null
  147. & claude plugin uninstall $PluginKey --scope project 2>&1 | Out-Null
  148. & claude plugin marketplace remove $PluginName --scope local 2>&1 | Out-Null
  149. & claude plugin marketplace remove $PluginName --scope project 2>&1 | Out-Null
  150. Write-Ok "Scopes local/project normalizados; Alfred se instalara como usuario global"
  151. }
  152. function Remove-StaleUserMarketplaceCheckout {
  153. param(
  154. [string]$ClaudeDir,
  155. [string]$PluginName
  156. )
  157. $marketplaceDir = Join-Path $ClaudeDir "plugins/marketplaces/$PluginName"
  158. if (Test-Path $marketplaceDir -PathType Container) {
  159. Remove-Item -Path $marketplaceDir -Recurse -Force
  160. Write-Ok "Checkout local del marketplace limpiado para evitar cache obsoleta"
  161. }
  162. }
  163. function Update-UserMarketplace {
  164. param([string]$PluginName)
  165. $updateResult = & claude plugin marketplace update $PluginName 2>&1
  166. if ($LASTEXITCODE -eq 0) {
  167. Write-Ok "Marketplace local actualizado"
  168. }
  169. else {
  170. Write-Info "No se pudo ejecutar 'claude plugin marketplace update'; continuo con el checkout recien registrado"
  171. }
  172. }
  173. function Assert-UserScopeInstallation {
  174. param([string]$PluginKey)
  175. $pluginListJson = & claude plugin list --json 2>$null
  176. if ($LASTEXITCODE -ne 0) {
  177. Write-Err "No se pudo confirmar el scope global con 'claude plugin list --json'"
  178. Write-Err "Alfred Dev debe quedar instalado como scope user."
  179. exit 1
  180. }
  181. try {
  182. $entries = @(($pluginListJson | Out-String) | ConvertFrom-Json)
  183. }
  184. catch {
  185. Write-Err "JSON invalido en claude plugin list --json: $_"
  186. exit 1
  187. }
  188. $matches = @($entries | Where-Object { $_.id -eq $PluginKey })
  189. if ($matches.Count -eq 0) {
  190. Write-Err "No aparece $PluginKey en claude plugin list --json"
  191. exit 1
  192. }
  193. $activeNonUser = @($matches | Where-Object { $_.enabled -eq $true -and $_.scope -ne "user" })
  194. if ($activeNonUser.Count -gt 0) {
  195. $details = @($activeNonUser | ForEach-Object {
  196. "scope=$($_.scope) projectPath=$($_.projectPath)"
  197. }) -join ", "
  198. Write-Err "Hay instalaciones activas no globales de ${PluginKey}: $details"
  199. exit 1
  200. }
  201. $enabledUser = @($matches | Where-Object { $_.enabled -eq $true -and $_.scope -eq "user" })
  202. if ($enabledUser.Count -eq 0) {
  203. $scopes = @($matches | ForEach-Object { "$($_.scope)" }) -join ", "
  204. Write-Err "$PluginKey existe, pero no hay entrada enabled con scope user. Scopes vistos: $scopes"
  205. exit 1
  206. }
  207. $staleNonUser = @($matches | Where-Object { $_.enabled -ne $true -and $_.scope -ne "user" })
  208. if ($staleNonUser.Count -gt 0) {
  209. $details = @($staleNonUser | ForEach-Object {
  210. "scope=$($_.scope) projectPath=$($_.projectPath)"
  211. }) -join ", "
  212. Write-Info "AVISO: quedan entradas antiguas no activas de ${PluginKey}: $details"
  213. }
  214. Write-Ok "Instalacion global de usuario confirmada (--scope user)"
  215. }
  216. # -- Verificaciones ---------------------------------------------------------
  217. $Python = Get-CompatiblePython
  218. if ($null -eq $Python) {
  219. Write-Err "No se encontro Python 3.10 o superior"
  220. Write-Err "Se buscaron: py -3.13, py -3.12, py -3.11, py -3.10, python3, python"
  221. Write-Err "Alfred Dev necesita Python para hooks, core y MCP tambien en Windows"
  222. exit 1
  223. }
  224. Write-Ok "Python $($Python.Version) detectado ($($Python.DisplayCommand))"
  225. if (-not $env:USERPROFILE -or -not (Test-Path $env:USERPROFILE -PathType Container)) {
  226. Write-Err "USERPROFILE no esta definido o no apunta a un directorio valido"
  227. exit 1
  228. }
  229. $ClaudeDir = Join-Path $env:USERPROFILE ".claude"
  230. if (-not (Test-Path $ClaudeDir)) {
  231. Write-Err "No se encontro el directorio $ClaudeDir"
  232. Write-Err "Asegurate de tener Claude Code instalado: https://code.claude.com/docs/en/setup"
  233. exit 1
  234. }
  235. if (-not (Get-Command claude -ErrorAction SilentlyContinue)) {
  236. Write-Err "El comando 'claude' no esta disponible en el PATH"
  237. Write-Err "Asegurate de tener Claude Code instalado y accesible desde la terminal"
  238. exit 1
  239. }
  240. # -- Instalacion ------------------------------------------------------------
  241. Write-Host ""
  242. Write-Host "Alfred Dev" -ForegroundColor White -NoNewline
  243. Write-Host " v$Version" -ForegroundColor DarkGray
  244. Write-Host "Plugin de ingenieria de software automatizada" -ForegroundColor DarkGray
  245. Write-Host ""
  246. # -- 1. Registrar fuente global en Claude Code ------------------------------
  247. Write-Info "Registrando fuente GitHub global en Claude Code..."
  248. $pluginKey = "$PluginName@$PluginName"
  249. Normalize-ToUserScopeInstallation -PluginName $PluginName -PluginKey $pluginKey
  250. $pluginList = & claude plugin list 2>&1
  251. if ($pluginList -match [regex]::Escape($pluginKey)) {
  252. & claude plugin uninstall $pluginKey --scope user 2>&1 | Out-Null
  253. }
  254. $marketplaceList = & claude plugin marketplace list 2>&1
  255. if ($marketplaceList -match $PluginName) {
  256. & claude plugin marketplace remove $PluginName --scope user 2>&1 | Out-Null
  257. }
  258. Remove-StaleUserMarketplaceCheckout -ClaudeDir $ClaudeDir -PluginName $PluginName
  259. $marketplaceResult = & claude plugin marketplace add $Repo --scope user 2>&1
  260. if ($LASTEXITCODE -eq 0) {
  261. Write-Ok "Fuente GitHub declarada"
  262. }
  263. else {
  264. Write-Err "No se pudo registrar la fuente GitHub"
  265. Write-Err "Verifica tu conexion a internet y que el repositorio sea accesible:"
  266. Write-Err " https://github.com/$Repo"
  267. exit 1
  268. }
  269. if (Test-GlobalSourceRegistration -ClaudeDir $ClaudeDir -PluginName $PluginName -Repo $Repo) {
  270. Write-Ok "Fuente GitHub registrada globalmente"
  271. }
  272. else {
  273. Write-Info "La CLI respondio OK, pero la fuente no quedo registrada; reintentando..."
  274. & claude plugin marketplace remove $PluginName --scope user 2>&1 | Out-Null
  275. $marketplaceResult = & claude plugin marketplace add $Repo --scope user 2>&1
  276. if ($LASTEXITCODE -eq 0 -and (Test-GlobalSourceRegistration -ClaudeDir $ClaudeDir -PluginName $PluginName -Repo $Repo)) {
  277. Write-Ok "Fuente GitHub registrada globalmente tras reintento"
  278. }
  279. else {
  280. Write-Err "Claude Code no dejo registrada la fuente global del plugin"
  281. Write-Err "Fichero esperado: $(Join-Path $ClaudeDir 'plugins/known_marketplaces.json')"
  282. Write-Err "Prueba a ejecutar manualmente:"
  283. Write-Err " claude plugin marketplace remove $PluginName --scope user"
  284. Write-Err " claude plugin marketplace add $Repo --scope user"
  285. exit 1
  286. }
  287. }
  288. Update-UserMarketplace -PluginName $PluginName
  289. # -- 2. Instalar plugin -----------------------------------------------------
  290. Write-Info "Instalando plugin..."
  291. $installResult = & claude plugin install $pluginKey --scope user 2>&1
  292. if ($LASTEXITCODE -eq 0) {
  293. Write-Ok "Plugin instalado y habilitado"
  294. }
  295. else {
  296. Write-Err "No se pudo instalar el plugin"
  297. Write-Err "Puedes intentar instalarlo manualmente:"
  298. Write-Err " claude plugin marketplace add $Repo --scope user"
  299. Write-Err " claude plugin install $pluginKey --scope user"
  300. exit 1
  301. }
  302. # -- 3. Parchear hooks y MCP con el Python detectado -----------------------
  303. $PluginRoot = Get-InstalledPluginRoot -ClaudeDir $ClaudeDir -PluginName $PluginName -Version $Version
  304. $hooksJson = $null
  305. $mcpJson = $null
  306. Write-Info "Usa /alfred-dev:alfred o /alfred-dev:feature. No se pisa ~/.claude/skills."
  307. Assert-UserScopeInstallation -PluginKey $pluginKey
  308. if ($PluginRoot) {
  309. $hooksPath = Join-Path $PluginRoot "hooks/hooks.json"
  310. $mcpPath = Join-Path $PluginRoot ".mcp.json"
  311. if (Test-Path $hooksPath -PathType Leaf) {
  312. $hooksJson = Get-Item $hooksPath
  313. }
  314. if (Test-Path $mcpPath -PathType Leaf) {
  315. $mcpJson = Get-Item $mcpPath
  316. }
  317. }
  318. if ($hooksJson) {
  319. $hooksData = (Get-Content $hooksJson.FullName -Raw -Encoding UTF8) | ConvertFrom-Json
  320. $patchedHooks = $false
  321. $quotedPython = '"' + $Python.ExecutablePath + '" ${CLAUDE_PLUGIN_ROOT}'
  322. foreach ($eventGroup in $hooksData.hooks.PSObject.Properties) {
  323. foreach ($matcher in $eventGroup.Value) {
  324. if (-not $matcher.hooks) { continue }
  325. foreach ($hook in $matcher.hooks) {
  326. if ($hook.type -ne 'command' -or -not $hook.command) { continue }
  327. if ($hook.command -eq 'python3') {
  328. $hook.command = $Python.ExecutablePath
  329. $patchedHooks = $true
  330. continue
  331. }
  332. if ($hook.command -match 'python3 \$\{CLAUDE_PLUGIN_ROOT\}') {
  333. $hook.command = $hook.command -replace 'python3 \$\{CLAUDE_PLUGIN_ROOT\}', $quotedPython
  334. $patchedHooks = $true
  335. }
  336. }
  337. }
  338. }
  339. if ($patchedHooks) {
  340. Write-TextFileAtomic $hooksJson.FullName ($hooksData | ConvertTo-Json -Depth 20)
  341. Write-Ok "hooks.json parcheado para usar $($Python.ExecutablePath)"
  342. }
  343. }
  344. else {
  345. Write-Info "Aviso: no se encontro hooks.json en la instalacion activa para parchear Python"
  346. }
  347. if ($mcpJson) {
  348. $mcpData = (Get-Content $mcpJson.FullName -Raw -Encoding UTF8) | ConvertFrom-Json
  349. $mcpServers = $mcpData
  350. if ($mcpData.PSObject.Properties.Name.Contains("mcpServers")) {
  351. $mcpServers = $mcpData.mcpServers
  352. }
  353. if ($mcpServers.'alfred-memory'.command -ne $Python.ExecutablePath) {
  354. $mcpServers.'alfred-memory'.command = $Python.ExecutablePath
  355. Write-TextFileAtomic $mcpJson.FullName ($mcpData | ConvertTo-Json -Depth 20)
  356. Write-Ok ".mcp.json parcheado para usar $($Python.ExecutablePath)"
  357. }
  358. }
  359. else {
  360. Write-Info "Aviso: no se encontro .mcp.json en la instalacion activa para parchear Python"
  361. }
  362. # -- Resultado --------------------------------------------------------------
  363. Write-Host ""
  364. Write-Host "Instalacion completada" -ForegroundColor Green
  365. Write-Host ""
  366. Write-Host " En Claude Code, ejecuta /reload-plugins y despues:"
  367. Write-Host " /alfred-dev:alfred" -ForegroundColor White
  368. Write-Host " Estado: /alfred-dev:progress · retomar: /alfred-dev:retomar" -ForegroundColor DarkGray
  369. Write-Host ""
  370. Write-Host " Si /reload-plugins avisa por MCP/coste de cache o no aparece el plugin, reinicia Claude Code." -ForegroundColor DarkGray
  371. Write-Host " Repositorio: https://github.com/$Repo" -ForegroundColor DarkGray
  372. Write-Host " Documentacion: https://alfred-dev.com" -ForegroundColor DarkGray
  373. Write-Host ""
install.sh · Bundled script · 522 lines · 1 finding marked
  1. #!/usr/bin/env bash
  2. # ---------------------------------------------------------------------------
  3. # Alfred Dev -- script de instalacion para Claude Code
  4. #
  5. # Uso:
  6. # curl -fsSL https://raw.githubusercontent.com/686f6c61/alfred-dev/main/install.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 6 on GitHub
  7. # bash ./install.sh
  8. #
  9. # Que hace:
  10. # 1. Verifica que Claude Code esta instalado
  11. # 2. Registra globalmente en Claude Code la fuente GitHub del plugin
  12. # 3. Instala el plugin con claude plugin install
  13. # 4. No pisa ~/.claude/skills ni instala alias global /alfred
  14. # 5. Listo para usar: /alfred-dev:alfred
  15. #
  16. # El script delega toda la gestion en la CLI nativa de Claude Code
  17. # (claude plugin marketplace / claude plugin install) para registrar una
  18. # fuente GitHub personalizada, no oficial, y mantener compatibilidad futura.
  19. # ---------------------------------------------------------------------------
  20. set -euo pipefail
  21. REPO="686f6c61/alfred-dev"
  22. PLUGIN_NAME="alfred-dev"
  23. VERSION="0.7.0"
  24. # -- Colores ----------------------------------------------------------------
  25. RED='\033[0;31m'
  26. GREEN='\033[0;32m'
  27. BLUE='\033[0;34m'
  28. DIM='\033[2m'
  29. BOLD='\033[1m'
  30. NC='\033[0m'
  31. info() { printf "${BLUE}>${NC} %s\n" "$1"; }
  32. ok() { printf "${GREEN}+${NC} %s\n" "$1"; }
  33. error() { printf "${RED}x${NC} %s\n" "$1" >&2; }
  34. resolve_installed_plugin_root() {
  35. local cache_dir="${HOME}/.claude/plugins/cache/${PLUGIN_NAME}"
  36. local exact="${cache_dir}/${PLUGIN_NAME}/${VERSION}"
  37. local legacy="${cache_dir}/${VERSION}"
  38. if [[ -d "${exact}" ]]; then
  39. printf '%s\n' "${exact}"
  40. return 0
  41. fi
  42. if [[ -d "${legacy}" ]]; then
  43. printf '%s\n' "${legacy}"
  44. return 0
  45. fi
  46. "${PYTHON_CMD}" - "${cache_dir}" "${VERSION}" <<'PYEOF'
  47. import json
  48. import os
  49. import sys
  50. cache_dir, target_version = sys.argv[1:3]
  51. candidates = []
  52. for root, _dirs, files in os.walk(cache_dir):
  53. if "plugin.json" not in files or ".claude-plugin" not in root:
  54. continue
  55. plugin_json = os.path.join(root, "plugin.json")
  56. try:
  57. with open(plugin_json, "r", encoding="utf-8") as fh:
  58. version = json.load(fh).get("version")
  59. except (OSError, json.JSONDecodeError):
  60. continue
  61. if version != target_version:
  62. continue
  63. plugin_root = os.path.dirname(root)
  64. try:
  65. mtime = os.path.getmtime(plugin_json)
  66. except OSError:
  67. mtime = 0
  68. candidates.append((mtime, plugin_root))
  69. if not candidates:
  70. sys.exit(1)
  71. candidates.sort(key=lambda item: item[0], reverse=True)
  72. print(candidates[0][1])
  73. PYEOF
  74. }
  75. is_global_source_registered() {
  76. local known_marketplaces_file="${HOME}/.claude/plugins/known_marketplaces.json"
  77. [[ -f "${known_marketplaces_file}" ]] || return 1
  78. "${PYTHON_CMD}" - "${known_marketplaces_file}" "${PLUGIN_NAME}" "${REPO}" <<'PYEOF'
  79. import json
  80. import sys
  81. path, plugin_name, repo = sys.argv[1:4]
  82. try:
  83. with open(path, "r", encoding="utf-8") as fh:
  84. data = json.load(fh)
  85. except (OSError, json.JSONDecodeError):
  86. sys.exit(1)
  87. entry = data.get(plugin_name)
  88. source = entry.get("source", {}) if isinstance(entry, dict) else {}
  89. if source.get("source") == "github" and source.get("repo") == repo:
  90. sys.exit(0)
  91. sys.exit(1)
  92. PYEOF
  93. }
  94. normalize_to_user_scope_installation() {
  95. # Alfred Dev solo soporta instalacion global de usuario. Si alguien lo
  96. # instalo antes en local/project, limpiamos ese rastro en el contexto actual
  97. # antes de reinstalar con --scope user.
  98. claude plugin uninstall "${PLUGIN_NAME}@${PLUGIN_NAME}" --scope local >/dev/null 2>&1 || true
  99. claude plugin uninstall "${PLUGIN_NAME}@${PLUGIN_NAME}" --scope project >/dev/null 2>&1 || true
  100. claude plugin marketplace remove "${PLUGIN_NAME}" --scope local >/dev/null 2>&1 || true
  101. claude plugin marketplace remove "${PLUGIN_NAME}" --scope project >/dev/null 2>&1 || true
  102. ok "Scopes local/project normalizados; Alfred se instalara como usuario global"
  103. }
  104. remove_stale_user_marketplace_checkout() {
  105. local marketplace_dir="${HOME}/.claude/plugins/marketplaces/${PLUGIN_NAME}"
  106. if [[ -d "${marketplace_dir}" ]]; then
  107. rm -rf "${marketplace_dir}"
  108. ok "Checkout local del marketplace limpiado para evitar cache obsoleta"
  109. fi
  110. }
  111. refresh_user_marketplace() {
  112. # Claude Code puede conservar un clon local obsoleto del marketplace aunque
  113. # 'plugin install' termine correctamente. Forzamos refresh antes de instalar
  114. # para que cache/alfred-dev materialice la version publicada actual.
  115. if claude plugin marketplace update "${PLUGIN_NAME}" 2>&1; then
  116. ok "Marketplace local actualizado"
  117. else
  118. info "No se pudo ejecutar 'claude plugin marketplace update'; continuo con el checkout recien registrado"
  119. fi
  120. }
  121. verify_user_scope_installation() {
  122. local plugin_key="${PLUGIN_NAME}@${PLUGIN_NAME}"
  123. local list_json
  124. local verify_output
  125. if ! list_json=$(claude plugin list --json 2>/dev/null); then
  126. error "No se pudo confirmar el scope global con 'claude plugin list --json'"
  127. error "Alfred Dev debe quedar instalado como scope user."
  128. return 1
  129. fi
  130. if verify_output=$(
  131. CLAUDE_PLUGIN_LIST_JSON="${list_json}" "${PYTHON_CMD}" - "${plugin_key}" <<'PYEOF'
  132. import json
  133. import os
  134. import sys
  135. plugin_key = sys.argv[1]
  136. try:
  137. entries = json.loads(os.environ.get("CLAUDE_PLUGIN_LIST_JSON", ""))
  138. except json.JSONDecodeError as exc:
  139. print(f"JSON invalido en claude plugin list --json: {exc}", file=sys.stderr)
  140. sys.exit(1)
  141. if not isinstance(entries, list):
  142. print("claude plugin list --json no devolvio una lista", file=sys.stderr)
  143. sys.exit(1)
  144. matches = [entry for entry in entries if isinstance(entry, dict) and entry.get("id") == plugin_key]
  145. if not matches:
  146. print(f"No aparece {plugin_key} en claude plugin list --json", file=sys.stderr)
  147. sys.exit(1)
  148. active_non_user = [
  149. entry for entry in matches
  150. if entry.get("enabled") is True and entry.get("scope") != "user"
  151. ]
  152. if active_non_user:
  153. details = ", ".join(
  154. f"scope={entry.get('scope', 'desconocido')} projectPath={entry.get('projectPath', '')}"
  155. for entry in active_non_user
  156. )
  157. print(f"Hay instalaciones activas no globales de {plugin_key}: {details}", file=sys.stderr)
  158. sys.exit(1)
  159. enabled_user = [
  160. entry for entry in matches
  161. if entry.get("enabled") is True and entry.get("scope") == "user"
  162. ]
  163. if not enabled_user:
  164. scopes = ", ".join(str(entry.get("scope", "desconocido")) for entry in matches)
  165. print(f"{plugin_key} existe, pero no hay entrada enabled con scope user. Scopes vistos: {scopes}", file=sys.stderr)
  166. sys.exit(1)
  167. stale_non_user = [
  168. entry for entry in matches
  169. if entry.get("enabled") is not True and entry.get("scope") != "user"
  170. ]
  171. if stale_non_user:
  172. details = ", ".join(
  173. f"scope={entry.get('scope', 'desconocido')} projectPath={entry.get('projectPath', '')}"
  174. for entry in stale_non_user
  175. )
  176. print(f"AVISO: quedan entradas antiguas no activas de {plugin_key}: {details}")
  177. PYEOF
  178. ); then
  179. if [[ -n "${verify_output}" ]]; then
  180. info "${verify_output}"
  181. fi
  182. ok "Instalacion global de usuario confirmada (--scope user)"
  183. return 0
  184. fi
  185. error "${verify_output}"
  186. return 1
  187. }
  188. # -- Verificaciones ---------------------------------------------------------
  189. # Python 3.10+ es necesario para los hooks y el core del plugin.
  190. # En macOS, /usr/bin/python3 suele ser 3.9 (Apple). Los usuarios pueden
  191. # tener 3.10+ via Homebrew, pyenv o instalador oficial como python3.13,
  192. # python3.12, etc. Buscamos la mejor version disponible.
  193. PYTHON_CMD=""
  194. PYTHON_VERSION=""
  195. # Buscar entre los candidatos mas comunes en orden descendente
  196. for candidate in python3 python3.13 python3.12 python3.11 python3.10; do
  197. if command -v "$candidate" &>/dev/null; then
  198. ver=$("$candidate" -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')" 2>/dev/null || echo "0.0")
  199. major=$(echo "$ver" | cut -d. -f1)
  200. minor=$(echo "$ver" | cut -d. -f2)
  201. if [[ "$major" -ge 3 ]] && [[ "$minor" -ge 10 ]]; then
  202. PYTHON_CMD="$candidate"
  203. PYTHON_VERSION="$ver"
  204. break
  205. fi
  206. fi
  207. done
  208. if [[ -z "$PYTHON_CMD" ]]; then
  209. # Ultimo intento: Homebrew en las rutas habituales de macOS
  210. for brew_path in /opt/homebrew/bin /usr/local/bin; do
  211. for candidate in python3.13 python3.12 python3.11 python3.10 python3; do
  212. full="${brew_path}/${candidate}"
  213. if [[ -x "$full" ]]; then
  214. ver=$("$full" -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')" 2>/dev/null || echo "0.0")
  215. major=$(echo "$ver" | cut -d. -f1)
  216. minor=$(echo "$ver" | cut -d. -f2)
  217. if [[ "$major" -ge 3 ]] && [[ "$minor" -ge 10 ]]; then
  218. PYTHON_CMD="$full"
  219. PYTHON_VERSION="$ver"
  220. break 2
  221. fi
  222. fi
  223. done
  224. done
  225. fi
  226. if [[ -z "$PYTHON_CMD" ]]; then
  227. error "No se encontro Python 3.10 o superior"
  228. error "Se buscaron: python3, python3.13, python3.12, python3.11, python3.10"
  229. error "Tambien en /opt/homebrew/bin y /usr/local/bin"
  230. error ""
  231. error "Instala Python desde https://www.python.org/downloads/"
  232. error "o con Homebrew: brew install python@3.12"
  233. exit 1
  234. fi
  235. ok "Python $PYTHON_VERSION detectado ($PYTHON_CMD)"
  236. # Si python3 del PATH no es el que encontramos, avisar al usuario
  237. DEFAULT_PY_VER=$(python3 -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')" 2>/dev/null || echo "0.0")
  238. if [[ "$PYTHON_CMD" != "python3" ]] && [[ "$DEFAULT_PY_VER" != "$PYTHON_VERSION" ]]; then
  239. info "Nota: 'python3' en tu PATH es $DEFAULT_PY_VER (demasiado antiguo)"
  240. info "Los hooks del plugin usaran '$PYTHON_CMD' en su lugar"
  241. fi
  242. if [[ -z "${HOME:-}" ]] || [[ ! -d "${HOME}" ]]; then
  243. error "La variable HOME no esta definida o no apunta a un directorio valido"
  244. exit 1
  245. fi
  246. if [ ! -d "${HOME}/.claude" ]; then
  247. error "No se encontro el directorio ~/.claude"
  248. error "Asegurate de tener Claude Code instalado: https://code.claude.com/docs/en/setup"
  249. exit 1
  250. fi
  251. if ! command -v claude &>/dev/null; then
  252. error "El comando 'claude' no esta disponible en el PATH"
  253. error "Asegurate de tener Claude Code instalado y accesible desde la terminal"
  254. exit 1
  255. fi
  256. # -- Instalacion ------------------------------------------------------------
  257. printf "\n${BOLD}Alfred Dev${NC} ${DIM}v${VERSION}${NC}\n"
  258. printf "${DIM}Plugin de ingenieria de software automatizada${NC}\n\n"
  259. # -- 1. Registrar fuente global en Claude Code ------------------------------
  260. # Si ya existe, la actualizamos eliminandola primero para forzar un refresh
  261. # del registro global y del cache con los ficheros mas recientes del repo.
  262. info "Registrando fuente GitHub global en Claude Code..."
  263. normalize_to_user_scope_installation
  264. # Si existe una instalacion previa, la quitamos antes de refrescar el
  265. # marketplace. Esto evita estados intermedios donde el plugin sigue apuntando
  266. # a un marketplace ya corrupto o incompleto en disco.
  267. if claude plugin list 2>/dev/null | grep -q "${PLUGIN_NAME}@${PLUGIN_NAME}"; then
  268. claude plugin uninstall "${PLUGIN_NAME}@${PLUGIN_NAME}" --scope user >/dev/null 2>&1 || true
  269. fi
  270. if claude plugin marketplace list 2>/dev/null | grep -q "${PLUGIN_NAME}"; then
  271. claude plugin marketplace remove "${PLUGIN_NAME}" --scope user >/dev/null 2>&1 || true
  272. fi
  273. remove_stale_user_marketplace_checkout
  274. if claude plugin marketplace add "${REPO}" --scope user 2>&1; then
  275. ok "Fuente GitHub declarada"
  276. else
  277. error "No se pudo registrar la fuente GitHub"
  278. error "Verifica tu conexion a internet y que el repositorio sea accesible:"
  279. error " https://github.com/${REPO}"
  280. exit 1
  281. fi
  282. # Lo que vuelve global la instalacion no es una carpeta concreta, sino que
  283. # Claude Code deje registrada la fuente en known_marketplaces.json.
  284. if is_global_source_registered; then
  285. ok "Fuente GitHub registrada globalmente"
  286. else
  287. info "La CLI respondio OK, pero la fuente no quedo registrada; reintentando..."
  288. claude plugin marketplace remove "${PLUGIN_NAME}" --scope user >/dev/null 2>&1 || true
  289. if claude plugin marketplace add "${REPO}" --scope user 2>&1 && is_global_source_registered; then
  290. ok "Fuente GitHub registrada globalmente tras reintento"
  291. else
  292. error "Claude Code no dejo registrada la fuente global del plugin"
  293. error "Fichero esperado: ${HOME}/.claude/plugins/known_marketplaces.json"
  294. error "Prueba a ejecutar manualmente:"
  295. error " claude plugin marketplace remove ${PLUGIN_NAME} --scope user"
  296. error " claude plugin marketplace add ${REPO} --scope user"
  297. exit 1
  298. fi
  299. fi
  300. refresh_user_marketplace
  301. # -- 2. Instalar plugin -----------------------------------------------------
  302. info "Instalando plugin..."
  303. if claude plugin install "${PLUGIN_NAME}@${PLUGIN_NAME}" --scope user 2>&1; then
  304. ok "Plugin instalado y habilitado"
  305. else
  306. error "No se pudo instalar el plugin"
  307. error "Puedes intentar instalarlo manualmente:"
  308. error " claude plugin marketplace add ${REPO} --scope user"
  309. error " claude plugin install ${PLUGIN_NAME}@${PLUGIN_NAME} --scope user"
  310. exit 1
  311. fi
  312. info "Usa /alfred-dev:alfred o /alfred-dev:feature. No se pisa ~/.claude/skills."
  313. verify_user_scope_installation
  314. # -- 3. Parchear hooks y MCP si python3 no es 3.10+ ------------------------
  315. # Si el python3 por defecto del sistema es demasiado antiguo pero encontramos
  316. # una version compatible (python3.12, python3.11, etc.), actualizamos la
  317. # configuracion instalada para que hooks y el MCP usen esa version concreta.
  318. if [[ "$PYTHON_CMD" != "python3" ]]; then
  319. _patch_in_place() {
  320. local file="$1"
  321. local expression="$2"
  322. if sed -i.bak "$expression" "$file" 2>/dev/null; then
  323. rm -f "${file}.bak"
  324. return 0
  325. fi
  326. # macOS sed tiene sintaxis diferente para -i
  327. sed -i '' "$expression" "$file" 2>/dev/null
  328. }
  329. # Obtener la ruta absoluta del Python compatible
  330. PYTHON_ABS=$(command -v "$PYTHON_CMD" 2>/dev/null || echo "$PYTHON_CMD")
  331. # Resolver de forma determinista la raiz del plugin recien instalado.
  332. # Si coexisten varias versiones en cache, preferimos la ruta exacta de
  333. # la version que acaba de instalarse y, en ultimo termino, la mas reciente
  334. # cuyo plugin.json declare esa version.
  335. PLUGIN_ROOT=$(resolve_installed_plugin_root 2>/dev/null || true)
  336. HOOKS_JSON=""
  337. MCP_JSON=""
  338. if [[ -n "${PLUGIN_ROOT}" ]]; then
  339. HOOKS_JSON="${PLUGIN_ROOT}/hooks/hooks.json"
  340. MCP_JSON="${PLUGIN_ROOT}/.mcp.json"
  341. fi
  342. if [[ -f "$HOOKS_JSON" ]]; then
  343. if "${PYTHON_CMD}" - "$HOOKS_JSON" "$PYTHON_ABS" <<'PYEOF'
  344. import json
  345. import os
  346. import sys
  347. import tempfile
  348. path, python_abs = sys.argv[1:3]
  349. with open(path, "r", encoding="utf-8") as fh:
  350. data = json.load(fh)
  351. patched = False
  352. for event_group in data.get("hooks", {}).values():
  353. if not isinstance(event_group, list):
  354. continue
  355. for matcher in event_group:
  356. if not isinstance(matcher, dict):
  357. continue
  358. for hook in matcher.get("hooks", []):
  359. if not isinstance(hook, dict) or hook.get("type") != "command":
  360. continue
  361. command = hook.get("command")
  362. if command == "python3":
  363. hook["command"] = python_abs
  364. patched = True
  365. elif isinstance(command, str) and "python3 ${CLAUDE_PLUGIN_ROOT}" in command:
  366. hook["command"] = command.replace(
  367. "python3 ${CLAUDE_PLUGIN_ROOT}",
  368. f"{python_abs} ${{CLAUDE_PLUGIN_ROOT}}",
  369. )
  370. patched = True
  371. if not patched:
  372. raise SystemExit("hooks.json no contiene hooks Python parcheables")
  373. directory = os.path.dirname(path)
  374. fd, tmp_path = tempfile.mkstemp(prefix=".tmp-plugin-", dir=directory)
  375. try:
  376. with os.fdopen(fd, "w", encoding="utf-8") as fh:
  377. json.dump(data, fh, ensure_ascii=False, indent=2)
  378. fh.write("\n")
  379. os.replace(tmp_path, path)
  380. except Exception:
  381. try:
  382. os.unlink(tmp_path)
  383. except OSError:
  384. pass
  385. raise
  386. PYEOF
  387. then
  388. ok "hooks.json parcheado para usar $PYTHON_ABS"
  389. else
  390. info "Aviso: no se pudo parchear hooks.json, los hooks usaran 'python3'"
  391. fi
  392. else
  393. info "Aviso: no se encontro hooks.json en la instalacion activa para parchear Python"
  394. fi
  395. if [[ -f "$MCP_JSON" ]]; then
  396. if "${PYTHON_CMD}" - "$MCP_JSON" "$PYTHON_ABS" <<'PYEOF'
  397. import json
  398. import os
  399. import sys
  400. import tempfile
  401. path, python_abs = sys.argv[1:3]
  402. with open(path, "r", encoding="utf-8") as fh:
  403. data = json.load(fh)
  404. mcp_servers = data.get("mcpServers") if isinstance(data.get("mcpServers"), dict) else data
  405. if not isinstance(mcp_servers, dict):
  406. raise SystemExit(".mcp.json no declara servidores MCP")
  407. alfred_memory = mcp_servers.get("alfred-memory")
  408. if not isinstance(alfred_memory, dict):
  409. raise SystemExit(".mcp.json no declara alfred-memory")
  410. alfred_memory["command"] = python_abs
  411. directory = os.path.dirname(path)
  412. fd, tmp_path = tempfile.mkstemp(prefix=".tmp-plugin-", dir=directory)
  413. try:
  414. with os.fdopen(fd, "w", encoding="utf-8") as fh:
  415. json.dump(data, fh, ensure_ascii=False, indent=2)
  416. fh.write("\n")
  417. os.replace(tmp_path, path)
  418. except Exception:
  419. try:
  420. os.unlink(tmp_path)
  421. except OSError:
  422. pass
  423. raise
  424. PYEOF
  425. then
  426. ok ".mcp.json parcheado para usar $PYTHON_ABS"
  427. else
  428. info "Aviso: no se pudo parchear .mcp.json, el MCP usara 'python3'"
  429. fi
  430. else
  431. info "Aviso: no se encontro .mcp.json en la instalacion activa para parchear Python"
  432. fi
  433. fi
  434. # -- Resultado --------------------------------------------------------------
  435. printf "\n${GREEN}${BOLD}Instalacion completada${NC}\n\n"
  436. printf " En Claude Code, ejecuta ${BOLD}/reload-plugins${NC} y despues:\n"
  437. printf " ${BOLD}/alfred-dev:alfred${NC}\n"
  438. printf " ${DIM}Estado: /alfred-dev:progress · retomar: /alfred-dev:retomar${NC}\n\n"
  439. printf " ${DIM}Si /reload-plugins avisa por MCP/coste de cache o no aparece el plugin, reinicia Claude Code.${NC}\n"
  440. printf " ${DIM}Repositorio: https://github.com/${REPO}${NC}\n"
  441. printf " ${DIM}Documentacion: https://alfred-dev.com${NC}\n\n"
scripts/release_audit.py · Bundled script · 4,056 lines · 2 findings marked
  1. #!/usr/bin/env python3
  2. """Verificador reproducible para la auditoria de release 0.7.0.
  3. El modo por defecto ejecuta checks locales rapidos: versionado, manifiestos,
  4. inventario del repositorio, documentacion de la auditoria y forma del MCP.
  5. Los smokes que dependen de herramientas externas se activan con flags.
  6. """
  7. from __future__ import annotations
  8. import argparse
  9. from collections import Counter
  10. import hashlib
  11. import importlib.util
  12. import json
  13. import os
  14. import re
  15. import selectors
  16. import subprocess
  17. import sys
  18. import tempfile
  19. import unicodedata
  20. from pathlib import Path
  21. from typing import Iterable
  22. ROOT = Path(__file__).resolve().parents[1]
  23. if str(ROOT) not in sys.path:
  24. sys.path.insert(0, str(ROOT))
  25. VERSION = "0.7.0"
  26. OLD_VERSION = "0.5" + ".3"
  27. INSTALLED_PLUGIN_DIR = Path.home() / ".claude" / "plugins" / "cache" / "alfred-dev" / "alfred-dev" / VERSION
  28. GLOBAL_ALFRED_ALIAS_FILE = Path.home() / ".claude" / "skills" / "alfred" / "SKILL.md"
  29. GLOBAL_ALFRED_COMMAND_FILE = Path.home() / ".claude" / "commands" / "alfred.md"
  30. INSTALLED_CACHE_FRESHNESS_ROOTS = (
  31. ".claude-plugin",
  32. "agents",
  33. "commands",
  34. "core",
  35. "hooks",
  36. "mcp",
  37. "skills",
  38. "templates",
  39. ".mcp.json",
  40. "package.json",
  41. "README.md",
  42. "scripts",
  43. )
  44. PUBLISHABLE_SYMLINK_ROOTS = INSTALLED_CACHE_FRESHNESS_ROOTS
  45. IGNORE_DIRS = {
  46. ".git",
  47. ".pytest_cache",
  48. "__pycache__",
  49. "node_modules",
  50. "dist",
  51. "coverage-html",
  52. "site/dist",
  53. "site/node_modules",
  54. }
  55. IGNORED_TEXT_FILE_GLOBS = {
  56. "docs/external-live-smoke*.json",
  57. "docs/manual-smoke*.json",
  58. "docs/manual-smoke*.md",
  59. }
  60. MANUAL_ONLY_SKILLS = (
  61. "skills/style-direction/SKILL.md",
  62. "skills/incident-response/SKILL.md",
  63. "skills/sonarqube/SKILL.md",
  64. "skills/pr-workflow/SKILL.md",
  65. )
  66. TEMPLATE_PATHS = (
  67. "templates/adr.md",
  68. "templates/changelog-entry.md",
  69. "templates/prd.md",
  70. "templates/release-notes.md",
  71. "templates/sbom.md",
  72. "templates/test-plan.md",
  73. "templates/threat-model.md",
  74. "templates/compliance.md",
  75. )
  76. PLUGIN_COMPONENT_FIELDS_REQUIRING_EXPLICIT_AUDIT = {
  77. "agents": "Claude los descubre desde agents/",
  78. "hooks": "usar hooks/hooks.json y mantener el gate especifico de hooks",
  79. "mcpServers": "usar .mcp.json raiz y mantener el gate especifico de MCP",
  80. "lspServers": "anadir gate de LSP antes de publicarlo",
  81. "outputStyles": "anadir gate de output-styles antes de publicarlo",
  82. "channels": "anadir gate de channels/MCP antes de publicarlo",
  83. "dependencies": "anadir gate de dependencias de plugins antes de publicarlas",
  84. }
  85. PLUGIN_EXPERIMENTAL_FIELDS_REQUIRING_EXPLICIT_AUDIT = {
  86. "themes": "anadir gate de themes antes de publicarlo",
  87. "monitors": "anadir gate de monitors antes de publicarlo",
  88. }
  89. MARKETPLACE_ENTRY_FIELDS_REQUIRING_EXPLICIT_AUDIT = {
  90. "agents": "no suplementar agentes fuera de plugin.json",
  91. "commands": "no suplementar comandos fuera de plugin.json",
  92. "dependencies": "no introducir dependencias de marketplace sin gate",
  93. "hooks": "no suplementar hooks fuera de hooks/hooks.json",
  94. "lspServers": "no activar LSP desde marketplace sin gate",
  95. "mcpServers": "no suplementar MCP fuera de .mcp.json",
  96. "outputStyles": "no activar output-styles desde marketplace sin gate",
  97. "skills": "no suplementar skills fuera de plugin.json",
  98. "experimental": "no activar componentes experimentales desde marketplace sin gate",
  99. "defaultEnabled": "no cambiar enablement desde marketplace; plugin.json/documentacion deben ser la autoridad",
  100. }
  101. HOOK_EVENTS_WITHOUT_MATCHER = {
  102. "CwdChanged",
  103. "MessageDisplay",
  104. "PostToolBatch",
  105. "SessionEnd",
  106. "Stop",
  107. "TaskCompleted",
  108. "TaskCreated",
  109. "TeammateIdle",
  110. "UserPromptSubmit",
  111. "WorktreeCreate",
  112. "WorktreeRemove",
  113. }
  114. HOOK_EVENTS_WITH_IF_SUPPORT = {
  115. "PreToolUse",
  116. "PostToolUse",
  117. "PostToolUseFailure",
  118. "PermissionRequest",
  119. "PermissionDenied",
  120. }
  121. HOOK_SYNC_TIMEOUT_LIMIT = 10
  122. SKILL_SUPPORTED_FIELDS = {
  123. "name",
  124. "description",
  125. "when_to_use",
  126. "argument-hint",
  127. "arguments",
  128. "disable-model-invocation",
  129. "user-invocable",
  130. "allowed-tools",
  131. "disallowed-tools",
  132. "model",
  133. "effort",
  134. "context",
  135. "agent",
  136. "hooks",
  137. "paths",
  138. "shell",
  139. }
  140. SKILL_BOOLEAN_FIELDS = {"disable-model-invocation", "user-invocable"}
  141. SKILL_BOOLEAN_VALUES = {"true", "false"}
  142. SKILL_CONTEXT_VALUES = {"fork"}
  143. SKILL_EFFORT_VALUES = {"low", "medium", "high", "xhigh", "max"}
  144. SKILL_LISTING_TEXT_LIMIT = 1536
  145. SKILL_SHELL_VALUES = {"bash", "powershell"}
  146. COMMAND_SUPPORTED_FIELDS = {
  147. "allowed-tools",
  148. "argument-hint",
  149. "description",
  150. "disallowed-tools",
  151. "disable-model-invocation",
  152. "model",
  153. }
  154. AGENT_SUPPORTED_FIELDS = {
  155. "name",
  156. "description",
  157. "prompt",
  158. "tools",
  159. "disallowedTools",
  160. "model",
  161. "maxTurns",
  162. "skills",
  163. "initialPrompt",
  164. "memory",
  165. "effort",
  166. "background",
  167. "isolation",
  168. "color",
  169. }
  170. PLUGIN_IGNORED_AGENT_FIELDS = {"hooks", "mcpServers", "permissionMode"}
  171. AGENT_MODEL_ALIASES = {"sonnet", "opus", "haiku", "fable", "inherit"}
  172. AGENT_MODEL_ID_RE = re.compile(r"^claude-[a-z0-9]+(?:-[a-z0-9]+)*$")
  173. AGENT_COLOR_VALUES = {"red", "blue", "green", "yellow", "purple", "orange", "pink", "cyan"}
  174. CLAUDE_TOOL_NAMES = {
  175. "Agent",
  176. "Artifact",
  177. "AskUserQuestion",
  178. "Bash",
  179. "CronCreate",
  180. "CronDelete",
  181. "CronList",
  182. "Edit",
  183. "EnterPlanMode",
  184. "EnterWorktree",
  185. "ExitPlanMode",
  186. "ExitWorktree",
  187. "Glob",
  188. "Grep",
  189. "ListMcpResourcesTool",
  190. "LSP",
  191. "Monitor",
  192. "NotebookEdit",
  193. "PowerShell",
  194. "PushNotification",
  195. "Read",
  196. "ReadMcpResourceTool",
  197. "RemoteTrigger",
  198. "SendMessage",
  199. "ShareOnboardingGuide",
  200. "WaitForMcpServers",
  201. "WebFetch",
  202. "WebSearch",
  203. "Workflow",
  204. "Write",
  205. }
  206. CLAUDE_PERMISSION_RULE_NAMES = CLAUDE_TOOL_NAMES | {"Skill"}
  207. SUBAGENT_UNAVAILABLE_TOOLS = {
  208. "AskUserQuestion",
  209. "EnterPlanMode",
  210. "ExitPlanMode",
  211. "ScheduleWakeup",
  212. "WaitForMcpServers",
  213. }
  214. ALFRED_AGENT_MODEL_POLICY = Counter({"inherit": 10})
  215. class AuditError(AssertionError):
  216. """Error de contrato de release."""
  217. def _read(path: str) -> str:
  218. return (ROOT / path).read_text(encoding="utf-8")
  219. def _json(path: str):
  220. return json.loads(_read(path))
  221. def _has_site() -> bool:
  222. return (ROOT / "site" / "package.json").is_file()
  223. def _fail(message: str) -> None:
  224. raise AuditError(message)
  225. def _rel(path: Path) -> str:
  226. return str(path.relative_to(ROOT))
  227. def _sha256(path: Path) -> str:
  228. return hashlib.sha256(path.read_bytes()).hexdigest()
  229. def _iter_installed_cache_freshness_files() -> Iterable[str]:
  230. for root_name in INSTALLED_CACHE_FRESHNESS_ROOTS:
  231. root_path = ROOT / root_name
  232. if root_path.is_file():
  233. yield root_name
  234. continue
  235. if not root_path.is_dir():
  236. continue
  237. for path in sorted(root_path.rglob("*")):
  238. if "__pycache__" in path.parts or path.suffix in {".pyc", ".pyo"}:
  239. continue
  240. if path.is_file():
  241. yield _rel(path)
  242. def _normalize(text: str) -> str:
  243. decomposed = unicodedata.normalize("NFKD", text)
  244. return "".join(ch for ch in decomposed if not unicodedata.combining(ch)).lower()
  245. def _iter_text_files() -> Iterable[Path]:
  246. for path in ROOT.rglob("*"):
  247. if not path.is_file():
  248. continue
  249. rel_path = path.relative_to(ROOT)
  250. rel_name = str(rel_path)
  251. if any(rel_path.match(pattern) or rel_name == pattern for pattern in IGNORED_TEXT_FILE_GLOBS):
  252. continue
  253. rel_parts = path.relative_to(ROOT).parts
  254. rel_prefixes = {
  255. "/".join(rel_parts[:index])
  256. for index in range(1, len(rel_parts) + 1)
  257. }
  258. if rel_prefixes & IGNORE_DIRS:
  259. continue
  260. if path.suffix in {".png", ".jpg", ".jpeg", ".gif", ".ico", ".db"}:
  261. continue
  262. yield path
  263. def check_versions() -> list[str]:
  264. plugin = _json(".claude-plugin/plugin.json")
  265. package = _json("package.json")
  266. version_points = {
  267. ".claude-plugin/plugin.json": plugin.get("version"),
  268. "package.json": package.get("version"),
  269. }
  270. if _has_site():
  271. site_package = _json("site/package.json")
  272. site_lock = _json("site/package-lock.json")
  273. version_points.update({
  274. "site/package.json": site_package.get("version"),
  275. "site/package-lock.json": site_lock.get("version"),
  276. "site/package-lock root": site_lock["packages"][""].get("version"),
  277. })
  278. bad = {
  279. name: value
  280. for name, value in version_points.items()
  281. if value != VERSION
  282. }
  283. if bad:
  284. _fail(f"Versiones no alineadas a {VERSION}: {bad}")
  285. offenders: list[str] = []
  286. for path in _iter_text_files():
  287. try:
  288. text = path.read_text(encoding="utf-8")
  289. except UnicodeDecodeError:
  290. continue
  291. if OLD_VERSION in text or f"v{OLD_VERSION}" in text:
  292. offenders.append(_rel(path))
  293. if offenders:
  294. _fail(f"Quedan restos vivos de {OLD_VERSION}: {offenders}")
  295. return [f"versiones alineadas a {VERSION}", f"sin restos de {OLD_VERSION}"]
  296. def _skill_files_from_manifest(plugin: dict) -> list[Path]:
  297. skill_files: list[Path] = []
  298. declared = plugin.get("skills") or ["./skills/"]
  299. for relative in declared:
  300. absolute = ROOT / relative.lstrip("./")
  301. if absolute.is_dir():
  302. skill_files.extend(sorted(absolute.rglob("SKILL.md")))
  303. elif absolute.name == "SKILL.md" and absolute.is_file():
  304. skill_files.append(absolute)
  305. return sorted(skill_files)
  306. def _manifest_component_paths(plugin: dict, field: str) -> tuple[list[Path], list[str]]:
  307. values = plugin.get(field)
  308. if field == "skills" and values is None:
  309. return [ROOT / "skills"], []
  310. if not isinstance(values, list):
  311. return [], [f"plugin.json {field} debe ser una lista"]
  312. paths: list[Path] = []
  313. problems: list[str] = []
  314. seen: set[str] = set()
  315. root = ROOT.resolve()
  316. for index, raw_value in enumerate(values):
  317. label = f"plugin.json {field}[{index}]"
  318. if not isinstance(raw_value, str):
  319. problems.append(f"{label} debe ser string relativo: {raw_value!r}")
  320. continue
  321. if not raw_value.startswith("./"):
  322. problems.append(f"{label} debe empezar por ./ para resolverse desde el root del plugin: {raw_value!r}")
  323. if Path(raw_value).is_absolute():
  324. problems.append(f"{label} no puede ser absoluto: {raw_value!r}")
  325. if ".." in Path(raw_value).parts:
  326. problems.append(f"{label} no puede atravesar fuera del plugin con ..: {raw_value!r}")
  327. normalized = raw_value[2:] if raw_value.startswith("./") else raw_value
  328. if normalized in seen:
  329. problems.append(f"{label} duplica una ruta del manifest: {raw_value!r}")
  330. seen.add(normalized)
  331. target = (ROOT / normalized).resolve()
  332. try:
  333. target.relative_to(root)
  334. except ValueError:
  335. problems.append(f"{label} resuelve fuera del root del plugin: {raw_value!r}")
  336. paths.append(ROOT / normalized)
  337. return paths, problems
  338. def check_inventory() -> list[str]:
  339. plugin = _json(".claude-plugin/plugin.json")
  340. marketplace = _json(".claude-plugin/marketplace.json")
  341. marketplace_plugins = marketplace.get("plugins")
  342. marketplace_problems: list[str] = []
  343. if marketplace.get("name") != plugin.get("name"):
  344. marketplace_problems.append(
  345. f"marketplace.name debe coincidir con plugin.name: {marketplace.get('name')!r}"
  346. )
  347. if not isinstance(marketplace.get("owner"), dict) or not marketplace["owner"].get("name"):
  348. marketplace_problems.append("marketplace.owner.name es obligatorio")
  349. if not isinstance(marketplace_plugins, list) or len(marketplace_plugins) != 1:
  350. marketplace_problems.append("marketplace.plugins debe contener exactamente una entrada")
  351. marketplace_plugin = {}
  352. else:
  353. marketplace_plugin = marketplace_plugins[0]
  354. if not isinstance(marketplace_plugin, dict):
  355. marketplace_problems.append("marketplace.plugins[0] debe ser objeto")
  356. marketplace_plugin = {}
  357. if marketplace_plugin:
  358. if marketplace_plugin.get("name") != plugin.get("name"):
  359. marketplace_problems.append(
  360. "marketplace.plugins[0].name debe coincidir con plugin.name: "
  361. f"{marketplace_plugin.get('name')!r}"
  362. )
  363. if marketplace_plugin.get("strict") is False:
  364. marketplace_problems.append(
  365. "marketplace.plugins[0].strict=false haria que marketplace reemplace plugin.json"
  366. )
  367. marketplace_problems.extend(
  368. f"marketplace.plugins[0] no debe declarar {field}: {reason}"
  369. for field, reason in sorted(MARKETPLACE_ENTRY_FIELDS_REQUIRING_EXPLICIT_AUDIT.items())
  370. if field in marketplace_plugin
  371. )
  372. if marketplace_problems:
  373. _fail("Marketplace de Alfred Dev desalineado: " + "; ".join(marketplace_problems))
  374. plugin_component_problems = [
  375. f"plugin.json no debe declarar {field}: {reason}"
  376. for field, reason in sorted(PLUGIN_COMPONENT_FIELDS_REQUIRING_EXPLICIT_AUDIT.items())
  377. if field in plugin
  378. ]
  379. experimental = plugin.get("experimental")
  380. if experimental is not None and not isinstance(experimental, dict):
  381. plugin_component_problems.append("plugin.json experimental debe ser un objeto")
  382. elif isinstance(experimental, dict):
  383. plugin_component_problems.extend(
  384. f"plugin.json no debe declarar experimental.{field}: {reason}"
  385. for field, reason in sorted(
  386. PLUGIN_EXPERIMENTAL_FIELDS_REQUIRING_EXPLICIT_AUDIT.items()
  387. )
  388. if field in experimental
  389. )
  390. if plugin_component_problems:
  391. _fail("Componentes de plugin sin auditoria explicita: " + "; ".join(plugin_component_problems))
  392. command_paths, command_path_problems = _manifest_component_paths(plugin, "commands")
  393. _skill_manifest_paths, skill_path_problems = _manifest_component_paths(plugin, "skills")
  394. path_problems = command_path_problems + skill_path_problems
  395. if path_problems:
  396. _fail("Paths de componentes del manifest incompatibles: " + "; ".join(path_problems))
  397. missing_commands = [_rel(path) for path in command_paths if not path.exists()]
  398. if missing_commands:
  399. _fail(f"Comandos publicados inexistentes: {missing_commands}")
  400. public_command_paths = {path.resolve() for path in command_paths}
  401. extra_command_files = sorted(
  402. path for path in (ROOT / "commands").glob("*.md")
  403. if path.resolve() not in public_command_paths
  404. )
  405. if set(_rel(path) for path in extra_command_files) != {
  406. "commands/_composicion.md",
  407. "commands/_docs_vivas.md",
  408. "commands/next.md",
  409. "commands/search.md",
  410. }:
  411. _fail(
  412. "commands/ contiene ficheros no publicados inesperados: "
  413. f"{[_rel(path) for path in extra_command_files]}"
  414. )
  415. agent_files = sorted((ROOT / "agents").glob("*.md"))
  416. nested_agent_files = [
  417. path for path in (ROOT / "agents").rglob("*.md")
  418. if path.parent != ROOT / "agents"
  419. ]
  420. agent_frontmatter_problems: list[str] = []
  421. agent_models: Counter[str] = Counter()
  422. for path in agent_files:
  423. agent_text = _read(_rel(path))
  424. frontmatter_values = _frontmatter_top_level_values(agent_text)
  425. field_set = set(frontmatter_values)
  426. ignored = sorted(field_set & PLUGIN_IGNORED_AGENT_FIELDS)
  427. unknown = sorted(field_set - AGENT_SUPPORTED_FIELDS - PLUGIN_IGNORED_AGENT_FIELDS)
  428. if ignored:
  429. agent_frontmatter_problems.append(
  430. f"{_rel(path)} usa campos ignorados en agentes de plugin: {ignored}"
  431. )
  432. if unknown:
  433. agent_frontmatter_problems.append(
  434. f"{_rel(path)} usa campos no soportados en frontmatter: {unknown}"
  435. )
  436. for required in ("name", "description", "model"):
  437. if required not in field_set:
  438. agent_frontmatter_problems.append(f"{_rel(path)} no declara {required}")
  439. model = frontmatter_values.get("model")
  440. if model:
  441. agent_models[model] += 1
  442. if not _is_supported_agent_model(model):
  443. agent_frontmatter_problems.append(
  444. f"{_rel(path)} usa modelo no soportado por Claude Code actual: {model!r}"
  445. )
  446. color = frontmatter_values.get("color")
  447. if color and color not in AGENT_COLOR_VALUES:
  448. agent_frontmatter_problems.append(
  449. f"{_rel(path)} usa color de subagente no soportado por Claude Code actual: {color!r}"
  450. )
  451. unavailable_tools = sorted(
  452. _frontmatter_tool_names(frontmatter_values.get("tools", ""))
  453. & SUBAGENT_UNAVAILABLE_TOOLS
  454. )
  455. unknown_tools = sorted(
  456. tool_name
  457. for tool_name in _frontmatter_tool_names(frontmatter_values.get("tools", ""))
  458. if not _is_known_agent_tool_name(tool_name)
  459. )
  460. if unknown_tools:
  461. agent_frontmatter_problems.append(
  462. f"{_rel(path)} lista herramientas desconocidas por Claude Code actual: {unknown_tools}"
  463. )
  464. if unavailable_tools:
  465. agent_frontmatter_problems.append(
  466. f"{_rel(path)} lista herramientas no disponibles en subagentes: {unavailable_tools}"
  467. )
  468. unavailable_mentions = sorted(
  469. tool for tool in SUBAGENT_UNAVAILABLE_TOOLS if tool in agent_text
  470. )
  471. if unavailable_mentions:
  472. agent_frontmatter_problems.append(
  473. f"{_rel(path)} instruye herramientas no disponibles en subagentes: {unavailable_mentions}"
  474. )
  475. if agent_models and agent_models != ALFRED_AGENT_MODEL_POLICY:
  476. agent_frontmatter_problems.append(
  477. "distribucion de modelos de agentes desalineada con la politica 0.7.0: "
  478. f"actual={dict(sorted(agent_models.items()))} "
  479. f"esperada={dict(sorted(ALFRED_AGENT_MODEL_POLICY.items()))}"
  480. )
  481. if agent_frontmatter_problems:
  482. _fail("Frontmatter de agentes incompatible: " + "; ".join(agent_frontmatter_problems))
  483. skill_files = _skill_files_from_manifest(plugin)
  484. skill_frontmatter_problems: list[str] = []
  485. skill_names: dict[str, list[str]] = {}
  486. for path in skill_files:
  487. skill_text = _read(_rel(path))
  488. frontmatter_values = _frontmatter_top_level_values(skill_text)
  489. field_set = set(frontmatter_values)
  490. unknown = sorted(field_set - SKILL_SUPPORTED_FIELDS)
  491. if unknown:
  492. skill_frontmatter_problems.append(
  493. f"{_rel(path)} usa campos no soportados en skill frontmatter: {unknown}"
  494. )
  495. for required in ("name", "description"):
  496. if required not in field_set:
  497. skill_frontmatter_problems.append(f"{_rel(path)} no declara {required}")
  498. listing_text_length = len(
  499. _frontmatter_field_text(skill_text, "description")
  500. + _frontmatter_field_text(skill_text, "when_to_use")
  501. )
  502. if listing_text_length > SKILL_LISTING_TEXT_LIMIT:
  503. skill_frontmatter_problems.append(
  504. f"{_rel(path)} excede el limite de listing de skills "
  505. f"{SKILL_LISTING_TEXT_LIMIT} chars: {listing_text_length}"
  506. )
  507. name = frontmatter_values.get("name")
  508. if name:
  509. skill_names.setdefault(name, []).append(_rel(path))
  510. if name != path.parent.name:
  511. skill_frontmatter_problems.append(
  512. f"{_rel(path)} declara name={name!r} pero el directorio es {path.parent.name!r}"
  513. )
  514. for boolean_field in sorted(SKILL_BOOLEAN_FIELDS):
  515. value = frontmatter_values.get(boolean_field)
  516. if value and value.lower() not in SKILL_BOOLEAN_VALUES:
  517. skill_frontmatter_problems.append(
  518. f"{_rel(path)} usa {boolean_field} no booleano: {value!r}"
  519. )
  520. model = frontmatter_values.get("model")
  521. if model and not _is_supported_agent_model(model):
  522. skill_frontmatter_problems.append(
  523. f"{_rel(path)} usa modelo de skill no soportado por Claude Code actual: {model!r}"
  524. )
  525. effort = frontmatter_values.get("effort")
  526. if effort and effort not in SKILL_EFFORT_VALUES:
  527. skill_frontmatter_problems.append(
  528. f"{_rel(path)} usa effort no soportado por Claude Code actual: {effort!r}"
  529. )
  530. context = frontmatter_values.get("context")
  531. if context and context not in SKILL_CONTEXT_VALUES:
  532. skill_frontmatter_problems.append(
  533. f"{_rel(path)} usa context no soportado por Claude Code actual: {context!r}"
  534. )
  535. if frontmatter_values.get("agent") and context != "fork":
  536. skill_frontmatter_problems.append(
  537. f"{_rel(path)} declara agent sin context: fork"
  538. )
  539. shell = frontmatter_values.get("shell")
  540. if shell and shell not in SKILL_SHELL_VALUES:
  541. skill_frontmatter_problems.append(
  542. f"{_rel(path)} usa shell no soportado por Claude Code actual: {shell!r}"
  543. )
  544. for tools_field in ("allowed-tools", "disallowed-tools"):
  545. unknown_tools = sorted(
  546. tool_name
  547. for tool_name in _frontmatter_tool_rule_names(
  548. _frontmatter_field_rule_text(skill_text, tools_field)
  549. )
  550. if not _is_known_permission_rule_name(tool_name)
  551. )
  552. if unknown_tools:
  553. skill_frontmatter_problems.append(
  554. f"{_rel(path)} {tools_field} declara herramientas desconocidas {unknown_tools}"
  555. )
  556. duplicated_skill_names = {
  557. name: paths for name, paths in sorted(skill_names.items()) if len(paths) > 1
  558. }
  559. if duplicated_skill_names:
  560. skill_frontmatter_problems.append(
  561. f"skills con name duplicado: {duplicated_skill_names}"
  562. )
  563. if skill_frontmatter_problems:
  564. _fail("Frontmatter de skills incompatible: " + "; ".join(skill_frontmatter_problems))
  565. domains = {
  566. path.relative_to(ROOT / "skills").parts[0]
  567. for path in skill_files
  568. if path.is_relative_to(ROOT / "skills")
  569. }
  570. if plugin.get("skills"):
  571. _fail(
  572. "plugin.json no debe listar skills: Claude las descubre en skills/*/SKILL.md"
  573. )
  574. if plugin.get("displayName") != "Alfred Dev":
  575. _fail("plugin.json debe declarar displayName humano 'Alfred Dev'")
  576. if marketplace_plugin.get("displayName") != plugin.get("displayName"):
  577. _fail("marketplace.json debe reutilizar el displayName humano del plugin")
  578. if "version" in marketplace_plugin:
  579. _fail(
  580. "marketplace.json no debe duplicar version cuando plugin.json ya "
  581. "declara version; Claude Code usa plugin.json como fuente canonica"
  582. )
  583. marketplace_source = marketplace_plugin.get("source")
  584. if isinstance(marketplace_source, str) and ".." in marketplace_source.split("/"):
  585. _fail("El source relativo del marketplace no debe escapar del root")
  586. if marketplace_source != "./":
  587. _fail(
  588. "El marketplace local debe apuntar al root del plugin para esta "
  589. f"auditoria: {marketplace_source!r}"
  590. )
  591. expected = {
  592. "commands": (len(plugin["commands"]), 18),
  593. "agents": (len(agent_files), 10),
  594. "nested_agents": (len(nested_agent_files), 0),
  595. "skills": (len(skill_files), 11),
  596. "skill_domains": (len(domains), 11),
  597. }
  598. bad = {
  599. key: {"actual": actual, "expected": wanted}
  600. for key, (actual, wanted) in expected.items()
  601. if actual != wanted
  602. }
  603. if bad:
  604. _fail(f"Inventario desalineado: {bad}")
  605. if not (ROOT / "commands" / "alfred.md").is_file():
  606. _fail("commands/alfred.md debe existir como comando publico")
  607. if "./commands/alfred.md" not in plugin.get("commands", []):
  608. _fail("plugin.json debe publicar ./commands/alfred.md")
  609. return [
  610. "18 comandos namespaced publicados",
  611. "commands/alfred.md publicado como entrada contextual",
  612. "commands/_composicion.md interno",
  613. "10 agentes en agents/ raiz",
  614. "frontmatter de agentes compatible con plugins",
  615. "herramientas de agentes validadas contra nombres oficiales de Claude Code",
  616. "herramientas no disponibles excluidas de subagentes",
  617. "modelos inherit en los 10 agentes",
  618. "11 skills planas",
  619. "frontmatter de skills compatible con Claude Code actual",
  620. "valores de frontmatter de skills validados contra Claude Code actual",
  621. "descripciones de skills dentro del limite de listing 1536",
  622. "displayName humano alineado entre manifest y marketplace",
  623. "version canonica solo en plugin.json; marketplace sin version duplicada",
  624. "marketplace no suplementa componentes ni enablement",
  625. "paths de comandos/skills acotados al root del plugin",
  626. "manifest sin componentes no auditados",
  627. ]
  628. def _command_names_from_manifest(plugin: dict) -> list[str]:
  629. return [
  630. Path(relative_path).stem
  631. for relative_path in plugin["commands"]
  632. ]
  633. def _public_route_names(plugin: dict | None = None) -> set[str]:
  634. plugin = plugin or _json(".claude-plugin/plugin.json")
  635. names = set(_command_names_from_manifest(plugin))
  636. return names
  637. def _public_argument_commands(plugin: dict | None = None) -> set[str]:
  638. """Comandos cuya superficie publica acepta texto, flags u opciones libres."""
  639. plugin = plugin or _json(".claude-plugin/plugin.json")
  640. commands: set[str] = set()
  641. for relative_path in plugin["commands"]:
  642. text = _read(relative_path.lstrip("./"))
  643. frontmatter = _frontmatter_block(text)
  644. if "$ARGUMENTS" in text or re.search(r"(?m)^argument-hint:\s*.+$", frontmatter):
  645. commands.add(Path(relative_path).stem)
  646. if (ROOT / "skills" / "alfred" / "alfred" / "SKILL.md").exists():
  647. commands.add("alfred")
  648. return commands
  649. def _validate_manual_option_contract_shape(manual_smoke, option_coverage: dict[str, list[str]]) -> None:
  650. """Evita falsos verdes por typos en los IDs de opciones manuales."""
  651. option_contracts = tuple(manual_smoke.OPTION_CONTRACTS)
  652. problems: list[str] = []
  653. duplicates = sorted({
  654. key for key in option_contracts
  655. if option_contracts.count(key) > 1
  656. })
  657. if duplicates:
  658. problems.append(f"OPTION_CONTRACTS duplicados: {duplicates}")
  659. malformed = sorted(
  660. key for key in option_contracts
  661. if key.count(":") != 1 or not key.split(":", 1)[0] or not key.split(":", 1)[1]
  662. )
  663. if malformed:
  664. problems.append(f"OPTION_CONTRACTS mal formados: {malformed}")
  665. public_commands = _public_route_names(_json(".claude-plugin/plugin.json"))
  666. aliases = getattr(manual_smoke, "_PUBLIC_COMMAND_ALIASES", {})
  667. unknown_prefixes = sorted({
  668. key.split(":", 1)[0]
  669. for key in option_contracts
  670. if key.count(":") == 1
  671. and key.split(":", 1)[0] not in public_commands
  672. and aliases.get(key.split(":", 1)[0]) not in public_commands
  673. })
  674. if unknown_prefixes:
  675. problems.append(f"OPTION_CONTRACTS con comandos no publicados: {unknown_prefixes}")
  676. from core import config_loader
  677. expected_config_options = {
  678. "config:exit-without-changes",
  679. *{
  680. f"config:{section.replace('_', '-')}"
  681. for section in config_loader._CONFIG_SECTION_ORDER
  682. },
  683. }
  684. actual_config_options = {
  685. key for key in option_contracts
  686. if key.startswith("config:")
  687. }
  688. missing_config_options = sorted(expected_config_options - actual_config_options)
  689. extra_config_options = sorted(actual_config_options - expected_config_options)
  690. if missing_config_options or extra_config_options:
  691. problems.append(
  692. "OPTION_CONTRACTS de /config desalineados: "
  693. f"missing={missing_config_options} extra={extra_config_options}"
  694. )
  695. expected_lucius_options = {
  696. "lucius:default-scope-all",
  697. "lucius:scope-all",
  698. "lucius:scope-security",
  699. "lucius:scope-tests",
  700. "lucius:scope-architecture",
  701. "lucius:scope-performance",
  702. "lucius:target-directory",
  703. "lucius:invalid-scope",
  704. }
  705. actual_lucius_options = {
  706. key for key in option_contracts
  707. if key.startswith("lucius:")
  708. }
  709. missing_lucius_options = sorted(expected_lucius_options - actual_lucius_options)
  710. extra_lucius_options = sorted(actual_lucius_options - expected_lucius_options)
  711. if missing_lucius_options or extra_lucius_options:
  712. problems.append(
  713. "OPTION_CONTRACTS de /lucius desalineados: "
  714. f"missing={missing_lucius_options} extra={extra_lucius_options}"
  715. )
  716. expected_human_menu_options = {
  717. "audit:sonarqube-docker-install-menu",
  718. "audit:sonarqube-docker-start-menu",
  719. "ship:deploy-confirmation-menu",
  720. "feature:user-gate-menu",
  721. "fix:user-gate-menu",
  722. "spike:conclusion-review-menu",
  723. "discuss:route-menu",
  724. "alfred:route-menu",
  725. "update:confirm-update-menu",
  726. }
  727. missing_human_menu_options = sorted(expected_human_menu_options - set(option_contracts))
  728. if missing_human_menu_options:
  729. problems.append(
  730. "OPTION_CONTRACTS sin menus humanos obligatorios: "
  731. f"{missing_human_menu_options}"
  732. )
  733. coverage_only = sorted(set(option_coverage) - set(option_contracts))
  734. if coverage_only:
  735. problems.append(f"option_coverage contiene claves fuera de OPTION_CONTRACTS: {coverage_only}")
  736. if problems:
  737. _fail("Contratos de opciones manuales invalidos: " + "; ".join(problems))
  738. def _validate_manual_runtime_contract_shape(manual_smoke, runtime_coverage: dict[str, list[str]]) -> None:
  739. """Valida que los contratos runtime describan scopes reales de /update."""
  740. runtime_contracts = tuple(manual_smoke.RUNTIME_CONTRACTS)
  741. problems: list[str] = []
  742. duplicates = sorted({
  743. key for key in runtime_contracts
  744. if runtime_contracts.count(key) > 1
  745. })
  746. if duplicates:
  747. problems.append(f"RUNTIME_CONTRACTS duplicados: {duplicates}")
  748. malformed = sorted(
  749. key for key in runtime_contracts
  750. if key.count(":") != 1 or not key.split(":", 1)[0] or not key.split(":", 1)[1]
  751. )
  752. if malformed:
  753. problems.append(f"RUNTIME_CONTRACTS mal formados: {malformed}")
  754. public_commands = _public_route_names(_json(".claude-plugin/plugin.json"))
  755. unknown_prefixes = sorted({
  756. key.split(":", 1)[0]
  757. for key in runtime_contracts
  758. if key.count(":") == 1 and key.split(":", 1)[0] not in public_commands
  759. })
  760. if unknown_prefixes:
  761. problems.append(f"RUNTIME_CONTRACTS con comandos no publicados: {unknown_prefixes}")
  762. expected_update_contracts = {
  763. "update:scope-user-or-unknown",
  764. "update:scope-local-to-user",
  765. "update:scope-project-to-user",
  766. "update:scope-managed",
  767. }
  768. actual_update_contracts = {
  769. key for key in runtime_contracts
  770. if key.startswith("update:")
  771. }
  772. missing_update = sorted(expected_update_contracts - actual_update_contracts)
  773. extra_update = sorted(actual_update_contracts - expected_update_contracts)
  774. if missing_update or extra_update:
  775. problems.append(
  776. "RUNTIME_CONTRACTS de /update desalineados: "
  777. f"missing={missing_update} extra={extra_update}"
  778. )
  779. coverage_only = sorted(set(runtime_coverage) - set(runtime_contracts))
  780. if coverage_only:
  781. problems.append(f"runtime_coverage contiene claves fuera de RUNTIME_CONTRACTS: {coverage_only}")
  782. if problems:
  783. _fail("Contratos runtime manuales invalidos: " + "; ".join(problems))
  784. def _validate_manual_case_contract_links(manual_smoke) -> None:
  785. """Asegura que cada contrato manual esté cubierto por un caso del comando correcto."""
  786. aliases = getattr(manual_smoke, "_PUBLIC_COMMAND_ALIASES", {})
  787. def _canon(name: str) -> str:
  788. return aliases.get(name, name)
  789. problems: list[str] = []
  790. for case in manual_smoke.CASES:
  791. case_commands = set(getattr(case, "commands", ()) or ())
  792. prompt = getattr(case, "prompt", "")
  793. prompt_commands = set(re.findall(r"/alfred-dev:([a-z0-9-]+)", prompt))
  794. if re.search(r"(?<!\S)/alfred(?:\s|$)", prompt):
  795. prompt_commands.add("alfred")
  796. mapped_case = {_canon(name) for name in case_commands}
  797. mapped_prompt = {_canon(name) for name in prompt_commands}
  798. if case_commands:
  799. missing_prompt_commands = sorted(mapped_case - mapped_prompt)
  800. extra_prompt_commands = sorted(mapped_prompt - mapped_case)
  801. if missing_prompt_commands:
  802. problems.append(
  803. f"{case.case_id}: prompt no invoca {missing_prompt_commands}"
  804. )
  805. if extra_prompt_commands:
  806. problems.append(
  807. f"{case.case_id}: prompt invoca comandos no declarados {extra_prompt_commands}"
  808. )
  809. elif prompt_commands:
  810. problems.append(
  811. f"{case.case_id}: prompt invoca comandos sin declarar {sorted(prompt_commands)}"
  812. )
  813. for key in getattr(case, "option_keys", ()) or ():
  814. command_name = key.split(":", 1)[0] if ":" in key else ""
  815. if _canon(command_name) not in mapped_case:
  816. problems.append(f"{case.case_id}: option {key} no corresponde a {sorted(case_commands)}")
  817. for key in getattr(case, "runtime_keys", ()) or ():
  818. command_name = key.split(":", 1)[0] if ":" in key else ""
  819. if _canon(command_name) not in mapped_case:
  820. problems.append(f"{case.case_id}: runtime {key} no corresponde a {sorted(case_commands)}")
  821. if problems:
  822. _fail("Contratos manuales enlazados al caso equivocado: " + "; ".join(problems))
  823. def _slash_command_names(text: str) -> list[str]:
  824. return re.findall(r"`/alfred-dev:([a-z0-9-]+)`", text)
  825. def _section_between(text: str, start: str, end: str) -> str:
  826. start_index = text.index(start)
  827. end_index = text.index(end, start_index)
  828. return text[start_index:end_index]
  829. def check_command_catalog() -> list[str]:
  830. plugin = _json(".claude-plugin/plugin.json")
  831. manifest_names = _command_names_from_manifest(plugin)
  832. manifest_set = set(manifest_names)
  833. architecture = _read("docs/architecture.md")
  834. alfred_text = _read("commands/alfred.md")
  835. unpublished = {"_composicion", "_docs_vivas", "next", "search"}
  836. disk_names = {
  837. path.stem
  838. for path in (ROOT / "commands").glob("*.md")
  839. if path.stem not in unpublished
  840. }
  841. problems: list[str] = []
  842. if manifest_set != disk_names:
  843. problems.append(
  844. "comandos publicados y commands/*.md no coinciden: "
  845. f"faltan={sorted(disk_names - manifest_set)} sobran={sorted(manifest_set - disk_names)}"
  846. )
  847. if "alfred" not in manifest_set:
  848. problems.append("falta el comando publico alfred")
  849. if "/alfred-dev:alfred" not in alfred_text and "/alfred" not in alfred_text:
  850. problems.append("commands/alfred.md debe describir la entrada contextual")
  851. if "18 comandos" not in architecture and "/alfred-dev:alfred" not in architecture:
  852. problems.append("docs/architecture.md debe mencionar 18 comandos o /alfred-dev:alfred")
  853. for relative_path, name in zip(plugin["commands"], manifest_names):
  854. text = _read(relative_path.lstrip("./"))
  855. if not text.startswith("---\n"):
  856. problems.append(f"{relative_path}: falta frontmatter")
  857. continue
  858. frontmatter = text.split("---", 2)[1]
  859. frontmatter_values = _frontmatter_top_level_values(text)
  860. unknown_fields = sorted(set(frontmatter_values) - COMMAND_SUPPORTED_FIELDS)
  861. if unknown_fields:
  862. problems.append(
  863. f"{relative_path}: campos de frontmatter no soportados {unknown_fields}"
  864. )
  865. if not re.search(r"(?m)^description:\s*['\"]?.+['\"]?\s*$", frontmatter):
  866. problems.append(f"{relative_path}: falta description en frontmatter")
  867. model = frontmatter_values.get("model")
  868. if model and not _is_supported_agent_model(model):
  869. problems.append(
  870. f"{relative_path}: usa modelo de comando no soportado por Claude Code actual: {model!r}"
  871. )
  872. for tools_field in ("allowed-tools", "disallowed-tools"):
  873. unknown_tools = sorted(
  874. tool_name
  875. for tool_name in _frontmatter_tool_rule_names(
  876. _frontmatter_field_rule_text(text, tools_field)
  877. )
  878. if not _is_known_permission_rule_name(tool_name)
  879. )
  880. if unknown_tools:
  881. problems.append(
  882. f"{relative_path}: {tools_field} declara herramientas desconocidas {unknown_tools}"
  883. )
  884. if f"/alfred-dev:{name}" not in text:
  885. problems.append(f"{relative_path}: no menciona su slash command")
  886. if problems:
  887. _fail("Catalogo de comandos desalineado: " + "; ".join(problems))
  888. return [
  889. "18 comandos namespaced alineados entre plugin.json y arquitectura",
  890. "commands/alfred.md publicado como entrada contextual",
  891. "frontmatter de comandos con description",
  892. "frontmatter de comandos compatible con Claude Code actual",
  893. "model de comandos validado contra Claude Code actual",
  894. ]
  895. def _frontmatter_block(text: str) -> str:
  896. if not text.startswith("---\n"):
  897. return ""
  898. parts = text.split("---", 2)
  899. return parts[1] if len(parts) >= 3 else ""
  900. def _frontmatter_top_level_fields(text: str) -> list[str]:
  901. fields: list[str] = []
  902. for line in _frontmatter_block(text).splitlines():
  903. match = re.match(r"^([A-Za-z][A-Za-z_-]*)\s*:", line)
  904. if match:
  905. fields.append(match.group(1))
  906. return fields
  907. def _frontmatter_top_level_values(text: str) -> dict[str, str]:
  908. values: dict[str, str] = {}
  909. for line in _frontmatter_block(text).splitlines():
  910. match = re.match(r"^([A-Za-z][A-Za-z_-]*)\s*:\s*(.*)$", line)
  911. if not match:
  912. continue
  913. key, value = match.groups()
  914. values[key] = value.strip().strip('"').strip("'")
  915. return values
  916. def _frontmatter_field_text(text: str, field: str) -> str:
  917. lines = _frontmatter_block(text).splitlines()
  918. for index, line in enumerate(lines):
  919. match = re.match(r"^([A-Za-z][A-Za-z_-]*)\s*:\s*(.*)$", line)
  920. if not match:
  921. continue
  922. key, value = match.groups()
  923. if key != field:
  924. continue
  925. stripped_value = value.strip()
  926. if stripped_value not in {"|", ">"}:
  927. return stripped_value.strip('"').strip("'")
  928. collected: list[str] = []
  929. for following in lines[index + 1:]:
  930. if re.match(r"^[A-Za-z][A-Za-z_-]*\s*:", following):
  931. break
  932. if following.startswith((" ", "\t")):
  933. collected.append(following.strip())
  934. return "\n".join(collected)
  935. return ""
  936. def _is_supported_agent_model(model: str) -> bool:
  937. return model in AGENT_MODEL_ALIASES or AGENT_MODEL_ID_RE.fullmatch(model) is not None
  938. def _frontmatter_tool_names(tools: str) -> set[str]:
  939. names: set[str] = set()
  940. for item in tools.split(","):
  941. name = item.strip()
  942. if not name:
  943. continue
  944. names.add(re.split(r"[\s(]", name, maxsplit=1)[0])
  945. return names
  946. def _frontmatter_tool_rule_names(rules: str) -> set[str]:
  947. return set(
  948. re.findall(r"(?:^|[\s,])([A-Za-z][A-Za-z0-9_]*)(?:\(|(?=$|[\s,]))", rules)
  949. )
  950. def _frontmatter_field_rule_text(text: str, field: str) -> str:
  951. """Devuelve reglas inline o de lista YAML simple para allowed/disallowed tools."""
  952. lines = _frontmatter_block(text).splitlines()
  953. values: list[str] = []
  954. collecting = False
  955. for line in lines:
  956. top_level = re.match(r"^([A-Za-z][A-Za-z_-]*)\s*:\s*(.*)$", line)
  957. if top_level:
  958. key, value = top_level.groups()
  959. collecting = key == field
  960. if collecting and value.strip():
  961. values.append(value.strip().strip("[]").strip('"').strip("'"))
  962. continue
  963. if collecting:
  964. list_item = re.match(r"^\s*-\s*(.+?)\s*$", line)
  965. if list_item:
  966. values.append(list_item.group(1))
  967. return " ".join(values)
  968. def _is_known_agent_tool_name(tool_name: str) -> bool:
  969. return tool_name in CLAUDE_TOOL_NAMES or tool_name.startswith("mcp__")
  970. def _is_known_permission_rule_name(tool_name: str) -> bool:
  971. return tool_name in CLAUDE_PERMISSION_RULE_NAMES or tool_name.startswith("mcp__")
  972. def check_command_execution_contracts() -> list[str]:
  973. """Verifica que cada comando publicado conserve su estrategia operativa."""
  974. plugin = _json(".claude-plugin/plugin.json")
  975. commands = {
  976. Path(relative_path).stem: _read(relative_path.lstrip("./"))
  977. for relative_path in plugin["commands"]
  978. }
  979. composition = _read("commands/_composicion.md")
  980. problems: list[str] = []
  981. for name, text in commands.items():
  982. frontmatter = _frontmatter_block(text)
  983. has_arguments = "$ARGUMENTS" in text
  984. has_hint = re.search(r"(?m)^argument-hint:\s*.+$", frontmatter) is not None
  985. if has_arguments and not has_hint:
  986. problems.append(f"{name}: usa $ARGUMENTS pero no declara argument-hint")
  987. if has_hint and not has_arguments:
  988. problems.append(f"{name}: declara argument-hint pero no inserta $ARGUMENTS")
  989. if re.search(r"`/alfred:[^`]*`|^/alfred:", text, re.MULTILINE):
  990. problems.append(f"{name}: contiene slash command legacy /alfred:")
  991. if re.search(r"\bTask\b", text):
  992. problems.append(f"{name}: contiene nomenclatura obsoleta Task")
  993. if re.search(r"\*\*GATE \(libre\):\*\*.*\bSe aprueba siempre\b", text):
  994. problems.append(
  995. f"{name}: gate libre promete aprobacion incondicional sin evidencia"
  996. )
  997. helper_contracts = {
  998. "alfred": [
  999. 'consume-prefetch "$PWD" --expected alfred',
  1000. 'alfred-continuity.py next "$PWD" --json',
  1001. "No ofrezcas un menú por defecto",
  1002. ],
  1003. "discuss": [
  1004. 'consume-prefetch "$PWD" --expected discuss',
  1005. 'alfred-continuity.py discuss "$PWD" --raw "$ARGUMENTS"',
  1006. "respuesta final",
  1007. "commands/_docs_vivas.md",
  1008. ],
  1009. "map-codebase": [
  1010. 'consume-prefetch "$PWD" --expected map-codebase',
  1011. 'alfred-continuity.py map-codebase "$PWD" --raw "$ARGUMENTS"',
  1012. "NO inventes stack, entrypoints o riesgos",
  1013. "commands/_docs_vivas.md",
  1014. ],
  1015. "memory-ui": [
  1016. 'consume-prefetch "$PWD" --expected memory-ui',
  1017. 'alfred-continuity.py memory-ui "$PWD" --raw "$ARGUMENTS"',
  1018. "--stop",
  1019. ],
  1020. "next": [
  1021. 'alfred-continuity.py next "$PWD" --json',
  1022. "un único `AskUserQuestion` navegable",
  1023. ],
  1024. "pause": [
  1025. 'alfred-continuity.py pause "$PWD"',
  1026. "Primero ejecuta el helper determinista",
  1027. "No la reenvuelvas con un segundo resumen",
  1028. ],
  1029. "progress": [
  1030. 'alfred-continuity.py progress "$PWD"',
  1031. "úsalo como respuesta final",
  1032. "NO uses `AskUserQuestion`",
  1033. ],
  1034. "quick": [
  1035. 'alfred-continuity.py quick "$PWD" --raw "$ARGUMENTS"',
  1036. "`Write` ni `Edit`",
  1037. "## Cierre canónico del comando",
  1038. ],
  1039. "search": [
  1040. 'alfred-continuity.py search "$PWD" --raw "$ARGUMENTS"',
  1041. "Si `$ARGUMENTS` está vacío, dilo claramente",
  1042. ],
  1043. "sync-github": [
  1044. 'alfred-continuity.py sync-github "$PWD" --raw "$ARGUMENTS"',
  1045. "Mantén la verdad local",
  1046. ],
  1047. "uat": [
  1048. 'alfred-continuity.py verify "$PWD" --raw "$ARGUMENTS"',
  1049. "NO marques una UAT como aprobada sin una indicación explícita",
  1050. "NO añadas una segunda capa de resumen",
  1051. ],
  1052. "retomar": [
  1053. 'alfred-continuity.py resume "$PWD"',
  1054. "Primero ejecuta el helper determinista",
  1055. ],
  1056. }
  1057. commands_for_contracts = dict(commands)
  1058. commands_for_contracts["alfred"] = _read("commands/alfred.md")
  1059. commands_for_contracts["next"] = _read("commands/next.md")
  1060. commands_for_contracts["search"] = _read("commands/search.md")
  1061. for name, needles in helper_contracts.items():
  1062. text = commands_for_contracts[name]
  1063. for needle in needles:
  1064. if needle not in text:
  1065. problems.append(f"{name}: falta contrato helper {needle!r}")
  1066. flow_contracts = {
  1067. "feature": [
  1068. "Flujo de hasta 7 fases",
  1069. "## HARD-GATES",
  1070. "Maximo 5 intentos",
  1071. "## Cierre canónico del comando",
  1072. "siguiente paso esperado",
  1073. "commands/_docs_vivas.md",
  1074. "check-project-docs",
  1075. ],
  1076. "fix": [
  1077. "Flujo de 3 fases",
  1078. "test que reproduce el bug",
  1079. "Maximo 5 intentos",
  1080. "## Cierre canónico del comando",
  1081. "bug/causa raíz en curso",
  1082. "commands/_docs_vivas.md",
  1083. ],
  1084. "quick": [
  1085. "Flujo ligero de 2 fases",
  1086. "Cuándo quick deja de ser quick",
  1087. "## Cierre canónico del comando",
  1088. "/alfred-dev:uat",
  1089. "commands/_docs_vivas.md",
  1090. "cierre",
  1091. ],
  1092. "spike": [
  1093. "Flujo de 2 fases",
  1094. "Los spikes NO generan código de producción",
  1095. "## Cierre canónico del comando",
  1096. "ADR",
  1097. "no implementar todavía",
  1098. ],
  1099. "ship": [
  1100. "Flujo de 4 fases",
  1101. "Gate de despliegue SIEMPRE interactiva",
  1102. "NUNCA auto-apruebes un despliegue",
  1103. "## Cierre canónico del comando",
  1104. "commands/_docs_vivas.md",
  1105. "hygiene",
  1106. ],
  1107. "audit": [
  1108. "Preflight de SonarQube",
  1109. "Lanza 4 agentes EN PARALELO",
  1110. "No toca código, solo genera informes",
  1111. "## Cierre canónico del comando",
  1112. "commands/_docs_vivas.md",
  1113. ],
  1114. }
  1115. for name, needles in flow_contracts.items():
  1116. text = commands[name]
  1117. for needle in needles:
  1118. if needle not in text:
  1119. problems.append(f"{name}: falta contrato de flujo {needle!r}")
  1120. composition_reader_contracts = ("feature", "fix", "quick", "spike", "ship", "audit")
  1121. for name in composition_reader_contracts:
  1122. text = commands[name]
  1123. for needle in (
  1124. "${CLAUDE_PLUGIN_ROOT}/commands/_composicion.md",
  1125. ):
  1126. if needle not in text:
  1127. problems.append(f"{name}: carga _composicion sin contrato de plugin: {needle!r}")
  1128. docs_reader_contracts = ("feature", "fix", "quick", "spike", "ship", "audit")
  1129. for name in docs_reader_contracts:
  1130. text = commands[name]
  1131. if "${CLAUDE_PLUGIN_ROOT}/commands/_docs_vivas.md" not in text:
  1132. problems.append(
  1133. f"{name}: carga _docs_vivas sin contrato de plugin: "
  1134. "'${CLAUDE_PLUGIN_ROOT}/commands/_docs_vivas.md'"
  1135. )
  1136. autopilot_texts = {
  1137. "_composicion": composition,
  1138. "feature": commands["feature"],
  1139. "fix": commands["fix"],
  1140. "ship": commands["ship"],
  1141. }
  1142. for name, text in autopilot_texts.items():
  1143. if '"autopilot": true' not in text:
  1144. problems.append(f"{name}: no reconoce el flag canonico de estado autopilot")
  1145. if '"modo": "autopilot"' not in text:
  1146. problems.append(f"{name}: no conserva el alias legacy de estado autopilot")
  1147. interactive_contracts = {
  1148. "ajustes": [
  1149. "principal navegable",
  1150. "core/config_cli.py",
  1151. "CONFIG_HEADLESS_MENU",
  1152. "no llames `AskUserQuestion`",
  1153. "vuelve cancelada",
  1154. "build_config_section_summaries()",
  1155. "build_config_section_menu()",
  1156. "build_config_section_change_preview()",
  1157. "update_config_section()",
  1158. ],
  1159. "lucius": [
  1160. "Argumentos del usuario: $ARGUMENTS",
  1161. "codex login",
  1162. "scope=all",
  1163. "No implementes ningún ítem",
  1164. "siguiente paso verificable",
  1165. ],
  1166. "update": [
  1167. "semver real",
  1168. "0.10.0",
  1169. "un único `AskUserQuestion`",
  1170. "ejecutar **`/reload-plugins`**",
  1171. "`/reload-plugins --force`",
  1172. "entonces debe reiniciar",
  1173. "## Cierre canónico del comando",
  1174. ],
  1175. }
  1176. for name, needles in interactive_contracts.items():
  1177. text = commands[name]
  1178. for needle in needles:
  1179. if needle not in text:
  1180. problems.append(f"{name}: falta contrato interactivo {needle!r}")
  1181. if problems:
  1182. _fail("Contratos de ejecución de comandos incompletos: " + "; ".join(problems))
  1183. return [
  1184. "18 comandos namespaced preservan argumentos, prefijo y nomenclatura actual",
  1185. "18 wrappers helper-first cubiertos",
  1186. "6 flujos principales con cierre canónico",
  1187. "_composicion se carga desde la instalación del plugin",
  1188. "config/lucius/update con contratos interactivos verificables",
  1189. "gates libres sin aprobacion incondicional",
  1190. "autopilot por config/estado sin flag publico fantasma",
  1191. ]
  1192. def _registered_hook_script_count() -> int:
  1193. hooks = _json("hooks/hooks.json").get("hooks", {})
  1194. scripts: set[str] = set()
  1195. for groups in hooks.values():
  1196. for group in groups:
  1197. for hook in group.get("hooks", []):
  1198. args = hook.get("args", [])
  1199. if not isinstance(args, list):
  1200. continue
  1201. for arg in args:
  1202. if isinstance(arg, str) and arg.startswith("${CLAUDE_PLUGIN_ROOT}/hooks/"):
  1203. scripts.add(Path(arg).name)
  1204. return len(scripts)
  1205. def check_public_claims() -> list[str]:
  1206. """Mantiene los claims publicos alineados con inventario y docs actuales."""
  1207. readme = _read("README.md")
  1208. architecture = _read("docs/architecture.md")
  1209. skills_doc = _read("docs/skills.md")
  1210. help_command = _read("commands/alfred.md")
  1211. alfred_agent = _read("agents/alfred.md")
  1212. lucius_agent = _read("agents/lucius.md")
  1213. agents_readme = _read("docs/agents/README.md")
  1214. has_site = _has_site()
  1215. personality = _read("docs/personality.md")
  1216. changelog = _read("CHANGELOG.md")
  1217. agent_count = len(list((ROOT / "agents").glob("*.md")))
  1218. skill_count = len(list((ROOT / "skills").rglob("SKILL.md")))
  1219. command_count = len(_json(".claude-plugin/plugin.json")["commands"])
  1220. hook_script_count = _registered_hook_script_count()
  1221. expected_counts = {
  1222. "agents": (agent_count, 10),
  1223. "skills": (skill_count, 11),
  1224. "commands": (command_count, 18),
  1225. "hooks": (hook_script_count, hook_script_count),
  1226. }
  1227. for label, (actual, expected) in expected_counts.items():
  1228. if actual != expected:
  1229. _fail(f"Inventario publico {label}={actual}, esperado {expected}")
  1230. required = {
  1231. "README.md": [
  1232. "10 agentes",
  1233. "11 skills",
  1234. "quality gates",
  1235. "https://code.claude.com/docs/en/overview",
  1236. "Novedades en v0.7.0",
  1237. ],
  1238. "docs/skills.md": [
  1239. "catalogo de 11 skills",
  1240. "disable-model-invocation: true",
  1241. "memory",
  1242. "style-direction",
  1243. ],
  1244. "docs/architecture.md": [
  1245. "18 comandos",
  1246. "El manifiesto no declara la clave `agents`",
  1247. ],
  1248. "commands/alfred.md": [
  1249. "Agent Teams",
  1250. "/alfred-dev:feature",
  1251. ],
  1252. "agents/alfred.md": [
  1253. "Alfred",
  1254. ],
  1255. "docs/agents/README.md": [
  1256. "Claude Code los descubre directamente desde `agents/`",
  1257. "el manifiesto `plugin.json` no declara una seccion `agents` manual",
  1258. "quality gates verificables con evidencia",
  1259. "El resultado no se promete determinista",
  1260. "reduce variabilidad",
  1261. ],
  1262. "agents/lucius.md": [
  1263. "No fuerces un modelo por tu cuenta",
  1264. "Codex CLI (configuración local del usuario)",
  1265. "codex exec",
  1266. "--sandbox read-only",
  1267. "--ephemeral",
  1268. "--json",
  1269. "--output-last-message",
  1270. "codex_report",
  1271. "codex_jsonl",
  1272. "approval_policy",
  1273. "status --porcelain=v1 -z",
  1274. ],
  1275. "CHANGELOG.md": [
  1276. "displayName: \"Alfred Dev\"",
  1277. "Alfred Dev (alfred-dev)",
  1278. "namespace técnico",
  1279. "42 opciones públicas",
  1280. "4 contratos runtime de `/update`",
  1281. ],
  1282. "site/src/i18n/data.es.ts": [
  1283. "displayName: \"Alfred Dev\"",
  1284. "Alfred Dev (alfred-dev)",
  1285. "namespace técnico",
  1286. "Claude Code 2.1.183",
  1287. "plugins, skills, hooks y MCP",
  1288. "claude update",
  1289. ],
  1290. "site/src/i18n/data.en.ts": [
  1291. "displayName: \"Alfred Dev\"",
  1292. "Alfred Dev (alfred-dev)",
  1293. "technical namespace",
  1294. "Claude Code 2.1.183",
  1295. "plugins, skills, hooks, and MCP",
  1296. "claude update",
  1297. "quality gates that require evidence before work can close",
  1298. ],
  1299. }
  1300. sources = {
  1301. "README.md": readme,
  1302. "docs/skills.md": skills_doc,
  1303. "docs/architecture.md": architecture,
  1304. "commands/alfred.md": help_command,
  1305. "agents/alfred.md": alfred_agent,
  1306. "docs/agents/README.md": agents_readme,
  1307. "agents/lucius.md": lucius_agent,
  1308. "CHANGELOG.md": changelog,
  1309. }
  1310. if has_site:
  1311. sources.update({
  1312. "site/src/i18n/data.es.ts": _read("site/src/i18n/data.es.ts"),
  1313. "site/src/i18n/data.en.ts": _read("site/src/i18n/data.en.ts"),
  1314. })
  1315. else:
  1316. required = {
  1317. path: needles
  1318. for path, needles in required.items()
  1319. if not path.startswith("site/")
  1320. }
  1321. missing: list[str] = []
  1322. for path, needles in required.items():
  1323. for needle in needles:
  1324. if needle not in sources[path]:
  1325. missing.append(f"{path}: {needle}")
  1326. if missing:
  1327. _fail(f"Claims publicos incompletos: {missing}")
  1328. stale_exact = {
  1329. "README.md": [
  1330. "### Skills (60)",
  1331. "### Hooks (12)",
  1332. "### Core (6 modulos)",
  1333. "### Core (6 módulos)",
  1334. "GPT-5.4",
  1335. "--autopilot",
  1336. "keywords contextuales",
  1337. "https://docs.anthropic.com/en/docs/claude-code",
  1338. "quality gates infranqueables",
  1339. "No hay excepciones, no hay modo de saltárselas",
  1340. ],
  1341. "docs/architecture.md": ["Agentes de nucleo** (9)", "se registran igualmente en `plugin.json`"],
  1342. "docs/agents/README.md": [
  1343. "tambien aparecen en `plugin.json`",
  1344. "quality gates infranqueables",
  1345. "El resultado es previsible y reproducible",
  1346. "produce resultados consistentes porque no arrastra",
  1347. ],
  1348. "commands/alfred.md": ["GPT-5.4"],
  1349. "agents/alfred.md": [
  1350. "9 agentes de nucleo + 8 opcionales",
  1351. "reglas infranqueables",
  1352. "NUNCA se pueden saltar",
  1353. ],
  1354. "agents/lucius.md": ["GPT-5.4", "gpt-5.4"],
  1355. "docs/personality.md": ["GPT-5.4"],
  1356. "CHANGELOG.md": [
  1357. "GPT-5.4",
  1358. "gpt-5.4",
  1359. "22 opciones/variantes",
  1360. "`codex review`",
  1361. "approval: never",
  1362. "sin prompt de confirmación al usuario",
  1363. "ejecuta el scanner end-to-end",
  1364. "Quality gates infranqueables",
  1365. ],
  1366. "site/src/i18n/data.es.ts": [
  1367. "6 módulos core",
  1368. "GPT-5.4",
  1369. "codex review",
  1370. "approval: never",
  1371. "--autopilot",
  1372. "sin pedir confirmación al usuario",
  1373. "Verificado end-to-end con Docker",
  1374. "ejecuta el scanner end-to-end",
  1375. "No hay requisito de versión mínima específica",
  1376. "Cualquier versión de Claude Code",
  1377. "Claude Code instalado.",
  1378. ],
  1379. "site/src/i18n/data.en.ts": [
  1380. "6 core modules",
  1381. "GPT-5.4",
  1382. "modelo configurado por el usuario",
  1383. "codex review",
  1384. "approval: never",
  1385. "--autopilot",
  1386. "quality gates the workflow cannot skip",
  1387. "without asking the user for confirmation",
  1388. "Verified end-to-end with Docker",
  1389. "runs the scanner end-to-end",
  1390. "There is no specific minimum version requirement",
  1391. "Any version of Claude Code",
  1392. "Claude Code installed.",
  1393. ],
  1394. "site/src/components/BrutalistLandingPage.astro": [
  1395. "GPT-5.4",
  1396. "codex review",
  1397. "Los quality gates son infranqueables",
  1398. ],
  1399. "hooks/session-start.sh": [
  1400. "Las quality gates son infranqueables",
  1401. ],
  1402. "site/src/components/Footer.astro": ["https://docs.anthropic.com/en/docs/claude-code"],
  1403. "docs/skills.md": [
  1404. "garantizar que el resultado sea consistente, reproducible y de calidad profesional",
  1405. "procedimiento verificable y reproducible",
  1406. "garantizar que el software sea usable por todas las personas",
  1407. ],
  1408. "docs/flows.md": [
  1409. "garantiza que cada linea de código tiene al menos un test",
  1410. "garantiza que cada línea de código tiene al menos un test",
  1411. ],
  1412. "docs/agents/security-officer.md": [
  1413. "garantizar que el software cumple con los estandares de seguridad",
  1414. ],
  1415. "agents/security-officer.md": [
  1416. "garantiza que nada con vulnerabilidades conocidas llega a los usuarios",
  1417. "bloqueantes absolutos. Sin excepciones",
  1418. "seguridad infranqueable",
  1419. ],
  1420. }
  1421. stale_sources = {
  1422. "README.md": readme,
  1423. "docs/skills.md": skills_doc,
  1424. "docs/flows.md": _read("docs/flows.md"),
  1425. "docs/agents/security-officer.md": _read("docs/agents/security-officer.md"),
  1426. "agents/security-officer.md": _read("agents/security-officer.md"),
  1427. "hooks/session-start.sh": _read("hooks/session-start.sh"),
  1428. "docs/architecture.md": architecture,
  1429. "commands/alfred.md": help_command,
  1430. "agents/alfred.md": alfred_agent,
  1431. "docs/agents/README.md": agents_readme,
  1432. "agents/lucius.md": lucius_agent,
  1433. "docs/personality.md": personality,
  1434. "CHANGELOG.md": changelog,
  1435. }
  1436. if has_site:
  1437. stale_sources.update({
  1438. "site/src/i18n/data.es.ts": _read("site/src/i18n/data.es.ts"),
  1439. "site/src/i18n/data.en.ts": _read("site/src/i18n/data.en.ts"),
  1440. "site/src/components/BrutalistLandingPage.astro": _read("site/src/components/BrutalistLandingPage.astro"),
  1441. "site/src/components/Footer.astro": _read("site/src/components/Footer.astro"),
  1442. })
  1443. else:
  1444. stale_exact = {
  1445. path: needles
  1446. for path, needles in stale_exact.items()
  1447. if not path.startswith("site/")
  1448. }
  1449. stale_hits: list[str] = []
  1450. for path, needles in stale_exact.items():
  1451. for needle in needles:
  1452. if needle in stale_sources[path]:
  1453. stale_hits.append(f"{path}: {needle}")
  1454. if stale_hits:
  1455. _fail(f"Claims obsoletos en superficie actual: {stale_hits}")
  1456. manual_only_problems: list[str] = []
  1457. for relative_path in MANUAL_ONLY_SKILLS:
  1458. frontmatter = _frontmatter_block(_read(relative_path))
  1459. if not re.search(r"(?m)^disable-model-invocation:\s*true\s*$", frontmatter):
  1460. manual_only_problems.append(relative_path)
  1461. if manual_only_problems:
  1462. _fail(
  1463. "Skills delicados sin activacion manual explicita: "
  1464. f"{manual_only_problems}"
  1465. )
  1466. legacy_runtime: list[str] = []
  1467. legacy_pattern = re.compile(r"/alfred\s+(feature|fix|ship|spike|audit|config)\b")
  1468. for path in sorted((ROOT / "agents").glob("*.md")):
  1469. text = path.read_text(encoding="utf-8")
  1470. for match in legacy_pattern.finditer(text):
  1471. legacy_runtime.append(f"{_rel(path)}:{match.group(0)}")
  1472. if legacy_runtime:
  1473. _fail(f"Prompts runtime con slash command legacy: {legacy_runtime}")
  1474. surface_message = (
  1475. "README, landing, arquitectura, help y agentes sin contadores antiguos"
  1476. if has_site
  1477. else "README, arquitectura, help y agentes sin contadores antiguos"
  1478. )
  1479. display_name_message = (
  1480. "displayName humano reflejado en README, changelog y landing"
  1481. if has_site
  1482. else "displayName humano reflejado en README y changelog"
  1483. )
  1484. return [
  1485. "inventario publico 10/11/18 verificado",
  1486. surface_message,
  1487. display_name_message,
  1488. "skills delicados mantienen activacion manual explicita",
  1489. "Lucius no fija modelo obsoleto de Codex CLI",
  1490. "prompts runtime sin /alfred legacy",
  1491. ]
  1492. def check_config_contracts() -> list[str]:
  1493. """Verifica que /alfred-dev:ajustes exponga las opciones reales del runtime."""
  1494. from core import config_loader
  1495. from core import optional_agents
  1496. def assert_ask_user_question_payload(label: str, payload: dict) -> None:
  1497. questions = payload.get("questions")
  1498. if not isinstance(questions, list) or len(questions) != 1:
  1499. _fail(f"{label} no expone questions[0] para AskUserQuestion: {payload}")
  1500. question = questions[0]
  1501. if not isinstance(question, dict):
  1502. _fail(f"{label}.questions[0] no es objeto: {question}")
  1503. for field in ("question", "header", "options", "multiSelect"):
  1504. if field not in question:
  1505. _fail(f"{label}.questions[0] no declara {field}")
  1506. if question["multiSelect"] is not False:
  1507. _fail(f"{label}.questions[0].multiSelect debe ser false")
  1508. if question["question"] != payload.get("question"):
  1509. _fail(f"{label}.questions[0].question no coincide con legacy question")
  1510. if question["header"] != payload.get("header"):
  1511. _fail(f"{label}.questions[0].header no coincide con legacy header")
  1512. if question["options"] != payload.get("options"):
  1513. _fail(f"{label}.questions[0].options no coincide con legacy options")
  1514. for index, option in enumerate(question["options"]):
  1515. if not isinstance(option, dict):
  1516. _fail(f"{label}.questions[0].options[{index}] no es objeto")
  1517. if not str(option.get("label", "")).strip():
  1518. _fail(f"{label}.questions[0].options[{index}] no declara label")
  1519. if not str(option.get("description", "")).strip():
  1520. _fail(f"{label}.questions[0].options[{index}] no declara description")
  1521. def assert_prompt_examples_use_current_ask_user_question_schema(
  1522. relative_path: str,
  1523. text: str,
  1524. ) -> None:
  1525. for match in re.finditer(r"AskUserQuestion\(\{(?P<body>.*?)^\}\)", text, re.DOTALL | re.MULTILINE):
  1526. body = match.group("body")
  1527. missing = [
  1528. needle
  1529. for needle in ("questions: [", "multiSelect: false", "options: [")
  1530. if needle not in body
  1531. ]
  1532. if missing:
  1533. _fail(
  1534. "Ejemplo AskUserQuestion obsoleto en "
  1535. f"{relative_path}: faltan {missing}"
  1536. )
  1537. expected_sections = (
  1538. "autonomia",
  1539. "proyecto",
  1540. "agentes_opcionales",
  1541. "memoria",
  1542. "compliance",
  1543. "integraciones",
  1544. "personalidad",
  1545. )
  1546. if tuple(config_loader._CONFIG_SECTION_ORDER) != expected_sections:
  1547. _fail(
  1548. "Orden de secciones config desalineado: "
  1549. f"{config_loader._CONFIG_SECTION_ORDER}"
  1550. )
  1551. labels = config_loader._CONFIG_SECTION_LABELS
  1552. if set(labels) != set(expected_sections):
  1553. _fail(f"Labels config desalineados: {sorted(labels)}")
  1554. summaries = config_loader.build_config_section_summaries(config_loader.DEFAULT_CONFIG)
  1555. summary_sections = tuple(section["section"] for section in summaries)
  1556. if summary_sections != expected_sections:
  1557. _fail(f"Summaries config desalineados: {summary_sections}")
  1558. menu = config_loader.build_config_section_menu(config_loader.DEFAULT_CONFIG)
  1559. menu_labels = [option["label"] for option in menu["options"]]
  1560. if menu_labels[0] != "Salir sin cambios":
  1561. _fail(f"Menu config sin salida inicial: {menu_labels}")
  1562. missing_labels = [
  1563. labels[section]
  1564. for section in expected_sections
  1565. if labels[section] not in menu_labels
  1566. ]
  1567. if missing_labels:
  1568. _fail(f"Menu config no expone secciones: {missing_labels}")
  1569. assert_ask_user_question_payload("build_config_section_menu", menu)
  1570. for group_name in optional_agents.OPTIONAL_AGENT_GROUP_ORDER:
  1571. assert_ask_user_question_payload(
  1572. f"build_optional_agent_group_menu[{group_name}]",
  1573. optional_agents.build_optional_agent_group_menu(group_name),
  1574. )
  1575. preview = config_loader.build_config_section_change_preview(
  1576. config_loader.DEFAULT_CONFIG,
  1577. "memoria",
  1578. {"enabled": True},
  1579. )
  1580. if not preview["changed"] or not preview["updated_config"]["memoria"]["enabled"]:
  1581. _fail(f"Preview config no detecta cambio de memoria: {preview}")
  1582. section_updates = {
  1583. "autonomia": {
  1584. "producto": "interactivo",
  1585. "calidad": "semi-autonomo",
  1586. },
  1587. "proyecto": {
  1588. "runtime": "node",
  1589. "lenguaje": "typescript",
  1590. "framework": "next",
  1591. "test_runner": "vitest",
  1592. "bundler": "vite",
  1593. },
  1594. "agentes_opcionales": {
  1595. "lucius": True,
  1596. "lucius": True,
  1597. },
  1598. "memoria": {
  1599. "enabled": True,
  1600. "sync_commits_limit": 3,
  1601. "retention_days": 30,
  1602. },
  1603. "compliance": {
  1604. "estilo": "strict",
  1605. "lint": False,
  1606. "format_on_save": False,
  1607. },
  1608. "integraciones": {
  1609. "git": False,
  1610. "ci": True,
  1611. "deploy": True,
  1612. },
  1613. "personalidad": {
  1614. "nivel_sarcasmo": 1,
  1615. "verbosidad": "alta",
  1616. "idioma": "es-ES",
  1617. "celebrar_victorias": False,
  1618. },
  1619. }
  1620. if tuple(section_updates) != expected_sections:
  1621. _fail(f"Matriz config desalineada: {tuple(section_updates)}")
  1622. stack_fixtures = {
  1623. "node-typescript": {
  1624. "files": {
  1625. "package.json": json.dumps({"dependencies": {"next": "^15.0.0"}}),
  1626. "tsconfig.json": "{}",
  1627. },
  1628. "expected": {"runtime": "node", "lenguaje": "typescript", "framework": "next"},
  1629. },
  1630. "python": {
  1631. "files": {"requirements.txt": "fastapi==0.110.0\npytest==8.0.0\n"},
  1632. "expected": {"runtime": "python", "lenguaje": "python", "framework": "fastapi"},
  1633. },
  1634. "rust": {
  1635. "files": {"Cargo.toml": "[package]\nname = \"demo\"\n"},
  1636. "expected": {"runtime": "rust", "lenguaje": "rust"},
  1637. },
  1638. "go": {
  1639. "files": {"go.mod": "module example.com/demo\n"},
  1640. "expected": {"runtime": "go", "lenguaje": "go"},
  1641. },
  1642. "ruby": {
  1643. "files": {"Gemfile": "source 'https://rubygems.org'\n"},
  1644. "expected": {"runtime": "ruby", "lenguaje": "ruby"},
  1645. },
  1646. "elixir": {
  1647. "files": {"mix.exs": "defmodule Demo.MixProject do\nend\n"},
  1648. "expected": {"runtime": "elixir", "lenguaje": "elixir"},
  1649. },
  1650. "java": {
  1651. "files": {
  1652. "pom.xml": (
  1653. "<project><dependencies>"
  1654. "<dependency><groupId>org.springframework.boot</groupId>"
  1655. "<artifactId>spring-boot-starter-web</artifactId></dependency>"
  1656. "</dependencies></project>"
  1657. ),
  1658. },
  1659. "expected": {"runtime": "jvm", "lenguaje": "java", "framework": "spring-boot"},
  1660. },
  1661. "kotlin": {
  1662. "files": {
  1663. "build.gradle.kts": (
  1664. "plugins { kotlin(\"jvm\") version \"2.0.0\" }\n"
  1665. "dependencies { implementation(\"io.quarkus:quarkus-rest\") }\n"
  1666. ),
  1667. },
  1668. "expected": {"runtime": "jvm", "lenguaje": "kotlin", "framework": "quarkus"},
  1669. },
  1670. "php": {
  1671. "files": {
  1672. "composer.json": json.dumps({"require": {"laravel/framework": "^11.0"}}),
  1673. },
  1674. "expected": {"runtime": "php", "lenguaje": "php", "framework": "laravel"},
  1675. },
  1676. "dotnet": {
  1677. "files": {"App.csproj": '<Project Sdk="Microsoft.NET.Sdk.Web"></Project>'},
  1678. "expected": {"runtime": "dotnet", "lenguaje": "csharp", "framework": "aspnet"},
  1679. },
  1680. "swift": {
  1681. "files": {
  1682. "Package.swift": (
  1683. "let package = Package("
  1684. "dependencies: [.package(url: \"https://github.com/vapor/vapor\", from: \"4.0.0\")])"
  1685. ),
  1686. },
  1687. "expected": {"runtime": "swift", "lenguaje": "swift", "framework": "vapor"},
  1688. },
  1689. }
  1690. with tempfile.TemporaryDirectory(prefix="alfred-stack-audit-") as tmp:
  1691. tmp_path = Path(tmp)
  1692. for fixture_name, fixture in stack_fixtures.items():
  1693. project_path = tmp_path / fixture_name
  1694. project_path.mkdir()
  1695. for relative_path, content in fixture["files"].items():
  1696. target = project_path / relative_path
  1697. target.parent.mkdir(parents=True, exist_ok=True)
  1698. target.write_text(content, encoding="utf-8")
  1699. stack = config_loader.detect_stack(str(project_path))
  1700. for key, expected_value in fixture["expected"].items():
  1701. actual = stack.get(key)
  1702. if actual != expected_value:
  1703. _fail(
  1704. "Deteccion de stack prometido desalineada: "
  1705. f"{fixture_name}.{key}={actual!r} != {expected_value!r}"
  1706. )
  1707. with tempfile.TemporaryDirectory(prefix="alfred-config-audit-") as tmp:
  1708. config_path = Path(tmp) / "alfred-dev.local.md"
  1709. config_path.write_text(
  1710. "---\n"
  1711. "memoria:\n"
  1712. " enabled: false\n"
  1713. "---\n\n"
  1714. "## Notas\n\n"
  1715. "Nota estable.\n",
  1716. encoding="utf-8",
  1717. )
  1718. for section_name, values in section_updates.items():
  1719. section_preview = config_loader.build_config_section_change_preview(
  1720. config_loader.DEFAULT_CONFIG,
  1721. section_name,
  1722. values,
  1723. )
  1724. if not section_preview["changed"]:
  1725. _fail(f"Preview config no detecta cambio en {section_name}: {section_preview}")
  1726. for key, value in values.items():
  1727. actual = section_preview["updated_config"][section_name].get(key)
  1728. if actual != value:
  1729. _fail(
  1730. "Preview config no aplica valor "
  1731. f"{section_name}.{key}: {actual!r} != {value!r}"
  1732. )
  1733. persisted_preview = config_loader.update_config_section(
  1734. str(config_path),
  1735. section_name,
  1736. values,
  1737. include_defaults=False,
  1738. )
  1739. if persisted_preview["section"] != section_name:
  1740. _fail(
  1741. "Persistencia config devuelve seccion incorrecta: "
  1742. f"{persisted_preview}"
  1743. )
  1744. reloaded = config_loader.load_config(str(config_path))
  1745. for key, value in values.items():
  1746. actual = reloaded[section_name].get(key)
  1747. if actual != value:
  1748. _fail(
  1749. "Persistencia config no conserva valor "
  1750. f"{section_name}.{key}: {actual!r} != {value!r}"
  1751. )
  1752. if "Nota estable" not in reloaded.get("notas", ""):
  1753. _fail(f"Persistencia config pierde notas tras {section_name}")
  1754. command_norm = _normalize(_read("commands/ajustes.md"))
  1755. docs_norm = _normalize(_read("docs/configuration.md"))
  1756. architecture = _read("docs/architecture.md")
  1757. assert_prompt_examples_use_current_ask_user_question_schema(
  1758. "commands/ajustes.md",
  1759. _read("commands/ajustes.md"),
  1760. )
  1761. assert_prompt_examples_use_current_ask_user_question_schema(
  1762. "commands/_composicion.md",
  1763. _read("commands/_composicion.md"),
  1764. )
  1765. required_human_labels = [
  1766. "autonomia por fase",
  1767. "proyecto",
  1768. "agentes opcionales",
  1769. "memoria persistente",
  1770. "compliance",
  1771. "integraciones",
  1772. "personalidad",
  1773. ]
  1774. missing: list[str] = []
  1775. for label in required_human_labels:
  1776. if label not in command_norm:
  1777. missing.append(f"commands/config.md: {label}")
  1778. if label not in docs_norm:
  1779. missing.append(f"docs/configuration.md: {label}")
  1780. helper_names = [
  1781. "build_config_section_summaries()",
  1782. "build_config_section_menu()",
  1783. "apply_config_section_update()",
  1784. "build_config_section_change_preview()",
  1785. "update_config_section()",
  1786. "update_project_config_section()",
  1787. ]
  1788. for helper_name in helper_names:
  1789. if helper_name not in _read("commands/ajustes.md"):
  1790. missing.append(f"commands/config.md: {helper_name}")
  1791. if helper_name not in _read("docs/configuration.md"):
  1792. missing.append(f"docs/configuration.md: {helper_name}")
  1793. if helper_name not in architecture:
  1794. missing.append(f"docs/architecture.md: {helper_name}")
  1795. for needle in ("questions[]", "multiselect: false"):
  1796. if needle not in docs_norm:
  1797. missing.append(f"docs/configuration.md: {needle}")
  1798. if missing:
  1799. _fail("Contratos config incompletos: " + "; ".join(missing))
  1800. return [
  1801. "7 secciones config alineadas con runtime",
  1802. "deteccion automatica cubre stacks prometidos",
  1803. "menu config principal expone salida y secciones canonicas",
  1804. "preview config antes/despues operativo",
  1805. "7 secciones config con round-trip preview/persistencia",
  1806. "docs y comando config cubren helpers canonicos",
  1807. "AskUserQuestion config/optional usa questions[] y multiSelect actuales",
  1808. ]
  1809. def check_flow_gate_claims() -> list[str]:
  1810. """Ejercita claims publicos de flujos, Selina, gates y autopilot."""
  1811. from core.config_loader import has_frontend
  1812. from core.orchestrator import (
  1813. FLOWS,
  1814. advance_phase,
  1815. check_gate,
  1816. create_session,
  1817. is_autopilot_gate_passable,
  1818. )
  1819. problems: list[str] = []
  1820. flows_doc = _read("docs/flows.md")
  1821. configuration_doc = _read("docs/configuration.md")
  1822. readme = _read("README.md")
  1823. has_site = _has_site()
  1824. free_gate_doc_requirements = {
  1825. "docs/flows.md": (
  1826. "evidencia directa del artefacto o checklist esperado",
  1827. "no la convierte en una aprobacion incondicional",
  1828. "Docs completas, gate libre con evidencia",
  1829. ),
  1830. "docs/configuration.md": (
  1831. "Requiere resultado favorable y evidencia/checklist; no pide aprobacion humana.",
  1832. ),
  1833. "README.md": (
  1834. "Todos los artefactos están documentados con checklist/evidencia revisable",
  1835. ),
  1836. }
  1837. free_gate_sources = {
  1838. "docs/flows.md": flows_doc,
  1839. "docs/configuration.md": configuration_doc,
  1840. "README.md": readme,
  1841. }
  1842. for path, needles in free_gate_doc_requirements.items():
  1843. for needle in needles:
  1844. if needle not in free_gate_sources[path]:
  1845. problems.append(f"{path}: gate libre/documentacion sin contrato honesto {needle!r}")
  1846. stale_free_gate_claims = {
  1847. "docs/flows.md": (
  1848. "Se supera siempre que el resultado sea favorable.",
  1849. "Avance automático con gate libre",
  1850. ),
  1851. "docs/configuration.md": (
  1852. "Se supera siempre que el resultado sea favorable.",
  1853. ),
  1854. "README.md": (
  1855. "Todos los artefactos están documentados |",
  1856. ),
  1857. }
  1858. for path, needles in stale_free_gate_claims.items():
  1859. for needle in needles:
  1860. if needle in free_gate_sources[path]:
  1861. problems.append(f"{path}: claim de gate libre demasiado laxo {needle!r}")
  1862. public_gate_sources = {
  1863. "README.md": readme,
  1864. "docs/README.md": _read("docs/README.md"),
  1865. "docs/agents/README.md": _read("docs/agents/README.md"),
  1866. "docs/hooks.md": _read("docs/hooks.md"),
  1867. "docs/release.md": _read("docs/release.md"),
  1868. }
  1869. public_gate_requirements = {
  1870. "README.md": (
  1871. "quality gates verificables",
  1872. "Autopilot solo resuelve gates de usuario configuradas",
  1873. "no salta tests, seguridad, evidencia ni confirmación humana de despliegue",
  1874. ),
  1875. "docs/README.md": ("quality gates verificables con evidencia",),
  1876. "docs/agents/README.md": ("quality gates verificables con evidencia",),
  1877. "docs/hooks.md": ("quality gates verificables con evidencia",),
  1878. "docs/release.md": ("quality gates son verificables por contrato local",),
  1879. }
  1880. if has_site:
  1881. public_gate_sources["site/src/i18n/data.en.ts"] = _read("site/src/i18n/data.en.ts")
  1882. public_gate_requirements["site/src/i18n/data.en.ts"] = (
  1883. "quality gates that require evidence before work can close",
  1884. )
  1885. for path, needles in public_gate_requirements.items():
  1886. for needle in needles:
  1887. if needle not in public_gate_sources[path]:
  1888. problems.append(f"{path}: claim de gates sin evidencia verificable {needle!r}")
  1889. public_gate_stale = {
  1890. "README.md": (
  1891. "quality gates infranqueables",
  1892. "No hay excepciones, no hay modo de saltárselas",
  1893. ),
  1894. "docs/README.md": ("quality gates infranqueables",),
  1895. "docs/agents/README.md": ("quality gates infranqueables",),
  1896. "docs/hooks.md": ("quality gates infranqueables",),
  1897. "docs/release.md": ("quality gates son infranqueables",),
  1898. }
  1899. if has_site:
  1900. public_gate_stale["site/src/i18n/data.en.ts"] = ("quality gates the workflow cannot skip",)
  1901. for path, needles in public_gate_stale.items():
  1902. for needle in needles:
  1903. if needle in public_gate_sources[path]:
  1904. problems.append(f"{path}: claim absoluto de gate sin matiz de evidencia {needle!r}")
  1905. feature_phases = FLOWS["feature"]["fases"]
  1906. if len(feature_phases) != 7:
  1907. problems.append(f"feature debe tener 7 fases, tiene {len(feature_phases)}")
  1908. estilo = feature_phases[1] if len(feature_phases) > 1 else {}
  1909. expected_style_contract = {
  1910. "nombre": "estilo_visual",
  1911. "agentes": ["selina"],
  1912. "gate_tipo": "usuario",
  1913. "condicion": "tiene_frontend",
  1914. }
  1915. for key, expected in expected_style_contract.items():
  1916. if estilo.get(key) != expected:
  1917. problems.append(f"estilo_visual.{key}={estilo.get(key)!r} != {expected!r}")
  1918. if not has_frontend({"framework": "next", "runtime": "node"}):
  1919. problems.append("has_frontend no reconoce Next como frontend")
  1920. if has_frontend({"framework": "fastapi", "runtime": "python"}):
  1921. problems.append("has_frontend trata FastAPI como frontend")
  1922. frontend_session = create_session(
  1923. "feature",
  1924. "Panel con UI",
  1925. stack={"runtime": "node", "framework": "next"},
  1926. )
  1927. frontend_session = advance_phase(frontend_session, resultado="aprobado")
  1928. if frontend_session["fase_actual"] != "estilo_visual":
  1929. problems.append("feature con frontend no entra en estilo_visual tras producto")
  1930. backend_session = create_session(
  1931. "feature",
  1932. "API sin UI",
  1933. stack={"runtime": "python", "framework": "fastapi"},
  1934. )
  1935. backend_session = advance_phase(backend_session, resultado="aprobado")
  1936. skipped_style = [
  1937. phase
  1938. for phase in backend_session.get("fases_completadas", [])
  1939. if phase.get("nombre") == "estilo_visual"
  1940. ]
  1941. if backend_session["fase_actual"] != "arquitectura" or not skipped_style:
  1942. problems.append("feature sin frontend no salta estilo_visual hacia arquitectura")
  1943. elif skipped_style[0].get("resultado") != "saltada":
  1944. problems.append(f"estilo_visual saltada registra resultado inesperado: {skipped_style[0]}")
  1945. gate_session = create_session("feature", "Gates estrictas")
  1946. gate_session = advance_phase(gate_session, resultado="aprobado")
  1947. gate_session = advance_phase(gate_session, resultado="aprobado")
  1948. gate_session = advance_phase(gate_session, resultado="aprobado")
  1949. if check_gate(gate_session, resultado="aprobado", tests_ok=False)["passed"]:
  1950. problems.append("gate automatica de desarrollo no bloquea tests rojos")
  1951. gate_session = advance_phase(gate_session, resultado="aprobado", tests_ok=True)
  1952. if check_gate(gate_session, resultado="aprobado", security_ok=False)["passed"]:
  1953. problems.append("gate automatico+seguridad de calidad no bloquea seguridad KO")
  1954. autopilot_session = create_session("feature", "Autopilot")
  1955. autopilot_session["autopilot"] = True
  1956. if not is_autopilot_gate_passable(autopilot_session)["passed"]:
  1957. problems.append("autopilot no aprueba gate de usuario")
  1958. autopilot_session = advance_phase(autopilot_session, resultado="aprobado")
  1959. autopilot_session = advance_phase(autopilot_session, resultado="aprobado")
  1960. autopilot_session = advance_phase(autopilot_session, resultado="aprobado")
  1961. if is_autopilot_gate_passable(autopilot_session, tests_ok=False)["passed"]:
  1962. problems.append("autopilot salta gate automatica con tests rojos")
  1963. ship_session = create_session("ship", "Release autopilot")
  1964. ship_session["autopilot"] = True
  1965. ship_session = advance_phase(ship_session, resultado="aprobado", tests_ok=True, security_ok=True)
  1966. ship_session = advance_phase(ship_session, resultado="aprobado")
  1967. ship_session = advance_phase(ship_session, resultado="aprobado", tests_ok=True, security_ok=True)
  1968. ship_gate = is_autopilot_gate_passable(ship_session, security_ok=True)
  1969. if ship_session["fase_actual"] != "despliegue":
  1970. problems.append(f"ship no llega a despliegue en la fase esperada: {ship_session['fase_actual']}")
  1971. if ship_gate["passed"] or "confirmación explícita del usuario" not in ship_gate.get("reason", ""):
  1972. problems.append("ship autopilot no conserva confirmacion humana de despliegue")
  1973. if problems:
  1974. _fail("Claims de flujos/gates desalineados: " + "; ".join(problems))
  1975. return [
  1976. "feature mantiene 7 fases con Selina condicional",
  1977. "Selina se ejecuta solo con frontend y se salta con backend",
  1978. "gates libres documentadas como evidencia sin aprobacion humana",
  1979. "gates automaticas bloquean tests rojos y seguridad KO",
  1980. "autopilot no salta gates automaticas ni despliegue humano",
  1981. ]
  1982. def check_hook_contracts() -> list[str]:
  1983. """Verifica que hooks.json siga el contrato moderno de Claude Code."""
  1984. hooks_config = _json("hooks/hooks.json")
  1985. hooks_by_event = hooks_config.get("hooks")
  1986. if not isinstance(hooks_by_event, dict):
  1987. _fail("hooks/hooks.json no declara hooks")
  1988. expected_events = {
  1989. "SessionStart",
  1990. "SessionEnd",
  1991. "UserPromptSubmit",
  1992. "PreToolUse",
  1993. "PostToolUse",
  1994. }
  1995. actual_events = set(hooks_by_event)
  1996. if actual_events != expected_events:
  1997. missing_events = sorted(expected_events - actual_events)
  1998. extra_events = sorted(actual_events - expected_events)
  1999. _fail(
  2000. "Eventos de hooks desalineados: "
  2001. f"actual={sorted(hooks_by_event)} missing={missing_events} extra={extra_events}"
  2002. )
  2003. visible_scripts = sorted(
  2004. path.name
  2005. for path in (ROOT / "hooks").iterdir()
  2006. if path.is_file()
  2007. and path.suffix in {".py", ".sh"}
  2008. and path.name not in {"evidence_guard_lib.py", "secret-guard.sh"}
  2009. )
  2010. if len(visible_scripts) != 10:
  2011. _fail(f"Hooks visibles inesperados: {visible_scripts}")
  2012. registered: list[tuple[str, str, dict]] = []
  2013. problems: list[str] = []
  2014. for event, groups in hooks_by_event.items():
  2015. if not isinstance(groups, list) or not groups:
  2016. problems.append(f"{event}: debe contener grupos")
  2017. continue
  2018. for group in groups:
  2019. if not isinstance(group, dict):
  2020. problems.append(f"{event}: grupo no es objeto")
  2021. continue
  2022. if event in HOOK_EVENTS_WITHOUT_MATCHER and "matcher" in group:
  2023. problems.append(
  2024. f"{event}: declara matcher que Claude Code ignora en este evento"
  2025. )
  2026. for hook in group.get("hooks", []):
  2027. if not isinstance(hook, dict) or hook.get("type") != "command":
  2028. problems.append(f"{event}: hook no command")
  2029. continue
  2030. if "if" in hook:
  2031. if event not in HOOK_EVENTS_WITH_IF_SUPPORT:
  2032. problems.append(
  2033. f"{event}: declara if que Claude Code no evalua en este evento"
  2034. )
  2035. elif not isinstance(hook["if"], str) or not hook["if"].strip():
  2036. problems.append(f"{event}: if debe ser string no vacio")
  2037. command = hook.get("command")
  2038. args = hook.get("args")
  2039. if not isinstance(command, str) or not command:
  2040. problems.append(f"{event}: command invalido")
  2041. continue
  2042. if "|| true" in command or "test -f" in command:
  2043. problems.append(f"{event}: command shell neutraliza errores: {command}")
  2044. if "${CLAUDE_PLUGIN_ROOT}" in command:
  2045. problems.append(f"{event}: usa placeholder en command en vez de args: {command}")
  2046. if not isinstance(args, list) or len(args) != 1 or not isinstance(args[0], str):
  2047. problems.append(f"{event}: hook sin args exec form para {command}")
  2048. continue
  2049. script_arg = args[0]
  2050. prefix = "${CLAUDE_PLUGIN_ROOT}/hooks/"
  2051. if not script_arg.startswith(prefix):
  2052. problems.append(f"{event}: args no apunta a hooks/: {script_arg}")
  2053. continue
  2054. script_name = script_arg.removeprefix(prefix)
  2055. script_path = ROOT / "hooks" / script_name
  2056. if not script_path.is_file():
  2057. problems.append(f"{event}: script no existe {script_name}")
  2058. continue
  2059. if script_name.endswith(".py") and command != "python3":
  2060. problems.append(f"{script_name}: debe usar command python3")
  2061. if script_name.endswith(".sh") and command != "bash":
  2062. problems.append(f"{script_name}: debe usar command bash")
  2063. if "async" in hook and not isinstance(hook["async"], bool):
  2064. problems.append(f"{script_name}: async debe ser booleano")
  2065. timeout = hook.get("timeout")
  2066. if hook.get("async") is not True:
  2067. if type(timeout) is not int:
  2068. problems.append(f"{script_name}: hook sincronico sin timeout entero")
  2069. elif timeout > HOOK_SYNC_TIMEOUT_LIMIT:
  2070. problems.append(
  2071. f"{script_name}: hook sincronico supera timeout "
  2072. f"{HOOK_SYNC_TIMEOUT_LIMIT}s ({timeout}s)"
  2073. )
  2074. registered.append((event, script_name, hook))
  2075. registered_names = {script_name for _, script_name, _ in registered}
  2076. missing = sorted(set(visible_scripts) - registered_names)
  2077. extras = sorted(registered_names - set(visible_scripts))
  2078. if missing:
  2079. problems.append(f"scripts sin registrar: {missing}")
  2080. if extras:
  2081. problems.append(f"scripts registrados inesperados: {extras}")
  2082. blocking = {
  2083. "secret-guard.py",
  2084. "dangerous-command-guard.py",
  2085. }
  2086. for script_name in blocking:
  2087. matches = [
  2088. (event, hook)
  2089. for event, registered_script, hook in registered
  2090. if registered_script == script_name
  2091. ]
  2092. if not matches:
  2093. problems.append(f"{script_name}: no registrado")
  2094. continue
  2095. for event, hook in matches:
  2096. if event != "PreToolUse":
  2097. problems.append(f"{script_name}: debe registrarse en PreToolUse, no {event}")
  2098. if hook.get("async"):
  2099. problems.append(f"{script_name}: no puede ser async")
  2100. if hook.get("timeout", 99) > 5:
  2101. problems.append(f"{script_name}: timeout debe ser <= 5")
  2102. for path in sorted((ROOT / "hooks").glob("*.py")):
  2103. source = path.read_text(encoding="utf-8")
  2104. compile(source, str(path), "exec")
  2105. for path in sorted((ROOT / "hooks").glob("*.sh")):
  2106. result = subprocess.run(
  2107. ["bash", "-n", str(path)],
  2108. cwd=ROOT,
  2109. text=True,
  2110. stdout=subprocess.PIPE,
  2111. stderr=subprocess.STDOUT,
  2112. check=False,
  2113. )
  2114. if result.returncode != 0:
  2115. problems.append(f"{_rel(path)}: bash -n fallo: {result.stdout}")
  2116. wrapper_needles = (
  2117. "EMBEDDED_PLUGIN_ROOT",
  2118. "CLAUDE_PLUGIN_ROOT",
  2119. "ALFRED_DEV_PLUGIN_ROOT",
  2120. "def _cache_candidates():",
  2121. "core/continuity.py",
  2122. )
  2123. for script_name in ("session-bootstrap.sh",):
  2124. source = _read(f"hooks/{script_name}")
  2125. for needle in wrapper_needles:
  2126. if needle not in source:
  2127. problems.append(f"{script_name}: wrapper no contiene {needle}")
  2128. hooks_doc = _read("docs/hooks.md")
  2129. if '"decisión": "block"' in hooks_doc:
  2130. problems.append("docs/hooks.md usa clave obsoleta \"decisión\" en vez de decision")
  2131. nested_hook_output = re.findall(
  2132. r"hookSpecificOutput\.(?:"
  2133. r"SessionStart|UserPromptSubmit|UserPromptExpansion|Stop|PreToolUse|PreCompact|PostToolUse|"
  2134. r"PostToolUseFailure|PostToolBatch|PermissionRequest|Notification|"
  2135. r"Setup|SubagentStart"
  2136. r")\.[A-Za-z]",
  2137. hooks_doc,
  2138. )
  2139. if nested_hook_output:
  2140. problems.append(
  2141. "docs/hooks.md usa hookSpecificOutput anidado por evento: "
  2142. f"{sorted(set(nested_hook_output))}"
  2143. )
  2144. for needle in (
  2145. '"decision": "block"',
  2146. "hookSpecificOutput.hookEventName",
  2147. "hookSpecificOutput.additionalContext",
  2148. "systemMessage",
  2149. "Claude Code ignora `matcher`",
  2150. "El campo `if` solo se evalua en eventos de herramientas",
  2151. "`manual\\|auto` omitido para cubrir ambos",
  2152. "Claude Code ignora cualquier JSON cuando el proceso sale con `2`",
  2153. "no mezcles JSON de control con `exit 2`",
  2154. ):
  2155. if needle not in hooks_doc:
  2156. problems.append(f"docs/hooks.md no documenta contrato moderno de hooks: {needle}")
  2157. if "Los hooks sincronos no deben superar los 10 segundos" not in hooks_doc:
  2158. problems.append("docs/hooks.md no documenta limite de timeout sincronico")
  2159. direct_checks = [
  2160. (
  2161. "secret-guard invalid json",
  2162. ["bash", str(ROOT / "hooks" / "secret-guard.sh")],
  2163. "not-json",
  2164. ),
  2165. (
  2166. "dangerous-command invalid json",
  2167. [sys.executable, str(ROOT / "hooks" / "dangerous-command-guard.py")],
  2168. "not-json",
  2169. ),
  2170. (
  2171. "dangerous-command rm root",
  2172. [sys.executable, str(ROOT / "hooks" / "dangerous-command-guard.py")],
  2173. json.dumps(
  2174. {
  2175. "hook_event_name": "PreToolUse",
  2176. "tool_name": "Bash",
  2177. "tool_input": {"command": "rm -rf /"},
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 2,361 on GitHub
  2178. }
  2179. ),
  2180. ),
  2181. ]
  2182. for name, command, stdin in direct_checks:
  2183. result = subprocess.run(
  2184. command,
  2185. cwd=ROOT,
  2186. input=stdin,
  2187. text=True,
  2188. stdout=subprocess.PIPE,
  2189. stderr=subprocess.PIPE,
  2190. check=False,
  2191. timeout=10,
  2192. )
  2193. if result.returncode != 2:
  2194. problems.append(
  2195. f"{name}: esperaba exit 2, obtuvo {result.returncode}; "
  2196. f"stdout={result.stdout!r} stderr={result.stderr!r}"
  2197. )
  2198. if result.stdout:
  2199. problems.append(
  2200. f"{name}: un hook con exit 2 no debe emitir JSON/stdout "
  2201. f"porque Claude Code lo ignora: {result.stdout!r}"
  2202. )
  2203. with tempfile.TemporaryDirectory() as tmpdir:
  2204. project = Path(tmpdir)
  2205. (project / ".claude").mkdir()
  2206. (project / ".claude" / "alfred-prefetch.json").write_text(
  2207. json.dumps(
  2208. {
  2209. "source_command": "alfred",
  2210. "prefetched_command": "map-codebase",
  2211. "response_text": "prefetch listo",
  2212. "expires_at": "2999-01-01T00:00:00+00:00",
  2213. }
  2214. ),
  2215. encoding="utf-8",
  2216. )
  2217. pass
  2218. if problems:
  2219. _fail("Contratos de hooks incompletos: " + "; ".join(problems))
  2220. return [
  2221. "10 hooks visibles registrados",
  2222. "scripts de hooks declarados existen y cubren los 9 visibles",
  2223. "exec form sin shell wrappers ni rutas sin comillas",
  2224. "hooks bloqueantes conservan exit 2",
  2225. "hooks con exit 2 no emiten JSON ignorado por Claude Code",
  2226. "eventos SessionStart, SessionEnd, UserPromptSubmit, PreToolUse y PostToolUse",
  2227. "eventos sin matcher no declaran matcher ignorado",
  2228. "hooks no usan if fuera de eventos de herramienta",
  2229. "hooks sincronos declaran timeout entero <= 10 segundos",
  2230. "sintaxis de hooks validada",
  2231. "wrapper helper-first resiliente a cache de plugin rotada",
  2232. "docs de hooks usan decision/hookSpecificOutput actuales",
  2233. ]
  2234. def check_mcp_config() -> list[str]:
  2235. mcp = _json(".mcp.json")
  2236. server = mcp.get("mcpServers", {}).get("alfred-memory")
  2237. if not isinstance(server, dict):
  2238. _fail(".mcp.json no declara mcpServers.alfred-memory")
  2239. if server.get("command") != "python3":
  2240. _fail("alfred-memory debe arrancar con command python3 para que los instaladores puedan parchearlo")
  2241. args = server.get("args")
  2242. if not isinstance(args, list) or not args or "memory_server.py" not in str(args[0]):
  2243. _fail("alfred-memory debe apuntar a mcp/memory_server.py")
  2244. if "${CLAUDE_PLUGIN_ROOT}" not in str(args[0]):
  2245. _fail("alfred-memory debe usar CLAUDE_PLUGIN_ROOT")
  2246. return ["MCP raiz portable con memory_server.py"]
  2247. def _npm_pack_dry_run_package() -> dict:
  2248. completed = subprocess.run(
  2249. ["npm", "pack", "--dry-run", "--json"],
  2250. cwd=ROOT,
  2251. text=True,
  2252. stdout=subprocess.PIPE,
  2253. stderr=subprocess.PIPE,
  2254. timeout=30,
  2255. check=False,
  2256. )
  2257. if completed.returncode != 0:
  2258. _fail(f"npm pack --dry-run fallo: {completed.stderr.strip()}")
  2259. try:
  2260. payload = json.loads(completed.stdout)
  2261. except json.JSONDecodeError as exc:
  2262. _fail(f"npm pack no devolvio JSON valido: {exc}: {completed.stdout[:500]}")
  2263. if not isinstance(payload, list) or not payload:
  2264. _fail(f"npm pack devolvio payload inesperado: {payload!r}")
  2265. package = payload[0]
  2266. if not isinstance(package, dict):
  2267. _fail(f"npm pack devolvio paquete inesperado: {package!r}")
  2268. return package
  2269. def _publishable_symlink_problems() -> list[str]:
  2270. problems: list[str] = []
  2271. root = ROOT.resolve()
  2272. for root_name in PUBLISHABLE_SYMLINK_ROOTS:
  2273. root_path = ROOT / root_name
  2274. if not root_path.exists() and not root_path.is_symlink():
  2275. continue
  2276. candidates = [root_path]
  2277. if root_path.is_dir() and not root_path.is_symlink():
  2278. candidates.extend(root_path.rglob("*"))
  2279. for path in candidates:
  2280. if not path.is_symlink():
  2281. continue
  2282. try:
  2283. target = path.resolve(strict=True)
  2284. except FileNotFoundError:
  2285. problems.append(f"{_rel(path)} es un symlink roto")
  2286. continue
  2287. try:
  2288. target.relative_to(root)
  2289. except ValueError:
  2290. problems.append(
  2291. f"{_rel(path)} es un symlink fuera del plugin: {os.readlink(path)!r}"
  2292. )
  2293. return problems
  2294. def check_packaging_contracts() -> list[str]:
  2295. """Verifica el paquete real que produciría npm antes de publicar."""
  2296. package = _npm_pack_dry_run_package()
  2297. if package.get("name") != "alfred-dev" or package.get("version") != VERSION:
  2298. _fail(f"npm pack empaqueta identidad inesperada: {package}")
  2299. packed_paths = {
  2300. entry.get("path")
  2301. for entry in package.get("files", [])
  2302. if isinstance(entry, dict)
  2303. }
  2304. required_paths = {
  2305. ".claude-plugin/plugin.json",
  2306. ".claude-plugin/marketplace.json",
  2307. ".mcp.json",
  2308. "commands/_composicion.md",
  2309. "commands/alfred.md",
  2310. "agents/alfred.md",
  2311. "hooks/hooks.json",
  2312. "mcp/memory_server.py",
  2313. "core/continuity.py",
  2314. "scripts/release_audit.py",
  2315. "visual/scripts/frame-template.html",
  2316. "visual/scripts/helper.js",
  2317. "visual/scripts/read-choice.py",
  2318. "visual/scripts/server.cjs",
  2319. "visual/scripts/start-server.sh",
  2320. "visual/scripts/stop-server.sh",
  2321. "visual/scripts/write-guided-style-options.py",
  2322. "visual/scripts/write-style-demo-gallery.py",
  2323. "visual/scripts/write-style-direction.py",
  2324. "visual/scripts/write-style-options.py",
  2325. "visual/scripts/write-style-selector.py",
  2326. }
  2327. required_paths.update(TEMPLATE_PATHS)
  2328. missing_required = sorted(required_paths - packed_paths)
  2329. if missing_required:
  2330. _fail(f"npm pack no incluye artefactos criticos: {missing_required}")
  2331. forbidden_prefixes = (
  2332. ".alfred-dev/",
  2333. ".claude/",
  2334. ".crupier/",
  2335. ".git/",
  2336. ".pytest_cache/",
  2337. "docs/manual-smoke",
  2338. "node_modules/",
  2339. "site/.astro/",
  2340. "site/dist/",
  2341. "site/node_modules/",
  2342. "tests/",
  2343. )
  2344. forbidden_suffixes = (
  2345. ".pyc",
  2346. ".pyo",
  2347. )
  2348. leaked = sorted(
  2349. path for path in packed_paths
  2350. if path and (
  2351. path.startswith(forbidden_prefixes)
  2352. or any(part == "__pycache__" for part in path.split("/"))
  2353. or path.endswith(forbidden_suffixes)
  2354. )
  2355. )
  2356. if leaked:
  2357. _fail(f"npm pack incluye artefactos locales o de test: {leaked[:20]}")
  2358. symlink_problems = _publishable_symlink_problems()
  2359. if symlink_problems:
  2360. _fail("Symlinks publicables incompatibles con la cache de Claude: " + "; ".join(symlink_problems))
  2361. manifest_command_paths = {
  2362. path.lstrip("./")
  2363. for path in _json(".claude-plugin/plugin.json")["commands"]
  2364. }
  2365. public_command_paths = [
  2366. path for path in packed_paths
  2367. if path in manifest_command_paths
  2368. ]
  2369. agent_paths = [
  2370. path for path in packed_paths
  2371. if path.startswith("agents/") and path.endswith(".md")
  2372. ]
  2373. skill_paths = [
  2374. path for path in packed_paths
  2375. if path.startswith("skills/") and path.endswith("/SKILL.md")
  2376. ]
  2377. template_paths = [
  2378. path for path in packed_paths
  2379. if path.startswith("templates/") and path.endswith(".md")
  2380. ]
  2381. if len(public_command_paths) != 18 or len(agent_paths) != 10 or len(skill_paths) != 11:
  2382. _fail(
  2383. "npm pack desalineado con inventario publico: "
  2384. f"commands={len(public_command_paths)} agents={len(agent_paths)} skills={len(skill_paths)}"
  2385. )
  2386. if sorted(template_paths) != sorted(TEMPLATE_PATHS):
  2387. _fail(
  2388. "npm pack desalineado con templates de artefactos: "
  2389. f"{sorted(template_paths)}"
  2390. )
  2391. return [
  2392. f"npm pack dry-run {VERSION} valido",
  2393. "paquete sin caches locales ni tests",
  2394. "paquete sin .claude/.crupier ni evidencias manuales",
  2395. "paquete sin symlinks publicables fuera del plugin",
  2396. "paquete contiene 18 comandos namespaced, 10 agentes y 11 skills",
  2397. "paquete contiene 8 templates de artefactos",
  2398. "paquete contiene runtime visual de Selina",
  2399. ]
  2400. def check_published_secret_scan() -> list[str]:
  2401. """Escanea el artefacto publicable para detectar secretos reales."""
  2402. from core.secrets import find_secret_label
  2403. package = _npm_pack_dry_run_package()
  2404. packed_paths = {
  2405. entry.get("path")
  2406. for entry in package.get("files", [])
  2407. if isinstance(entry, dict)
  2408. }
  2409. findings: list[str] = []
  2410. for relative in sorted(path for path in packed_paths if isinstance(path, str)):
  2411. path = ROOT / relative
  2412. if not path.is_file():
  2413. continue
  2414. try:
  2415. text = path.read_text(encoding="utf-8")
  2416. except UnicodeDecodeError:
  2417. continue
  2418. label = find_secret_label(text)
  2419. if label:
  2420. findings.append(f"{relative}: {label}")
  2421. if findings:
  2422. _fail(
  2423. "El paquete publicable contiene posibles secretos reales: "
  2424. + "; ".join(findings[:20])
  2425. )
  2426. return ["paquete publicable sin patrones de secretos reales"]
  2427. def check_install_update_contracts() -> list[str]:
  2428. """Verifica instalación, desinstalación y update con scopes explícitos."""
  2429. install_sh = _read("install.sh")
  2430. install_ps1 = _read("install.ps1")
  2431. uninstall_sh = _read("uninstall.sh")
  2432. uninstall_ps1 = _read("uninstall.ps1")
  2433. update_command = _read("commands/update.md")
  2434. installation_docs = _read("docs/installation.md")
  2435. requirements = {
  2436. "install.sh": [
  2437. 'claude plugin uninstall "${PLUGIN_NAME}@${PLUGIN_NAME}" --scope local',
  2438. 'claude plugin uninstall "${PLUGIN_NAME}@${PLUGIN_NAME}" --scope project',
  2439. 'claude plugin marketplace remove "${PLUGIN_NAME}" --scope local',
  2440. 'claude plugin marketplace remove "${PLUGIN_NAME}" --scope project',
  2441. 'claude plugin uninstall "${PLUGIN_NAME}@${PLUGIN_NAME}" --scope user',
  2442. 'claude plugin marketplace remove "${PLUGIN_NAME}" --scope user',
  2443. 'claude plugin marketplace add "${REPO}" --scope user',
  2444. 'claude plugin install "${PLUGIN_NAME}@${PLUGIN_NAME}" --scope user',
  2445. "claude plugin list --json",
  2446. "Instalacion global de usuario confirmada (--scope user)",
  2447. "No se pisa ~/.claude/skills",
  2448. 'HOOKS_JSON="${PLUGIN_ROOT}/hooks/hooks.json"',
  2449. 'MCP_JSON="${PLUGIN_ROOT}/.mcp.json"',
  2450. "/reload-plugins",
  2451. "MCP/coste de cache",
  2452. ],
  2453. "install.ps1": [
  2454. "claude plugin uninstall $PluginKey --scope local",
  2455. "claude plugin uninstall $PluginKey --scope project",
  2456. "claude plugin marketplace remove $PluginName --scope local",
  2457. "claude plugin marketplace remove $PluginName --scope project",
  2458. "claude plugin uninstall $pluginKey --scope user",
  2459. "claude plugin marketplace remove $PluginName --scope user",
  2460. "claude plugin marketplace add $Repo --scope user",
  2461. "claude plugin install $pluginKey --scope user",
  2462. "claude plugin list --json",
  2463. "Instalacion global de usuario confirmada (--scope user)",
  2464. "No se pisa ~/.claude/skills",
  2465. 'Join-Path $PluginRoot "hooks/hooks.json"',
  2466. 'Join-Path $PluginRoot ".mcp.json"',
  2467. "/reload-plugins",
  2468. "MCP/coste de cache",
  2469. ],
  2470. "uninstall.sh": [
  2471. 'claude plugin uninstall "${PLUGIN_KEY}" --scope user',
  2472. 'claude plugin marketplace remove "${PLUGIN_NAME}" --scope user',
  2473. 'known_marketplaces.json',
  2474. 'installed_plugins.json',
  2475. 'enabledPlugins',
  2476. "Alias global /alfred eliminado",
  2477. "Shim de comando global /alfred eliminado",
  2478. ],
  2479. "uninstall.ps1": [
  2480. "claude plugin uninstall $PluginKey --scope user",
  2481. "claude plugin marketplace remove $PluginName --scope user",
  2482. "known_marketplaces.json",
  2483. "installed_plugins.json",
  2484. "enabledPlugins",
  2485. "Alias global /alfred eliminado",
  2486. "Shim de comando global /alfred eliminado",
  2487. ],
  2488. "commands/update.md": [
  2489. "claude plugin list --json",
  2490. "semver real",
  2491. "un único `AskUserQuestion`",
  2492. "Actualizar ahora",
  2493. "Ahora no",
  2494. "normaliza a `--scope user`",
  2495. "no pisa `~/.claude/skills`",
  2496. "No uses `claude plugin update --scope local`",
  2497. "`claude plugin update --scope project`",
  2498. "curl -fsSL https://raw.githubusercontent.com/686f6c61/alfred-dev/main/install.sh | bash",
  2499. "ejecutar **`/reload-plugins`**",
  2500. "`/reload-plugins --force`",
  2501. "entonces debe reiniciar",
  2502. ],
  2503. "docs/installation.md": [
  2504. "--scope user",
  2505. "instalación global de usuario",
  2506. "No pisa",
  2507. "~/.claude/commands/alfred.md",
  2508. "claude plugin list --json",
  2509. "No usa un marketplace oficial de Anthropic",
  2510. "`/reload-plugins` aplica los cambios",
  2511. "`/reload-plugins --force`",
  2512. ],
  2513. }
  2514. sources = {
  2515. "install.sh": install_sh,
  2516. "install.ps1": install_ps1,
  2517. "uninstall.sh": uninstall_sh,
  2518. "uninstall.ps1": uninstall_ps1,
  2519. "commands/update.md": update_command,
  2520. "docs/installation.md": installation_docs,
  2521. }
  2522. missing = []
  2523. for path, needles in requirements.items():
  2524. for needle in needles:
  2525. if needle not in sources[path]:
  2526. missing.append(f"{path}: {needle}")
  2527. if missing:
  2528. _fail("Contratos install/update incompletos: " + "; ".join(missing))
  2529. stateful_plugin_command = re.compile(
  2530. r"\bclaude plugin "
  2531. r"(?:(?:marketplace\s+(?:add|remove))|(?:install|uninstall|update))\b"
  2532. )
  2533. bad_scope = []
  2534. for path in ("install.sh", "install.ps1", "uninstall.sh", "uninstall.ps1"):
  2535. for line_number, line in enumerate(sources[path].splitlines(), start=1):
  2536. stripped = line.strip()
  2537. if not stripped or stripped.startswith("#"):
  2538. continue
  2539. if not stateful_plugin_command.search(stripped):
  2540. continue
  2541. scope_match = re.search(r"--scope\s+([A-Za-z_$\{\}]+)", stripped)
  2542. if not scope_match:
  2543. bad_scope.append(f"{path}:{line_number}: {stripped}")
  2544. continue
  2545. scope = scope_match.group(1).strip("${}").lstrip("$")
  2546. if scope == "user":
  2547. continue
  2548. is_cleanup = (
  2549. path in {"install.sh", "install.ps1"}
  2550. and scope in {"local", "project"}
  2551. and (
  2552. "plugin uninstall" in stripped
  2553. or "plugin marketplace remove" in stripped
  2554. )
  2555. )
  2556. if not is_cleanup:
  2557. bad_scope.append(f"{path}:{line_number}: scope {scope} prohibido")
  2558. if bad_scope:
  2559. _fail(
  2560. "CLI plugin sin scope explicito user o limpieza local/project permitida: "
  2561. + "; ".join(bad_scope)
  2562. )
  2563. if "instalación local que limpiar" in uninstall_sh:
  2564. _fail("uninstall.sh no debe describir Alfred Dev como instalacion local")
  2565. return [
  2566. "instaladores usan scope user explicito",
  2567. "instaladores verifican scope user despues de instalar",
  2568. "instaladores limpian scopes local/project heredados antes de instalar user",
  2569. "instaladores no pisan ~/.claude/skills ni instalan alias global /alfred",
  2570. "update conserva semver y menu humano, normaliza a scope user y documenta reload/reinicio",
  2571. ]
  2572. def check_audit_docs() -> list[str]:
  2573. package = _json("package.json")
  2574. readme = _read("README.md")
  2575. docs_readme = _read("docs/README.md")
  2576. architecture = _read("docs/architecture.md")
  2577. install = _read("docs/installation.md")
  2578. release_doc = _read("docs/release.md")
  2579. gitignore = _read(".gitignore")
  2580. npmignore = _read(".npmignore")
  2581. required = {
  2582. "README.md": [
  2583. "Novedades en v0.7.0",
  2584. "docs/release.md",
  2585. "MCP stdio moderno",
  2586. ],
  2587. "docs/README.md": [
  2588. "release.md",
  2589. "11 skills",
  2590. "18 comandos",
  2591. ],
  2592. "docs/installation.md": [
  2593. "plugin:alfred-dev:alfred-memory",
  2594. "Pending approval",
  2595. "No hay que aprobar esa entrada de proyecto",
  2596. 'claude plugin marketplace add "$PWD" --scope user',
  2597. "Claude Code actual sí ofrece diagnósticos útiles",
  2598. "claude plugin details alfred-dev@alfred-dev",
  2599. "claude plugin validate . --strict",
  2600. "claude --debug",
  2601. "/plugin validate",
  2602. ],
  2603. "docs/architecture.md": [
  2604. "`matcher` es opcional",
  2605. "solo se declara en eventos donde Claude Code lo soporta",
  2606. "Claude Code lo ignora",
  2607. "PreCompact",
  2608. "manuales como automáticas",
  2609. ],
  2610. "docs/release.md": [
  2611. "18 comandos",
  2612. "10 agentes",
  2613. "11 skills",
  2614. "10 hooks",
  2615. "displayName: \"Alfred Dev\"",
  2616. "namespace técnico es `alfred-dev`",
  2617. "no pisa `~/.claude/skills`",
  2618. "`_composicion.md`",
  2619. "`_docs_vivas.md`",
  2620. "commands/ como skills planas soportadas",
  2621. "UX pública",
  2622. "`/alfred-dev:*`",
  2623. "argument-hint",
  2624. "$ARGUMENTS",
  2625. "1.536 caracteres",
  2626. "disable-model-invocation: true",
  2627. "npm run release:audit",
  2628. "npm run release:audit:manual",
  2629. "npm run release:audit:manual:evidence",
  2630. "npm run release:audit:prepublish",
  2631. "18 rutas publicas",
  2632. "40 opciones publicas",
  2633. "4 contratos runtime",
  2634. "--auth-preflight",
  2635. "core/secrets.py",
  2636. "permisos `0600`",
  2637. "evidence_file",
  2638. "evidence_sha256",
  2639. "plugin_surface.sha256",
  2640. "notes_low_quality",
  2641. "notes_repeated",
  2642. "--require-current-auth-preflight",
  2643. "auth_preflight.status=ok",
  2644. "scripts/manual_smoke.py",
  2645. "scripts/external_live_smoke.py",
  2646. "no crea issues, no arranca contenedores",
  2647. "quality gates son verificables por contrato local",
  2648. "questions[]",
  2649. "multiSelect",
  2650. "hookSpecificOutput.additionalContext",
  2651. "No aprueba la release por sí mismo",
  2652. "Pendientes que no cubre el contrato local",
  2653. "claude auth login",
  2654. "scripts/claude_auth_recovery.py",
  2655. ],
  2656. }
  2657. sources = {
  2658. "README.md": readme,
  2659. "docs/README.md": docs_readme,
  2660. "docs/architecture.md": architecture,
  2661. "docs/installation.md": install,
  2662. "docs/release.md": release_doc,
  2663. }
  2664. missing = []
  2665. for path, needles in required.items():
  2666. for needle in needles:
  2667. if needle not in sources[path]:
  2668. missing.append(f"{path}: {needle}")
  2669. if re.search(r"PreCompact[^.\n]*(?:ignora|ignorado)", architecture):
  2670. _fail("docs/architecture.md afirma incorrectamente que PreCompact ignora matcher")
  2671. if 'displayName: "Alfred Dev"' not in release_doc:
  2672. _fail("docs/release.md debe documentar displayName humano")
  2673. if re.search(r"plugin_surface\.sha256=[0-9a-f]{64}", release_doc):
  2674. _fail("docs/release.md no debe congelar plugin_surface.sha256")
  2675. if "docs/manual-smoke*.json" not in gitignore:
  2676. _fail(".gitignore debe excluir evidencias/reviews manuales docs/manual-smoke*.json")
  2677. if "docs/manual-smoke*.json" not in npmignore:
  2678. _fail(".npmignore debe excluir evidencias/reviews manuales docs/manual-smoke*.json")
  2679. if "docs/manual-smoke*.md" not in gitignore:
  2680. _fail(".gitignore debe excluir reportes manuales docs/manual-smoke*.md")
  2681. if "docs/manual-smoke*.md" not in npmignore:
  2682. _fail(".npmignore debe excluir reportes manuales docs/manual-smoke*.md")
  2683. if "docs/project/" not in gitignore:
  2684. _fail(".gitignore debe excluir estado operativo local docs/project/")
  2685. if "docs/project/" not in npmignore:
  2686. _fail(".npmignore debe excluir estado operativo local docs/project/")
  2687. if "docs/external-live-smoke*.json" not in gitignore:
  2688. _fail(".gitignore debe excluir evidencias externas docs/external-live-smoke*.json")
  2689. if "docs/external-live-smoke*.json" not in npmignore:
  2690. _fail(".npmignore debe excluir evidencias externas docs/external-live-smoke*.json")
  2691. if "docs/claude-auth-recovery*.json" not in gitignore:
  2692. _fail(".gitignore debe excluir diagnosticos de auth docs/claude-auth-recovery*.json")
  2693. if "docs/claude-auth-recovery*.json" not in npmignore:
  2694. _fail(".npmignore debe excluir diagnosticos de auth docs/claude-auth-recovery*.json")
  2695. if missing:
  2696. _fail(f"Documentacion de auditoria incompleta: {missing}")
  2697. scripts = package.get("scripts", {})
  2698. expected_scripts = {
  2699. "release:audit:external:preflight": (
  2700. "python3 scripts/external_live_smoke.py --output docs/external-live-smoke-0.7.0.json"
  2701. ),
  2702. "release:audit:claude:commands": "python3 scripts/claude_command_discovery.py",
  2703. "release:audit:manual": "python3 scripts/manual_smoke.py",
  2704. "release:audit:manual:evidence": (
  2705. "python3 scripts/manual_smoke.py --auth-preflight --output docs/manual-smoke-0.7.0.json"
  2706. ),
  2707. "release:audit:manual:evidence:installed": (
  2708. "python3 scripts/manual_smoke.py --installed --auth-preflight --output docs/manual-smoke-installed-0.7.0.json"
  2709. ),
  2710. "release:audit:manual:preflight": "python3 scripts/manual_smoke.py --auth-preflight --preflight-only",
  2711. "release:audit:manual:preflight:diagnose": (
  2712. "python3 scripts/manual_smoke.py --auth-preflight --preflight-only --allow-auth-failure"
  2713. ),
  2714. "release:audit:manual:auth:diagnose": "python3 scripts/claude_auth_recovery.py",
  2715. "release:audit:manual:auth:strict": "python3 scripts/claude_auth_recovery.py --strict",
  2716. "release:audit:manual:review:init": (
  2717. "python3 scripts/manual_review_gate.py --init-template docs/manual-smoke-0.7.0.json docs/manual-smoke-review-0.7.0.json"
  2718. ),
  2719. "release:audit:manual:review": (
  2720. "python3 scripts/manual_review_gate.py --require-current-auth-preflight --expect-plugin-source worktree docs/manual-smoke-0.7.0.json docs/manual-smoke-review-0.7.0.json"
  2721. ),
  2722. "release:audit:manual:report": (
  2723. "python3 scripts/manual_review_report.py docs/manual-smoke-0.7.0.json docs/manual-smoke-review-0.7.0.json --output docs/manual-smoke-report-0.7.0.md"
  2724. ),
  2725. "release:audit:manual:review:installed:init": (
  2726. "python3 scripts/manual_review_gate.py --init-template docs/manual-smoke-installed-0.7.0.json docs/manual-smoke-installed-review-0.7.0.json"
  2727. ),
  2728. "release:audit:manual:review:installed": (
  2729. "python3 scripts/manual_review_gate.py --require-current-auth-preflight --expect-plugin-source installed-cache docs/manual-smoke-installed-0.7.0.json docs/manual-smoke-installed-review-0.7.0.json"
  2730. ),
  2731. "release:audit:manual:report:installed": (
  2732. "python3 scripts/manual_review_report.py docs/manual-smoke-installed-0.7.0.json docs/manual-smoke-installed-review-0.7.0.json --output docs/manual-smoke-installed-report-0.7.0.md"
  2733. ),
  2734. "release:audit:prepublish:prepare": (
  2735. "npm run release:audit:full && "
  2736. "npm run release:audit:manual:evidence && "
  2737. "npm run release:audit:manual:evidence:installed"
  2738. ),
  2739. "release:audit:prepublish": (
  2740. "npm run release:audit:full && "
  2741. "npm run release:audit:manual:preflight && "
  2742. "npm run release:audit:manual:review && "
  2743. "npm run release:audit:manual:review:installed"
  2744. ),
  2745. }
  2746. bad_scripts = {
  2747. name: {"actual": scripts.get(name), "expected": expected}
  2748. for name, expected in expected_scripts.items()
  2749. if scripts.get(name) != expected
  2750. }
  2751. if bad_scripts:
  2752. _fail(f"Scripts npm de smoke manual desalineados: {bad_scripts}")
  2753. if not (ROOT / "scripts" / "manual_smoke.py").is_file():
  2754. _fail("Falta scripts/manual_smoke.py para reproducir la matriz manual")
  2755. if not (ROOT / "scripts" / "manual_review_gate.py").is_file():
  2756. _fail("Falta scripts/manual_review_gate.py para validar la revision humana")
  2757. if not (ROOT / "scripts" / "external_live_smoke.py").is_file():
  2758. _fail("Falta scripts/external_live_smoke.py para capturar preflight externo")
  2759. if not (ROOT / "scripts" / "claude_command_discovery.py").is_file():
  2760. _fail("Falta scripts/claude_command_discovery.py para probar /alfred-dev:alfred interactivo")
  2761. if not (ROOT / "docs" / "release.md").is_file():
  2762. _fail("Falta docs/release.md para auditar claims y readiness de salida")
  2763. prepare = scripts.get("release:audit:prepublish:prepare", "")
  2764. required_prepare_parts = (
  2765. "npm run release:audit:full",
  2766. "npm run release:audit:manual:evidence",
  2767. "npm run release:audit:manual:evidence:installed",
  2768. )
  2769. missing_prepare = [
  2770. part for part in required_prepare_parts if part not in prepare
  2771. ]
  2772. if missing_prepare:
  2773. _fail(f"release:audit:prepublish:prepare incompleto: {missing_prepare}")
  2774. prepublish = scripts.get("release:audit:prepublish", "")
  2775. required_prepublish_parts = (
  2776. "npm run release:audit:full",
  2777. "npm run release:audit:manual:preflight",
  2778. "npm run release:audit:manual:review",
  2779. "npm run release:audit:manual:review:installed",
  2780. )
  2781. missing_prepublish = [
  2782. part for part in required_prepublish_parts if part not in prepublish
  2783. ]
  2784. if missing_prepublish:
  2785. _fail(f"release:audit:prepublish incompleto: {missing_prepublish}")
  2786. prepublish_parts = {part.strip() for part in prepublish.split("&&")}
  2787. forbidden_prepublish_parts = {
  2788. "npm run release:audit:manual:evidence",
  2789. "npm run release:audit:manual:evidence:installed",
  2790. }
  2791. forbidden_present = sorted(prepublish_parts & forbidden_prepublish_parts)
  2792. if forbidden_present:
  2793. _fail(
  2794. "release:audit:prepublish no debe regenerar evidencias ya revisadas: "
  2795. f"{forbidden_present}"
  2796. )
  2797. spec = importlib.util.spec_from_file_location(
  2798. "manual_smoke_release_audit",
  2799. ROOT / "scripts" / "manual_smoke.py",
  2800. )
  2801. if spec is None or spec.loader is None:
  2802. _fail("No se pudo cargar scripts/manual_smoke.py para auditar cobertura")
  2803. manual_smoke = importlib.util.module_from_spec(spec)
  2804. spec.loader.exec_module(manual_smoke)
  2805. if "plugin_surface.sha256" not in release_doc:
  2806. _fail("docs/release.md debe exigir plugin_surface.sha256 de la run, no un hash congelado")
  2807. manual_smoke_text = _read("scripts/manual_smoke.py")
  2808. manual_review_gate_text = _read("scripts/manual_review_gate.py")
  2809. manual_review_report_text = _read("scripts/manual_review_report.py")
  2810. manual_smoke_runtime_needles = (
  2811. '"--permission-mode",',
  2812. '"bypassPermissions",',
  2813. 'parser.add_argument("--budget", default="1.50"',
  2814. 'parser.add_argument(\n "--preflight-only"',
  2815. 'if args.preflight_only:',
  2816. 'error_max_budget_usd',
  2817. )
  2818. missing_manual_smoke_runtime = [
  2819. needle for needle in manual_smoke_runtime_needles if needle not in manual_smoke_text
  2820. ]
  2821. if missing_manual_smoke_runtime:
  2822. _fail(
  2823. "El smoke manual debe reproducir claude -p real sin permisos interactivos ni presupuesto bajo: "
  2824. f"{missing_manual_smoke_runtime}"
  2825. )
  2826. preview_sanitizer_needles = (
  2827. "from core.secrets import sanitize_text",
  2828. "def _safe_preview(",
  2829. "path.chmod(0o600)",
  2830. "previews[relative] = _safe_preview(",
  2831. '"response_preview": _safe_preview(response_text, 2000)',
  2832. '"stderr_preview": _safe_preview(result.stderr, 2000)',
  2833. '"response_preview": _safe_preview(response_text, 500)',
  2834. '"stderr_preview": _safe_preview(result.stderr, 500)',
  2835. )
  2836. missing_preview_sanitizer = [
  2837. needle for needle in preview_sanitizer_needles if needle not in manual_smoke_text
  2838. ]
  2839. if missing_preview_sanitizer:
  2840. _fail(
  2841. "La evidencia manual debe sanear previews con core/secrets.py: "
  2842. f"{missing_preview_sanitizer}"
  2843. )
  2844. review_secret_gate_needles = (
  2845. "from core.secrets import find_secret_label",
  2846. "def _iter_secret_findings(",
  2847. "evidence_secret_findings = _iter_secret_findings(evidence, \"evidence\")",
  2848. "review_secret_findings = _iter_secret_findings(review, \"review\")",
  2849. "evidence contiene posibles secretos reales",
  2850. "review contiene posibles secretos reales",
  2851. "No se crea plantilla de revisión con evidencia que contiene",
  2852. "review_path.chmod(0o600)",
  2853. "GENERIC_REVIEW_NOTES",
  2854. "MIN_REVIEW_NOTE_CHARS",
  2855. "MIN_REVIEW_NOTE_WORDS",
  2856. "def _is_low_quality_review_note(",
  2857. "review.cases con notes humanas demasiado genericas o cortas",
  2858. "review.cases contiene notes humanas repetidas",
  2859. "--require-current-auth-preflight",
  2860. "preflight actual de Claude CLI no esta ok",
  2861. )
  2862. missing_review_secret_gate = [
  2863. needle for needle in review_secret_gate_needles if needle not in manual_review_gate_text
  2864. ]
  2865. if missing_review_secret_gate:
  2866. _fail(
  2867. "El gate de revision manual debe rechazar secretos con core/secrets.py: "
  2868. f"{missing_review_secret_gate}"
  2869. )
  2870. review_report_note_needles = (
  2871. "def _plugin_surface_flags(",
  2872. "## Superficie Del Plugin",
  2873. "evidence.plugin_surface.roots no coincide con el plugin actual",
  2874. "evidence.plugin_surface.file_count no coincide con el plugin actual",
  2875. "evidence.plugin_surface.sha256 no coincide con el plugin actual",
  2876. "def _review_quality_flags(",
  2877. "_manual_review_gate_module()",
  2878. "## Calidad De Review Humana",
  2879. "notes_missing",
  2880. "notes_low_quality",
  2881. "notes_repeated",
  2882. "review_secret_findings",
  2883. "Sin flags automaticos de notas humanas",
  2884. )
  2885. missing_review_report_notes = [
  2886. needle
  2887. for needle in review_report_note_needles
  2888. if needle not in manual_review_report_text
  2889. ]
  2890. if missing_review_report_notes:
  2891. _fail(
  2892. "El reporte de revision manual debe mostrar notas humanas debiles o repetidas: "
  2893. f"{missing_review_report_notes}"
  2894. )
  2895. review_traceability_needles = (
  2896. "review.evidence_file es obligatorio",
  2897. "review.evidence_file no coincide con el evidence pasado al gate",
  2898. "review.evidence_file coincide",
  2899. "review.cases desalineados con matriz actual",
  2900. "review.cases coincide con la matriz manual actual",
  2901. )
  2902. missing_review_traceability = [
  2903. needle
  2904. for needle in review_traceability_needles
  2905. if needle not in manual_review_gate_text
  2906. ]
  2907. if missing_review_traceability:
  2908. _fail(
  2909. "El gate de revision manual debe atar evidence_file a la evidencia validada: "
  2910. f"{missing_review_traceability}"
  2911. )
  2912. _validate_manual_case_contract_links(manual_smoke)
  2913. coverage = manual_smoke._case_command_coverage()
  2914. missing = [name for name, case_ids in coverage.items() if not case_ids]
  2915. if len(coverage) != 18 or missing:
  2916. _fail(f"La matriz manual no cubre las 18 rutas publicas: missing={missing}")
  2917. option_coverage = manual_smoke._case_option_coverage()
  2918. missing_options = [
  2919. name for name, case_ids in option_coverage.items()
  2920. if not case_ids
  2921. ]
  2922. expected_option_contracts = len(manual_smoke.OPTION_CONTRACTS)
  2923. if len(option_coverage) != expected_option_contracts or missing_options:
  2924. _fail(
  2925. "La matriz manual no cubre las opciones publicas: "
  2926. f"total={len(option_coverage)} missing={missing_options}"
  2927. )
  2928. _validate_manual_option_contract_shape(manual_smoke, option_coverage)
  2929. aliases = getattr(manual_smoke, "_PUBLIC_COMMAND_ALIASES", {})
  2930. covered_option_commands = set()
  2931. for name, case_ids in option_coverage.items():
  2932. if not case_ids:
  2933. continue
  2934. prefix = name.split(":", 1)[0]
  2935. covered_option_commands.add(prefix)
  2936. mapped = aliases.get(prefix)
  2937. if mapped:
  2938. covered_option_commands.add(mapped)
  2939. argument_commands = _public_argument_commands()
  2940. missing_argument_commands = sorted(argument_commands - covered_option_commands)
  2941. if missing_argument_commands:
  2942. _fail(
  2943. "Comandos con argument-hint/$ARGUMENTS sin contrato de opcion manual: "
  2944. f"{missing_argument_commands}"
  2945. )
  2946. runtime_coverage = manual_smoke._case_runtime_coverage()
  2947. missing_runtime = [
  2948. name for name, case_ids in runtime_coverage.items()
  2949. if not case_ids
  2950. ]
  2951. _validate_manual_runtime_contract_shape(manual_smoke, runtime_coverage)
  2952. if len(runtime_coverage) != 4 or missing_runtime:
  2953. _fail(
  2954. "La matriz manual no cubre los contratos runtime: "
  2955. f"total={len(runtime_coverage)} missing={missing_runtime}"
  2956. )
  2957. return [
  2958. "docs/release.md es la pagina viva de auditoria",
  2959. "nota project-scope MCP documentada",
  2960. "commands/ documentado como skills planas soportadas",
  2961. "matriz manual cubre 18 rutas publicas",
  2962. f"matriz manual cubre {expected_option_contracts} opciones publicas",
  2963. "matriz manual valida IDs de opcion contra comandos publicos",
  2964. "matriz manual enlaza contratos al comando correcto",
  2965. "matriz manual valida prompts contra comandos declarados",
  2966. "matriz manual ata cada argument-hint a una opcion cubierta",
  2967. "matriz manual valida contratos runtime de update",
  2968. "matriz manual cubre 4 contratos runtime",
  2969. "manual smoke usa worktree por defecto y --installed explicito",
  2970. "manual smoke tiene preflight de autenticacion real y evidencia fail-fast",
  2971. "evidencia manual y plantillas se escriben con permisos 0600",
  2972. "evidencias manuales ignoradas por git y npm",
  2973. "estado operativo docs/project ignorado por git y npm",
  2974. "evidencia manual sanea previews con core/secrets.py",
  2975. "manual review gate exige aprobacion humana explicita",
  2976. "manual review gate rechaza evidencia/review con secretos",
  2977. "manual review gate no crea plantillas desde evidencia con secretos",
  2978. "manual review gate exige preflight actual antes de aprobar",
  2979. "manual review report muestra notas humanas debiles o repetidas",
  2980. "manual review gate exige origen worktree/installed correcto",
  2981. "manual review gate ata evidence_file al JSON validado",
  2982. "plugin_surface.sha256 se exige en revision humana, no se congela en docs",
  2983. "manual review gate valida metadatos de casos contra matriz actual",
  2984. "manual review gate valida metadatos de review contra matriz actual",
  2985. "manual review gate valida mapas de cobertura contra matriz actual",
  2986. "scripts npm manual/preflight alineados",
  2987. "prepublish:prepare genera evidencias manuales antes de la revision humana",
  2988. "prepublish valida evidencias manuales ya revisadas sin regenerarlas",
  2989. "matriz documenta empaquetado seco",
  2990. "plugin details documenta displayName humano",
  2991. "docs oficiales revalidadas 2026-08-15",
  2992. "readiness de salida mantiene pendientes humanos y externos",
  2993. "runbook de revision humana documenta criterios y bloqueos",
  2994. ]
  2995. def check_human_contracts() -> list[str]:
  2996. """Verifica contratos prompt-level de trato humano y honestidad operativa."""
  2997. command_names = [
  2998. "_composicion",
  2999. "alfred",
  3000. "ajustes",
  3001. "discuss",
  3002. "feature",
  3003. "fix",
  3004. "map-codebase",
  3005. "memory-ui",
  3006. "next",
  3007. "pause",
  3008. "progress",
  3009. "quick",
  3010. "retomar",
  3011. "search",
  3012. "ship",
  3013. "sync-github",
  3014. "uat",
  3015. "update",
  3016. ]
  3017. commands = {name: _read(f"commands/{name}.md") for name in command_names}
  3018. commands_norm = {name: _normalize(text) for name, text in commands.items()}
  3019. alfred_agent = _read("agents/alfred.md")
  3020. alfred_agent_norm = _normalize(alfred_agent)
  3021. requirements = {
  3022. "clarifying questions": [
  3023. ("Solo usa `AskUserQuestion` si de verdad hay dos caminos plausibles", commands["alfred"]),
  3024. ("una sola pregunta corta", commands["alfred"]),
  3025. ("único `AskUserQuestion` con menú seleccionable real", commands["alfred"]),
  3026. ("Si necesitas preguntar por ambigüedad real", commands["next"]),
  3027. ("un único `AskUserQuestion` navegable", commands["next"]),
  3028. ("NO uses `AskUserQuestion` por defecto", commands["discuss"]),
  3029. ("no hace falta el menú", commands["discuss"]),
  3030. ("DISCUSS_ROUTE_MENU_HEADLESS", commands["discuss"]),
  3031. ("vuelve cancelada", commands["discuss"]),
  3032. ("principal navegable", commands_norm["ajustes"]),
  3033. ("config_headless_menu", commands_norm["ajustes"]),
  3034. ("un único `AskUserQuestion`", commands["update"]),
  3035. ],
  3036. "human gates": [
  3037. ("Si una gate de usuario queda pendiente, usa un único `AskUserQuestion`", commands["feature"]),
  3038. ("Si una gate de usuario queda pendiente, usa un único `AskUserQuestion`", commands["fix"]),
  3039. ("gate de despliegue siempre interactiva", commands_norm["ship"]),
  3040. ("nunca auto-apruebes un despliegue", commands_norm["ship"]),
  3041. ("NO marques una UAT como aprobada sin una indicación explícita del usuario", commands["uat"]),
  3042. ("`/alfred-dev:verify aprobado`", commands["uat"]),
  3043. ],
  3044. "operational honesty": [
  3045. ("Honestidad operativa y antifingimiento", commands["_composicion"]),
  3046. ("No digas \"he ejecutado\", \"ha pasado\" o \"está validado\" si solo lo has inferido", commands["_composicion"]),
  3047. ("Distingue siempre entre \"recomiendo ejecutar X\" y \"he ejecutado X", commands["_composicion"]),
  3048. ("No finjas evidencia", commands["alfred"]),
  3049. ("salida de herramienta", commands["alfred"]),
  3050. ("siguiente paso verificable", commands["alfred"]),
  3051. ("No finjas evidencia", alfred_agent),
  3052. ("confirmación explícita del usuario", alfred_agent),
  3053. ],
  3054. "grounded fallbacks": [
  3055. ("NO inventes stack, entrypoints o riesgos", commands["map-codebase"]),
  3056. ("NO inventes un handoff", commands["pause"]),
  3057. ("aceptacion manual prematura", commands_norm["uat"]),
  3058. ("Si `$ARGUMENTS` está vacío, dilo claramente y no inventes una búsqueda", commands["search"]),
  3059. ],
  3060. }
  3061. missing: list[str] = []
  3062. for group, checks in requirements.items():
  3063. for needle, haystack in checks:
  3064. if needle not in haystack:
  3065. missing.append(f"{group}: {needle}")
  3066. helper_wrappers = [
  3067. "alfred",
  3068. "discuss",
  3069. "map-codebase",
  3070. "memory-ui",
  3071. "pause",
  3072. "progress",
  3073. "retomar",
  3074. "search",
  3075. "sync-github",
  3076. "uat",
  3077. ]
  3078. final_markers = (
  3079. "respuesta final",
  3080. "tal cual",
  3081. "usala y termina",
  3082. "usalo como respuesta final",
  3083. "no sigas explorando",
  3084. "segunda capa",
  3085. "no la reenvuelvas",
  3086. )
  3087. for name in helper_wrappers:
  3088. text_norm = commands_norm[name]
  3089. if "helper" not in text_norm and "alfred-continuity.py" not in commands[name]:
  3090. missing.append(f"helper-first {name}: falta helper")
  3091. if not any(marker in text_norm for marker in final_markers):
  3092. missing.append(f"helper-first {name}: falta regla de salida final sin reenvolver")
  3093. if "No digas" not in commands["_composicion"] or "siguiente paso verificable" not in commands["alfred"]:
  3094. missing.append("humanidad: falta contrato antifingimiento central")
  3095. if "No finjas evidencia" not in alfred_agent:
  3096. missing.append("humanidad: falta contrato antifingimiento en agente Alfred")
  3097. if missing:
  3098. _fail("Contratos de humanidad incompletos: " + "; ".join(missing))
  3099. return [
  3100. "AskUserQuestion limitado a ambigüedad real y gates humanas",
  3101. "helpers operativos no duplican ni reenvuelven salida",
  3102. "UAT exige indicación humana explícita",
  3103. "antifingimiento centralizado en comandos y agente Alfred",
  3104. ]
  3105. def check_external_contracts() -> list[str]:
  3106. audit = _read("commands/audit.md")
  3107. audit_norm = _normalize(audit)
  3108. sonarqube = _read("skills/sonarqube/SKILL.md")
  3109. sonarqube_norm = _normalize(sonarqube)
  3110. sync = _read("commands/sync-github.md")
  3111. sync_norm = _normalize(sync)
  3112. lucius_command = _read("commands/lucius.md")
  3113. lucius_agent = _read("agents/lucius.md")
  3114. lucius_all = lucius_command + "\n" + lucius_agent
  3115. lucius_norm = _normalize(lucius_all)
  3116. ship = _read("commands/ship.md")
  3117. ship_norm = _normalize(ship)
  3118. requirements = {
  3119. "audit SonarQube preflight": [
  3120. ("docker --version", audit),
  3121. ("docker info", audit),
  3122. ("AskUserQuestion", audit),
  3123. ("NO intentes instalarlo por tu cuenta", audit),
  3124. ("NO intentes arrancarlo por tu cuenta", audit),
  3125. ("incluso si el proyecto esta en modo autopilot", audit_norm),
  3126. ("sonarqube se omitio por decision explicita del usuario", audit_norm),
  3127. ],
  3128. "sonarqube skill permission": [
  3129. ("no instales docker, no abras docker desktop y no arranques el daemon sin aprobacion explicita del usuario.", sonarqube_norm),
  3130. ("si no existe una autorizacion previa, pidela ahora y espera respuesta.", sonarqube_norm),
  3131. ("puerto `9000` ya esta en uso", sonarqube_norm),
  3132. ("docker rm -f sonarqube-alfred", sonarqube),
  3133. ("intenta igualmente la limpieza final del contenedor temporal", sonarqube_norm),
  3134. ],
  3135. "sync-github safe mirror": [
  3136. ('python3 .claude/alfred-continuity.py sync-github "$PWD" --raw "$ARGUMENTS"', sync),
  3137. ("gh --version", sync),
  3138. ("gh auth status", sync),
  3139. ("NO uses `AskUserQuestion` por defecto", sync),
  3140. ("No borres issues ajenos a Alfred", sync),
  3141. ("Mantén la verdad local", sync),
  3142. ],
  3143. "lucius external audit": [
  3144. ("codex --version", lucius_all),
  3145. ("codex login", lucius_all),
  3146. ("confirmación explícita", lucius_all),
  3147. ("codex exec", lucius_all),
  3148. ("--sandbox read-only", lucius_all),
  3149. ("--ephemeral", lucius_all),
  3150. ("--json", lucius_all),
  3151. ("--output-last-message", lucius_all),
  3152. ("codex_report", lucius_all),
  3153. ("codex_jsonl", lucius_all),
  3154. ("approval_policy", lucius_all),
  3155. ("status --porcelain=v1 -z", lucius_all),
  3156. ("no modifiques ningun fichero", lucius_norm),
  3157. ("nunca ejecutas codigo del proyecto", lucius_norm),
  3158. ("no sustituyes a `qa-engineer`, `security-officer` ni `architect`", lucius_norm),
  3159. ("no reemplaza el sign-off canonico", lucius_norm),
  3160. ],
  3161. "ship deploy gate": [
  3162. ("gate de despliegue", ship_norm),
  3163. ("siempre interactiva", ship_norm),
  3164. ("un único `AskUserQuestion`", ship),
  3165. ("nunca auto-apruebes un despliegue", ship_norm),
  3166. ("usuario+seguridad", ship),
  3167. ],
  3168. }
  3169. missing: list[str] = []
  3170. for group, checks in requirements.items():
  3171. for needle, haystack in checks:
  3172. if needle not in haystack:
  3173. missing.append(f"{group}: {needle}")
  3174. if missing:
  3175. _fail("Contratos externos incompletos: " + "; ".join(missing))
  3176. return [
  3177. "Docker/SonarQube pide permiso y documenta omisiones",
  3178. "sync-github mantiene GitHub como espejo seguro",
  3179. "Lucius confirma coste y no modifica ficheros",
  3180. "ship mantiene deploy con gate humana",
  3181. ]
  3182. def run_command(name: str, command: list[str], timeout: int = 120) -> str:
  3183. result = subprocess.run(
  3184. command,
  3185. cwd=ROOT,
  3186. text=True,
  3187. stdout=subprocess.PIPE,
  3188. stderr=subprocess.STDOUT,
  3189. timeout=timeout,
  3190. check=False,
  3191. )
  3192. if result.returncode != 0:
  3193. raise AuditError(
  3194. f"{name} fallo con codigo {result.returncode}\n{result.stdout}"
  3195. )
  3196. return result.stdout
  3197. def _materialized_alfred_alias_bytes(*, invocable: bool = True) -> bytes:
  3198. alias_source = ROOT / "skills" / "alfred" / "alfred" / "SKILL.md"
  3199. text = alias_source.read_text(encoding="utf-8")
  3200. value = "true" if invocable else "false"
  3201. if re.search(r"(?m)^user-invocable:\s*(true|false)\s*$", text):
  3202. text = re.sub(
  3203. r"(?m)^user-invocable:\s*(true|false)\s*$",
  3204. f"user-invocable: {value}",
  3205. text,
  3206. count=1,
  3207. )
  3208. elif text.startswith("---\n"):
  3209. text = text.replace("---\n", f"---\nuser-invocable: {value}\n", 1)
  3210. return text.encode("utf-8")
  3211. def check_installed_cache_freshness() -> list[str]:
  3212. if not INSTALLED_PLUGIN_DIR.is_dir():
  3213. _fail(
  3214. "No existe la cache instalada 0.7.0 de Claude. Refrescala con:\n"
  3215. "claude plugin marketplace remove alfred-dev --scope user\n"
  3216. "claude plugin marketplace add \"$PWD\" --scope user\n"
  3217. "claude plugin uninstall alfred-dev@alfred-dev --scope user\n"
  3218. "claude plugin install alfred-dev@alfred-dev --scope user"
  3219. )
  3220. missing: list[str] = []
  3221. drifted: list[str] = []
  3222. for relative in _iter_installed_cache_freshness_files():
  3223. worktree_path = ROOT / relative
  3224. installed_path = INSTALLED_PLUGIN_DIR / relative
  3225. if not installed_path.is_file():
  3226. missing.append(relative)
  3227. continue
  3228. if _sha256(worktree_path) != _sha256(installed_path):
  3229. drifted.append(relative)
  3230. if missing or drifted:
  3231. details = []
  3232. if missing:
  3233. details.append("missing=" + ", ".join(missing[:12]))
  3234. if drifted:
  3235. details.append("drifted=" + ", ".join(drifted[:12]))
  3236. _fail(
  3237. "La cache instalada de Claude no coincide con el worktree auditado "
  3238. f"({'; '.join(details)}). Refrescala con:\n"
  3239. "claude plugin marketplace remove alfred-dev --scope user\n"
  3240. "claude plugin marketplace add \"$PWD\" --scope user\n"
  3241. "claude plugin uninstall alfred-dev@alfred-dev --scope user\n"
  3242. "claude plugin install alfred-dev@alfred-dev --scope user"
  3243. )
  3244. return [
  3245. "cache instalada 0.7.0 completa y coincide con el worktree"
  3246. ]
  3247. def _run_continuity(project_dir: Path, *args: str, timeout: int = 60) -> str:
  3248. return run_command(
  3249. f"continuity {' '.join(args)}",
  3250. [sys.executable, str(ROOT / "core" / "continuity.py"), *args],
  3251. timeout=timeout,
  3252. )
  3253. def _run_continuity_raw(project_dir: Path, *args: str, timeout: int = 60) -> subprocess.CompletedProcess[str]:
  3254. return subprocess.run(
  3255. [sys.executable, str(ROOT / "core" / "continuity.py"), *args],
  3256. cwd=ROOT,
  3257. text=True,
  3258. stdout=subprocess.PIPE,
  3259. stderr=subprocess.PIPE,
  3260. timeout=timeout,
  3261. check=False,
  3262. )
  3263. def _complete_quick_session(project_dir: Path) -> None:
  3264. from core.orchestrator import advance_phase, create_session, save_state
  3265. session = create_session("quick", "Ajustar copy login")
  3266. while session["fase_actual"] != "completado":
  3267. session = advance_phase(session, resultado="aprobado", artefactos=[])
  3268. save_state(session, str(project_dir / ".claude" / "alfred-dev-state.json"))
  3269. def check_continuity_smoke() -> list[str]:
  3270. with tempfile.TemporaryDirectory(prefix="alfred-release-audit-") as tmp:
  3271. project = Path(tmp)
  3272. (project / "src").mkdir()
  3273. (project / "package.json").write_text('{"name":"fixture"}\n', encoding="utf-8")
  3274. (project / "src" / "app.js").write_text(
  3275. "export function label() { return 'Login'; }\n",
  3276. encoding="utf-8",
  3277. )
  3278. sync_empty = project / "sync-empty"
  3279. sync_empty.mkdir()
  3280. sync_fail = _run_continuity_raw(sync_empty, "sync-github", str(sync_empty), "--raw", "owner/repo")
  3281. if sync_fail.returncode == 0:
  3282. _fail("sync-github deberia fallar sin tareas sincronizables preparadas para GitHub")
  3283. sync_error = sync_fail.stderr + sync_fail.stdout
  3284. if (
  3285. "No hay tareas con identificador [T-XXX]" not in sync_error
  3286. and "No hay tareas en docs/project/kanban/" not in sync_error
  3287. ):
  3288. _fail(f"sync-github no fallo de forma explicita sin tareas: {sync_error}")
  3289. next_initial = json.loads(_run_continuity(project, "next", str(project), "--json"))
  3290. if next_initial.get("command") != "map-codebase":
  3291. _fail(f"next inicial esperaba map-codebase, obtuvo {next_initial}")
  3292. mapped = json.loads(
  3293. _run_continuity(project, "map-codebase", str(project), "--raw", "login", "--json")
  3294. )
  3295. if mapped.get("recommended_command") != "discuss":
  3296. _fail(f"map-codebase esperaba recommend discuss, obtuvo {mapped}")
  3297. if not (project / "docs" / "project" / "codebase-map.md").exists():
  3298. _fail("map-codebase no creo docs/project/codebase-map.md")
  3299. from core.continuity import save_prefetch_result
  3300. save_prefetch_result(
  3301. str(project),
  3302. {
  3303. "source_command": "map-codebase",
  3304. "prefetched_command": "map-codebase",
  3305. "project_name": "fixture",
  3306. "stack": {"runtime": "node", "framework": "desconocido"},
  3307. "recommended_command": "discuss",
  3308. },
  3309. )
  3310. consumed = _run_continuity(
  3311. project,
  3312. "consume-prefetch",
  3313. str(project),
  3314. "--expected",
  3315. "map-codebase",
  3316. )
  3317. if "## Mapeo brownfield completado" not in consumed:
  3318. _fail("consume-prefetch no devolvio la respuesta helper-first esperada")
  3319. if (project / ".claude" / "alfred-prefetch.json").exists():
  3320. _fail("consume-prefetch no limpio el prefetch transitorio")
  3321. discussed = json.loads(
  3322. _run_continuity(project, "discuss", str(project), "--raw", "ajustar login", "--json")
  3323. )
  3324. if discussed.get("recommended_command") not in {"feature", "quick", "fix", "spike"}:
  3325. _fail(f"discuss devolvio recomendacion inesperada: {discussed}")
  3326. quick = _run_continuity(project, "quick", str(project), "--raw", "cambiar CTA")
  3327. if "## Quick preparado" not in quick or "/alfred-dev:verify" not in quick:
  3328. _fail("quick no devolvio resumen humano con siguiente verify")
  3329. handoff = json.loads(_run_continuity(project, "write-handoff", str(project)))
  3330. handoff_path = project / ".claude" / "alfred-handoff.json"
  3331. handoff_payload = json.loads(handoff_path.read_text(encoding="utf-8")) if handoff_path.exists() else {}
  3332. if handoff_payload.get("command") != "quick" or not Path(handoff.get("json_path", "")).exists():
  3333. _fail(f"write-handoff no persistio handoff de quick: {handoff}")
  3334. bypass = json.loads(
  3335. _run_continuity(
  3336. project,
  3337. "allow-stop-once",
  3338. str(project),
  3339. "--command",
  3340. "/alfred-dev:status",
  3341. )
  3342. )
  3343. if bypass.get("command") != "/alfred-dev:status" or not Path(bypass.get("bypass_path", "")).exists():
  3344. _fail(f"allow-stop-once no armo bypass valido: {bypass}")
  3345. status = _run_continuity(project, "status", str(project))
  3346. if "## Estado operativo de Alfred Dev" not in status:
  3347. _fail("status no devolvio resumen operativo")
  3348. pause = _run_continuity(project, "pause", str(project))
  3349. if "## Sesión pausada" not in pause:
  3350. _fail("pause no dejo salida humana de pausa")
  3351. resume = _run_continuity(project, "resume", str(project))
  3352. if "## Sesión reanudada" not in resume:
  3353. _fail("resume no dejo salida humana de reanudacion")
  3354. for command, expected in [
  3355. ("progress", "## Resumen operativo del proyecto"),
  3356. ("standup", "## Standup diario"),
  3357. ("blocked", "## Tareas en blocked"),
  3358. ("in-progress", "## Tareas en in progress"),
  3359. ("validate", "## Validación operativa"),
  3360. ]:
  3361. output = _run_continuity(project, command, str(project))
  3362. if expected not in output:
  3363. _fail(f"{command} no contiene {expected!r}")
  3364. search = _run_continuity(project, "search", str(project), "--raw", "login")
  3365. if "## Resultados para `login`" not in search:
  3366. _fail("search no devolvio resultados humanos")
  3367. kanban = project / "docs" / "project" / "kanban"
  3368. kanban.mkdir(parents=True, exist_ok=True)
  3369. (kanban / "backlog.md").write_text(
  3370. "# Backlog\n\n"
  3371. "### [T-010] Validar login con /alfred-dev:verify\n\n"
  3372. "- **Agente:** alfred:verify\n",
  3373. encoding="utf-8",
  3374. )
  3375. for lane in ("in-progress", "done", "blocked"):
  3376. (kanban / f"{lane}.md").write_text(f"# {lane.title()}\n", encoding="utf-8")
  3377. normalize = _run_continuity(project, "normalize-kanban", str(project))
  3378. if "## Normalización de kanban" not in normalize or "Tareas ajustadas" not in normalize:
  3379. _fail("normalize-kanban no devolvio resumen de normalizacion")
  3380. memory_started = False
  3381. try:
  3382. memory_ui = json.loads(
  3383. _run_continuity(
  3384. project,
  3385. "memory-ui",
  3386. str(project),
  3387. "--json",
  3388. "--no-open",
  3389. timeout=90,
  3390. )
  3391. )
  3392. memory_started = True
  3393. if not str(memory_ui.get("url", "")).startswith("http://127.0.0.1:"):
  3394. _fail(f"memory-ui no devolvio URL local valida: {memory_ui}")
  3395. if not (project / ".claude" / "alfred-memory-ui.json").exists():
  3396. _fail("memory-ui no persistio .claude/alfred-memory-ui.json")
  3397. finally:
  3398. if memory_started:
  3399. _run_continuity(project, "memory-ui", str(project), "--stop", "--json", timeout=90)
  3400. _complete_quick_session(project)
  3401. verify = _run_continuity(project, "verify", str(project), "--raw", "aprobado")
  3402. uat_path = project / ".claude" / "alfred-uat.json"
  3403. uat = json.loads(uat_path.read_text(encoding="utf-8")) if uat_path.exists() else {}
  3404. if (
  3405. "Verificación manual / UAT" not in verify
  3406. or "aprobada" not in verify.lower()
  3407. or uat.get("status") != "approved"
  3408. ):
  3409. _fail("verify aprobado no registro UAT humana")
  3410. return [
  3411. "next/map-codebase/discuss/quick",
  3412. "status/pause/resume/progress/standup",
  3413. "blocked/in-progress/validate/search/verify",
  3414. "write-handoff/allow-stop-once/consume-prefetch/normalize-kanban/memory-ui/sync-github-fail-closed",
  3415. ]
  3416. class _MCPJsonlClient:
  3417. def __init__(self, project_dir: Path) -> None:
  3418. self._next_id = 1
  3419. self._proc = subprocess.Popen(
  3420. [sys.executable, str(ROOT / "mcp" / "memory_server.py")],
  3421. cwd=project_dir,
  3422. text=True,
  3423. stdin=subprocess.PIPE,
  3424. stdout=subprocess.PIPE,
  3425. stderr=subprocess.PIPE,
  3426. )
  3427. self._selector = selectors.DefaultSelector()
  3428. assert self._proc.stdout is not None
  3429. self._selector.register(self._proc.stdout, selectors.EVENT_READ)
  3430. def close(self) -> None:
  3431. if self._proc.stdin is not None:
  3432. try:
  3433. self._proc.stdin.close()
  3434. except OSError:
  3435. pass
  3436. try:
  3437. self._proc.wait(timeout=5)
  3438. except subprocess.TimeoutExpired:
  3439. self._proc.terminate()
  3440. self._proc.wait(timeout=5)
  3441. if self._proc.returncode not in {0, None}:
  3442. stderr = self._proc.stderr.read() if self._proc.stderr else ""
  3443. _fail(f"Servidor MCP termino con codigo {self._proc.returncode}: {stderr}")
  3444. def notify(self, method: str, params: dict | None = None) -> None:
  3445. assert self._proc.stdin is not None
  3446. payload = {"jsonrpc": "2.0", "method": method}
  3447. if params is not None:
  3448. payload["params"] = params
  3449. self._proc.stdin.write(json.dumps(payload, ensure_ascii=False) + "\n")
  3450. self._proc.stdin.flush()
  3451. def request(self, method: str, params: dict | None = None) -> dict:
  3452. assert self._proc.stdin is not None
  3453. request_id = self._next_id
  3454. self._next_id += 1
  3455. payload = {"jsonrpc": "2.0", "id": request_id, "method": method}
  3456. if params is not None:
  3457. payload["params"] = params
  3458. self._proc.stdin.write(json.dumps(payload, ensure_ascii=False) + "\n")
  3459. self._proc.stdin.flush()
  3460. events = self._selector.select(timeout=10)
  3461. if not events:
  3462. stderr = self._proc.stderr.read() if self._proc.stderr else ""
  3463. _fail(f"Timeout esperando respuesta MCP para {method}: {stderr}")
  3464. line = self._proc.stdout.readline() # type: ignore[union-attr]
  3465. if not line:
  3466. stderr = self._proc.stderr.read() if self._proc.stderr else ""
  3467. _fail(f"Servidor MCP cerro stdout durante {method}: {stderr}")
  3468. response = json.loads(line)
  3469. if response.get("id") != request_id:
  3470. _fail(f"Respuesta MCP con id inesperado: {response}")
  3471. if "error" in response:
  3472. _fail(f"Error MCP en {method}: {response['error']}")
  3473. return response["result"]
  3474. def call_tool(self, name: str, arguments: dict | None = None) -> dict:
  3475. result = self.request(
  3476. "tools/call",
  3477. {"name": name, "arguments": arguments or {}},
  3478. )
  3479. if result.get("isError"):
  3480. _fail(f"{name} devolvio isError: {result}")
  3481. content = result.get("content") or []
  3482. if not content or content[0].get("type") != "text":
  3483. _fail(f"{name} no devolvio contenido text: {result}")
  3484. return json.loads(content[0]["text"])
  3485. def check_mcp_tools_smoke() -> list[str]:
  3486. with tempfile.TemporaryDirectory(prefix="alfred-mcp-audit-") as tmp:
  3487. project = Path(tmp)
  3488. (project / ".claude").mkdir()
  3489. adr_dir = project / "docs" / "adr"
  3490. adr_dir.mkdir(parents=True)
  3491. (adr_dir / "0001-cache.md").write_text(
  3492. "# Usar Redis\n\n"
  3493. "## Contexto\n\nNecesitamos cachear lecturas frecuentes.\n\n"
  3494. "## Decisión\n\nUsar Redis para cache compartida.\n",
  3495. encoding="utf-8",
  3496. )
  3497. client = _MCPJsonlClient(project)
  3498. try:
  3499. init = client.request(
  3500. "initialize",
  3501. {
  3502. "protocolVersion": "2025-11-25",
  3503. "clientInfo": {"name": "alfred-release-audit", "version": VERSION},
  3504. "capabilities": {},
  3505. },
  3506. )
  3507. if init.get("serverInfo", {}).get("name") != "alfred-memory":
  3508. _fail(f"initialize inesperado: {init}")
  3509. client.notify("notifications/initialized")
  3510. tools = client.request("tools/list")["tools"]
  3511. tool_names = [tool["name"] for tool in tools]
  3512. if len(tool_names) != 15:
  3513. _fail(f"tools/list esperaba 15 herramientas, obtuvo {tool_names}")
  3514. tool_by_name = {tool["name"]: tool for tool in tools}
  3515. expected_limits = {
  3516. "memory_search": 100,
  3517. "memory_get_decisions": 200,
  3518. "memory_import": 1000,
  3519. }
  3520. for tool_name, maximum in expected_limits.items():
  3521. schema = tool_by_name[tool_name]["inputSchema"]["properties"]["limit"]
  3522. if schema.get("minimum") != 1 or schema.get("maximum") != maximum:
  3523. _fail(
  3524. f"{tool_name} no declara limites MCP defensivos: {schema}"
  3525. )
  3526. event_schema = tool_by_name["memory_log_event"]["inputSchema"]["properties"]
  3527. expected_event_bounds = {
  3528. "event_type": 80,
  3529. "phase": 80,
  3530. "summary": 500,
  3531. "content": 8000,
  3532. }
  3533. for field, maximum in expected_event_bounds.items():
  3534. if event_schema[field].get("maxLength") != maximum:
  3535. _fail(f"memory_log_event no declara maxLength para {field}: {event_schema[field]}")
  3536. if "preview" not in event_schema["payload"].get("description", ""):
  3537. _fail("memory_log_event no documenta preview para payload enorme")
  3538. started = client.call_tool(
  3539. "memory_manage_iteration",
  3540. {"action": "start", "command": "feature", "description": "Login release audit"},
  3541. )
  3542. iteration_id = started.get("iteration_id")
  3543. if not iteration_id:
  3544. _fail(f"memory_manage_iteration no devolvio iteration_id: {started}")
  3545. dec1 = client.call_tool(
  3546. "memory_log_decision",
  3547. {
  3548. "title": "Cache de login",
  3549. "chosen": "Redis",
  3550. "context": "Login con lecturas frecuentes",
  3551. "tags": ["release-audit"],
  3552. },
  3553. )["decision_id"]
  3554. dec2 = client.call_tool(
  3555. "memory_log_decision",
  3556. {
  3557. "title": "Sesion de usuario",
  3558. "chosen": "Cookie segura",
  3559. "tags": ["release-audit"],
  3560. },
  3561. )["decision_id"]
  3562. client.call_tool(
  3563. "memory_update_decision",
  3564. {"id": dec1, "status": "superseded", "tags": ["mcp-smoke"]},
  3565. )
  3566. client.call_tool(
  3567. "memory_link_decisions",
  3568. {"source_id": dec1, "target_id": dec2, "link_type": "relates"},
  3569. )
  3570. client.call_tool(
  3571. "memory_log_commit",
  3572. {
  3573. "sha": "abc123releaseaudit",
  3574. "message": "feat: login cache",
  3575. "author": "Alfred Audit",
  3576. "decision_ids": [dec1],
  3577. "files": ["src/login.py"],
  3578. },
  3579. )
  3580. client.call_tool(
  3581. "memory_log_event",
  3582. {
  3583. "event_type": "gate_passed",
  3584. "phase": "calidad",
  3585. "summary": "Redis cache validada",
  3586. "payload": {"note": "redis cache validada"},
  3587. },
  3588. )
  3589. large_event = client.call_tool(
  3590. "memory_log_event",
  3591. {
  3592. "event_type": "custom",
  3593. "phase": "calidad",
  3594. "summary": "evento MCP grande",
  3595. "content": "x" * 9000,
  3596. "payload": {"blob": "y" * 9000},
  3597. },
  3598. )
  3599. if not large_event.get("content_truncated") or not large_event.get("payload_truncated"):
  3600. _fail(f"memory_log_event no recorto content/payload enormes: {large_event}")
  3601. search = client.call_tool("memory_search", {"query": "Redis", "limit": 10})
  3602. if search.get("total", 0) < 1:
  3603. _fail(f"memory_search no encontro datos sembrados: {search}")
  3604. capped_search = client.call_tool(
  3605. "memory_search",
  3606. {"query": "Redis", "limit": 999999},
  3607. )
  3608. if capped_search.get("applied_limit") != 100:
  3609. _fail(f"memory_search no recorto limit abusivo: {capped_search}")
  3610. if client.call_tool("memory_get_iteration", {"id": iteration_id}).get("iteration") is None:
  3611. _fail("memory_get_iteration no devolvio la iteracion creada")
  3612. if client.call_tool("memory_get_timeline", {"iteration_id": iteration_id}).get("total", 0) < 1:
  3613. _fail("memory_get_timeline no devolvio eventos")
  3614. if client.call_tool("memory_get_decisions", {"tags": ["release-audit"]}).get("total", 0) < 2:
  3615. _fail("memory_get_decisions no devolvio decisiones sembradas")
  3616. if client.call_tool("memory_stats").get("total_decisions", 0) < 2:
  3617. _fail("memory_stats no conto decisiones")
  3618. if client.call_tool("memory_health").get("status") != "healthy":
  3619. _fail("memory_health no devolvio healthy")
  3620. export_path = str(project / "DECISIONS.md")
  3621. if client.call_tool("memory_export", {"format": "markdown", "path": export_path}).get("exported", 0) < 2:
  3622. _fail("memory_export no exporto decisiones")
  3623. if not Path(export_path).exists():
  3624. _fail("memory_export no creo DECISIONS.md")
  3625. blocked_export = client.request(
  3626. "tools/call",
  3627. {
  3628. "name": "memory_export",
  3629. "arguments": {
  3630. "format": "markdown",
  3631. "path": str(project.parent / "OUTSIDE.md"),
  3632. },
  3633. },
  3634. )
  3635. if not blocked_export.get("isError"):
  3636. _fail(f"memory_export permitio escribir fuera del proyecto: {blocked_export}")
  3637. if client.call_tool("memory_import", {"source": "adr", "path": str(adr_dir)}).get("imported") != 1:
  3638. _fail("memory_import adr no importo el ADR fixture")
  3639. purge = client.call_tool("memory_purge", {"retention_days": 1})
  3640. if "purged_events" not in purge:
  3641. _fail("memory_purge no devolvio purged_events")
  3642. client.call_tool("memory_manage_iteration", {"action": "complete", "iteration_id": iteration_id})
  3643. finally:
  3644. client.close()
  3645. return [
  3646. "15 tools listadas",
  3647. "15 tools invocadas con datos reales",
  3648. "limites MCP defensivos en schemas y handlers",
  3649. "memory_log_event recorta payload/content MCP enormes",
  3650. "rutas MCP acotadas al proyecto",
  3651. "SQLite temporal saludable",
  3652. ]
  3653. def check_external(args: argparse.Namespace) -> list[str]:
  3654. ok: list[str] = []
  3655. if args.with_external_contracts:
  3656. for line in check_external_contracts():
  3657. ok.append(f"external {line}")
  3658. if args.with_human_contracts:
  3659. for line in check_human_contracts():
  3660. ok.append(f"human {line}")
  3661. if args.with_continuity:
  3662. for line in check_continuity_smoke():
  3663. ok.append(f"continuity {line}")
  3664. if args.with_mcp_tools:
  3665. for line in check_mcp_tools_smoke():
  3666. ok.append(f"mcp-tools {line}")
  3667. if args.with_claude:
  3668. for line in check_installed_cache_freshness():
  3669. ok.append(f"claude {line}")
  3670. details = run_command(
  3671. "claude plugin validate/details",
  3672. [
  3673. "sh",
  3674. "-c",
  3675. "claude plugin validate . --strict && "
  3676. "claude plugin details alfred-dev@alfred-dev | sed -n '1,18p' && "
  3677. "claude mcp get plugin:alfred-dev:alfred-memory",
  3678. ],
  3679. timeout=90,
  3680. )
  3681. for needle in ("Alfred Dev (alfred-dev) 0.7.0", "Skills (11)", "Agents (10)", "MCP servers (1)", "Status: ✔ Connected"):
  3682. if needle not in details:
  3683. _fail(f"Smoke Claude no contiene {needle!r}")
  3684. ok.append("Claude CLI valida inventario y MCP")
  3685. discovery = run_command(
  3686. "claude interactive /alfred discovery",
  3687. [sys.executable, str(ROOT / "scripts" / "claude_command_discovery.py")],
  3688. timeout=35,
  3689. )
  3690. if "ok claude interactive command discovery" not in discovery:
  3691. _fail("Smoke Claude no confirmo descubrimiento interactivo de /alfred")
  3692. if "FAIL claude-command-discovery" in discovery:
  3693. _fail("Smoke Claude sigue mostrando fallo de descubrimiento interactivo de /alfred")
  3694. ok.append("Claude CLI descubre /alfred en selector interactivo")
  3695. if args.with_site:
  3696. run_command("npm site check/build", ["sh", "-c", "npm --prefix site run check && npm --prefix site run build"], timeout=180)
  3697. ok.append("site check/build")
  3698. if args.with_tests:
  3699. run_command("pytest completo", ["python3", "-m", "pytest", "tests/", "-q"], timeout=300)
  3700. ok.append("pytest completo")
  3701. if args.with_syntax:
  3702. run_command(
  3703. "syntax/json/diff",
  3704. [
  3705. "sh",
  3706. "-c",
  3707. "bash -n install.sh && "
  3708. "python3 -m json.tool .mcp.json >/dev/null && "
  3709. "python3 -m json.tool .claude-plugin/plugin.json >/dev/null && "
  3710. "python3 -m json.tool .claude-plugin/marketplace.json >/dev/null && "
  3711. "git diff --check",
  3712. ],
  3713. timeout=60,
  3714. )
  3715. ok.append("syntax/json/diff-check")
  3716. return ok
  3717. def main(argv: list[str] | None = None) -> int:
  3718. parser = argparse.ArgumentParser(description=__doc__)
  3719. parser.add_argument("--with-claude", action="store_true", help="Ejecuta smokes con claude plugin/mcp.")
  3720. parser.add_argument("--with-site", action="store_true", help="Ejecuta npm --prefix site run check/build.")
  3721. parser.add_argument("--with-tests", action="store_true", help="Ejecuta python3 -m pytest tests/ -q.")
  3722. parser.add_argument("--with-syntax", action="store_true", help="Ejecuta bash -n, json.tool y git diff --check.")
  3723. parser.add_argument("--with-continuity", action="store_true", help="Ejecuta smoke operativo de helpers en fixture temporal.")
  3724. parser.add_argument("--with-mcp-tools", action="store_true", help="Invoca las 15 herramientas MCP en una SQLite temporal.")
  3725. parser.add_argument("--with-external-contracts", action="store_true", help="Verifica prompts seguros para Docker, GitHub, Lucius y deploy.")
  3726. parser.add_argument("--with-human-contracts", action="store_true", help="Verifica trato humano, AskUserQuestion, UAT y antifingimiento.")
  3727. parser.add_argument("--full", action="store_true", help="Activa todos los smokes externos.")
  3728. args = parser.parse_args(argv)
  3729. if args.full:
  3730. args.with_claude = args.with_site = args.with_tests = True
  3731. args.with_syntax = args.with_continuity = True
  3732. args.with_mcp_tools = args.with_external_contracts = True
  3733. args.with_human_contracts = True
  3734. checks = [
  3735. ("versionado", check_versions),
  3736. ("inventario", check_inventory),
  3737. ("catalogo", check_command_catalog),
  3738. ("comandos", check_command_execution_contracts),
  3739. ("claims", check_public_claims),
  3740. ("config", check_config_contracts),
  3741. ("flows", check_flow_gate_claims),
  3742. ("hooks", check_hook_contracts),
  3743. ("mcp", check_mcp_config),
  3744. ("packaging", check_packaging_contracts),
  3745. ("secrets", check_published_secret_scan),
  3746. ("install", check_install_update_contracts),
  3747. ("docs", check_audit_docs),
  3748. ]
  3749. try:
  3750. for name, check in checks:
  3751. for line in check():
  3752. print(f"ok {name}: {line}")
  3753. for line in check_external(args):
  3754. print(f"ok smoke: {line}")
  3755. except (AuditError, subprocess.TimeoutExpired) as exc:
  3756. print(f"FAIL release-audit: {exc}", file=sys.stderr)
  3757. return 1
  3758. print(f"release-audit {VERSION} ok")
  3759. return 0
  3760. if __name__ == "__main__":
  3761. raise SystemExit(main())
uninstall.ps1 · Bundled script · 191 lines · 1 finding marked
  1. # ---------------------------------------------------------------------------
  2. # Alfred Dev -- script de desinstalacion (Windows)
  3. #
  4. # Uso:
  5. # irm https://raw.githubusercontent.com/686f6c61/alfred-dev/main/uninstall.ps1 | iex
    • Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
    • Line 5 on GitHub
  6. #
  7. # Estrategia:
  8. # 1. Si Claude CLI está disponible, desinstalar el plugin y eliminar el
  9. # marketplace usando la vía nativa.
  10. # 2. Limpiar cualquier resto físico en cache/ y marketplaces/.
  11. # 3. Limpiar de forma residual los JSON internos si todavía quedan rastros.
  12. # ---------------------------------------------------------------------------
  13. $ErrorActionPreference = 'Stop'
  14. $PluginName = "alfred-dev"
  15. $ClaudeDir = Join-Path $env:USERPROFILE ".claude"
  16. $PluginsDir = Join-Path $ClaudeDir "plugins"
  17. # La ruta de cache sigue la convencion de Claude Code: cache/<marketplace>/<plugin>/<version>.
  18. # Se borra el directorio completo del marketplace para cubrir instalaciones viejas y nuevas.
  19. $CacheDir = Join-Path $PluginsDir "cache" $PluginName
  20. $MarketplaceDir = Join-Path $PluginsDir "marketplaces" $PluginName
  21. $InstalledFile = Join-Path $PluginsDir "installed_plugins.json"
  22. $KnownMarketplaces = Join-Path $PluginsDir "known_marketplaces.json"
  23. $SettingsFile = Join-Path $ClaudeDir "settings.json"
  24. $PluginKey = "$PluginName@$PluginName"
  25. $GlobalAliasDir = Join-Path $ClaudeDir "skills/alfred"
  26. $GlobalAliasFile = Join-Path $GlobalAliasDir "SKILL.md"
  27. $GlobalCommandAliasDir = Join-Path $ClaudeDir "commands"
  28. $GlobalCommandAliasFile = Join-Path $GlobalCommandAliasDir "alfred.md"
  29. # -- Funciones auxiliares ---------------------------------------------------
  30. function Write-Info { param([string]$Msg) Write-Host ">" $Msg -ForegroundColor Blue }
  31. function Write-Ok { param([string]$Msg) Write-Host "+" $Msg -ForegroundColor Green }
  32. function Write-Err { param([string]$Msg) Write-Host "x" $Msg -ForegroundColor Red }
  33. function Read-JsonFile {
  34. param([string]$Path)
  35. if (-not (Test-Path $Path)) { return $null }
  36. try {
  37. return (Get-Content $Path -Raw -Encoding UTF8) | ConvertFrom-Json
  38. }
  39. catch {
  40. Write-Err "El fichero '$Path' contiene JSON invalido: $_"
  41. throw
  42. }
  43. }
  44. # Escribir JSON de forma atomica (fichero temporal en mismo directorio + mover).
  45. # Crear el temporal junto al destino garantiza que Move-Item sea un rename
  46. # atomico del sistema de ficheros, sin copias entre discos.
  47. function Write-JsonFileAtomic {
  48. param([string]$Path, [object]$Data)
  49. $targetDir = Split-Path $Path -Parent
  50. $tmpFile = Join-Path $targetDir ".tmp-$([System.IO.Path]::GetRandomFileName())"
  51. try {
  52. $Data | ConvertTo-Json -Depth 10 | Set-Content $tmpFile -Encoding UTF8
  53. Move-Item -Path $tmpFile -Destination $Path -Force
  54. }
  55. catch {
  56. if (Test-Path $tmpFile) { Remove-Item $tmpFile -Force -ErrorAction SilentlyContinue }
  57. throw
  58. }
  59. }
  60. function Test-EmptyDirectory {
  61. param([string]$Path)
  62. if (-not (Test-Path -LiteralPath $Path -PathType Container)) {
  63. return $false
  64. }
  65. return $null -eq (Get-ChildItem -LiteralPath $Path -Force -ErrorAction SilentlyContinue)
  66. }
  67. function Remove-GlobalAlfredAlias {
  68. $removed = $false
  69. if (Test-Path $GlobalAliasFile -PathType Leaf) {
  70. $content = Get-Content $GlobalAliasFile -Raw -Encoding UTF8
  71. if ($content -match "Alfred Dev global alias") {
  72. Remove-Item $GlobalAliasFile -Force
  73. if (Test-EmptyDirectory $GlobalAliasDir) {
  74. Remove-Item $GlobalAliasDir -Force
  75. }
  76. Write-Ok "Alias global /alfred eliminado"
  77. $removed = $true
  78. }
  79. else {
  80. Write-Info "Se conserva ${GlobalAliasFile}: no parece ser el alias de Alfred Dev"
  81. }
  82. }
  83. if (Test-Path $GlobalCommandAliasFile -PathType Leaf) {
  84. $content = Get-Content $GlobalCommandAliasFile -Raw -Encoding UTF8
  85. if ($content -match "Alfred Dev global alias") {
  86. Remove-Item $GlobalCommandAliasFile -Force
  87. if (Test-EmptyDirectory $GlobalCommandAliasDir) {
  88. Remove-Item $GlobalCommandAliasDir -Force
  89. }
  90. Write-Ok "Shim de comando global /alfred eliminado"
  91. $removed = $true
  92. }
  93. else {
  94. Write-Info "Se conserva ${GlobalCommandAliasFile}: no parece ser el alias de Alfred Dev"
  95. }
  96. }
  97. if (-not $removed) {
  98. Write-Info "No se encontro alias global /alfred"
  99. }
  100. }
  101. # ---------------------------------------------------------------------------
  102. Write-Host ""
  103. Write-Host "Desinstalando Alfred Dev" -ForegroundColor White
  104. Write-Host ""
  105. # Intentar primero la vía canónica de Claude Code.
  106. $ClaudeCli = Get-Command claude -ErrorAction SilentlyContinue
  107. if ($null -ne $ClaudeCli) {
  108. Write-Info "Desinstalando plugin con Claude CLI..."
  109. & claude plugin uninstall $PluginKey --scope user 2>&1 | Out-Null
  110. & claude plugin marketplace remove $PluginName --scope user 2>&1 | Out-Null
  111. Write-Ok "Claude CLI ha intentado desregistrar el plugin y el marketplace"
  112. }
  113. else {
  114. Write-Info "El comando 'claude' no esta disponible; se aplicara limpieza manual de seguridad"
  115. }
  116. # Eliminar cache del plugin
  117. if (Test-Path $CacheDir) {
  118. Remove-Item $CacheDir -Recurse -Force
  119. Write-Ok "Cache del plugin eliminada"
  120. }
  121. else {
  122. Write-Info "No se encontro cache del plugin"
  123. }
  124. # Eliminar directorio de marketplace
  125. if (Test-Path $MarketplaceDir) {
  126. Remove-Item $MarketplaceDir -Recurse -Force
  127. Write-Ok "Directorio de marketplace eliminado"
  128. }
  129. else {
  130. Write-Info "No se encontro directorio de marketplace"
  131. }
  132. Remove-GlobalAlfredAlias
  133. # Eliminar marketplace de known_marketplaces.json
  134. if (Test-Path $KnownMarketplaces) {
  135. $known = Read-JsonFile $KnownMarketplaces
  136. if ($null -ne $known -and $known.PSObject.Properties.Name -contains $PluginName) {
  137. $known.PSObject.Properties.Remove($PluginName)
  138. Write-JsonFileAtomic $KnownMarketplaces $known
  139. Write-Ok "Marketplace limpiado de known_marketplaces.json"
  140. }
  141. }
  142. # Eliminar registro de installed_plugins.json
  143. if (Test-Path $InstalledFile) {
  144. $installed = Read-JsonFile $InstalledFile
  145. if ($null -ne $installed -and
  146. $installed.PSObject.Properties.Name -contains 'plugins' -and
  147. $installed.plugins.PSObject.Properties.Name -contains $PluginKey) {
  148. $installed.plugins.PSObject.Properties.Remove($PluginKey)
  149. Write-JsonFileAtomic $InstalledFile $installed
  150. Write-Ok "Registro limpiado de installed_plugins.json"
  151. }
  152. }
  153. # Deshabilitar en settings.json
  154. if (Test-Path $SettingsFile) {
  155. $settings = Read-JsonFile $SettingsFile
  156. if ($null -ne $settings -and
  157. $settings.PSObject.Properties.Name -contains 'enabledPlugins' -and
  158. $settings.enabledPlugins.PSObject.Properties.Name -contains $PluginKey) {
  159. $settings.enabledPlugins.PSObject.Properties.Remove($PluginKey)
  160. Write-JsonFileAtomic $SettingsFile $settings
  161. Write-Ok "Plugin limpiado de settings.json"
  162. }
  163. }
  164. else {
  165. Write-Info "No se encontro settings.json (nada que deshabilitar)"
  166. }
  167. Write-Host ""
  168. Write-Host "Alfred Dev desinstalado" -ForegroundColor Green
  169. Write-Host " Reinicia Claude Code para aplicar los cambios." -ForegroundColor DarkGray
  170. Write-Host ""
uninstall.sh · Bundled script · 276 lines · 1 finding marked
  1. #!/usr/bin/env bash
  2. # ---------------------------------------------------------------------------
  3. # Alfred Dev -- script de desinstalación
  4. #
  5. # Uso:
  6. # curl -fsSL https://raw.githubusercontent.com/686f6c61/alfred-dev/main/uninstall.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 6 on GitHub
  7. # bash ./uninstall.sh
  8. #
  9. # Estrategia:
  10. # 1. Si Claude CLI está disponible, desinstalar el plugin y eliminar el
  11. # marketplace usando la vía nativa.
  12. # 2. Limpiar cualquier resto físico en cache/ y marketplaces/.
  13. # 3. Como red de seguridad, limpiar known_marketplaces.json,
  14. # installed_plugins.json y settings.json si todavía contienen rastros.
  15. # ---------------------------------------------------------------------------
  16. set -euo pipefail
  17. PLUGIN_NAME="alfred-dev"
  18. PLUGIN_KEY="${PLUGIN_NAME}@${PLUGIN_NAME}"
  19. CLAUDE_DIR="${HOME}/.claude"
  20. PLUGINS_DIR="${CLAUDE_DIR}/plugins"
  21. MARKETPLACE_DIR="${PLUGINS_DIR}/marketplaces/${PLUGIN_NAME}"
  22. INSTALLED_FILE="${PLUGINS_DIR}/installed_plugins.json"
  23. KNOWN_MARKETPLACES="${PLUGINS_DIR}/known_marketplaces.json"
  24. SETTINGS_FILE="${CLAUDE_DIR}/settings.json"
  25. GLOBAL_ALIAS_DIR="${CLAUDE_DIR}/skills/alfred"
  26. GLOBAL_ALIAS_FILE="${GLOBAL_ALIAS_DIR}/SKILL.md"
  27. GLOBAL_COMMAND_ALIAS_DIR="${CLAUDE_DIR}/commands"
  28. GLOBAL_COMMAND_ALIAS_FILE="${GLOBAL_COMMAND_ALIAS_DIR}/alfred.md"
  29. RED='\033[0;31m'
  30. GREEN='\033[0;32m'
  31. BLUE='\033[0;34m'
  32. BOLD='\033[1m'
  33. DIM='\033[2m'
  34. NC='\033[0m'
  35. info() { printf "${BLUE}>${NC} %s\n" "$1"; }
  36. ok() { printf "${GREEN}+${NC} %s\n" "$1"; }
  37. error() { printf "${RED}x${NC} %s\n" "$1" >&2; }
  38. remove_global_alfred_alias() {
  39. local removed=0
  40. if [[ -f "${GLOBAL_ALIAS_FILE}" ]]; then
  41. if grep -q "Alfred Dev global alias" "${GLOBAL_ALIAS_FILE}"; then
  42. rm -f "${GLOBAL_ALIAS_FILE}"
  43. rmdir "${GLOBAL_ALIAS_DIR}" >/dev/null 2>&1 || true
  44. ok "Alias global /alfred eliminado"
  45. removed=1
  46. else
  47. info "Se conserva ${GLOBAL_ALIAS_FILE}: no parece ser el alias de Alfred Dev"
  48. fi
  49. fi
  50. if [[ -f "${GLOBAL_COMMAND_ALIAS_FILE}" ]]; then
  51. if grep -q "Alfred Dev global alias" "${GLOBAL_COMMAND_ALIAS_FILE}"; then
  52. rm -f "${GLOBAL_COMMAND_ALIAS_FILE}"
  53. rmdir "${GLOBAL_COMMAND_ALIAS_DIR}" >/dev/null 2>&1 || true
  54. ok "Shim de comando global /alfred eliminado"
  55. removed=1
  56. else
  57. info "Se conserva ${GLOBAL_COMMAND_ALIAS_FILE}: no parece ser el alias de Alfred Dev"
  58. fi
  59. fi
  60. if [[ "${removed}" -eq 0 ]]; then
  61. info "No se encontro alias global /alfred"
  62. fi
  63. }
  64. find_compatible_python() {
  65. local candidate ver major minor
  66. for candidate in python3 python3.13 python3.12 python3.11 python3.10; do
  67. if ! command -v "$candidate" &>/dev/null; then
  68. continue
  69. fi
  70. ver=$("$candidate" -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')" 2>/dev/null || echo "0.0")
  71. major=$(echo "$ver" | cut -d. -f1)
  72. minor=$(echo "$ver" | cut -d. -f2)
  73. if [[ "$major" -ge 3 ]] && [[ "$minor" -ge 10 ]]; then
  74. printf '%s\n' "$candidate"
  75. return 0
  76. fi
  77. done
  78. for brew_path in /opt/homebrew/bin /usr/local/bin; do
  79. for candidate in python3.13 python3.12 python3.11 python3.10 python3; do
  80. local full="${brew_path}/${candidate}"
  81. if [[ ! -x "$full" ]]; then
  82. continue
  83. fi
  84. ver=$("$full" -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')" 2>/dev/null || echo "0.0")
  85. major=$(echo "$ver" | cut -d. -f1)
  86. minor=$(echo "$ver" | cut -d. -f2)
  87. if [[ "$major" -ge 3 ]] && [[ "$minor" -ge 10 ]]; then
  88. printf '%s\n' "$full"
  89. return 0
  90. fi
  91. done
  92. done
  93. return 1
  94. }
  95. # Validar que HOME apunta a un directorio real
  96. if [[ -z "${HOME:-}" ]] || [[ ! -d "${HOME}" ]]; then
  97. error "La variable HOME no está definida o no apunta a un directorio válido"
  98. exit 1
  99. fi
  100. if [[ ! -d "${CLAUDE_DIR}" ]]; then
  101. info "No se encontró ${CLAUDE_DIR}; no hay instalación de usuario que limpiar"
  102. exit 0
  103. fi
  104. printf "\n${BOLD}Desinstalando Alfred Dev${NC}\n\n"
  105. # Intentar primero la vía canónica de Claude Code.
  106. if command -v claude &>/dev/null; then
  107. info "Desinstalando plugin con Claude CLI..."
  108. claude plugin uninstall "${PLUGIN_KEY}" --scope user >/dev/null 2>&1 || true
  109. claude plugin marketplace remove "${PLUGIN_NAME}" --scope user >/dev/null 2>&1 || true
  110. ok "Claude CLI ha intentado desregistrar el plugin y el marketplace"
  111. else
  112. info "El comando 'claude' no está disponible; se aplicará limpieza manual de seguridad"
  113. fi
  114. # Eliminar cache del plugin.
  115. # Se borra el directorio completo del marketplace en caché (cache/alfred-dev/)
  116. # para limpiar tanto instalaciones nuevas (cache/alfred-dev/alfred-dev/<version>)
  117. # como antiguas (cache/alfred-dev/<version>) de forma uniforme.
  118. CACHE_MARKETPLACE_DIR="${PLUGINS_DIR}/cache/${PLUGIN_NAME}"
  119. if [ -d "${CACHE_MARKETPLACE_DIR}" ]; then
  120. rm -rf "${CACHE_MARKETPLACE_DIR}"
  121. ok "Cache del plugin eliminada"
  122. else
  123. info "No se encontró cache del plugin"
  124. fi
  125. # Eliminar directorio de marketplace
  126. if [ -d "${MARKETPLACE_DIR}" ]; then
  127. rm -rf "${MARKETPLACE_DIR}"
  128. ok "Directorio de marketplace eliminado"
  129. else
  130. info "No se encontró directorio de marketplace"
  131. fi
  132. remove_global_alfred_alias
  133. # Si no hay Python compatible, no podemos aplicar la limpieza residual de JSON.
  134. PYTHON_CMD="$(find_compatible_python || true)"
  135. if [[ -z "${PYTHON_CMD}" ]]; then
  136. info "No se encontro Python 3.10+; se omite la limpieza residual de ficheros JSON"
  137. printf "\n${GREEN}${BOLD}Alfred Dev desinstalado${NC}\n"
  138. printf " ${DIM}Reinicia Claude Code para aplicar los cambios.${NC}\n\n"
  139. exit 0
  140. fi
  141. # Eliminar marketplace de known_marketplaces.json si aún quedara rastro.
  142. if [ -f "${KNOWN_MARKETPLACES}" ]; then
  143. "${PYTHON_CMD}" - "${KNOWN_MARKETPLACES}" "${PLUGIN_NAME}" <<'PYEOF'
  144. import json, os, sys, tempfile
  145. known_file, marketplace_name = sys.argv[1:3]
  146. try:
  147. with open(known_file, 'r') as f:
  148. data = json.load(f)
  149. except json.JSONDecodeError as e:
  150. print(f"Error: '{known_file}' contiene JSON inválido: {e}", file=sys.stderr)
  151. sys.exit(1)
  152. except OSError as e:
  153. print(f"Error: no se pudo leer '{known_file}': {e}", file=sys.stderr)
  154. sys.exit(1)
  155. if marketplace_name in data:
  156. del data[marketplace_name]
  157. # Escritura atómica
  158. try:
  159. tmp_fd, tmp_path = tempfile.mkstemp(dir=os.path.dirname(known_file))
  160. with os.fdopen(tmp_fd, 'w') as f:
  161. json.dump(data, f, indent=2)
  162. os.replace(tmp_path, known_file)
  163. except OSError as e:
  164. print(f"Error: no se pudo escribir '{known_file}': {e}", file=sys.stderr)
  165. try:
  166. os.unlink(tmp_path)
  167. except OSError:
  168. pass
  169. sys.exit(1)
  170. PYEOF
  171. ok "Marketplace limpiado de known_marketplaces.json"
  172. fi
  173. # Eliminar registro de installed_plugins.json si aún quedara rastro.
  174. if [ -f "${INSTALLED_FILE}" ]; then
  175. "${PYTHON_CMD}" - "${INSTALLED_FILE}" "${PLUGIN_KEY}" <<'PYEOF'
  176. import json, os, sys, tempfile
  177. installed_file, plugin_key = sys.argv[1:3]
  178. try:
  179. with open(installed_file, 'r') as f:
  180. data = json.load(f)
  181. except json.JSONDecodeError as e:
  182. print(f"Error: '{installed_file}' contiene JSON inválido: {e}", file=sys.stderr)
  183. sys.exit(1)
  184. except OSError as e:
  185. print(f"Error: no se pudo leer '{installed_file}': {e}", file=sys.stderr)
  186. sys.exit(1)
  187. if plugin_key in data.get('plugins', {}):
  188. del data['plugins'][plugin_key]
  189. # Escritura atómica
  190. try:
  191. tmp_fd, tmp_path = tempfile.mkstemp(dir=os.path.dirname(installed_file))
  192. with os.fdopen(tmp_fd, 'w') as f:
  193. json.dump(data, f, indent=2)
  194. os.replace(tmp_path, installed_file)
  195. except OSError as e:
  196. print(f"Error: no se pudo escribir '{installed_file}': {e}", file=sys.stderr)
  197. try:
  198. os.unlink(tmp_path)
  199. except OSError:
  200. pass
  201. sys.exit(1)
  202. PYEOF
  203. ok "Registro limpiado de installed_plugins.json"
  204. fi
  205. # Deshabilitar en settings.json si aún quedara rastro.
  206. if [ -f "${SETTINGS_FILE}" ]; then
  207. "${PYTHON_CMD}" - "${SETTINGS_FILE}" "${PLUGIN_KEY}" <<'PYEOF'
  208. import json, os, sys, tempfile
  209. settings_file, plugin_key = sys.argv[1:3]
  210. try:
  211. with open(settings_file, 'r') as f:
  212. data = json.load(f)
  213. except json.JSONDecodeError as e:
  214. print(f"Error: '{settings_file}' contiene JSON inválido: {e}", file=sys.stderr)
  215. sys.exit(1)
  216. except OSError as e:
  217. print(f"Error: no se pudo leer '{settings_file}': {e}", file=sys.stderr)
  218. sys.exit(1)
  219. if plugin_key in data.get('enabledPlugins', {}):
  220. del data['enabledPlugins'][plugin_key]
  221. # Escritura atómica
  222. try:
  223. tmp_fd, tmp_path = tempfile.mkstemp(dir=os.path.dirname(settings_file))
  224. with os.fdopen(tmp_fd, 'w') as f:
  225. json.dump(data, f, indent=2)
  226. os.replace(tmp_path, settings_file)
  227. except OSError as e:
  228. print(f"Error: no se pudo escribir '{settings_file}': {e}", file=sys.stderr)
  229. try:
  230. os.unlink(tmp_path)
  231. except OSError:
  232. pass
  233. sys.exit(1)
  234. PYEOF
  235. ok "Plugin limpiado de settings.json"
  236. else
  237. info "No se encontró settings.json (nada que deshabilitar)"
  238. fi
  239. printf "\n${GREEN}${BOLD}Alfred Dev desinstalado${NC}\n"
  240. printf " ${DIM}Reinicia Claude Code para aplicar los cambios.${NC}\n\n"

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.